Subversion Repositories havirt

Rev

Rev 20 | 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();
74
   print Dumper( $main::statusDB->{'nodePopulation'} ) if $main::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
123
   print "Preparing to update " . join( "\n", @_ ) . "\n" if $main::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 ) = @_;
9 rodolico 141
   print "getXMLValue: looking for [$key] $string\n" if $main::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 ) = @_;
155
 
156
   my @keysToSave = ( 'uuid', 'memory', 'vcpu','vnc' );
157
   my $filename = "$main::confDir/$virt.xml";
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;
7 rodolico 168
}
169
 
15 rodolico 170
# returns xml definition of a domain
171
# if the definition exists in conf/, simply open and read
172
# if the definition file does not exist, or if $force is set, find the 
173
# running domain, perform an xml dump of it, save it to conf/, then 
174
# return it.
7 rodolico 175
sub getVirtConfig {
176
   my ($virt,$filename) = @_;
177
   my $return;
15 rodolico 178
   print "In getVirtConfig looking for $virt with file $filename, force is $main::force\n" if $main::DEBUG;
179
   if ( -f $filename && ! $main::force) {
7 rodolico 180
      open XML, "<$filename" or die "Could not read from $filename: $!\n";
181
      $return = join( '', <XML> );
182
      close XML;
183
   } else {
12 rodolico 184
      &main::readDB();
185
      foreach my $node ( keys %{$main::statusDB->{'nodePopulation'}} ) {
9 rodolico 186
         print "getVirtConfig Looking on $node for $virt\n" if $main::DEBUG > 1;;
12 rodolico 187
         if ( exists( $main::statusDB->{'nodePopulation'}->{$node}->{'running'}->{$virt} ) ) { # we found it
9 rodolico 188
            print "Found $virt on node $node\n" if $main::DEBUG;;
7 rodolico 189
            $return = `ssh $node 'virsh dumpxml $virt'`;
9 rodolico 190
            print "Writing config for $virt from $node into $filename\n" if $main::DEBUG;
7 rodolico 191
            open XML,">$filename" or die "Could not write to $filename: $!\n";
192
            print XML $return;
193
            close XML;
194
         } # if
195
      } # foreach
196
   } # if..else
197
   return $return;
198
} # sub getVirtConfig
12 rodolico 199
 
200
# start a domain
201
sub start {
202
   my ( $virt, $node ) = @_;
16 rodolico 203
   my $return;
12 rodolico 204
   $node = `hostname` unless $node;
205
   chomp $node;
18 rodolico 206
   return "Domain $virt in maintenance mode, can not start\n" if $main::statusDB->{'virt'}->{$virt}->{'maintenance'};
207
   return "Node $node in maintenance mode, can not start\n" if $main::statusDB->{'node'}->{$node}->{'maintenance'};
208
   # these are replaced by the safer findDomain
209
   #&main::forceScan();
210
   #&main::readDB();
211
   if ( my $foundNode = &main::findDomain( $virt ) ) {
212
      die "$virt already running on $foundNode, not starting\n";
12 rodolico 213
   }
214
   die "I do not have a definition for $virt\n" unless exists( $main::statusDB->{'virt'}->{$virt} );
215
   print Dumper( $main::statusDB->{'nodePopulation'} ) if $main::DEBUG > 2;
216
   my $filename = "$main::confDir/$virt.xml";
16 rodolico 217
   my $command = &main::makeCommand( $node, "virsh create $filename" );
218
   if ( $main::force ) { # we'll actually do it
219
      $return = ( &main::executeAndWait( $command, $node, $virt, 1 ) ? 'Success' : 'Can not start');
220
      &main::forceScan();
221
   } else {
222
      $return =  $command;;
223
   }
224
   return "$return\n";
12 rodolico 225
}
13 rodolico 226
 
227
sub shutdown {
228
   my $virt = shift;
14 rodolico 229
   my $node = '';
15 rodolico 230
   my $return;
18 rodolico 231
   # these are replaced by the safer findDomain
232
   #&main::forceScan();
233
   #&main::readDB();
234
   $node = &main::findDomain( $virt );
235
   die "I could not find the domain $virt running\n" unless $node;
14 rodolico 236
   print Dumper( $main::statusDB->{'nodePopulation'} ) if $main::DEBUG > 2;
237
   die "I can not find $virt on any node\n" unless $node;
15 rodolico 238
   my $command = &main::makeCommand( $node, "virsh shutdown $virt" );
239
   if ( $main::force ) { # they want us to actually do it
240
      $return = ( &main::executeAndWait( $command, $node, $virt, 0 ) ? 'Success' : 'Time Out waiting for shutdown');
241
      &main::forceScan();
242
   } else {
243
      $return = $command;
244
   }
245
   return "$return\n";
13 rodolico 246
}
247
 
248
sub migrate {
249
   my ( $virt, $target ) = @_;
17 rodolico 250
   my $return;
251
   my $node;
18 rodolico 252
   # these are replaced by the safer findDomain
253
   #&main::forceScan();
254
   #&main::readDB();
255
   $node = &main::findDomain( $virt );
17 rodolico 256
   print Dumper( $main::statusDB->{'nodePopulation'} ) if $main::DEBUG > 2;
257
   die "I can not find $virt on any node\n" unless $node;
18 rodolico 258
   die "Domain $virt in maintenance mode, can not migrate it\n" if $main::statusDB->{'virt'}->{$virt}->{'maintenance'};
259
   die "Node $target in maintenance mode, can not migrate anything to it\n" if $main::statusDB->{'node'}->{$target}->{'maintenance'};
260
   die "$virt already on $target\n" if $target eq $node;
17 rodolico 261
   my $command = &main::makeCommand( $node, "virsh migrate --live --persistent --verbose  $virt qemu+ssh://$target/system" );
262
   if ( $main::force ) { # they want us to actually do it
263
      $return = ( &main::executeAndWait( $command, $node, $virt, 0 ) ? 'Success' : 'Time Out waiting for shutdown');
264
      &main::forceScan();
265
   } else {
266
      $return = $command;
267
   }
268
   return "$return\n";
14 rodolico 269
}
270
 
271
# find an unused VNC port
272
sub findVNCPort {
273
   my $currentPorts = shift;
274
   my $return = 5900;
275
   while ( $currentPorts->{$return} ) {
276
      $return++;
277
   }
278
   return $return;
279
}
280
 
281
 
282
sub printMac {
283
   my $mac = shift;
284
   my @return;
285
   my $separator = ':';
286
   for ( my $i = 0; $i < length( $mac ); $i += 2 ) {
287
      push @return, substr( $mac, $i, 2 );
288
   }
289
   return join( $separator, @return );
290
}
291
 
292
 
293
sub makeMac {
294
   my $numDigits = 12; # 12 hex digits in a mac address
295
   my $macBaseXen = '00163e'; # Xen has 00:16:3E* assigned to it.
296
   my $hexDigits = '0123456789abcdef';
297
 
298
   my $baseMac = $macBaseXen;
299
 
300
   while (length( $baseMac ) < $numDigits ) {
301
      $baseMac .= substr($hexDigits, int(rand(length($hexDigits))),1 );
302
   }
303
 
304
   return  &printMac( $baseMac );
305
}
306
 
307
# generate a virt-install statement, verifying things are not already being used
308
sub new {
309
   my %config;
310
   $config{'name'} = shift;
311
   my $return;
312
   my $template = $main::scriptDir . '/virt-install.template';
313
   &main::readDB();
314
   my %current;
315
   foreach my $virt ( keys %{$main::statusDB->{'virt'} } ) {
316
      $current{'vnc'}{$main::statusDB->{'virt'}->{$virt}->{'vnc'}} = 1;
317
      #$current{'mac'}{'null'} = 1;
318
   }
319
   $config{'vnc'} = &findVNCPort( \%{$current{'vnc'}} );
320
   $config{'mac'} = &makeMac();
321
   $config{'uuid'} = `uuidgen`;
322
   chomp $config{'uuid'};
323
   if ( open TEMPLATE, "<$template" ) {
324
      $return = join( '', <TEMPLATE> );
325
      close TEMPLATE;
326
      foreach my $key ( keys %config ) {
327
         $return =~ s/<$key>/$config{$key}/gi if $config{$key};
328
      }
329
   } else {
330
      $return = "Template $template not found, the following values should be used\n";
331
      foreach my $key ( keys %config ) {
332
         $return .= "$key: $config{$key}\n";
333
      }
334
   }
335
   return $return;
336
}
17 rodolico 337
 
338
sub maintenance {
339
   my ( $domain, $action ) = @_;
340
   &main::readDB(1);
341
   if ( $action ) {
342
      $main::statusDB->{'virt'}->{$domain}->{'maintenance'} = ( lc( $action ) eq 'on' ) ? 1 : 0;
343
   }
344
   &main::writeDB();
345
   return "Maintenance set to " . ( $main::statusDB->{'virt'}->{$domain}->{'maintenance'} ? 'On' : 'Off' ) . "\n";
346
}
347