Subversion Repositories havirt

Rev

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