Subversion Repositories havirt

Rev

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