Subversion Repositories havirt

Rev

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