Subversion Repositories havirt

Rev

Go to most recent revision | Details | 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;
35
our $VERSION = version->declare("0.0.1");
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
 
14 rodolico 72
# find node a domain is on
73
# first parameter is the domain name
74
# rest of @_ is list of nodes to search
75
# if no nodes passed in, will search all known nodes
76
# returns first node found with the domain, or an empty string if not found
16 rodolico 77
# possibly not being used??
14 rodolico 78
sub findDomain {
79
   my $domainName = shift;
80
   my @node = @_;
81
   my $foundNode = '';
82
   unless ( @node ) {
83
      @node = keys %{$main::statusDB->{'node'} };
84
   }
85
   foreach my $thisNode ( @node ) {
86
      my $output = `ssh $thisNode 'virsh list'`;
87
      return $thisNode if ( $output =~ m/domainName/ );
88
   }
89
   return '';
90
}
91
 
7 rodolico 92
sub list {
12 rodolico 93
   &main::readDB();
94
   print Dumper( $main::statusDB->{'nodePopulation'} ) if $main::DEBUG > 2;
7 rodolico 95
 
96
   my @header;
97
   my @data;
98
 
14 rodolico 99
   foreach my $node ( sort keys %{$main::statusDB->{'nodePopulation'}} ) {
100
      foreach my $virt (sort keys %{$main::statusDB->{'nodePopulation'}->{$node}->{'running'}} ) {
7 rodolico 101
         unless ( @header ) {
102
            # if we don't have a header yet, create it from the keys in this one. Assumes every entry has same keys
12 rodolico 103
            @header = sort keys %{ $main::statusDB->{'virt'}->{$virt} };
104
            unshift @header, 'Domain';
7 rodolico 105
            unshift @header, 'Node';
106
         } # unless
107
         my @line;
108
         push @line, $node;
109
         push @line, $virt;
12 rodolico 110
         foreach my $column ( sort keys %{ $main::statusDB->{'virt'}->{$virt} } ) {
111
            push @line, $main::statusDB->{'virt'}->{$virt}->{$column};
7 rodolico 112
         }
113
         push @data, \@line;
114
      }
115
   }
116
 
117
   return &main::report( \@header, \@data );
118
}
119
 
15 rodolico 120
# reread the domain definition file and freshen the database
7 rodolico 121
sub update {
12 rodolico 122
   &main::readDB(1); # loading it for write, so lock
8 rodolico 123
   unless ( @_ ) {
124
      # they didn't pass in anything, so do everything
12 rodolico 125
      @_ = keys %{ $main::statusDB->{'virt'} }
8 rodolico 126
   } # unless
127
   print "Preparing to update " . join( "\n", @_ ) . "\n" if $main::DEBUG > 1;
7 rodolico 128
   while ( my $virt = shift ) {
129
      &parseDomain( $virt );
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;
15 rodolico 206
   &main::forceScan();
12 rodolico 207
   &main::readDB();
208
   for my $myNode ( keys %{$main::statusDB->{'nodePopulation'} } ) {
209
      die "$virt already running on $myNode, not starting\n" if ( $main::statusDB->{'nodePopulation'}->{$myNode}->{'running'}->{$virt} );
210
   }
211
   die "I do not have a definition for $virt\n" unless exists( $main::statusDB->{'virt'}->{$virt} );
212
   print Dumper( $main::statusDB->{'nodePopulation'} ) if $main::DEBUG > 2;
213
   my $filename = "$main::confDir/$virt.xml";
16 rodolico 214
   my $command = &main::makeCommand( $node, "virsh create $filename" );
215
   if ( $main::force ) { # we'll actually do it
216
      $return = ( &main::executeAndWait( $command, $node, $virt, 1 ) ? 'Success' : 'Can not start');
217
      &main::forceScan();
218
   } else {
219
      $return =  $command;;
220
   }
221
   return "$return\n";
12 rodolico 222
}
13 rodolico 223
 
224
sub shutdown {
225
   my $virt = shift;
14 rodolico 226
   my $node = '';
15 rodolico 227
   my $return;
228
   &main::forceScan();
14 rodolico 229
   &main::readDB();
230
   for my $myNode ( keys %{$main::statusDB->{'nodePopulation'} } ) {
231
      if ( $main::statusDB->{'nodePopulation'}->{$myNode}->{'running'}->{$virt} ) {
232
         $node = $myNode;
233
         last;
234
      }
235
   }
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;
252
   &main::forceScan();
253
   &main::readDB();
254
   for my $myNode ( keys %{$main::statusDB->{'nodePopulation'} } ) {
255
      if ( $main::statusDB->{'nodePopulation'}->{$myNode}->{'running'}->{$virt} ) {
256
         $node = $myNode;
257
         last;
258
      }
259
   }
260
   print Dumper( $main::statusDB->{'nodePopulation'} ) if $main::DEBUG > 2;
261
   die "I can not find $virt on any node\n" unless $node;
262
   my $command = &main::makeCommand( $node, "virsh migrate --live --persistent --verbose  $virt qemu+ssh://$target/system" );
263
   if ( $main::force ) { # they want us to actually do it
264
      $return = ( &main::executeAndWait( $command, $node, $virt, 0 ) ? 'Success' : 'Time Out waiting for shutdown');
265
      &main::forceScan();
266
   } else {
267
      $return = $command;
268
   }
269
   return "$return\n";
14 rodolico 270
}
271
 
272
# find an unused VNC port
273
sub findVNCPort {
274
   my $currentPorts = shift;
275
   my $return = 5900;
276
   while ( $currentPorts->{$return} ) {
277
      $return++;
278
   }
279
   return $return;
280
}
281
 
282
 
283
sub printMac {
284
   my $mac = shift;
285
   my @return;
286
   my $separator = ':';
287
   for ( my $i = 0; $i < length( $mac ); $i += 2 ) {
288
      push @return, substr( $mac, $i, 2 );
289
   }
290
   return join( $separator, @return );
291
}
292
 
293
 
294
sub makeMac {
295
   my $numDigits = 12; # 12 hex digits in a mac address
296
   my $macBaseXen = '00163e'; # Xen has 00:16:3E* assigned to it.
297
   my $hexDigits = '0123456789abcdef';
298
 
299
   my $baseMac = $macBaseXen;
300
 
301
   while (length( $baseMac ) < $numDigits ) {
302
      $baseMac .= substr($hexDigits, int(rand(length($hexDigits))),1 );
303
   }
304
 
305
   return  &printMac( $baseMac );
306
}
307
 
308
# generate a virt-install statement, verifying things are not already being used
309
sub new {
310
   my %config;
311
   $config{'name'} = shift;
312
   my $return;
313
   my $template = $main::scriptDir . '/virt-install.template';
314
   &main::readDB();
315
   my %current;
316
   foreach my $virt ( keys %{$main::statusDB->{'virt'} } ) {
317
      $current{'vnc'}{$main::statusDB->{'virt'}->{$virt}->{'vnc'}} = 1;
318
      #$current{'mac'}{'null'} = 1;
319
   }
320
   $config{'vnc'} = &findVNCPort( \%{$current{'vnc'}} );
321
   $config{'mac'} = &makeMac();
322
   $config{'uuid'} = `uuidgen`;
323
   chomp $config{'uuid'};
324
   if ( open TEMPLATE, "<$template" ) {
325
      $return = join( '', <TEMPLATE> );
326
      close TEMPLATE;
327
      foreach my $key ( keys %config ) {
328
         $return =~ s/<$key>/$config{$key}/gi if $config{$key};
329
      }
330
   } else {
331
      $return = "Template $template not found, the following values should be used\n";
332
      foreach my $key ( keys %config ) {
333
         $return .= "$key: $config{$key}\n";
334
      }
335
   }
336
   return $return;
337
}
17 rodolico 338
 
339
sub maintenance {
340
   my ( $domain, $action ) = @_;
341
   &main::readDB(1);
342
   if ( $action ) {
343
      $main::statusDB->{'virt'}->{$domain}->{'maintenance'} = ( lc( $action ) eq 'on' ) ? 1 : 0;
344
   }
345
   &main::writeDB();
346
   return "Maintenance set to " . ( $main::statusDB->{'virt'}->{$domain}->{'maintenance'} ? 'On' : 'Off' ) . "\n";
347
}
348