Subversion Repositories havirt

Rev

Rev 14 | Rev 16 | 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;
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";
9 rodolico 63
   return join( "\n", @return ) . "\n";
64
}
65
 
7 rodolico 66
 
14 rodolico 67
# find node a domain is on
68
# first parameter is the domain name
69
# rest of @_ is list of nodes to search
70
# if no nodes passed in, will search all known nodes
71
# returns first node found with the domain, or an empty string if not found
72
sub findDomain {
73
   my $domainName = shift;
74
   my @node = @_;
75
   my $foundNode = '';
76
   unless ( @node ) {
77
      @node = keys %{$main::statusDB->{'node'} };
78
   }
79
   foreach my $thisNode ( @node ) {
80
      my $output = `ssh $thisNode 'virsh list'`;
81
      return $thisNode if ( $output =~ m/domainName/ );
82
   }
83
   return '';
84
}
85
 
7 rodolico 86
sub list {
12 rodolico 87
   &main::readDB();
88
   print Dumper( $main::statusDB->{'nodePopulation'} ) if $main::DEBUG > 2;
7 rodolico 89
 
90
   my @header;
91
   my @data;
92
 
14 rodolico 93
   foreach my $node ( sort keys %{$main::statusDB->{'nodePopulation'}} ) {
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
101
         my @line;
102
         push @line, $node;
103
         push @line, $virt;
12 rodolico 104
         foreach my $column ( sort keys %{ $main::statusDB->{'virt'}->{$virt} } ) {
105
            push @line, $main::statusDB->{'virt'}->{$virt}->{$column};
7 rodolico 106
         }
107
         push @data, \@line;
108
      }
109
   }
110
 
111
   return &main::report( \@header, \@data );
112
}
113
 
15 rodolico 114
# reread the domain definition file and freshen the database
7 rodolico 115
sub update {
12 rodolico 116
   &main::readDB(1); # loading it for write, so lock
8 rodolico 117
   unless ( @_ ) {
118
      # they didn't pass in anything, so do everything
12 rodolico 119
      @_ = keys %{ $main::statusDB->{'virt'} }
8 rodolico 120
   } # unless
121
   print "Preparing to update " . join( "\n", @_ ) . "\n" if $main::DEBUG > 1;
7 rodolico 122
   while ( my $virt = shift ) {
123
      &parseDomain( $virt );
124
   } # while
12 rodolico 125
   &main::writeDB( $main::domainDBName, $main::statusDB->{'virt'} );
9 rodolico 126
   return "Updated\n";
7 rodolico 127
}
128
 
15 rodolico 129
 
130
# finds one xml value in file.
131
# since libvirt does not use good xml which can be parsed by
132
# several libraries, we must do it manually with regex's
7 rodolico 133
sub getXMLValue {
134
   my ( $key, $string ) = @_;
9 rodolico 135
   print "getXMLValue: looking for [$key] $string\n" if $main::DEBUG > 2;
7 rodolico 136
   my $start = "<$key";
137
   my $end = "</$key>";
138
   $string =~ m/$start([^>]*)>([^<]+)$end/;
139
   return ($1,$2);
140
}
141
 
15 rodolico 142
 
143
# parse an xml file to find the values we want to save
144
# if config file exists in conf, just read it. If it does not
145
# exist, or if force is set, do a dumpxml on the running
146
# domain, put it into conf/ and load it.
7 rodolico 147
sub parseDomain {
148
   my ($virt, $nodePopulations ) = @_;
149
 
150
   my @keysToSave = ( 'uuid', 'memory', 'vcpu','vnc' );
151
   my $filename = "$main::confDir/$virt.xml";
152
   my $xml = &getVirtConfig( $virt, $filename );
153
   my ($param,$value) = &getXMLValue( 'uuid', $xml );
12 rodolico 154
   $main::statusDB->{'virt'}->{$virt}->{'uuid'} = $value;
7 rodolico 155
   ($param,$value) = &getXMLValue( 'memory', $xml );
12 rodolico 156
   $main::statusDB->{'virt'}->{$virt}->{'memory'} = $value;
7 rodolico 157
   ($param,$value) = &getXMLValue( 'vcpu', $xml );
12 rodolico 158
   $main::statusDB->{'virt'}->{$virt}->{'vcpu'} = $value;
7 rodolico 159
 
160
   $xml =~ m/type='vnc' port='(\d+)'/;
12 rodolico 161
   $main::statusDB->{'virt'}->{$virt}->{'vnc'} = $1;
7 rodolico 162
}
163
 
15 rodolico 164
# returns xml definition of a domain
165
# if the definition exists in conf/, simply open and read
166
# if the definition file does not exist, or if $force is set, find the 
167
# running domain, perform an xml dump of it, save it to conf/, then 
168
# return it.
7 rodolico 169
sub getVirtConfig {
170
   my ($virt,$filename) = @_;
171
   my $return;
15 rodolico 172
   print "In getVirtConfig looking for $virt with file $filename, force is $main::force\n" if $main::DEBUG;
173
   if ( -f $filename && ! $main::force) {
7 rodolico 174
      open XML, "<$filename" or die "Could not read from $filename: $!\n";
175
      $return = join( '', <XML> );
176
      close XML;
177
   } else {
12 rodolico 178
      &main::readDB();
179
      foreach my $node ( keys %{$main::statusDB->{'nodePopulation'}} ) {
9 rodolico 180
         print "getVirtConfig Looking on $node for $virt\n" if $main::DEBUG > 1;;
12 rodolico 181
         if ( exists( $main::statusDB->{'nodePopulation'}->{$node}->{'running'}->{$virt} ) ) { # we found it
9 rodolico 182
            print "Found $virt on node $node\n" if $main::DEBUG;;
7 rodolico 183
            $return = `ssh $node 'virsh dumpxml $virt'`;
9 rodolico 184
            print "Writing config for $virt from $node into $filename\n" if $main::DEBUG;
7 rodolico 185
            open XML,">$filename" or die "Could not write to $filename: $!\n";
186
            print XML $return;
187
            close XML;
188
         } # if
189
      } # foreach
190
   } # if..else
191
   return $return;
192
} # sub getVirtConfig
12 rodolico 193
 
194
# start a domain
195
sub start {
196
   my ( $virt, $node ) = @_;
197
   $node = `hostname` unless $node;
198
   chomp $node;
15 rodolico 199
   &main::forceScan();
200
   #if ( my $alreadyRunning = &findDomain( $node ) ) {
201
   #   die "$virt already running on $alreadyRunning; not starting\n";
202
   #}
12 rodolico 203
   &main::readDB();
204
   for my $myNode ( keys %{$main::statusDB->{'nodePopulation'} } ) {
205
      die "$virt already running on $myNode, not starting\n" if ( $main::statusDB->{'nodePopulation'}->{$myNode}->{'running'}->{$virt} );
206
   }
207
   die "I do not have a definition for $virt\n" unless exists( $main::statusDB->{'virt'}->{$virt} );
208
   print Dumper( $main::statusDB->{'nodePopulation'} ) if $main::DEBUG > 2;
209
   my $filename = "$main::confDir/$virt.xml";
210
   return "ssh $node 'virsh create $filename'\n";
211
}
13 rodolico 212
 
213
sub shutdown {
214
   my $virt = shift;
14 rodolico 215
   my $node = '';
15 rodolico 216
   my $return;
217
   &main::forceScan();
14 rodolico 218
   &main::readDB();
219
   for my $myNode ( keys %{$main::statusDB->{'nodePopulation'} } ) {
220
      if ( $main::statusDB->{'nodePopulation'}->{$myNode}->{'running'}->{$virt} ) {
221
         $node = $myNode;
222
         last;
223
      }
224
   }
225
   print Dumper( $main::statusDB->{'nodePopulation'} ) if $main::DEBUG > 2;
226
   die "I can not find $virt on any node\n" unless $node;
15 rodolico 227
   my $command = &main::makeCommand( $node, "virsh shutdown $virt" );
228
   if ( $main::force ) { # they want us to actually do it
229
      $return = ( &main::executeAndWait( $command, $node, $virt, 0 ) ? 'Success' : 'Time Out waiting for shutdown');
230
      &main::forceScan();
231
   } else {
232
      $return = $command;
233
   }
234
   return "$return\n";
13 rodolico 235
}
236
 
237
sub migrate {
238
   my ( $virt, $target ) = @_;
239
   return "I don't know how to migrate yet\n";
14 rodolico 240
}
241
 
242
# find an unused VNC port
243
sub findVNCPort {
244
   my $currentPorts = shift;
245
   my $return = 5900;
246
   while ( $currentPorts->{$return} ) {
247
      $return++;
248
   }
249
   return $return;
250
}
251
 
252
 
253
sub printMac {
254
   my $mac = shift;
255
   my @return;
256
   my $separator = ':';
257
   for ( my $i = 0; $i < length( $mac ); $i += 2 ) {
258
      push @return, substr( $mac, $i, 2 );
259
   }
260
   return join( $separator, @return );
261
}
262
 
263
 
264
sub makeMac {
265
   my $numDigits = 12; # 12 hex digits in a mac address
266
   my $macBaseXen = '00163e'; # Xen has 00:16:3E* assigned to it.
267
   my $hexDigits = '0123456789abcdef';
268
 
269
   my $baseMac = $macBaseXen;
270
 
271
   while (length( $baseMac ) < $numDigits ) {
272
      $baseMac .= substr($hexDigits, int(rand(length($hexDigits))),1 );
273
   }
274
 
275
   return  &printMac( $baseMac );
276
}
277
 
278
# generate a virt-install statement, verifying things are not already being used
279
sub new {
280
   my %config;
281
   $config{'name'} = shift;
282
   my $return;
283
   my $template = $main::scriptDir . '/virt-install.template';
284
   &main::readDB();
285
   my %current;
286
   foreach my $virt ( keys %{$main::statusDB->{'virt'} } ) {
287
      $current{'vnc'}{$main::statusDB->{'virt'}->{$virt}->{'vnc'}} = 1;
288
      #$current{'mac'}{'null'} = 1;
289
   }
290
   $config{'vnc'} = &findVNCPort( \%{$current{'vnc'}} );
291
   $config{'mac'} = &makeMac();
292
   $config{'uuid'} = `uuidgen`;
293
   chomp $config{'uuid'};
294
   if ( open TEMPLATE, "<$template" ) {
295
      $return = join( '', <TEMPLATE> );
296
      close TEMPLATE;
297
      foreach my $key ( keys %config ) {
298
         $return =~ s/<$key>/$config{$key}/gi if $config{$key};
299
      }
300
   } else {
301
      $return = "Template $template not found, the following values should be used\n";
302
      foreach my $key ( keys %config ) {
303
         $return .= "$key: $config{$key}\n";
304
      }
305
   }
306
   return $return;
307
}