-
Notifications
You must be signed in to change notification settings - Fork 2
/
ManageBulkInstances.pm
3277 lines (2288 loc) · 78.7 KB
/
ManageBulkInstances.pm
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
#!/usr/bin/env perl
package ManageBulkInstances;
use strict;
use warnings;
eval "use Parallel::ForkManager 0.7.6; 1"
or die "module required: sudo apt-get install build-essential ; perl -MCPAN -e \'install Parallel::ForkManager\'";
eval "use File::Flock; 1"
or die "module required: sudo apt-get install libfile-flock-perl \n OR perl -MCPAN -e \'install File::Flock\'";
#use Parallel::ForkManager 0.7.6;
#new version: sudo apt-get install build-essential ; perl -MCPAN -e 'install Parallel::ForkManager'
#old version: sudo apt-get install libparallel-forkmanager-perl
use lib $ENV{"HOME"}."/projects/libraries/"; # path to SubmitVM module
use SubmitVM;
use Getopt::Long;
use List::Util qw(first);
eval "use LWP::UserAgent; 1"
or die "module required: cpan install LWP::UserAgent";
eval "use JSON; 1"
or die "module required: cpan install JSON";
use Data::Dumper;
eval "use Text::ASCIITable; 1"
or die "module required: cpan install Text::ASCIITable";
# purpose of this module: wrapper for nova tools
##############################
# parameters
#my $image = "b24d27d8-146c-4eea-9153-378d2642959d";
#my $image_name = "w_base_snapshot"; # or "Ubuntu Precise 12.04 (Preferred Image)"
#our $key_name = "dmnewmagellanpub";
#our $sshkey = "~/.ssh/dm_new_magellan.pem";
my $os_tenant_name = $ENV{'OS_TENANT_NAME'}; # tenant name or tenant ID needs to defined.
my $os_tenant_id = $ENV{'OS_TENANT_ID'};
my $os_username = $ENV{'OS_USERNAME'};
my $os_password = $ENV{'OS_PASSWORD'};
my $os_auth_url = $ENV{'OS_AUTH_URL'};
my $ssh_options = "-o StrictHostKeyChecking=no"; # StrictHostKeyChecking=no because I am too lazy to check for the question.
my $vm_user = 'ubuntu';
my @hobbitlist = ("Frodo","Samwise","Meriadoc","Peregrin","Gandalf","Aragorn","Legolas","Gimli","Denethor","Boromir","Faramir","Galadriel","Celeborn","Elrond","Bilbo","Theoden","Eomer","Eowyn","Treebeard");
my $default_namelist = \@hobbitlist;
#deprecated
our $nova = "nova --insecure --no-cache ";
my $os_token;
my $nova_endpoint_uri;
my $volume_endpoint_uri;
my $timeout=30;
my $debug=0;
our $options_basicactions = ["Nova actions",
"create=i" => "create i new instances from snapshot/image" , \&createAndAddToHash,
#TODO "createtemp=i" => "create i new instances from snapshot/image" , \&createAndAddToHashAndDelete, # perl object with destroyer
"delete" => "use with --group,ipfile or iplist", \&deletebulk,
"reboot=s" => "reboot all instances, \"soft\" or \"hard\"", \&reboot,
"info" => "list all instances, volumes, flavors...", \&info,
"listgroup=s" => "list all instances in this group (must be owner)", \&list_group_print,
"list" => "list all instances by group or instance_names/ip/id", \&list_ips_print,
"savegroup=s" => "save group in ipfile", \&saveGroupInIpFile,
"newgroupname=s" => "rename group (will not change hostname!)", \&renameGroup
] ;
our $options_vmactions = ["VM actions",
"sshtest" => "try to ssh all instances", undef
] ;
our $options_create_opts = ["Create options",
"flavor_name=s" => "flavor name for hardware selection", undef,
"image=s" => "image identifier", undef,
"image_name=s" => "image name, as alternative to image identifer", undef,
#"sshkey=s" => "required, path to ssh key file", undef,
"key_name=s" => "ssh key_name as in Openstack", undef,
"groupname=s" => "required, name of the new group", undef,
"nogroupcheck" => "use this to add VMs to existing group", undef,
"onlygroupname" => "instance names all equal groupname", undef,
"namelist=s" => "comma-separated list of names to choose from", undef,
"owner=s" => "optional, metadata information on VM, default os_username", undef,
"disksize=i" => "in GB, creates, attaches, partitions and mounts volume",undef,
"wantip" => "external IP, only with count=1", undef,
"user-data=s" => "pass user data file to new instances", undef,
"security_groups=s"=> "security_groups", undef,
"saveIpToFile" => "saves list of IPs in file", undef,
"greedy" => "continue with VM creation, even if some fail", undef,
"to_srv_create=s" => "timeout server create", undef,
"max_threads=s" => "max threads (default 8)", undef
];
our $options_specify = [ "Specify existing VMs for actions and deletion",
#"ipfile=s" => "file containing list of ips with names", undef,
"group=s" => "use VMs with this groupname (metadata-field)", undef,
"instance_names=s" => "VMs with these names, requires --groupname", undef,
"instance_ids=s" => "VMs with these IDs, requires --groupname", undef,
"instance_ips=s" => "list of IPs, comma separated, use with --groupname", undef
];
our $options_other_opts = ["Other options",
"noownercheck" => "disables owner check", undef,
"debug" => "debug info", undef
];
our @options_all = ($options_basicactions, $options_vmactions, $options_create_opts, $options_other_opts, $options_specify);
##############################
# subroutines
sub deploy {
SubmitVM::deploy(@_);
}
sub renameGroup {
my $arg_hash = shift(@_);
unless (defined $arg_hash->{'newgroupname'} ) {
die;
}
my $newgroupname = $arg_hash->{'newgroupname'};
my $server_hash = ManageBulkInstances::get_instances_by_hash( $arg_hash , {'return_hash' => 1} );
my $groupname;
if (defined $arg_hash->{"group"}) {
$groupname = $arg_hash->{"group"};
}
if (defined $arg_hash->{"groupname"}) {
$groupname = $arg_hash->{"groupname"};
}
print "would rename these guys=".join(',', keys(%$server_hash))."\n";
#my $servers_details = openstack_api('GET', 'nova', '/servers/detail');
my %names_used;
# get list of used names and complain if groupname is already beeing used
foreach my $server_id (keys(%$server_hash)) {
my $old_name = $server_hash->{$server_id}->{'name'};
unless (defined $old_name) {
print STDERR "error: old name not found\n";
exit(1);
}
unless ($old_name =~ /^$groupname/i) {
print STDERR "error: old groupname $groupname do not match ($old_name)\n";
exit(1);
}
my ($name_suffix) = $old_name =~ /^$groupname\_(\S+)$/i;
unless (defined $name_suffix) {
print STDERR "error: name suffix not found\n";
exit(1);
}
$names_used{lc($name_suffix)}=1;
}
my @nameslist;
if (defined $arg_hash->{"namelist"}) {
@nameslist = split(',', $arg_hash->{"namelist"});
} else {
@nameslist = @{$default_namelist};
}
# remove names already used from nameslist;
my @tmp_names=();
for (my $i = 0; $i < @nameslist; $i++) {
unless (defined($names_used{lc($nameslist[$i])})) {
push(@tmp_names, $nameslist[$i]);
}
}
@nameslist=@tmp_names;
my $suffix_name_counter = 1;
foreach my $server_id (keys(%$server_hash)) {
my $server = $server_hash->{$server_id};
my $old_name = $server->{'name'};
unless (defined $old_name) {
print STDERR "error: old name not found\n";
exit(1);
}
unless ($old_name =~ /^$groupname/i) {
print STDERR "error: old groupname $groupname do not match ($old_name)\n";
exit(1);
}
my ($name_suffix) = $old_name =~ /^$groupname\_(\S+)$/i;
my $new_instance_name = $newgroupname;
unless (defined $arg_hash->{'onlygroupname'}) {
unless (defined $name_suffix) {
die;
}
if (defined($names_used{lc($name_suffix)}) || 1) {
#change name !
my $new_suffix_name;
if (@nameslist > 0) {
$new_suffix_name = shift(@nameslist);
} else {
$new_suffix_name = $suffix_name_counter;
while (defined($names_used{$new_suffix_name})) {
$suffix_name_counter++;
$new_suffix_name = $suffix_name_counter;
}
}
print STDERR "info: rename instance from $name_suffix to $new_suffix_name\n";
$name_suffix = $new_suffix_name;
}
$new_instance_name .= '_'.$name_suffix;
}
print "new instance name: $new_instance_name and new group: $newgroupname\n";
# chnage instance name
my $new_name_json = { 'server' => {'name' => $new_instance_name}};
my $ret_hash = openstack_api('PUT', 'nova', '/servers/'.$server_id, $new_name_json);
#print Dumper($ret_hash);
# confirm change
unless (defined($ret_hash->{'server'}->{'name'}) && lc($ret_hash->{'server'}->{'name'}) eq lc($new_instance_name)) {
print Dumper($ret_hash);
print STDERR "error: instance name not changed\n";
exit(1);
}
#change metadata field group
my $new_metadata_json ={'metadata' => {'group' => $newgroupname } } ;
$ret_hash = openstack_api('POST', 'nova', '/servers/'.$server_id.'/metadata', $new_metadata_json);
#print Dumper($ret_hash);
unless (defined($ret_hash->{'metadata'}->{'group'}) && lc($ret_hash->{'metadata'}->{'group'}) eq lc($newgroupname)) {
print Dumper($ret_hash);
print STDERR "error: metadata field not changed\n";
exit(1);
}
if (0) { # ugly
my $key_name = $server->{'key_name'};
unless (defined $key_name) {
print Dumper($server);
exit(1);
}
my $sshkey = get_ssh_key_file($key_name);
my $ssh = "ssh $ssh_options -i $sshkey";
my $scp = "scp $ssh_options -i $sshkey";
my $server_address_private = $server->{'ip'};
my $remote = "$vm_user\@$server_address_private";
my $newhostname = $new_instance_name;
$newhostname =~ s/[^0-9a-zA-Z]/-/g;
SubmitVM::remote_system($ssh, $remote, "cat /etc/hostname");
#change hostname
SubmitVM::remote_system($ssh, $remote, "sudo echo $newhostname > /etc/hostname");
SubmitVM::remote_system($ssh, $remote, "cat /etc/hostname");
SubmitVM::remote_system($ssh, $remote, "sudo service hostname start");
}
}
}
sub get_ssh_key_file {
my $key_name = shift(@_);
my $key_file = $ENV{HOME}."/.ssh/".$key_name ; #.".pem";
#print "A $key_file\n";
if ( -e $key_file ) {
print "key_name: $key_name , file: $key_file\n";
return $key_file;
}
# try .pem-file
my $pemkey_file = $key_file.'.pem';
if ( -e $pemkey_file ) {
print "key_name: $key_name , file: $pemkey_file\n";
} else {
print "error: did not find the private ssh keyfile $key_file (or $pemkey_file) for key_name $key_name\n";
print "either rename your private key or create a symlink in ~/.ssh/\n";
exit(1);
}
return $pemkey_file;
}
sub parallell_job_new {
my $arg_hash = shift(@_);
print "parallell_job_new: ".join(',', keys(%$arg_hash))."\n";
my $server_hash = ManageBulkInstances::get_instances_by_hash( $arg_hash , {'return_hash' => 1} );
unless (defined $arg_hash->{"username"}) {
$arg_hash->{"username"} = $vm_user;
}
#my $owner=$arg_hash->{"os_username"}||$os_username;
#my $group = $arg_hash->{"group"} || $arg_hash->{"groupname"};
#unless(defined($arg_hash->{"vmips_ref"})) { # TODO find a solution for vmips_ref. then remove the IP-to-key_name mapping
# my $group_iplist = ManageBulkInstances::get_instances( $arg_hash );
# $arg_hash->{"vmips_ref"} = $group_iplist;
#}
my @iplist = ();
#get IP-to-key_name mapping:
my $ip_to_key_mapping={};
my $key_name_to_key_file={};
#my $servers_details = openstack_api('GET', 'nova', '/servers/detail');
#foreach my $server (@{$servers_details->{'servers'}}) {
foreach my $server_id (keys(%$server_hash)) {
my $server = $server_hash->{$server_id};
my $key_name = $server->{'key_name'};
unless (defined $key_name) {
die;
}
my $ip = $server->{'ip'};
unless (defined $ip) {
die;
}
push(@iplist, $ip);
#my $vm_owner = $server->{'metadata'}->{'owner'};
#my $vm_group = $server->{'metadata'}->{'group'};
#unless (defined $vm_owner) {
# next;
#}
#unless (defined $vm_group) {
# next;
#}
#unless (lc($vm_owner) eq lc($owner)) {
# next;
#}
#if (defined $group) {
# unless (lc($vm_group) eq lc($group)) {
# next;
# }
#}
$key_name_to_key_file->{$key_name}=1;
#my @networks;
#foreach my $address (@{$server->{'addresses'}->{'service'}}) {
# $ip_to_key_mapping->{$address->{'addr'}} = $key_name;
#}
$ip_to_key_mapping->{$ip} = $key_name;
}
foreach my $key_name (keys(%$key_name_to_key_file)) {
#print "got key: $key_name\n";
$key_name_to_key_file->{$key_name} = get_ssh_key_file($key_name);
#print "B\n";
}
my $ip_to_keyfile={};
foreach my $ip (keys(%$ip_to_key_mapping)) {
my $key_name = $ip_to_key_mapping->{$ip};
my $keyfile = $key_name_to_key_file->{$key_name};
$ip_to_keyfile->{$ip} = $keyfile;
}
#exit(0);
if (@iplist == 0 ) {
print STDERR "error: (parallell_job_new) iplist empty\n";
exit(1);
}
my $result = SubmitVM::parallell_job_new(
{ "vmips_ref" => \@iplist, #$arg_hash->{"vmips_ref"},
"vmargs_ref" => $arg_hash->{"vmargs_ref"},
"function_ref" => $arg_hash->{"function_ref"},
"ip_to_keyfile" => $ip_to_keyfile,
"username" => $arg_hash->{"username"},
"max_threads" => $arg_hash->{"max_threads"}
}
);
if (defined $arg_hash->{"delete"}) { # this will not be set by command line but by script.
deletebulk($arg_hash);
}
return $result;
}
#example my $value = get_nested_hash_value($hash, 'name', '1', [key,value] or {($_->{$key}||"") eq $val});
# returns value, if last step is [key,value], it returns array
sub get_nested_hash_value {
my $hash_ref = shift(@_);
my @route = @_;
my $h = $hash_ref;
#foreach my $value (@route) {
for ( my $i = 0 ; $i < @route ; ++$i) {
my $value = $route[$i];
#print "operation $i \n";
if (ref($h) eq "HASH") {
#print "operation_hash\n";
$h = $h->{$value};
unless (defined $h) {
return undef;
}
} elsif (ref($h) eq "ARRAY") {
#print "operation_array\n";
if (ref($value)) {
# value is reference to tuple
my @matches;
if (ref($value) eq "ARRAY") {
my ($key, $val) = @{$value};
#print "operation_array type array\n";
@matches = grep( ($_->{$key}||"") eq $val , @{$h});
} elsif (ref($value) eq "CODE") {
#print "operation_array type code\n";
@matches = grep( $value , @{$h});
} else {
print STDERR "ref: ".ref($value)."\n";
die;
}
if ($i == @route-1) {
return @matches;
} else {
if (@matches == 0) {
print STDERR Dumper(@route)."\n";
print STDERR Dumper($hash_ref)."\n";
print STDERR "error: no matching array element with (i=$i)\n";
return undef;
} elsif (@matches == 1) {
$h = shift(@matches);
} else {
print STDERR "error: array element is not unique (i=$i)\n";
print STDERR "count: ".@matches."\n";
return undef;
}
}
} else {
# value (scalar) is a position in array
$h = @{$h}[$value];
}
unless (defined $h) {
return undef;
}
} else {
print STDERR "error: HASH or ARRAY expected";
return undef;
}
}
return $h;
}
sub runActions { # disable action by overwriting subroutine reference with "undef"
my $arg_hash_ref = shift(@_);
my $options_array_ref = shift(@_);
my $action_results = {};
foreach my $option_group (@$options_array_ref) {
print " ".${$option_group}[0].":\n";
for (my $i = 1; $i < @$option_group; $i+=3) {
my $option = ${$option_group}[$i];
#print "opt: ".$option."\n";
($option) = split('\=', $option);
#print "opt_prefix: ".$option."\n";
if (defined $arg_hash_ref->{$option}) { # check if the action was requested
if (defined ${$option_group}[$i+2]) { # check if a function is assigned
print "start action $option\n";
my $result = ${$option_group}[$i+2]($arg_hash_ref);
if (defined $result) {
$action_results->{$option} = $result;
}
}
}
}
}
return $action_results;
}
sub getOptionsHash {
my $options_array_ref = shift(@_);
my $arg_hash_ref = shift(@_);
my @raw_options;
# fill raw_options
foreach my $option_group (@$options_array_ref) {
#print " ".${$option_group}[0].":\n";
for (my $i = 1; $i < @$option_group; $i+=3) {
my $option = ${$option_group}[$i];
#print "opt: ".$option."\n";
push(@raw_options, $option);
}
}
my $result_getopt = GetOptions ($arg_hash_ref, @raw_options);
unless ($result_getopt) {
die;
}
print Dumper($arg_hash_ref)."\n";
return;
}
sub print_usage {
my $options_array = shift(@_);
foreach my $option_group (@$options_array) {
print " ".${$option_group}[0].":\n";
for (my $i = 1; $i < @$option_group; $i+=3) {
my $option = ${$option_group}[$i];
my $text = ${$option_group}[$i+1];
print " --".$option. ' 'x (20-length($option)). $text."\n";
}
print "\n";
}
print " \n";
print " Option priorities: 1) command line 2) ipfile 3) ~/.bulkvm ; for 2 and 3 use: sshkey=~/.ssh/dm_new_magellan.pem\n";
return;
}
sub read_config_file {
my $arg_hash = shift(@_);
my $config_file = shift(@_);
if ($config_file eq "default") {
$config_file = $ENV{"HOME"} . "/.bulkvm";
unless (-e $config_file) {
print "config file $config_file not found, continue\n";
return;
}
} else {
$config_file = glob($config_file);
unless (-e $config_file) {
print "error: (read_config_file) \"$config_file\" not found\n";
exit(1);
}
}
print "read configuration from ".$config_file."\n";
open CONFIG_FILE_STREAM, $config_file or die $!;
while (my $line = <CONFIG_FILE_STREAM>) {
chomp($line);
if (length($line) < 2) {
next;
}
if (substr($line, 0 ,1) eq "\#") {
next;
}
my ($config_key, $config_value) = split('\=', $line);
if (defined($config_key) && defined($config_value) ) {
#print "$config_key $config_value\n";
#unless (defined $arg_hash->{$config_key}) {
if ($config_key eq "iplist") { # ugly
my @iparray = split(/,/ , $config_value);
$arg_hash->{$config_key} = \@iparray;
} else {
unless (defined $arg_hash->{$config_key}) {
print "write configuration: ".$config_key." ".$config_value."\n";
$arg_hash->{$config_key} = $config_value;
}
}
print "use configuration: ".$line."\n";
#}
} else {
print STDERR "error parsing line from config file: ".$line."\n";
exit(1);
}
}
}
sub try_load {
my $mod = shift;
eval("use $mod");
if ($@) {
#print "\$@ = $@\n";
return(0);
} else {
return(1);
}
}
#deprecated
sub nova2hash{
my $command = shift(@_);
my $printtable = shift(@_);
print $command."\n";
#pipe stderr to stdout !
$command .= " 2>&1";
my %hash;
my @header;
my $linenum = -1;
open(COM, $command." |") or die "Failed: $!\n";
while (my $line = <COM> ) {
$linenum++;
if ($printtable) {
print $line;
}
if (length($line) <=1 ) {
next;
}
my $is_data = 0;
if (substr($line, 0 ,1) eq '|') {
$is_data = 1;
}
if ($line =~ /^ERROR/) {
print $line;
close (COM);
$hash{"ERROR"} = 1;
$hash{"ERRORMESSAGE"} = $line;
return \%hash; # used to be undef
}
$line = substr($line, 1, length($line)-3);
if ($linenum == 1) {
@header = split('\|', $line);
@header = grep(s/\s*$//g, @header);
@header = grep(s/^\s*//g, @header);
#print "header: ".join(",", @header)."\n";
next;
}
if ($line =~ /^\-\-\-\-/) {
next;
}
if ($is_data ==1 ) {
#my @data = $line =~ /\s+(\S+)\s+\|/g;
my @data = split('\|', $line);
@data = grep(s/\s*$//g, @data);
@data = grep(s/^\s*//g, @data);
#print "data: ".join(",", @data)."\n";
for (my $i = 1 ; $i < @data; $i++) {
#print $data[0]." ".$header[$i]." ".$data[$i]."\n";
$hash{$data[0]}{$header[$i]}=$data[$i];
}
}
}
close (COM);
return \%hash;
}
sub getIP {
my $newip = undef;
# try to find available IP
my $floating_ips = openstack_api('GET', 'nova', '/os-floating-ips');
foreach my $ip_hash ( @{$floating_ips->{'floating_ips'}} ) {
unless (defined $ip_hash->{'instance_id'}) {
$newip = $ip_hash->{'ip'};
last;
}
}
if (defined $newip) {
return $newip;
}
# if no IP found, try to request a new one:
my $post_floating_ips= openstack_api('POST', 'nova', '/os-floating-ips', { 'pool' => 'nova'});
$newip = $post_floating_ips->{'floating_ip'}->{'ip'};
unless (defined $newip) {
print STDERR "warning: IP allocation failed\n";
}
return $newip;
}
sub delete_IP {
my $ip = shift(@_);
my $floating_ips_hash = openstack_api('GET', 'nova', '/os-floating-ips');
my @ip_ids = get_nested_hash_value($floating_ips_hash, ['ip',$ip]);
if (@ip_ids == 0) {
print STDERR "warning: did not find ID for ip $ip\n";
} elsif (@ip_ids > 1) {
print STDERR "warning: found mulitple IDs for ip $ip\n";
} else {
my $ip_id = shift(@ip_ids);
my $ip_del = openstack_api('DELETE', 'nova', '/os-floating-ips/'.$ip_id);
}
}
sub systemp {
print join(' ', @_)."\n";
return system(@_);
}
#depecated
sub getHashValue {
my $hashref = shift(@_);
my $row = shift(@_);
my $col = shift(@_);
my $return_value = $hashref->{$row}{$col};
unless (defined $return_value) {
print STDERR "error: no value for \"$row\" \"$col\" \n";
print STDERR "keys in hash: ".join(',', keys %$hashref)."\n";
exit(1);
}
return $return_value;
}
#depecated
sub waitNovaHashValue {
my $nova_command = shift(@_);
my $row = shift(@_);
my $col = shift(@_);
my $value = shift(@_);
my $timestep = shift(@_);
my $timetotal = shift(@_);
my $mytime = 0;
my $vol_status;
while (1) {
my $hash = nova2hash($nova." ".$nova_command, 1);
unless (defined $hash->{"ERROR"}) {
$vol_status = getHashValue($hash, $row, $col);
if ($vol_status eq $value) {
return 1;
}
}
if ($mytime > $timetotal ) {
return 0;
}
$mytime+=$timestep;
sleep $timestep;
}
}
sub volumeAttachWait {
my $instance_id = shift(@_);
my $volume_id = shift(@_);
my $device = shift(@_);
# attach volume to instance
my $attach_request_json = { 'volumeAttachment' => {
'volumeId' => $volume_id,
'device' => $device
}
};
my $new_attachment = openstack_api('POST', 'nova', '/servers/'.$instance_id.'/os-volume_attachments', $attach_request_json)->{'volumeAttachment'};
#print Dumper($new_attachment);
my $time_out = 0;
while (1) {
my $attachment_info = openstack_api('GET', 'volume', '/volumes/'.$volume_id)->{'volume'};
#print Dumper($attachment_info);
if (lc($attachment_info->{'status'}) eq 'in-use' ) {
return 1; # good
} elsif (lc($attachment_info->{'status'}) eq 'error') {
print Dumper($attachment_info);
return 0; # bad
}
$time_out += 5;
if ($time_out > 60) {
print Dumper($attachment_info);
return 0; # bad
}
sleep(5);
}
return 0;
}
sub delete_volume {
my $volume_id = shift(@_);
my $vol_timeout = 0;
# wait until available before deleting it
while ( 1) {
my $vol_info = openstack_api('GET', 'volume', '/volumes/'.$volume_id);
unless (defined $vol_info) {
print STDERR "error: no vol info returned\n";
return undef;
}
my $vol_status = $vol_info->{'volume'}->{'status'};
unless (defined $vol_status) {
print STDERR "error: not volume status returned\n";
return undef;
}
if ($vol_status eq 'available') {
last;
} else {
print "volume status: $vol_status (volume id: $volume_id)\n";
}
if ($vol_timeout > 60) {
print STDERR "error: A) delete volume timeout\n";
return undef;
}
sleep 5;
$vol_timeout+=5;
}
#delete volume
my $vol_del = openstack_api('DELETE', 'volume', '/volumes/'.$volume_id, {'volume_id'=>$volume_id} );
# wait until volume is gone
$vol_timeout = 0;
while(1) {
my $volumes = openstack_api('GET', 'volume', '/volumes/detail');
if (defined $volumes) {
my @vol = get_nested_hash_value($volumes, 'volumes', ['id', $volume_id]);
if (@vol == 0) {
last;
} else {
my $volume = shift(@vol);
my $vol_status = $volume->{'status'} || "NA";
print STDERR "volume still exists.. wait... (status: $vol_status)\n";
}
} else {
print STDERR "warning: /volumes/detail was not returned\n";
}
if ($vol_timeout > 60) {
print STDERR "error: B) delete volume timeout\n";
return undef;
}
sleep 5;
$vol_timeout+=5;
}
return $vol_del;
}
sub volumeCreateWait{
my $instname = shift(@_);
my $disksize = shift(@_);
my $owner = shift(@_);
unless (defined $owner) {