Subversion Repositories havirt

Rev

Rev 25 | Rev 29 | Go to most recent revision | Details | Compare with Previous | Last modification | View Log | RSS feed

Rev Author Line No. Line
3 rodolico 1
#!/usr/bin/env perl
2
 
3
# Common library for havirt. Basically, just a place to put things which may be used by any
4 rodolico 4
# part of havirt. More for organizations purposes.
3 rodolico 5
 
4 rodolico 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
 
3 rodolico 25
# v0.0.1 20240602 RWR
26
# Initial setup
26 rodolico 27
#
28
# v1.2.0 20240826 RWR
29
# Added some code to migrate domains if node placed in maintenance mode
30
# Added a lot of 'verbose' print lines, and modified for new flag structure
31
#
3 rodolico 32
 
33
package havirt;
34
 
35
use warnings;
36
use strict;  
37
 
25 rodolico 38
BEGIN {
39
   use FindBin;
40
   use File::Spec;
41
   # use libraries from the directory this script is in
42
   use Cwd 'abs_path';
43
   use File::Basename;
44
   use lib dirname( abs_path( __FILE__ ) );
45
}
46
 
3 rodolico 47
use Data::Dumper qw(Dumper); # Import the Dumper() subroutine
48
 
4 rodolico 49
# define the version number
50
# see https://metacpan.org/pod/release/JPEACOCK/version-0.97/lib/version.pod
51
use version;
26 rodolico 52
our $VERSION = version->declare("1.2.0");
4 rodolico 53
 
54
 
3 rodolico 55
use Exporter;
56
 
57
our @ISA = qw( Exporter );
58
our @EXPORT = qw( 
25 rodolico 59
                  &readDB
60
                  &writeDB
61
                  &report
62
                  &scan
63
                  &makeCommand
64
                  &forceScan
15 rodolico 65
                  &executeAndWait
18 rodolico 66
                  &findDomain
67
                  &diffArray
25 rodolico 68
                  &makeConfig
69
                  &readConfig
70
                  &getAvailableResources
71
                  &resource
72
                  &validateResources
73
                  &migrate
3 rodolico 74
                );
75
 
12 rodolico 76
# read a DB file (just a YAML)
77
# if $lock is set, will create a "lock" file so other processes will
78
# not try to write to it. Using custom code as flock is automagically
79
# release when the file is read
3 rodolico 80
 
81
sub readDB {
12 rodolico 82
   my $lock = shift;
25 rodolico 83
   my $lockFileName = "$main::config->{'status db filename'}.lock";
12 rodolico 84
   my $lockTime = 5; # maximum time to wait for lock to clear
85
   # wait for lock to clear if it exists, if we are wanting a lock
86
   # and we have tried it for $locktime iterations
87
   while ( $lock && -f $lockFileName && $lockTime-- ) {
88
      sleep 1; # wait one second, then try again
89
   }
90
   if ( $lock ) {
25 rodolico 91
      die "Something has $main::config->{'status db filename'} locked, aborting\n" if -f $lockFileName;
12 rodolico 92
      `touch $lockFileName`;
93
   }
3 rodolico 94
   my $yaml = YAML::Tiny->new( {} );
25 rodolico 95
   if ( -f $main::config->{'status db filename'} ) {
96
      $yaml = YAML::Tiny->read( $main::config->{'status db filename'} );
3 rodolico 97
   }
12 rodolico 98
   $main::statusDB = $yaml->[0];
3 rodolico 99
}
100
 
26 rodolico 101
# Write the statusDB file out, overwriting the current one
102
# remove the lock file, if it exists
3 rodolico 103
sub writeDB {
12 rodolico 104
   my $yaml = YAML::Tiny->new( $main::statusDB );
25 rodolico 105
   $yaml->write( $main::config->{'status db filename'} );
106
   unlink "$main::config->{'status db filename'}.lock" if -f "$main::config->{'status db filename'}.lock"; # release any lock we might have on it
3 rodolico 107
}
108
 
26 rodolico 109
# create a report and send to STDOUT.
4 rodolico 110
sub report {
25 rodolico 111
   if ( $main::config->{'flags'}->{'format'} eq 'tsv' ) {
4 rodolico 112
      return &report_tsv( @_ );
113
   } else {
114
      return &report_screen( @_ );
115
   }
116
}
117
 
26 rodolico 118
# report as a tab separated values, no encapulation
3 rodolico 119
sub report_tsv {
120
   my ( $header, $data ) = @_;
121
   my @output;
122
   push @output, join( "\t", @$header );
123
   for( my $line = 0; $line < @$data; $line++ ) {
124
      push @output, join( "\t", @{$data->[$line]} );
125
   } # for
126
   return join( "\n", @output ) . "\n";
127
}
128
 
26 rodolico 129
# report suitable for screen, with fixed width columns
3 rodolico 130
sub report_screen {
131
   my ( $header, $data ) = @_;
132
   my @output;
133
   my @widths;
134
   my $column;
135
   my $row;
136
   # First, initialize by using the length of the headers
137
   for ( $column = 0; $column < @$header; $column++ ) {
138
      @widths[$column] = length( $header->[$column] );
139
   }
140
   # now, go through all data in each row, for each column, and increment the width if it is larger
141
   for ( $row = 0; $row < @$data; $row++ ) {
142
      for ( $column = 0; $column < @$header; $column++ ) {
143
         $widths[$column] = length( $data->[$row][$column] ) 
144
            if length( $data->[$row][$column] ) > $widths[$column];
145
      } # for column
146
   } # for row
147
   # actually do the print now
148
   my @format;
149
   for ( $column = 0; $column < @widths; $column++ ) {
150
      push ( @format, '%' . $widths[$column] . 's' );
151
   }
152
   my $format = join( ' ', @format ) . "\n";
153
   my $output = sprintf( $format, @$header );
154
   for ( $row = 0; $row < @$data; $row++ ) {
155
      $output .= sprintf( $format, @{$data->[$row]} );
156
   } # for row
157
   return $output;
158
}
10 rodolico 159
 
15 rodolico 160
# scans a node to determine which domains are running on it
26 rodolico 161
# updates each domain to reflect when it was last seen
15 rodolico 162
sub getDomainsOnNode {
163
   my $node = shift;
25 rodolico 164
   my $command = &main::makeCommand( $node, 'virsh list' );
165
   print "havirt.pm:getDomainsOnNode, command is $command\n" if $main::config->{'flags'}->{'debug'} > 2;
166
   my @nodeList = grep { /^\s*\d/ } `$command`;
15 rodolico 167
   for ( my $i = 0; $i < @nodeList; $i++ ) {
168
      if ( $nodeList[$i] =~ m/\s*\d+\s*([^ ]+)/ ) {
169
         $nodeList[$i] = $1;
170
      }
171
   }
172
   my %hash = map{ $_ => time } @nodeList;
173
   return \%hash;
174
}
175
 
18 rodolico 176
# find node a domain is on
177
# first parameter is the domain name
178
# rest of @_ is list of nodes to search
179
# if no nodes passed in, will search all known nodes
180
# returns first node found with the domain, or an empty string if not found
181
# possibly not being used??
182
sub findDomain {
183
   my $domainName = shift;
184
   my @node = @_;
185
   my $foundNode = '';
186
   &readDB();
187
   unless ( @node ) {
188
      @node = keys %{$main::statusDB->{'node'} };
25 rodolico 189
      print "findDomain, nodes = " . join( "\t", @node ) . "\n" if $main::config->{'flags'}->{'debug'} > 1;
18 rodolico 190
   }
26 rodolico 191
   if ( $main::config->{'flags'}->{'paranoid'} ) { # we will scan all nodes just to make sure
192
      foreach my $thisNode ( @node ) {
193
         my $command = &main::makeCommand( $thisNode, 'virsh list' );
194
         my $output = `$command`;
195
         print "findDomain, $thisNode list =\n" . $output . "\n" if $main::config->{'flags'}->{'debug'} > 1;;
196
         return $thisNode if ( $output =~ m/$domainName/ );
197
      }
198
   } else { # not paranoid mode, so just look through the status file
199
      foreach my $thisNode ( @node ) {
200
         if ( $main::statusDB->{'nodePopulation'}->{$thisNode}->{'running'}->{$domainName} ) {
201
            return $thisNode;
202
         }
203
      }
18 rodolico 204
   }
205
   return '';
206
}
15 rodolico 207
 
208
# check one or more nodes and determine which domains are running on them.
209
# defaults to everything in the node database, but the -t can have it run on only one
210
# this is the function that should be run every few minutes on one of the servers
211
sub scan {
25 rodolico 212
   my @targets = @_;
26 rodolico 213
   if ( -f $main::config->{'last scan filename'} && ! $main::config->{'flags'}->{'force'} ) {
25 rodolico 214
      my $lastScan = time - ( stat( $main::config->{'last scan filename'} ) ) [9];
26 rodolico 215
      return "Scan was run $lastScan seconds ago\n" unless $lastScan > $main::config->{'min scan time'};
15 rodolico 216
   }
25 rodolico 217
   `touch $main::config->{'last scan filename'}`;
15 rodolico 218
   &main::readDB(1);
25 rodolico 219
   print Dumper( $main::statusDB->{'nodePopulation'} ) if $main::config->{'flags'}->{'debug'} > 2;
220
   if ( $main::config->{'flags'}->{'target'} ) {
221
      push @targets, $main::config->{'flags'}->{'target'};
15 rodolico 222
   }
25 rodolico 223
   @targets = keys %{$main::statusDB->{'node'}} unless @targets;
224
   print "Scanning " . join( "\n", @targets ) . "\n" if $main::config->{'flags'}->{'debug'};
15 rodolico 225
   foreach my $node (@targets) {
26 rodolico 226
      print "Scanning $node\n" if $main::config->{'flags'}->{'verbose'};
15 rodolico 227
      $main::statusDB->{'nodePopulation'}->{$node}->{'running'} = &getDomainsOnNode( $node );
228
      $main::statusDB->{'nodePopulation'}->{$node}->{'lastchecked'} = time;
26 rodolico 229
      print "Found " . @{$main::statusDB->{'nodePopulation'}->{$node}->{'running'}} . " domains on node $node\n" if $main::config->{'flags'}->{'verbose'};
15 rodolico 230
      foreach my $domain ( keys %{$main::statusDB->{'nodePopulation'}->{$node}->{'running'}} ) {
231
         # make sure there is an entry for all of these domains
232
         $main::statusDB->{'virt'}->{$domain} = {} unless exists( $main::statusDB->{'virt'}->{$domain} );
233
      }
25 rodolico 234
      print Dumper( $main::statusDB->{'nodePopulation'}->{$node} ) if $main::config->{'flags'}->{'debug'} > 2;
15 rodolico 235
   }
236
   &main::writeDB();
237
   return "Node(s) updated\n";
238
}
239
 
18 rodolico 240
# makes the command that will be run on a node
241
# Created as a sub so we can change format easily
25 rodolico 242
# if node is the node we're on, we don't need to do a remote call
243
# if node is null, we'll assume we do the command here
244
# otherwise, we'll do an ssh to the node and run the command there
15 rodolico 245
sub makeCommand {
246
   my ( $node, $command ) = @_;
25 rodolico 247
   my $me = `hostname`;
248
   chomp $me;
249
   if ( ! $node || $node eq $me ) {
250
      return $command;
251
   } else {
252
      return "ssh $node '$command'";
253
   }
15 rodolico 254
}
255
 
18 rodolico 256
# force a node scan, even if time has not expired
26 rodolico 257
# do this by setting force to 1, calling scan, then resetting
258
# it to old value
15 rodolico 259
sub forceScan {
26 rodolico 260
   my $save = $main::config->{'flags'}->{'force'};
261
   $main::config->{'flags'}->{'force'} = 0;
15 rodolico 262
   &main::scan();
26 rodolico 263
   $main::config->{'flags'}->{'force'} = $save;
15 rodolico 264
}
265
 
266
 
267
# executes command $command, then repeatedly runs virsh list
268
# on $scanNode, grep'ing for $scanDomain
26 rodolico 269
# $condition is 1, to wait for domain to start
270
# or 0 (false) to wait for it to shut down
15 rodolico 271
sub executeAndWait {
272
   my ( $command, $scanNode, $scanDomain, $condition ) = @_;
273
   my $waitSeconds = 5; # number of seconds to wait before checking again
274
   my $maxIterations = 60 / $waitSeconds; # maximum number of tries
25 rodolico 275
   print "Running [$command], then waiting $waitSeconds to check if complete\n" if $main::config->{'flags'}->{'debug'};
15 rodolico 276
   `$command`;
277
   my $waitCommand = &makeCommand( $scanNode, "virsh list | grep $scanDomain" );
278
   my $output = '';
279
   do {
280
      return 0 unless ( $maxIterations-- ); # we've waited too long, so probably not working
281
      print '. ';
25 rodolico 282
      sleep 1;
15 rodolico 283
      $output = `$waitCommand`;
25 rodolico 284
      print "[$waitCommand] returned [$output]\n" if $main::config->{'flags'}->{'debug'} > 1;
15 rodolico 285
   } until ( $condition ? $output : !$output );
286
   return 1; # made it successful
287
} 
288
 
18 rodolico 289
# find the differences between two arrays (passed by reference)
290
# first sorts the array, then walks through them one by one
291
# @$arr1 MUST be larger than @$arr2
26 rodolico 292
# used by domain.pm:list to find non-running domains for output
18 rodolico 293
sub diffArray {
294
   my ( $arr1, $arr2 ) = @_;
295
   my @result;
296
 
297
   @$arr1 = sort @$arr1;
298
   @$arr2 = sort @$arr2;
299
   my $i=0;
300
   my $j=0;
301
 
302
   while ( $i < @$arr1 ) {
303
      if ( $arr1->[$i] eq $arr2->[$j] ) {
304
         $i++;
305
         $j++;
306
      } elsif ( $arr1->[$i] lt $arr2->[$j] ) {
307
         push @result, $arr1->[$i];
308
         $i++;
309
      } else {
310
         push @result, $arr2->[$j];
311
         $j++;
312
      }
313
   }
314
   return \@result;
315
}
25 rodolico 316
 
317
 
318
# create a config file if one does not exist
319
sub makeConfig {
320
   my ( $config, $filename ) = @_;
321
   $config->{'script dir'} = $FindBin::RealBin;
322
   $config->{'script name'} = $FindBin::Script;
323
   $config->{'db dir'} = $config->{'script dir'} . '/var';
324
   $config->{'conf dir'} = $config->{'script dir'} . '/conf';
325
   $config->{'status db filename'} = $config->{'db dir'} . '/status.yaml';
326
   $config->{'last scan filename'} = $config->{'script dir'} . '/var/lastscan';
26 rodolico 327
   $config->{'min scan time'} = 5 * 60; # five minutes
25 rodolico 328
   $config->{'node reserved memory'} = 8 * 1024 * 1024; # 8 gigabytes
329
   $config->{'node reserved vcpu' } = 0; # turn off reserved vcpu
26 rodolico 330
   $config->{'paranoid'} = 1; # rescan all nodes on any action which will modify it
331
   $config->{'flags'}->{'debug'} = 0;
332
   $config->{'flags'}->{'dryrun'} = 1;
333
   $config->{'flags'}->{'force'} = 0;
25 rodolico 334
   $config->{'flags'}->{'format'} = 'screen';
26 rodolico 335
   #$config->{'flags'}->{'help'} = 0; # used, but don't put in config file
25 rodolico 336
   $config->{'flags'}->{'quiet'} = 0;
337
   $config->{'flags'}->{'target'} = '';
26 rodolico 338
   $config->{'flags'}->{'verbose'} = 1;
339
   #$config->{'flags'}->{'version'} = 0; # used, but don't put in config file
25 rodolico 340
   my $yaml = YAML::Tiny->new( $config );
341
   $yaml->write( $filename );
342
}
343
 
344
# read the config file and return it
345
sub readConfig {
346
   my $filename = shift;
347
   my $yaml = YAML::Tiny->new( {} );
348
   if ( -f $filename ) {
349
      $yaml = YAML::Tiny->read( $filename );
350
   }
351
   return $yaml->[0];
352
}
353
 
26 rodolico 354
# find available resource on a node, total RAM and threads
25 rodolico 355
sub resource {
356
   my $node = shift;
357
   die "Can not find node $node in havirt.pm:resource\n"
358
      unless $main::statusDB->{'node'}->{$node};
359
   my $return = {
360
      'memory' => 0,
361
      'cpu_count' => 0
362
      };
363
   foreach my $key ( keys %$return ) {
364
      $return->{$key} = $main::statusDB->{'node'}->{$node}->{$key}
365
         if defined $main::statusDB->{'node'}->{$node}->{$key};
366
   } # foreach
367
   return $return;
368
}
369
 
26 rodolico 370
# determine resources used on a node, total RAM and VCPU
25 rodolico 371
sub getAvailableResources {
372
   my $node = shift;
373
   &readDB();
26 rodolico 374
   die "Can not find node $node in havirt.pm:resource\n" unless $main::statusDB->{'node'}->{$node};
25 rodolico 375
   my $totalResources = &resource( $node );
376
   print Dumper( $totalResources ) if $main::config->{'flags'}->{'debug'};
377
   foreach my $domain ( keys %{ $main::statusDB->{'nodePopulation'}->{$node}->{'running'} } ) {
378
      $totalResources->{'memory'} -= $main::statusDB->{'virt'}->{$domain}->{'memory'};
379
      $totalResources->{'cpu_count'} -= $main::statusDB->{'virt'}->{$domain}->{'vcpu'};
380
   }
381
   return $totalResources;
382
}
383
 
384
# validate that node has enough resources for the domains which occupy the
385
# remainder of the stack
386
# returns 0 on success, or one or more error messages in a string on failure
387
sub validateResources {
388
   my $node = shift;
389
   &readDB();
390
   my @return;
391
   my $nodeResources = &getAvailableResources( $node );
392
   print "In havirt.pm:validateResources, checking if enough room on $node for\n" . join( "\n", @_ ) . "\n"
26 rodolico 393
      if $main::config->{'flags'}->{'debug'};
394
   print "Checking resources on $node\n" if $main::config->{'flags'}->{'verbose'};
25 rodolico 395
   # subtract the reserved memory from the node
396
   $nodeResources->{'memory'} -= $main::config->{'node reserved memory'};
397
   $nodeResources->{'cpu_count'} -= $main::config->{'node reserved vcpu'} if $main::config->{'node reserved vcpu'};
398
   while ( my $domain = shift ) {
399
      $nodeResources->{'memory'} -= $main::statusDB->{'virt'}->{$domain}->{'memory'};
400
      $nodeResources->{'cpu_count'} -= $main::statusDB->{'virt'}->{$domain}->{'vcpu'};
401
   }
402
   print "In havirt.pm:validateResources, $node will have $nodeResources->{memory} memory and $nodeResources->{cpu_count} vcpu's after task\n"
403
      if ( $main::config->{'flags'}->{'debug'} > 1 );
404
 
405
   push @return, "This action would result in memory of $nodeResources->{memory}" if $nodeResources->{'memory'} <= 0;
406
   push @return, "This action would result in virtual cpu count of $nodeResources->{cpu_count}" if $nodeResources->{'cpu_count'} <= 0 && $main::config->{'flags'}->{'node reserved vcpu'};
407
   return @return ? join( "\n", @return ) . "\n" : 0;
408
}
409
 
410
# migrate domain from current node it is on to $target
411
sub migrate {
412
   my ( $virt, $target ) = @_;
413
   my $return;
26 rodolico 414
   my $node  = &main::findDomain( $virt );
25 rodolico 415
   print Dumper( $main::statusDB->{'nodePopulation'} ) if $main::config->{'flags'}->{'debug'} > 2;
416
   die "I can not find $virt on any node\n" unless $node;
417
   die "Domain $virt in maintenance mode, can not migrate it\n" if $main::statusDB->{'virt'}->{$virt}->{'maintenance'};
418
   die "Node $target in maintenance mode, can not migrate anything to it\n" if $main::statusDB->{'node'}->{$target}->{'maintenance'};
419
   die "$virt already on $target\n" if $target eq $node;
420
   my $command = &main::makeCommand( $node, "virsh migrate --live --persistent --verbose  $virt qemu+ssh://$target/system" );
26 rodolico 421
   if ( $main::config->{'flags'}->{'dryrun'} ) { # they want us to actually do it
422
      $return = $command;
423
   } else {
25 rodolico 424
      $return = ( &main::executeAndWait( $command, $node, $virt, 0 ) ? 'Success' : 'Time Out waiting for shutdown');
425
      &main::forceScan();
426
   }
427
   return "$return\n";
428
}
429