Subversion Repositories havirt

Rev

Go to most recent revision | Details | Last modification | View Log | RSS feed

Rev Author Line No. Line
2 rodolico 1
#! /usr/bin/env perl
2
 
3
use strict;
4
use warnings;
3 rodolico 5
 
6
# havirt
7
# Basically an extension of virsh which will perform actions on virtuals 
8
# running on multiple, connected hypervisors (virsh calls them nodes)
9
# existing as a cluster of hypervisors where virtuals can be shut down,
10
# started and migrated at need.
11
#
12
# Progam consists of one executable (havirt) and multiple Perl Modules
13
# (*.pm), each of which encompasses a function. However, this is NOT
14
# written as an Object Oriented system.
15
#
16
# havirt --help gives a brief help screen.
17
 
18
# Copyright 2024 Daily Data, Inc.
19
# 
20
# Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following 
21
# conditions are met:
22
#
23
#   Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer.
24
#   Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer 
25
#   in the documentation and/or other materials provided with the distribution.
26
#   Neither the name of the copyright holder nor the names of its contributors may be used to endorse or promote products derived
27
#   from this software without specific prior written permission.
28
# 
29
# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT
30
# NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL
31
# THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
32
# (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
33
# INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE
34
# OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
35
 
36
 
2 rodolico 37
#use experimental "switch";
38
 
39
# requires File::Slurp. 
40
# In Debian derivatives
41
# apt install libfile-slurp-perl
42
 
43
# apt install libxml-libxml-perl libyaml-tiny-perl
44
 
45
 
46
BEGIN {
47
   use FindBin;
48
   use File::Spec;
49
   # use libraries from the directory this script is in
6 rodolico 50
   use Cwd 'abs_path';
51
   use File::Basename;
52
   use lib dirname( abs_path( __FILE__ ) );
2 rodolico 53
}
54
 
6 rodolico 55
 
56
 
57
 
58
 
3 rodolico 59
use havirt; # Load all our shared stuff
60
 
2 rodolico 61
use Data::Dumper;
62
use YAML::Tiny;
63
 
4 rodolico 64
# define the version number
65
# see https://metacpan.org/pod/release/JPEACOCK/version-0.97/lib/version.pod
66
use version;
67
our $VERSION = version->declare("0.0.1");
68
 
69
 
70
# see https://perldoc.perl.org/Getopt/Long.html
71
use Getopt::Long;
72
# allow -vvn (ie, --verbose --verbose --dryrun)
73
Getopt::Long::Configure ("bundling");
74
 
75
 
2 rodolico 76
# global variables
77
my $scriptDir = $FindBin::RealBin;
78
my $scriptName = $FindBin::Script;
79
my $dbDir = "$scriptDir/var";
9 rodolico 80
our $confDir = "$scriptDir/conf";
3 rodolico 81
our $nodeDBName = "$dbDir/node.yaml";
4 rodolico 82
our $domainDBName = "$dbDir/domains.yaml";
3 rodolico 83
our $nodePopulationDBName = "$dbDir/node_population.yaml";
2 rodolico 84
 
85
# these contain the values from the databases
86
# loaded on demand
3 rodolico 87
our $nodeDB;
88
our $virtDB;
89
our $nodePopulations;
2 rodolico 90
 
4 rodolico 91
# options variables
92
our $reportFormat = 'screen';
93
our $targetNode = '';
94
our $dryRun = 1;
95
our $DEBUG = 0;
96
my $help = 0;
97
my $version = 0;
2 rodolico 98
 
99
sub help {
100
   print "$0 command [argument]\n";
101
   print "where command is one of\n";
9 rodolico 102
   print "\tnode update|list|scan # work with a node\n";
103
   print "\tdomain update|list # work with individual domains\n";
2 rodolico 104
   print "\tcluster status # report of memory and vcpu status on all nodes\n";
9 rodolico 105
   print "For additional help, run command help\n";
106
   print "\tnode help # or domain, or cluster\n";
4 rodolico 107
   print "Some flags can be used where appropriate\n";
108
   print "\t--help|-h # show this screen\n";
109
   print "\t--version|-v # show version of program\n";
110
   print "\t--format|-f screen|tsv # output of list commands is either padded for screen or Tab Delim\n";
111
   print "\t--target|-t NODE # the action use NODE for the target of actions\n";
112
   print "\t--dryrun|-n # does not perform the actions, simply shows what commands would be executed\n";
9 rodolico 113
   print "\t--debug|d # increases verbosity, with -ddd, totally outragious\n";
2 rodolico 114
}
115
 
116
sub loadVirtDB {
117
   return if $virtDB;
118
   $virtDB = &readDB( $domainDBName );
119
}
120
 
121
sub domain {
122
   my $action = lc shift;
123
   my $return = '';
124
   &loadVirtDB();
125
   &loadNodePopulations();
126
   @_ = keys( %$virtDB ) if ( $_[0] && $_[0] eq 'ALL' );
127
   if ( $_[0] && $_[0] eq 'RUNNING' ) {
128
      my @running;
129
      foreach my $node ( keys %$nodePopulations ) {
130
         push @running, keys %{ $nodePopulations->{$node}->{'running'} };
131
      }
132
      @_ = @running;
133
   }
134
   if ( $action eq 'update' ) { # download xml to var and update database
135
      while ( my $virt = shift ) {
136
         &parseDomain( $virt );
137
      } # while
138
      &writeDB( $domainDBName, $virtDB );
139
   } elsif ( $action eq 'list' ) { # dump domain as a tab separated data file
140
      my @return;
141
      foreach my $node ( keys %$nodePopulations ) {
142
         foreach my $virt (keys %{$nodePopulations->{$node}->{'running'}} ) {
143
            push @return, &listDomain( $virt, $node );
144
         }
145
      }
146
      $return = join( "\n", sort @return ) . "\n";;
147
   }
148
   return $return;;
149
} # sub domain
150
 
151
sub listDomain {
152
   my ($virt,$node) = @_;
153
   my @return;
154
   push @return, $virt;
155
   push @return, $node;
156
   foreach my $column ( sort keys %{ $virtDB->{$virt} } ) {
157
      push @return, $virtDB->{$virt}->{$column};
158
   }
159
   return join( "\t", @return);
160
}
161
 
162
 
163
 
164
# get the XML definition file of a running domain off of whatever
165
# node it is running on, and save it to disk
166
sub getVirtConfig {
167
   my ($virt,$filename) = @_;
168
   my $return;
169
   print "In getVirtConfig looking for $virt with file $filename\n" if $DEBUG;
170
   if ( -f $filename ) {
171
      open XML, "<$filename" or die "Could not read from $filename: $!\n";
172
      $return = join( '', <XML> );
173
      close XML;
174
   } else {
175
      &loadNodePopulations();
176
      #die Dumper( $nodePopulations );
177
      foreach my $node ( keys %$nodePopulations ) {
178
         print "getVirtConfig Looking on $node for $virt\n";
179
         if ( exists( $nodePopulations->{$node}->{'running'}->{$virt} ) ) { # we found it
180
            print "Found $virt on node $node\n";
181
            $return = `ssh $node 'virsh dumpxml $virt'`;
182
            open XML,">$filename" or die "Could not write to $filename: $!\n";
183
            print XML $return;
184
            close XML;
185
         } # if
186
      } # foreach
187
   } # if..else
188
   return $return;
189
} # sub getVirtConfig
190
 
191
sub getXMLValue {
192
   my ( $key, $string ) = @_;
193
   my $start = "<$key";
194
   my $end = "</$key>";
195
   $string =~ m/$start([^>]*)>([^<]+)$end/;
196
   return ($1,$2);
197
}
198
 
199
sub parseDomain {
200
   my ($virt, $nodePopulations ) = @_;
201
 
202
   my @keysToSave = ( 'uuid', 'memory', 'vcpu' );
203
   my $filename = "$confDir/$virt.xml";
204
   my $xml = &getVirtConfig( $virt, $filename );
205
   my ($param,$value) = &getXMLValue( 'uuid', $xml );
206
   $virtDB->{$virt}->{'uuid'} = $value;
207
   ($param,$value) = &getXMLValue( 'memory', $xml );
208
   $virtDB->{$virt}->{'memory'} = $value;
209
   ($param,$value) = &getXMLValue( 'vcpu', $xml );
210
   $virtDB->{$virt}->{'vcpu'} = $value;
211
 
212
   $xml =~ m/type='vnc' port='(\d+)'/;
213
   $virtDB->{$virt}->{'vnc'} = $1;
214
}
215
 
216
sub cluster {
217
   my $action = lc shift;
218
   my $return = '';
219
   if ( $action eq 'status' ) {
220
      &loadVirtDB();
221
      &loadNodePopulations();
222
      &loadNodeDB();
223
      print "Node\tThreads\tMemory\tDomains\tvcpu\tmem_used\n";
224
      my $usedmem = 0;
225
      my $usedcpu = 0;
226
      my $availmem = 0;
227
      my $availcpu = 0;
228
      my $totalDomains = 0;
229
      foreach my $node (sort keys %$nodeDB ) {
230
         my $memory = 0;
231
         my $vcpus = 0;
232
         my $count = 0;
233
         foreach my $domain ( keys %{ $nodePopulations->{$node}->{'running'} } ) {
234
            $memory += $virtDB->{$domain}->{'memory'};
235
            $vcpus += $virtDB->{$domain}->{'vcpu'};
236
            $count++;
237
         }
238
         $return .= "$node\t$nodeDB->{$node}->{cpu_count}\t$nodeDB->{$node}->{memory}\t$count\t$vcpus\t$memory\n";
239
         $usedmem += $memory;
240
         $usedcpu += $vcpus;
241
         $totalDomains += $count;
242
         $availmem += $nodeDB->{$node}->{memory};
243
         $availcpu += $nodeDB->{$node}->{cpu_count};
244
      } # outer for
245
      $return .= "Total\t$availcpu\t$availmem\t$totalDomains\t$usedcpu\t$usedmem\n";
246
   }
247
   return $return;
248
}
249
 
250
 
4 rodolico 251
# handle any command line parameters that may have been passed in
252
 
253
GetOptions (
254
   'format|f=s' => \$reportFormat,
255
   'target|t=s' => \$targetNode,
256
   'dryrun|n!' => \$dryRun,
257
   'debug|d+' => \$DEBUG,
258
   'help|h' => \$help,
259
   'version|v' => \$version
260
) or die "Error parsing command line\n";
261
 
6 rodolico 262
my $command = shift; # the first one is the actual subsection
263
my $action = shift; # second is action to run
4 rodolico 264
 
6 rodolico 265
if ( $help || ! $command ) { &help() ; exit; }
4 rodolico 266
if ( $version ) { use File::Basename; print basename($0) . " v$VERSION\n"; exit; }
267
 
2 rodolico 268
 
5 rodolico 269
print "Parameters are\nreportFormat\t$reportFormat\ntargetNode\t$targetNode\ndryRun\t$dryRun\nDEBUG\t$DEBUG\n" if $DEBUG;
270
print "Command = $command\nAction = $action\n" if $DEBUG;
4 rodolico 271
 
8 rodolico 272
# we allow a three part command for some actions on a domain, ie start, shutdown, migrate and destroy
273
# for simplicity, if the command is one of the above, allow the user to enter like that, but we will
274
# restructure the command as if they had used the full, three part (ie, with domain as the command)
275
# so, the following are equivilent
276
# havirt domain start nameofdomain
277
# havirt start nameofdomain
278
 
279
if ( $command eq 'start' || $command eq 'shutdown' || $command eq 'migrate' || $command eq 'destroy' ) { # shortcut for working with domains
280
   push @ARGV, $action; # this is the domain we are working with
281
   $action = $command; # this is what we want to do (start, shutdown, etc...)
282
   $command = 'domain'; # keywork domain, for correct module
2 rodolico 283
}
284
 
8 rodolico 285
# ok, this is some serious weirdness. $command is actually the name of a module, and $action is a method
286
# defined in the module.
2 rodolico 287
 
8 rodolico 288
# I use 'require' which loads at runtime, not compile time, so it will only load a module if needed.
289
# then, I check to see if a method named in $action is defined within that module and, if so
290
# execute it and return the result. If not, gives an error message.
291
 
292
# This means to add functionality, we simply add a method (sub) in a given module, or create a whole
293
# new module.
294
 
295
 
296
# we have to concat here since the double colon causes some interpretation problems
297
my $execute = $command . '::' . $action;
298
# load the module, die if it doesn't exist. Might make this an eval later
299
require "$command.pm";
300
Module->import( $command ); # for require, you must manually import
301
 
302
if ( defined &{\&{$execute}} ) { # check if module::sub exists (ie, $command::action)
303
  print &{\&{$execute}}(@ARGV); # yes, it exists, so call it with any remaining arguments
304
} else { # method $action does not exist in module $command, so just a brief error message
305
  die "Error, could not find action $action for module $command\n";
306
} 
307
 
308
 
2 rodolico 309
1;