Subversion Repositories havirt

Rev

Rev 29 | Go to most recent revision | Details | Compare with Previous | Last modification | View Log | RSS feed

Rev Author Line No. Line
5 rodolico 1
#!/usr/bin/env perl
2
 
3
# All functions related to maniplating domains
4
# part of havirt.
5
 
6
# Copyright 2024 Daily Data, Inc.
7
# 
8
# Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following 
9
# conditions are met:
10
#
11
#   Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer.
12
#   Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer 
13
#   in the documentation and/or other materials provided with the distribution.
14
#   Neither the name of the copyright holder nor the names of its contributors may be used to endorse or promote products derived
15
#   from this software without specific prior written permission.
16
# 
17
# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT
18
# NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL
19
# THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
20
# (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
21
# INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE
22
# OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
23
 
24
# v0.0.1 20240602 RWR
25
# Initial setup
26 rodolico 26
#
27
# v1.2.0 20240826 RWR
28
# Added some code to migrate domains if node placed in maintenance mode
29
# Added a lot of 'verbose' print lines, and modified for new flag structure
30
#
38 rodolico 31
# v1.2.1 20240828 RWR
32
# force rescan after domain migrate (pulled out of havirt.pm:scan)
5 rodolico 33
 
26 rodolico 34
 
5 rodolico 35
package domain;
36
 
37
use warnings;
38
use strict;  
39
 
40
# define the version number
41
# see https://metacpan.org/pod/release/JPEACOCK/version-0.97/lib/version.pod
42
use version;
38 rodolico 43
our $VERSION = version->declare("1.2.1");
5 rodolico 44
 
45
 
46
use Data::Dumper;
47
 
48
use Exporter;
49
 
50
our @ISA = qw( Exporter );
51
our @EXPORT = qw( 
7 rodolico 52
                  &list
5 rodolico 53
                );
54
 
9 rodolico 55
sub help {
56
   my @return;
57
   push @return, "domain update [domainname|-t domainname]";
58
   push @return, "\tUpdates capabilities on one or more domains, default is all domains";
59
   push @return, "domain list [--format|-f screen|tsv]";
60
   push @return, "\tLists all domains with some statistics about them as screen or tsv (default screen)";
12 rodolico 61
   push @return, "domain start domainname [node]";
62
   push @return, "\tstarts domainname on node. If node not set, will pick a node.";
13 rodolico 63
   push @return, "domain shutdown domainname";
64
   push @return, "\tInitiates a shutdown on a running domain and puts it in to manual mode";
65
   push @return, "domain migrate domainname [node]";
66
   push @return, "\tmigrates domain from current node to target. If target node not specified";
67
   push @return, "\twill be automatically selected";
14 rodolico 68
   push @return, "domain new [domainname]";
69
   push @return, "\tgenerates a virt-install command that will fill in several blanks";
70
   push @return, "\tNOTE: MAC address not guaranteed to be unique";
29 rodolico 71
   push @return, "domain migrate domainname targetnode";
17 rodolico 72
   push @return, "\tMigates a domain from its current location to targetnode";
73
   push @return, "domain maintenance domainname [on|off]";
74
   push @return, "\tSet/Unset/display maintenance flag on domain";
75
   push @return, "\tIf maintenance flag is set, no havirt will refuse any actions";
9 rodolico 76
   return join( "\n", @return ) . "\n";
77
}
78
 
7 rodolico 79
 
26 rodolico 80
# dipslay a list of domains, which node they are on and some information on them
7 rodolico 81
sub list {
12 rodolico 82
   &main::readDB();
38 rodolico 83
   #@_ = keys %{$main::statusDB->{'nodes'} } unless ( @_ );
25 rodolico 84
   print Dumper( $main::statusDB->{'nodePopulation'} ) if $main::config->{'flags'}->{'debug'} > 2;
7 rodolico 85
 
86
   my @header;
87
   my @data;
18 rodolico 88
   my @found;
7 rodolico 89
 
14 rodolico 90
   foreach my $node ( sort keys %{$main::statusDB->{'nodePopulation'}} ) {
38 rodolico 91
   #while ( my $node = shift ) {
14 rodolico 92
      foreach my $virt (sort keys %{$main::statusDB->{'nodePopulation'}->{$node}->{'running'}} ) {
7 rodolico 93
         unless ( @header ) {
94
            # if we don't have a header yet, create it from the keys in this one. Assumes every entry has same keys
12 rodolico 95
            @header = sort keys %{ $main::statusDB->{'virt'}->{$virt} };
96
            unshift @header, 'Domain';
7 rodolico 97
            unshift @header, 'Node';
98
         } # unless
18 rodolico 99
         push @found, $virt;
7 rodolico 100
         my @line;
101
         push @line, $node;
102
         push @line, $virt;
12 rodolico 103
         foreach my $column ( sort keys %{ $main::statusDB->{'virt'}->{$virt} } ) {
104
            push @line, $main::statusDB->{'virt'}->{$virt}->{$column};
7 rodolico 105
         }
106
         push @data, \@line;
107
      }
108
   }
18 rodolico 109
   my @allDomains = keys %{$main::statusDB->{'virt'} };
110
   my $notRunning = &main::diffArray( \@allDomains, \@found );
111
   my @padding;
112
   while ( @padding < @header - 2 ) {
113
      push @padding, '';
114
   }
115
   for ( my $i = 0; $i < @$notRunning; $i++ ) {
116
      my @line;
117
      push @line, 'Down';
118
      push @line, $notRunning->[$i];
119
      push @line, @padding;
120
      push @data, \@line;
121
   }
122
 
7 rodolico 123
   return &main::report( \@header, \@data );
124
}
125
 
15 rodolico 126
# reread the domain definition file and freshen the database
7 rodolico 127
sub update {
18 rodolico 128
   my @requiredFields = ( 'maintenance' );
12 rodolico 129
   &main::readDB(1); # loading it for write, so lock
8 rodolico 130
   unless ( @_ ) {
131
      # they didn't pass in anything, so do everything
12 rodolico 132
      @_ = keys %{ $main::statusDB->{'virt'} }
8 rodolico 133
   } # unless
26 rodolico 134
   print "Preparing to update " . join( "\n", @_ ) . "\n" 
135
      if $main::config->{'flags'}->{'debug'} > 1 or $main::config->{'flags'}->{'verbose'};
136
   while ( my $virt = shift ) { # for every domain they passed in
137
      &parseDomain( $virt ); # parse it and update definition
138
      foreach my $field ( @requiredFields ) { # make sure the required fields are in there
18 rodolico 139
         $main::statusDB->{'virt'}->{$virt}->{$field} = '' 
140
            unless defined ( $main::statusDB->{'virt'}->{$virt}->{$field} );
141
      } # foreach
7 rodolico 142
   } # while
12 rodolico 143
   &main::writeDB( $main::domainDBName, $main::statusDB->{'virt'} );
26 rodolico 144
   return "Domain(s) updated\n";
7 rodolico 145
}
146
 
15 rodolico 147
 
148
# finds one xml value in file.
149
# since libvirt does not use good xml which can be parsed by
150
# several libraries, we must do it manually with regex's
7 rodolico 151
sub getXMLValue {
152
   my ( $key, $string ) = @_;
25 rodolico 153
   print "getXMLValue: looking for [$key] $string\n" if $main::config->{'flags'}->{'debug'} > 2;
7 rodolico 154
   my $start = "<$key";
155
   my $end = "</$key>";
156
   $string =~ m/$start([^>]*)>([^<]+)$end/;
157
   return ($1,$2);
158
}
159
 
15 rodolico 160
 
161
# parse an xml file to find the values we want to save
162
# if config file exists in conf, just read it. If it does not
163
# exist, or if force is set, do a dumpxml on the running
164
# domain, put it into conf/ and load it.
7 rodolico 165
sub parseDomain {
166
   my ($virt, $nodePopulations ) = @_;
25 rodolico 167
   print "Parsing domain $virt in domain.pm:parseDomain\n" if $main::config->{'flags'}->{'debug'};
26 rodolico 168
   print "\tParsing domain $virt\n" if $main::config->{'flags'}->{'verbose'};
169
 
7 rodolico 170
   my @keysToSave = ( 'uuid', 'memory', 'vcpu','vnc' );
25 rodolico 171
   my $filename = "$main::config->{'conf dir'}/$virt.xml";
7 rodolico 172
   my $xml = &getVirtConfig( $virt, $filename );
173
   my ($param,$value) = &getXMLValue( 'uuid', $xml );
12 rodolico 174
   $main::statusDB->{'virt'}->{$virt}->{'uuid'} = $value;
7 rodolico 175
   ($param,$value) = &getXMLValue( 'memory', $xml );
12 rodolico 176
   $main::statusDB->{'virt'}->{$virt}->{'memory'} = $value;
7 rodolico 177
   ($param,$value) = &getXMLValue( 'vcpu', $xml );
12 rodolico 178
   $main::statusDB->{'virt'}->{$virt}->{'vcpu'} = $value;
7 rodolico 179
 
180
   $xml =~ m/type='vnc' port='(\d+)'/;
12 rodolico 181
   $main::statusDB->{'virt'}->{$virt}->{'vnc'} = $1;
25 rodolico 182
   print "After Parsing $virt in domain.pm:parseDomain\n" . Dumper($main::statusDB->{'virt'}->{$virt}) . "\n"  if $main::config->{'flags'}->{'debug'} > 2;
7 rodolico 183
}
184
 
15 rodolico 185
# returns xml definition of a domain
186
# if the definition exists in conf/, simply open and read
187
# if the definition file does not exist, or if $force is set, find the 
188
# running domain, perform an xml dump of it, save it to conf/, then 
189
# return it.
7 rodolico 190
sub getVirtConfig {
191
   my ($virt,$filename) = @_;
192
   my $return;
25 rodolico 193
   print "In getVirtConfig looking for $virt with file $filename, force is $main::config->{'flags'}->{'yes'}\n" if $main::config->{'flags'}->{'debug'};
26 rodolico 194
   if ( -f $filename && ! $main::config->{'flags'}->{'force'}) {
7 rodolico 195
      open XML, "<$filename" or die "Could not read from $filename: $!\n";
196
      $return = join( '', <XML> );
197
      close XML;
198
   } else {
12 rodolico 199
      &main::readDB();
200
      foreach my $node ( keys %{$main::statusDB->{'nodePopulation'}} ) {
25 rodolico 201
         print "getVirtConfig Looking on $node for $virt\n" if $main::config->{'flags'}->{'debug'} > 1;;
12 rodolico 202
         if ( exists( $main::statusDB->{'nodePopulation'}->{$node}->{'running'}->{$virt} ) ) { # we found it
26 rodolico 203
            print "Getting copy of XML file for $virt from $node\n" if $main::config->{'flags'}->{'verbose'};
25 rodolico 204
            print "Found $virt on node $node\n" if $main::config->{'flags'}->{'debug'};;
205
            my $command = &main::makeCommand($node, "virsh dumpxml $virt");
206
            $return = `$command`;
207
            print "Writing config for $virt from $node into $filename\n" if $main::config->{'flags'}->{'debug'};
7 rodolico 208
            open XML,">$filename" or die "Could not write to $filename: $!\n";
209
            print XML $return;
210
            close XML;
211
         } # if
212
      } # foreach
213
   } # if..else
214
   return $return;
215
} # sub getVirtConfig
12 rodolico 216
 
26 rodolico 217
 
12 rodolico 218
# start a domain
219
sub start {
220
   my ( $virt, $node ) = @_;
16 rodolico 221
   my $return;
12 rodolico 222
   $node = `hostname` unless $node;
223
   chomp $node;
18 rodolico 224
   return "Domain $virt in maintenance mode, can not start\n" if $main::statusDB->{'virt'}->{$virt}->{'maintenance'};
225
   return "Node $node in maintenance mode, can not start\n" if $main::statusDB->{'node'}->{$node}->{'maintenance'};
226
   if ( my $foundNode = &main::findDomain( $virt ) ) {
227
      die "$virt already running on $foundNode, not starting\n";
12 rodolico 228
   }
229
   die "I do not have a definition for $virt\n" unless exists( $main::statusDB->{'virt'}->{$virt} );
25 rodolico 230
   print Dumper( $main::statusDB->{'nodePopulation'} ) if $main::config->{'flags'}->{'debug'} > 2;
231
   if ( my $error = &main::validateResources( $node, $virt ) ) {
232
      die $error;
233
   }
234
   my $filename = "$main::config->{'conf dir'}/$virt.xml";
16 rodolico 235
   my $command = &main::makeCommand( $node, "virsh create $filename" );
26 rodolico 236
   print "Starting $virt on $node\n" if $main::config->{'flags'}->{'verbose'};
237
   if ( $main::config->{'flags'}->{'dryrun'} ) { # we'll actually do it
238
      $return =  $command;;
239
   } else {
16 rodolico 240
      $return = ( &main::executeAndWait( $command, $node, $virt, 1 ) ? 'Success' : 'Can not start');
241
      &main::forceScan();
242
   }
243
   return "$return\n";
12 rodolico 244
}
13 rodolico 245
 
246
sub shutdown {
247
   my $virt = shift;
14 rodolico 248
   my $node = '';
15 rodolico 249
   my $return;
18 rodolico 250
   $node = &main::findDomain( $virt );
251
   die "I could not find the domain $virt running\n" unless $node;
25 rodolico 252
   print Dumper( $main::statusDB->{'nodePopulation'} ) if $main::config->{'flags'}->{'debug'} > 2;
14 rodolico 253
   die "I can not find $virt on any node\n" unless $node;
15 rodolico 254
   my $command = &main::makeCommand( $node, "virsh shutdown $virt" );
26 rodolico 255
   print "Attempting to shut down $virt currently on $node\n" if $main::config->{'flags'}->{'verbose'};
256
   if ( $main::config->{'flags'}->{'dryrun'} ) { # they want us to actually do it
257
      $return = $command;
258
   } else {
15 rodolico 259
      $return = ( &main::executeAndWait( $command, $node, $virt, 0 ) ? 'Success' : 'Time Out waiting for shutdown');
260
      &main::forceScan();
261
   }
262
   return "$return\n";
13 rodolico 263
}
264
 
26 rodolico 265
# Migrate a single domain
266
# this is defined in havirt.pm, which is set up to migrate multiple domains
267
# but has an entry point here for just one
268
# domain is domain to migrate, target is where to put it
13 rodolico 269
sub migrate {
25 rodolico 270
   my ( $domain, $target ) = @_;
271
   if ( my $error = &main::validateResources( $target, $domain ) ) {
272
      die $error;
17 rodolico 273
   }
38 rodolico 274
   my $return = &main::migrate( $domain, $target );
275
   &main::forceScan();
276
   return $return;
14 rodolico 277
}
278
 
279
# find an unused VNC port
280
sub findVNCPort {
281
   my $currentPorts = shift;
282
   my $return = 5900;
283
   while ( $currentPorts->{$return} ) {
284
      $return++;
285
   }
286
   return $return;
287
}
288
 
26 rodolico 289
# print MAC address in the correct format
290
# two character hex digits separated by colons, lower case
14 rodolico 291
sub printMac {
292
   my $mac = shift;
293
   my @return;
294
   my $separator = ':';
295
   for ( my $i = 0; $i < length( $mac ); $i += 2 ) {
296
      push @return, substr( $mac, $i, 2 );
297
   }
298
   return join( $separator, @return );
299
}
300
 
26 rodolico 301
 
302
# generate a random MAC address for new function.
303
# NOTE: this is not checked for duplication at this time
14 rodolico 304
sub makeMac {
305
   my $numDigits = 12; # 12 hex digits in a mac address
306
   my $macBaseXen = '00163e'; # Xen has 00:16:3E* assigned to it.
307
   my $hexDigits = '0123456789abcdef';
308
 
309
   my $baseMac = $macBaseXen;
310
 
311
   while (length( $baseMac ) < $numDigits ) {
312
      $baseMac .= substr($hexDigits, int(rand(length($hexDigits))),1 );
313
   }
314
 
315
   return  &printMac( $baseMac );
316
}
317
 
318
# generate a virt-install statement, verifying things are not already being used
319
sub new {
320
   my %config;
321
   $config{'name'} = shift;
322
   my $return;
25 rodolico 323
   my $template = $main::config->{'script dir'} . '/virt-install.template';
14 rodolico 324
   &main::readDB();
325
   my %current;
326
   foreach my $virt ( keys %{$main::statusDB->{'virt'} } ) {
327
      $current{'vnc'}{$main::statusDB->{'virt'}->{$virt}->{'vnc'}} = 1;
328
      #$current{'mac'}{'null'} = 1;
329
   }
330
   $config{'vnc'} = &findVNCPort( \%{$current{'vnc'}} );
331
   $config{'mac'} = &makeMac();
332
   $config{'uuid'} = `uuidgen`;
333
   chomp $config{'uuid'};
334
   if ( open TEMPLATE, "<$template" ) {
335
      $return = join( '', <TEMPLATE> );
336
      close TEMPLATE;
337
      foreach my $key ( keys %config ) {
338
         $return =~ s/<$key>/$config{$key}/gi if $config{$key};
339
      }
340
   } else {
341
      $return = "Template $template not found, the following values should be used\n";
342
      foreach my $key ( keys %config ) {
343
         $return .= "$key: $config{$key}\n";
344
      }
345
   }
346
   return $return;
347
}
17 rodolico 348
 
26 rodolico 349
 
350
# put domain in maintenance mode
351
# in maintenance mode, it can not be started, stopped or migrated by havirt
17 rodolico 352
sub maintenance {
353
   my ( $domain, $action ) = @_;
354
   &main::readDB(1);
355
   if ( $action ) {
356
      $main::statusDB->{'virt'}->{$domain}->{'maintenance'} = ( lc( $action ) eq 'on' ) ? 1 : 0;
357
   }
358
   &main::writeDB();
359
   return "Maintenance set to " . ( $main::statusDB->{'virt'}->{$domain}->{'maintenance'} ? 'On' : 'Off' ) . "\n";
360
}
361