Subversion Repositories havirt

Rev

Rev 42 | 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)
42 rodolico 33
#
34
# v1.2.2 20250511 RWR
35
# Do not force rescan on migrate if dryrun or testing are set
47 rodolico 36
#
37
# v1.2.3 20260102 RWR
38
# Refactored all command executions to use centralized execute() function
39
# Updated getVirtConfig, start, and new functions to use execute()
5 rodolico 40
 
26 rodolico 41
 
5 rodolico 42
package domain;
43
 
44
use warnings;
45
use strict;  
46
 
47
# define the version number
48
# see https://metacpan.org/pod/release/JPEACOCK/version-0.97/lib/version.pod
49
use version;
47 rodolico 50
our $VERSION = version->declare("1.2.3");
5 rodolico 51
 
52
 
53
use Data::Dumper;
54
 
55
use Exporter;
56
 
57
our @ISA = qw( Exporter );
58
our @EXPORT = qw( 
7 rodolico 59
                  &list
5 rodolico 60
                );
61
 
9 rodolico 62
sub help {
63
   my @return;
64
   push @return, "domain update [domainname|-t domainname]";
65
   push @return, "\tUpdates capabilities on one or more domains, default is all domains";
66
   push @return, "domain list [--format|-f screen|tsv]";
67
   push @return, "\tLists all domains with some statistics about them as screen or tsv (default screen)";
12 rodolico 68
   push @return, "domain start domainname [node]";
69
   push @return, "\tstarts domainname on node. If node not set, will pick a node.";
13 rodolico 70
   push @return, "domain shutdown domainname";
71
   push @return, "\tInitiates a shutdown on a running domain and puts it in to manual mode";
72
   push @return, "domain migrate domainname [node]";
73
   push @return, "\tmigrates domain from current node to target. If target node not specified";
74
   push @return, "\twill be automatically selected";
14 rodolico 75
   push @return, "domain new [domainname]";
76
   push @return, "\tgenerates a virt-install command that will fill in several blanks";
77
   push @return, "\tNOTE: MAC address not guaranteed to be unique";
29 rodolico 78
   push @return, "domain migrate domainname targetnode";
17 rodolico 79
   push @return, "\tMigates a domain from its current location to targetnode";
80
   push @return, "domain maintenance domainname [on|off]";
81
   push @return, "\tSet/Unset/display maintenance flag on domain";
82
   push @return, "\tIf maintenance flag is set, no havirt will refuse any actions";
39 rodolico 83
   push @return, "domain pin domainname node [node]";
84
   push @return, "\tPin a domain to one or more nodes. Restricts a node to only run on specific node(s)";
9 rodolico 85
   return join( "\n", @return ) . "\n";
86
}
87
 
7 rodolico 88
 
26 rodolico 89
# dipslay a list of domains, which node they are on and some information on them
7 rodolico 90
sub list {
12 rodolico 91
   &main::readDB();
38 rodolico 92
   #@_ = keys %{$main::statusDB->{'nodes'} } unless ( @_ );
25 rodolico 93
   print Dumper( $main::statusDB->{'nodePopulation'} ) if $main::config->{'flags'}->{'debug'} > 2;
7 rodolico 94
 
95
   my @header;
96
   my @data;
18 rodolico 97
   my @found;
7 rodolico 98
 
14 rodolico 99
   foreach my $node ( sort keys %{$main::statusDB->{'nodePopulation'}} ) {
38 rodolico 100
   #while ( my $node = shift ) {
14 rodolico 101
      foreach my $virt (sort keys %{$main::statusDB->{'nodePopulation'}->{$node}->{'running'}} ) {
7 rodolico 102
         unless ( @header ) {
103
            # if we don't have a header yet, create it from the keys in this one. Assumes every entry has same keys
12 rodolico 104
            @header = sort keys %{ $main::statusDB->{'virt'}->{$virt} };
105
            unshift @header, 'Domain';
7 rodolico 106
            unshift @header, 'Node';
107
         } # unless
18 rodolico 108
         push @found, $virt;
7 rodolico 109
         my @line;
110
         push @line, $node;
111
         push @line, $virt;
12 rodolico 112
         foreach my $column ( sort keys %{ $main::statusDB->{'virt'}->{$virt} } ) {
113
            push @line, $main::statusDB->{'virt'}->{$virt}->{$column};
7 rodolico 114
         }
115
         push @data, \@line;
116
      }
117
   }
18 rodolico 118
   my @allDomains = keys %{$main::statusDB->{'virt'} };
119
   my $notRunning = &main::diffArray( \@allDomains, \@found );
120
   my @padding;
121
   while ( @padding < @header - 2 ) {
122
      push @padding, '';
123
   }
124
   for ( my $i = 0; $i < @$notRunning; $i++ ) {
125
      my @line;
126
      push @line, 'Down';
127
      push @line, $notRunning->[$i];
128
      push @line, @padding;
129
      push @data, \@line;
130
   }
131
 
7 rodolico 132
   return &main::report( \@header, \@data );
133
}
134
 
15 rodolico 135
# reread the domain definition file and freshen the database
7 rodolico 136
sub update {
18 rodolico 137
   my @requiredFields = ( 'maintenance' );
12 rodolico 138
   &main::readDB(1); # loading it for write, so lock
8 rodolico 139
   unless ( @_ ) {
140
      # they didn't pass in anything, so do everything
12 rodolico 141
      @_ = keys %{ $main::statusDB->{'virt'} }
8 rodolico 142
   } # unless
26 rodolico 143
   print "Preparing to update " . join( "\n", @_ ) . "\n" 
144
      if $main::config->{'flags'}->{'debug'} > 1 or $main::config->{'flags'}->{'verbose'};
145
   while ( my $virt = shift ) { # for every domain they passed in
146
      &parseDomain( $virt ); # parse it and update definition
147
      foreach my $field ( @requiredFields ) { # make sure the required fields are in there
18 rodolico 148
         $main::statusDB->{'virt'}->{$virt}->{$field} = '' 
149
            unless defined ( $main::statusDB->{'virt'}->{$virt}->{$field} );
150
      } # foreach
7 rodolico 151
   } # while
12 rodolico 152
   &main::writeDB( $main::domainDBName, $main::statusDB->{'virt'} );
26 rodolico 153
   return "Domain(s) updated\n";
7 rodolico 154
}
155
 
15 rodolico 156
 
157
# finds one xml value in file.
158
# since libvirt does not use good xml which can be parsed by
159
# several libraries, we must do it manually with regex's
7 rodolico 160
sub getXMLValue {
161
   my ( $key, $string ) = @_;
25 rodolico 162
   print "getXMLValue: looking for [$key] $string\n" if $main::config->{'flags'}->{'debug'} > 2;
7 rodolico 163
   my $start = "<$key";
164
   my $end = "</$key>";
165
   $string =~ m/$start([^>]*)>([^<]+)$end/;
166
   return ($1,$2);
167
}
168
 
15 rodolico 169
 
170
# parse an xml file to find the values we want to save
171
# if config file exists in conf, just read it. If it does not
172
# exist, or if force is set, do a dumpxml on the running
173
# domain, put it into conf/ and load it.
7 rodolico 174
sub parseDomain {
175
   my ($virt, $nodePopulations ) = @_;
25 rodolico 176
   print "Parsing domain $virt in domain.pm:parseDomain\n" if $main::config->{'flags'}->{'debug'};
26 rodolico 177
   print "\tParsing domain $virt\n" if $main::config->{'flags'}->{'verbose'};
178
 
7 rodolico 179
   my @keysToSave = ( 'uuid', 'memory', 'vcpu','vnc' );
25 rodolico 180
   my $filename = "$main::config->{'conf dir'}/$virt.xml";
7 rodolico 181
   my $xml = &getVirtConfig( $virt, $filename );
182
   my ($param,$value) = &getXMLValue( 'uuid', $xml );
12 rodolico 183
   $main::statusDB->{'virt'}->{$virt}->{'uuid'} = $value;
7 rodolico 184
   ($param,$value) = &getXMLValue( 'memory', $xml );
12 rodolico 185
   $main::statusDB->{'virt'}->{$virt}->{'memory'} = $value;
7 rodolico 186
   ($param,$value) = &getXMLValue( 'vcpu', $xml );
12 rodolico 187
   $main::statusDB->{'virt'}->{$virt}->{'vcpu'} = $value;
7 rodolico 188
 
189
   $xml =~ m/type='vnc' port='(\d+)'/;
12 rodolico 190
   $main::statusDB->{'virt'}->{$virt}->{'vnc'} = $1;
25 rodolico 191
   print "After Parsing $virt in domain.pm:parseDomain\n" . Dumper($main::statusDB->{'virt'}->{$virt}) . "\n"  if $main::config->{'flags'}->{'debug'} > 2;
7 rodolico 192
}
193
 
15 rodolico 194
# returns xml definition of a domain
195
# if the definition exists in conf/, simply open and read
196
# if the definition file does not exist, or if $force is set, find the 
197
# running domain, perform an xml dump of it, save it to conf/, then 
198
# return it.
7 rodolico 199
sub getVirtConfig {
200
   my ($virt,$filename) = @_;
201
   my $return;
39 rodolico 202
   print "In getVirtConfig looking for $virt with file $filename, force is $main::config->{'flags'}->{'force'}\n" if $main::config->{'flags'}->{'debug'};
26 rodolico 203
   if ( -f $filename && ! $main::config->{'flags'}->{'force'}) {
7 rodolico 204
      open XML, "<$filename" or die "Could not read from $filename: $!\n";
205
      $return = join( '', <XML> );
206
      close XML;
207
   } else {
12 rodolico 208
      &main::readDB();
209
      foreach my $node ( keys %{$main::statusDB->{'nodePopulation'}} ) {
25 rodolico 210
         print "getVirtConfig Looking on $node for $virt\n" if $main::config->{'flags'}->{'debug'} > 1;;
12 rodolico 211
         if ( exists( $main::statusDB->{'nodePopulation'}->{$node}->{'running'}->{$virt} ) ) { # we found it
26 rodolico 212
            print "Getting copy of XML file for $virt from $node\n" if $main::config->{'flags'}->{'verbose'};
25 rodolico 213
            print "Found $virt on node $node\n" if $main::config->{'flags'}->{'debug'};;
214
            my $command = &main::makeCommand($node, "virsh dumpxml $virt");
47 rodolico 215
            $return = &main::execute($command);
25 rodolico 216
            print "Writing config for $virt from $node into $filename\n" if $main::config->{'flags'}->{'debug'};
7 rodolico 217
            open XML,">$filename" or die "Could not write to $filename: $!\n";
218
            print XML $return;
219
            close XML;
220
         } # if
221
      } # foreach
222
   } # if..else
223
   return $return;
224
} # sub getVirtConfig
12 rodolico 225
 
26 rodolico 226
 
12 rodolico 227
# start a domain
228
sub start {
229
   my ( $virt, $node ) = @_;
16 rodolico 230
   my $return;
47 rodolico 231
   $node = &main::execute('hostname') unless $node;
12 rodolico 232
   chomp $node;
18 rodolico 233
   return "Domain $virt in maintenance mode, can not start\n" if $main::statusDB->{'virt'}->{$virt}->{'maintenance'};
234
   return "Node $node in maintenance mode, can not start\n" if $main::statusDB->{'node'}->{$node}->{'maintenance'};
235
   if ( my $foundNode = &main::findDomain( $virt ) ) {
236
      die "$virt already running on $foundNode, not starting\n";
12 rodolico 237
   }
238
   die "I do not have a definition for $virt\n" unless exists( $main::statusDB->{'virt'}->{$virt} );
25 rodolico 239
   print Dumper( $main::statusDB->{'nodePopulation'} ) if $main::config->{'flags'}->{'debug'} > 2;
240
   if ( my $error = &main::validateResources( $node, $virt ) ) {
241
      die $error;
242
   }
243
   my $filename = "$main::config->{'conf dir'}/$virt.xml";
16 rodolico 244
   my $command = &main::makeCommand( $node, "virsh create $filename" );
26 rodolico 245
   print "Starting $virt on $node\n" if $main::config->{'flags'}->{'verbose'};
246
   if ( $main::config->{'flags'}->{'dryrun'} ) { # we'll actually do it
247
      $return =  $command;;
248
   } else {
47 rodolico 249
      $return = ( &main::executeAndWait( $command, $node, $virt, 1, 60, 15 ) ? 'Success' : 'Can not start');
16 rodolico 250
      &main::forceScan();
251
   }
252
   return "$return\n";
12 rodolico 253
}
13 rodolico 254
 
255
sub shutdown {
256
   my $virt = shift;
14 rodolico 257
   my $node = '';
15 rodolico 258
   my $return;
18 rodolico 259
   $node = &main::findDomain( $virt );
260
   die "I could not find the domain $virt running\n" unless $node;
25 rodolico 261
   print Dumper( $main::statusDB->{'nodePopulation'} ) if $main::config->{'flags'}->{'debug'} > 2;
14 rodolico 262
   die "I can not find $virt on any node\n" unless $node;
15 rodolico 263
   my $command = &main::makeCommand( $node, "virsh shutdown $virt" );
26 rodolico 264
   print "Attempting to shut down $virt currently on $node\n" if $main::config->{'flags'}->{'verbose'};
265
   if ( $main::config->{'flags'}->{'dryrun'} ) { # they want us to actually do it
266
      $return = $command;
267
   } else {
47 rodolico 268
      $return = ( &main::executeAndWait( $command, $node, $virt, 0, 120, 15 ) ? 'Success' : 'Time Out waiting for shutdown');
15 rodolico 269
      &main::forceScan();
270
   }
271
   return "$return\n";
13 rodolico 272
}
273
 
26 rodolico 274
# Migrate a single domain
275
# this is defined in havirt.pm, which is set up to migrate multiple domains
276
# but has an entry point here for just one
277
# domain is domain to migrate, target is where to put it
13 rodolico 278
sub migrate {
25 rodolico 279
   my ( $domain, $target ) = @_;
280
   if ( my $error = &main::validateResources( $target, $domain ) ) {
281
      die $error;
17 rodolico 282
   }
38 rodolico 283
   my $return = &main::migrate( $domain, $target );
42 rodolico 284
   &main::forceScan() unless $main::config->{'flags'}->{'dryrun'} || $main::config->{'flags'}->{'testing'};
38 rodolico 285
   return $return;
14 rodolico 286
}
287
 
288
# find an unused VNC port
289
sub findVNCPort {
290
   my $currentPorts = shift;
291
   my $return = 5900;
292
   while ( $currentPorts->{$return} ) {
293
      $return++;
294
   }
295
   return $return;
296
}
297
 
26 rodolico 298
# print MAC address in the correct format
299
# two character hex digits separated by colons, lower case
14 rodolico 300
sub printMac {
301
   my $mac = shift;
302
   my @return;
303
   my $separator = ':';
304
   for ( my $i = 0; $i < length( $mac ); $i += 2 ) {
305
      push @return, substr( $mac, $i, 2 );
306
   }
307
   return join( $separator, @return );
308
}
309
 
26 rodolico 310
 
311
# generate a random MAC address for new function.
312
# NOTE: this is not checked for duplication at this time
14 rodolico 313
sub makeMac {
314
   my $numDigits = 12; # 12 hex digits in a mac address
315
   my $macBaseXen = '00163e'; # Xen has 00:16:3E* assigned to it.
316
   my $hexDigits = '0123456789abcdef';
317
 
318
   my $baseMac = $macBaseXen;
319
 
320
   while (length( $baseMac ) < $numDigits ) {
321
      $baseMac .= substr($hexDigits, int(rand(length($hexDigits))),1 );
322
   }
323
 
324
   return  &printMac( $baseMac );
325
}
326
 
327
# generate a virt-install statement, verifying things are not already being used
328
sub new {
329
   my %config;
330
   $config{'name'} = shift;
331
   my $return;
25 rodolico 332
   my $template = $main::config->{'script dir'} . '/virt-install.template';
14 rodolico 333
   &main::readDB();
334
   my %current;
335
   foreach my $virt ( keys %{$main::statusDB->{'virt'} } ) {
336
      $current{'vnc'}{$main::statusDB->{'virt'}->{$virt}->{'vnc'}} = 1;
337
      #$current{'mac'}{'null'} = 1;
338
   }
339
   $config{'vnc'} = &findVNCPort( \%{$current{'vnc'}} );
340
   $config{'mac'} = &makeMac();
47 rodolico 341
   $config{'uuid'} = &main::execute('uuidgen');
14 rodolico 342
   chomp $config{'uuid'};
343
   if ( open TEMPLATE, "<$template" ) {
344
      $return = join( '', <TEMPLATE> );
345
      close TEMPLATE;
346
      foreach my $key ( keys %config ) {
347
         $return =~ s/<$key>/$config{$key}/gi if $config{$key};
348
      }
349
   } else {
350
      $return = "Template $template not found, the following values should be used\n";
351
      foreach my $key ( keys %config ) {
352
         $return .= "$key: $config{$key}\n";
353
      }
354
   }
355
   return $return;
356
}
17 rodolico 357
 
26 rodolico 358
 
359
# put domain in maintenance mode
360
# in maintenance mode, it can not be started, stopped or migrated by havirt
17 rodolico 361
sub maintenance {
362
   my ( $domain, $action ) = @_;
363
   &main::readDB(1);
364
   if ( $action ) {
365
      $main::statusDB->{'virt'}->{$domain}->{'maintenance'} = ( lc( $action ) eq 'on' ) ? 1 : 0;
366
   }
367
   &main::writeDB();
368
   return "Maintenance set to " . ( $main::statusDB->{'virt'}->{$domain}->{'maintenance'} ? 'On' : 'Off' ) . "\n";
369
}
370
 
39 rodolico 371
 
372
sub pin {
373
   my $domain = shift;
374
   &main::readDB(1);
375
   while ( my $node = shift ) {
376
      $main::statusDB->{'virt'}->{$domain}->{'pin'}->{$node} = 1;
377
   }
378
   &main::writeDB();
379
   return "domain pin functionality not yet implemented\n";
42 rodolico 380
}