Subversion Repositories havirt

Rev

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