Subversion Repositories havirt

Rev

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