-
Notifications
You must be signed in to change notification settings - Fork 0
/
control_vm_esxi.sh
executable file
·5246 lines (4721 loc) · 166 KB
/
control_vm_esxi.sh
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 bash
# Script for simply control (create/destroy/restart) of virtual machines on ESXi
# (c) 2021 Maksim Lekomtsev <[email protected]>
MY_DEPENDENCIES=("govc" "scp" "sort" "ssh" "sshpass" "stat" "ping")
MY_NAME="Script for simply control of virtual machines on ESXi"
MY_VARIABLES=("CACHE_DIR" "CACHE_VALID" "ESXI_CONFIG_PATH")
MY_VERSION="4.220427"
# The directory for saving cache files
CACHE_DIR="${CACHE_DIR:-"${0%/*}/.cache"}"
# The seconds mount while cache files are valid
CACHE_VALID="${CACHE_VALID:-3600}" # 1 hour
# The configuration file path
ESXI_CONFIG_PATH="${ESXI_CONFIG_PATH:-"${0%.sh}.ini"}"
my_name="${0}"
my_dir="${0%/*}"
# ${my_params[@]} - Associative array with all parameters from configuration file
# Keys - ${id}.${name}
# ${id} - the resource identifier, the digit "0" is reserved for default settings
# other resource numbers will be referenced in my_*_list associative arrays
# ${name} - the parameter name
# ${my_params_last_id} - The identifier of last recorded resource
# ${my_config_esxi_list[@]} - List of esxi hypervisors filled from configuration file
# Keys - the hypervisor identifier
# Values - the hypervisor name
# ${my_config_vm_list[@]} - List of virtual machines filled from configuration file
# Keys - the virtual machine identifier
# Values - the virtual machine name
# ${my_real_vm_list[@]} - List of real virtual machines filled from hypervisors
# Keys - the real virtual machine identifier
# Values - the virtual machine name
#
# for example:
#
# my_params=(
# [0.esxi_password]="password"
# [0.vm_guest_type]="debian8-64"
# [0.vm_ipv4_address]="7.7.7.7"
# [1.esxi_hostname]="esxi1.local"
# [2.vm_ipv4_address]="192.168.0.1"
# [3.vm_esxi_datastore]="hdd1"
# )
# my_config_esxi_list=(
# [1]="esxi.test"
# )
# my_config_vm_list=(
# [2]="vm.test.local"
# )
# my_real_vm_list=(
# [3]="vm3"
# )
#
declare \
my_params_last_id=0
declare -A \
my_params=(
[0.esxi_hostname]="REQUIRED"
[0.esxi_ssh_password]=""
[0.esxi_ssh_port]="22"
[0.esxi_ssh_username]="root"
[0.local_hook_path]=""
[0.local_iso_path]=""
[0.local_vmdk_path]=""
[0.vm_autostart]="no"
[0.vm_dns_servers]="8.8.8.8 8.8.4.4"
[0.vm_esxi_datastore]="datastore1"
[0.vm_guest_type]="debian8-64"
[0.vm_hdd_devtype]="pvscsi"
[0.vm_hdd_gb]="5"
[0.vm_ipv4_address]="REQUIRED"
[0.vm_ipv4_netmask]="255.255.255.0"
[0.vm_ipv4_gateway]="REQUIRED"
[0.vm_mac_address]="auto"
[0.vm_memory_mb]="1024"
[0.vm_network_name]="VM Network"
[0.vm_ssh_password]=""
[0.vm_ssh_port]="22"
[0.vm_ssh_username]="root"
[0.vm_timezone]="Etc/UTC"
[0.vm_vcpus]="1"
[0.vm_vnc_port]="off"
[0.vm_vnc_password]=""
) \
my_config_esxi_list=() \
my_config_vm_list=() \
my_real_vm_list=()
# ${my_options[@]} - Array with options which were specified on the command line
# Keys - the command line option name
# Values - "yes" string
# ${my_options_desc[@]} - Array with all supported command line options and them descriptions
# Keys - the command line option name
# Values - the option description
declare -A \
my_options=() \
my_options_desc=(
[-d]="Destroy the same virtual machine on another hypervisor (migration analogue)"
[-da]="Don't enable hypervisor's autostart manager automatically if it's disabled"
[-ed]="Enable destroy virtual machines with hard disk (!!! use with caution)"
[-f]="Recreate a virtual machine on destination hypervisor if it already exists"
[-ff]="Force check checksums for existed images/templates on hypervisor"
[-fr]="Force reboot (use reset instead) if 'vmware-tools' package is not installed"
[-fs]="Force shutdown (use poweroff instead) if 'vmware-tools' package is not installed"
[-i]="Do not stop the script if any of hypervisors are not available"
[-n]="Skip virtual machine availability check on all hypervisors"
[-sn]="Skip checking network parameters of virtual machine (for cases where the gateway is out of the subnet)"
[-sr]="Skip the automatically images/templates removing from hypervisors"
[-t]="Trust the .sha1 files (don't recalculate checksums for images/templates if .sha1 file is readable)"
)
# ${my_esxi_autostart_params[@]} - The list with supported parameters of autostart manager on ESXi
# Keys - the parameter name
# Values - default values for automatically enabled autostart manager
# ${my_params_map[@]} - The map of parameters between configuration file and ESXi VMX file
# Keys - the parameter name in VMX file
# The 'special.' prefix signals that the conversion is not direct
# Values - the parameter name in configuration file of this script
# ${my_updated_params[@]} - The array of parameter names that the script can update
#
declare -A \
my_esxi_autostart_params=(
[enabled]="true"
[startDelay]="15s"
[stopDelay]="15s"
[waitForHeartbeat]="true"
[stopAction]="systemDefault"
) \
my_params_map=(
[ethernet0.networkname]="vm_network_name"
[guestinfo.dns_servers]="vm_dns_servers"
[guestinfo.ipv4_address]="vm_ipv4_address"
[guestinfo.ipv4_netmask]="vm_ipv4_netmask"
[guestinfo.ipv4_gateway]="vm_ipv4_gateway"
[guestinfo.timezone]="vm_timezone"
[guestos]="vm_guest_type"
[memsize]="vm_memory_mb"
[numvcpus]="vm_vcpus"
[scsi0.virtualdev]="vm_hdd_devtype"
[special.local_iso_path]="local_iso_path"
[special.local_vmdk_path]="local_vmdk_path"
[special.vm_autostart]="vm_autostart"
[special.vm_esxi_datastore]="vm_esxi_datastore"
[special.vm_hdd_gb]="vm_hdd_gb"
[special.vm_mac_address]="vm_mac_address"
[special.vm_vnc_password]="vm_vnc_password"
[special.vm_vnc_port]="vm_vnc_port"
)
declare \
my_updated_params=(
"local_iso_path"
"vm_dns_servers"
"vm_vnc_port"
"vm_timezone"
)
# ${my_*_ids[@]} - Arrays with statuses of processed hypervisors, virtual machines or images
# Keys - the resource identifier (esxi_id, vm_id or image_id)
# Values - the 'SKIPPING' message if the error has occurred
# ${my_*_ids_ordered[@]} - The arrays with ordered list of processed hypervisors, virtual machines or images
# The list of virtual machines ${my_vm_ids_ordered[@]} is ordered according to the order
# in which they are specified on the command line
# Other lists are ordered indirectly as mentioned in the process of virtual machines
declare -A \
my_esxi_ids=() \
my_image_ids=() \
my_vm_ids=()
declare \
my_esxi_ids_ordered=() \
my_image_ids_ordered=() \
my_vm_ids_ordered=()
# ${my_failed_remove_files[@]} - The list with failed remove files (mostly used for caсhe files)
# Keys - the failed remove file identifier
# Values - the path of failed remove file
declare -A \
my_failed_remove_files=()
set -o errexit
set -o errtrace
if ! \
source \
"${my_dir}"/functions.sh.inc \
2>/dev/null
then
echo >&2 "!!! ERROR: Can't load a functions file (functions.sh.inc)"
echo >&2 " Please check archive of this script or use 'git checkout --force' command if it cloned from git"
exit 1
fi
#
### Auxiliary functions
#
# Function to append virtual machines or hypervisors identifiers
# to ${my_.._ids[@]} and ${my_.._ids_ordered[@]} arrays ('..' -> 'vm' or 'esxi')
#
# Input: ${@} - The list of identifiers to be added in corresponding arrays
# ${my_config_esxi_list[@]} - GLOBAL (see description at top)
# ${my_config_vm_list[@]} - GLOBAL (see description at top)
# ${my_real_vm_list[@]} - GLOBAL (see description at top)
# Modify: ${my_esxi_ids[@]} - GLOBAL (see description at top)
# ${my_esxi_ids_ordered[@]} - GLOBAL (see description at top)
# ${my_vm_ids[@]} - GLOBAL (see description at top)
# ${my_vm_ids_ordered[@]} - GLOBAL (see description at top)
# Return: 0 - Specified identifiers founded at corresponding arrays
#
function append_my_ids {
local \
id=""
for id in "${@}"
do
if [ -v my_config_esxi_list[${id}] ]
then
if [ ! -v my_esxi_ids[${id}] ]
then
my_esxi_ids[${id}]=""
my_esxi_ids_ordered+=(
"${id}"
)
fi
elif [ -v my_config_vm_list[${id}] \
-o -v my_real_vm_list[${id}] ]
then
if [ ! -v my_vm_ids[${id}] ]
then
my_vm_ids[${id}]=""
my_vm_ids_ordered+=(
"${id}"
)
fi
else
internal \
"The bad '${id}' value of \${id}" \
"(The element don't exists in \${my_config_esxi_list[@]}, \${my_config_vm_list[@]} and \${my_real_vm_list[@]} arrays)"
fi
done
return 0
}
# Function to append images identifiers
# to ${my_image_ids[@]} and ${my_image_ids_ordered[@]} arrays
# with fill ${my_params[@]} parameters of images
#
# Input: ${1} - The image identifier will be added in corresponding arrays
# ${2} - The image type ('iso' or 'vmdk' value supported)
# ${3} - Predefined status of image will be added as 'status' parameter
# ${params[@]} - The array with parameters
# Modify: ${my_image_ids[@]} - GLOBAL (see description at top)
# ${my_image_ids_ordered[@]} - GLOBAL (see description at top)
# ${my_params[@]} - GLOBAL (see description at top)
# Return: 0
#
function append_my_image_ids {
local \
esxi_image_path="" \
image_id="${1}" \
image_status="${3}" \
image_type="${2}" \
local_image_path="" \
vm_esxi_datastore=""
if [ "${params[vmx_parameters]}" = "yes" \
-a -v params[special.vm_esxi_datastore] \
-a -v params[special.local_${image_type}_path] ]
then
local_image_path="${params[special.local_${image_type}_path]}"
vm_esxi_datastore="${params[special.vm_esxi_datastore]}"
else
local_image_path="${params[local_${image_type}_path]}"
vm_esxi_datastore="${params[vm_esxi_datastore]}"
fi
case "${image_type}"
in
"iso" )
esxi_image_path="/vmfs/volumes/${vm_esxi_datastore}/.iso/${local_image_path##*/}"
;;
"vmdk" )
esxi_image_path="/vmfs/volumes/${vm_esxi_datastore}/.templates/${local_image_path##*/}"
;;
* )
internal \
"The bad '${image_type}' value of \$image_type (only 'iso' and 'vmdk' is supported)"
;;
esac
my_image_ids[${image_id}]=""
my_image_ids_ordered+=("${image_id}")
my_params[${image_id}.esxi_datastore]="${vm_esxi_datastore}"
my_params[${image_id}.esxi_id]="${params[at]}"
my_params[${image_id}.esxi_image_path]="${esxi_image_path}"
my_params[${image_id}.local_image_path]="${local_image_path}"
my_params[${image_id}.status]="${image_status}"
my_params[${image_id}.type]="${image_type}"
return 0
}
# Function to check cache parameters
#
# Input: ${CACHE_DIR} - GLOBAL (see description at top)
# ${CACHE_VALID} - GLOBAL (see description at top)
# Return: 0 - Check is complete
#
function check_cache_params {
progress "Checking cache parameters"
if [ "${CACHE_DIR}" = "-" ]
then
echo -en "${COLOR_GRAY}"
echo " Use temporary directory '${temp_dir}' as cache directory (because CACHE_DIR=\"-\" specified)"
echo -en "${COLOR_NORMAL}"
CACHE_DIR="${temp_dir}"
elif [ ! -d "${CACHE_DIR}" ]
then
error \
"The directory for caching '${CACHE_DIR}' is not exists" \
"Please check of it existance, create if needed and try again"
elif [[ "${CACHE_VALID}" =~ ^[[:digit:]]+$
&& "${CACHE_VALID}" -ge 0
&& "${CACHE_VALID}" -le 43200 ]]
then
:
else
error \
"The 'CACHE_VALID' environment variable must be a number from 0 to 43200, not '${CACHE_VALID}'" \
"Please correct it value and try again"
fi
return 0
}
# Function for checking virtual machine parameters values
#
# Input: ${1} - The checked parameter name or 'all'
# ${my_options[@]} - GLOBAL (see description at top)
# ${params[@]} - The array with parameters
# Return: 0 - If all checks are completed
# 1 - Otherwise
#
function check_vm_params {
local \
check_vm_param="${1}"
# Function to convert ipv4 address from string to integer value
function ip4_addr_to_int {
set -- ${1//./ }
echo $((${1}*256*256*256+${2}*256*256+${3}*256+${4}))
}
progress "Checking '${check_vm_param}' virtual machine parameter(s)"
case "${check_vm_param}"
in
# local_image_path is INTERNAL use only
"all"|"local_hook_path"|"local_image_path"|"local_iso_path"|"local_vmdk_path" )
local \
param="" \
param_value=""
for param in "${check_vm_param/#all/local_hook_path local_image_path local_iso_path local_vmdk_path}"
do
param_value="${params[${param}]}"
if [ -n "${param_value}" ]
then
if [ ! -f "${param_value}" ]
then
skipping \
"The specified ${param} file '${param_value}' is not exists" \
"Please check it, correct and try again"
return 1
elif [ "${param}" = "hook" \
-a ! -x "${param_value}" ]
then
skipping \
"The specified ${param} file '${param_value}' is not executable" \
"Please set right permissions (+x) and try again"
return 1
fi
fi
done
;;&
"all"|"vm_ipv4_address"|"vm_ipv4_netmask"|"vm_ipv4_gateway" )
if [ "${params[vm_ipv4_address]}" = "${params[vm_ipv4_gateway]}" ]
then
skipping \
"The specified gateway '${params[vm_ipv4_gateway]}' cannot be equal to an address" \
"Please correct address or gateway address of virtual machine"
return 1
elif [ $((`ip4_addr_to_int "${params[vm_ipv4_address]}"` & `ip4_addr_to_int "${params[vm_ipv4_netmask]}"`)) \
-ne $((`ip4_addr_to_int "${params[vm_ipv4_gateway]}"` & `ip4_addr_to_int "${params[vm_ipv4_netmask]}"`)) ]
then
if [ "${my_options[-sn]}" = "yes" ]
then
echo " Skipped checking of network paramaters because '-sn' option is specified"
else
skipping \
"The specified gateway '${params[vm_ipv4_gateway]}' does not match the specified address '${params[vm_ipv4_address]}' and netmask '${params[vm_ipv4_netmask]}'" \
"Please correct address with netmask or gateway address of virtual machine or use '-sn' option to ignore this check"
return 1
fi
fi
;;&
esac
return 0
}
# Function to enable VNC-access to virtual machine
#
# Input: ${my_config_esxi_list[@]} - GLOBAL (see description at top)
# ${params[@]} - GLOBAL (see description at top)
# ${vm_name} - The virtual machine name for which VNC-access will be enabled
# Modify: ${enable_vnc_result} - The output of govc if operation is successfule
# Return: 0 - The operation is successful
# another - An error occurred during the operation or
# the specified VNC-port is already in use by another virtual machine
#
function enable_vnc {
local \
govc_vnc_port="${params[vm_vnc_port]}" \
real_vm_id=""
enable_vnc_result=""
progress "Enable VNC-access to virtual machine (govc vm.vnc)"
if [ "${govc_vnc_port}" = "auto" ]
then
govc_vnc_port="-1"
else
for real_vm_id in "${!my_real_vm_list[@]}"
do
if [ "${my_params[${real_vm_id}.at]}" = "${esxi_id}" \
-a "${my_real_vm_list[${real_vm_id}]}" != "${vm_name}" \
-a -v my_params[${real_vm_id}.special.vm_vnc_port] \
-a "${my_params[${real_vm_id}.special.vm_vnc_port]}" = "${govc_vnc_port}" ]
then
enable_vnc_result="VNC-port '${govc_vnc_port}' is already used by another virtual machine with '${my_real_vm_list[${real_vm_id}]}' (id=${my_params[${real_vm_id}.vm_esxi_id]}) name"
echo " ${enable_vnc_result}"
return 1
fi
done
fi
enable_vnc_result=$(
run_govc \
vm.vnc \
-enable=true \
-password="${params[vm_vnc_password]}" \
-port="${govc_vnc_port}" \
"${vm_name}"
) \
|| return
# Hack for Esxi v6.7+
# Re-set password, because otherwise there will be a password-free login
if ! \
run_govc \
vm.change \
-e "remotedisplay.vnc.password=${params[vm_vnc_password]}" \
-vm "${vm_name}"
then
enable_vnc_result="Unable to re-set password (hack for ESXi v6.7+)"
echo " ${enable_vnc_result}"
return 1
fi
}
# Function to run simple operation on virtual machine
#
# Input: ${1} - The virtual machine operation: 'destroy', 'power on', 'power off', 'power reboot', 'power reset', 'power shutdown' or 'status'
# ${2} - The virtual machine identifier at ${my_real_vm_list[@]} array
# ${my_params[@]} - GLOBAL (see description at top)
# ${my_config_esxi_list[@]} - GLOBAL (see description at top)
# ${temp_dir} - The temporary directory to save commands outputs
# Modify: ${vm_state} - The state of virtual machine
# Return: 0 - If simple operation is successful
# another - In other cases
#
function esxi_vm_simple_command {
# Function to get virtual machine status
#
# Input: ${esxi_id} - The identifier of hypervisor
# ${esxi_name} - The name of esxi instance
# ${vm_esxi_id} - The virtual machine indentifier on esxi instance
# ${vm_state_filepath} - The path to temporary state file
# Modify: ${vm_state} - The state of virtual machine ('Present', 'Absent', 'Powered on', 'Powered off')
# Return: 0 - If virtual machine status is getted successfully
# another - In other cases
function esxi_get_vm_state {
run_on_hypervisor \
>"${vm_state_filepath}" \
"${esxi_id}" \
"ssh" \
"set -o pipefail" \
"vim-cmd vmsvc/getallvms | awk 'BEGIN { state=\"Absent\"; } \$1 == \"${vm_esxi_id}\" { state=\"Present\"; } END { print state; }'" \
"|| Failed to get virtual machine presence on '${esxi_name}' hypervisor (vim-cmd vmsvc/getallvms)" \
|| return 1
if ! \
read -r \
vm_state \
<"${vm_state_filepath}"
then
skipping \
"Failed to get virtual machine presence from '${vm_state_filepath}' file"
return 1
elif [ "${vm_state}" != "Present" \
-a "${vm_state}" != "Absent" ]
then
skipping \
"Can't parse the virtual machine presence" \
"'${vm_state}'"
return 1
fi
if [ "${vm_state}" = "Present" ]
then
run_on_hypervisor \
>"${vm_state_filepath}" \
"${esxi_id}" \
"ssh" \
"set -o pipefail" \
"vim-cmd vmsvc/power.getstate \"${vm_esxi_id}\" | awk 'NR == 2 { print \$0; }'" \
"|| Failed to get virtual machine power status on '${esxi_name}' hypervisor (vim-cmd vmsvc/power.getstatus)" \
|| return 1
if ! \
read -r \
vm_state \
<"${vm_state_filepath}"
then
skipping \
"Failed to get virtual machine power status from '${vm_state_filepath}' file"
return 1
elif [ "${vm_state}" != "Powered on" \
-a "${vm_state}" != "Powered off" ]
then
skipping \
"Can't parse the virtual machine power status" \
"'${vm_state}'"
return 1
fi
fi
return 0
}
local \
vm_operation="${1}" \
real_vm_id="${2}"
if [ "${vm_operation}" != "destroy" \
-a "${vm_operation}" != "power on" \
-a "${vm_operation}" != "power off" \
-a "${vm_operation}" != "power reboot" \
-a "${vm_operation}" != "power reset" \
-a "${vm_operation}" != "power shutdown" \
-a "${vm_operation}" != "status" ]
then
internal \
"The \${vm_operation} must be 'destroy', 'power on', 'power off', 'power reboot', 'power reset', 'power shutdown' or 'status', but not '${vm_operation}'"
elif [ ! -v my_real_vm_list[${real_vm_id}] ]
then
internal \
"For virtual machine with \${real_vm_id} = '${real_vm_id}' don't exists at \${my_real_vm_list[@]} array"
fi
local \
esxi_id="${my_params[${real_vm_id}.at]}"
local \
esxi_name="${my_config_esxi_list[${esxi_id}]}" \
vm_esxi_id="${my_params[${real_vm_id}.vm_esxi_id]}" \
vm_state_filepath="${temp_dir}/vm_state"
vm_state=""
if [ "${vm_operation}" = "destroy" \
-a -n "${my_params[${real_vm_id}.special.vm_hdd_gb]}" \
-a "${my_options[-ed]}" != "yes" ]
then
skipping \
"Destroying a virtual machine with a hard disk is not safe and disabled by default" \
"If you are confident in your actions, please use the '-ed' option" \
"And remember to save a hard disk backup before destroying the virtual machine" \
"The operation is irreversible, be careful"
return 1
fi
esxi_get_vm_state \
|| return 1
[ "${vm_operation}" = "status" ] \
&& return 0
progress "${vm_operation^} the virtual machine (id='${vm_esxi_id}') on '${esxi_name}' hypervisor (vim-cmd vmsvc/${vm_operation// /.})"
if [ "${vm_state}" = "Powered on" ]
then
if [ "${vm_operation}" = "power on" ]
then
echo " The virtual machine is already powered on, skipping"
return 0
elif [ "${vm_operation}" = "destroy" ]
then
esxi_vm_simple_command \
"power shutdown" \
"${real_vm_id}" \
|| return 1
fi
elif [ "${vm_operation}" = "power reboot" \
-o "${vm_operation}" = "power reset" ]
then
skipping "Unable to reboot powered off virtual machine"
return 1
elif [ "${vm_operation}" = "power off" \
-o "${vm_operation}" = "power shutdown" ]
then
echo " The virtual machine is already powered off, skipping"
return 0
fi
if [ "${vm_state}" = "Absent" ]
then
echo " Skipping ${vm_operation/status/status request} because a virtual machine is absent on hypervisor"
echo " Probably the cache is out of date..."
else
if [ "${vm_operation}" = "power shutdown" \
-o "${vm_operation}" = "power reboot" ]
then
local \
vm_tools_status=""
get_vm_tools_status \
"${esxi_id}" \
"${vm_esxi_id}" \
|| return 1
if [ "${vm_tools_status}" != "toolsOk" ]
then
local \
current_operation="" \
future_operation="" \
test_option=""
for test_option in \
"power shutdown:-fs:power off" \
"power reboot:-fr:power reset"
do
IFS=":" \
read \
current_operation \
test_option \
future_operation \
<<<"${test_option}"
if [ "${current_operation}" = "${vm_operation}" ]
then
if [ "${my_options[${test_option}]}" != "yes" ]
then
skipping \
"Failed to ${current_operation#power } due 'vmware-tools' is not runned on virtual machine" \
"Run 'vmware-tools' on virtual machine and try again" \
"Or use '${test_option}' option to ${future_operation} machine instead of ${current_operation#power } (use carefully)"
return 1
fi
echo " Option '${test_option}' is specified, virtual machine will be ${future_operation}"
vm_operation="${future_operation}"
break
fi
done
fi
fi
run_on_hypervisor \
"${esxi_id}" \
"ssh" \
"vim-cmd vmsvc/${vm_operation// /.} \"${vm_esxi_id}\" >/dev/null" \
"|| Failed to ${vm_operation} machine on '${esxi_name}' hypervisor (vim-cmd vmsvc/${vm_operation// /.})" \
|| return 1
fi
if [ "${vm_operation}" = "destroy" ]
then
remove_cachefile_for \
"${esxi_id}" \
autostart_defaults \
autostart_seq \
filesystems \
vms
fi
if [ "${vm_operation}" != "power reboot" \
-a "${vm_operation}" != "power reset" ]
then
local \
attempts=10
until
esxi_get_vm_state \
|| return 1;
[ ${attempts} -lt 1 ] \
|| [ "${vm_operation}" = "destroy" -a "${vm_state}" = "Absent" ] \
|| [ "${vm_operation}" = "power on" -a "${vm_state}" = "Powered on" ] \
|| [ "${vm_operation}" = "power off" -a "${vm_state}" = "Powered off" ] \
|| [ "${vm_operation}" = "power shutdown" -a "${vm_state}" = "Powered off" ]
do
let attempts--
echo " The virtual machine is still in state '${vm_state}', wait another 5 seconds (${attempts} attempts left)"
sleep 5
done
if [ "${attempts}" -lt 1 ]
then
skipping \
"Failed to ${vm_operation} machine on '${esxi_name}' hypervisor (is still in state '${vm_state}')"
return 1
fi
if [ "${vm_operation}" = "destroy" ]
then
my_params[${real_vm_id}.status]="destroyed"
fi
fi
echo " The virtual machine is ${vm_operation}'ed, continue"
return 0
}
# Function to prepare the esxi list where the virtual machine is located
#
# Input: ${esxi_id} - The hypervisor identifier on which the virtual machine is located
# ${my_real_vm_list[@]} - GLOBAL (see description at top)
# ${vm_name} - The virtual machine name for which the esxi list is prepared
# Modify: ${another_esxi_id} - The hypervisor identifier where else a virtual machine was found
# ${another_esxi_names[@]} - The array with hypervisors names where else a virtual machine was found
# ${another_vm_real_id} - The virtual machine identifier at ${my_real_vm_list[@]} array which was found on another hypervisor
# ${my_params[@]} - GLOBAL (see description at top)
# ${vm_real_id} - The virtual machine identifier at ${my_real_vm_list[@]} array which was found on current hypervisor
# Return: 0 - Prepare the esxi list is successful
# another - Found multiple virtual machines with the same name on hypervisor
#
function get_another_esxi_names {
vm_real_id=""
another_esxi_id=""
another_esxi_names=()
another_vm_real_id=""
local \
real_vm_id=""
for real_vm_id in "${!my_real_vm_list[@]}"
do
if [ "${my_real_vm_list[${real_vm_id}]}" = "${vm_name}" ]
then
if [ "${my_params[${real_vm_id}.at]}" = "${esxi_id}" ]
then
if [ -n "${vm_real_id}" ]
then
skipping \
"Found multiple virtual machines with the same name on hypervisor" \
"with '${my_params[${vm_real_id}.vm_esxi_id]}' and '${my_params[${real_vm_id}.vm_esxi_id]}' identifiers on hypervisor" \
"Please check it manually and rename the one of the virtual machine"
return 1
fi
vm_real_id="${real_vm_id}"
else
another_esxi_id="${my_params[${real_vm_id}.at]}"
another_esxi_names[${another_esxi_id}]="${my_config_esxi_list[${another_esxi_id}]} (${my_params[${another_esxi_id}.esxi_hostname]})"
another_vm_real_id="${real_vm_id}"
fi
fi
done
my_params[${vm_real_id}.vm_id]="${vm_id}"
return 0
}
# The function for retrieve the cachefile path for specified esxi_id or real_vm_id
#
# Input: ${1} - The esxi_id or real_vm_id for which function
# the retrieve the actual cachefile path
# ${2} - Type of cache if esxi_id specified in ${1}
# ${CACHE_DIR} - GLOBAL (see description at top)
# ${my_params[@]} - GLOBAL (see description at top)
# ${my_config_esxi_list[@]} - GLOBAL (see description at top)
# ${my_real_vm_list[@]} - GLOBAL (see description at top)
# Output: >&1 - The actual path to cachefile
# Return: 0 - The cachefile path is returned correctly
#
function get_cachefile_path_for {
local \
cachefile_for="${1}" \
cachefile_type="${2}" \
esxi_id=""
if [ -v my_config_esxi_list[${cachefile_for}] ]
then
esxi_id="${cachefile_for}"
cachefile_for="esxi"
elif [ -v my_real_vm_list[${cachefile_for}] ]
then
esxi_id="${my_params[${cachefile_for}.at]}"
else
internal \
"The unknown \${cachefile_for}=\"${cachefile_for}\" specified" \
"This value not exists on \${my_config_esxi_list[@]} and \${my_real_vm_list[@]} arrays"
fi
local \
esxi_name="${my_config_esxi_list[${esxi_id}]}" \
esxi_hostname="${my_params[${esxi_id}.esxi_hostname]}"
local \
cachefile_basepath="${CACHE_DIR}/esxi-${esxi_name}-${esxi_hostname}"
if [ "${cachefile_for}" = "esxi" ]
then
echo "${cachefile_basepath}/${cachefile_type:-vms}.map"
else
local \
vm_name="${my_real_vm_list[${cachefile_for}]}" \
vm_esxi_id="${my_params[${cachefile_for}.vm_esxi_id]}"
echo "${cachefile_basepath}/vm-${vm_esxi_id}-${vm_name}.vmx"
fi
return 0
}
# Function to getting ${image_id} and? verify status of the corresponding image
#
# Input: ${1} - The type of image: 'iso' or 'vmdk' now
# ${2} - Verify or not the status of the corresponding image
# Possible values: without_check, no, or anything
# ${my_image_ids[@]} - GLOBAL (see description at top)
# ${params[@]} - The array with parameters
# Modify: ${image_id} - The image identifier
# Return: 0 - It's alright
# 1 - Error to getting ${image_id}
# or there is problem with upload/checking image
function get_image_id {
local \
image_type="${1}" \
check_type="${2}"
if [[ ! "${image_type}" =~ ^iso|vmdk$ ]]
then
internal \
"The bad '${image_type}' value of \$image_type (only 'iso' and 'vmdk' is supported)"
fi
local \
hash_source=""
if [ "${params[vmx_parameters]}" = "yes" \
-a -n "${params[special.vm_esxi_datastore]}" \
-a -n "${params[special.local_${image_type}_path]}" ]
then
hash_source="${params[at]}-${params[special.vm_esxi_datastore]}-${params[special.local_${image_type}_path]}"
elif [ -n "${params[vm_esxi_datastore]}" \
-a -n "${params[local_${image_type}_path]}" ]
then
hash_source="${params[at]}-${params[vm_esxi_datastore]}-${params[local_${image_type}_path]##*/}"
else
image_id=""
return 0
fi
if ! \
image_id=$(
get_hash "${hash_source}"
)
then
skipping \
"Failed to calculate the hash of image location (sha1sum)"
return 1
fi
if [ "${check_type}" != "without_check" \
-a "${check_type}" != "no" ]
then
if [ ! -v my_image_ids[${image_id}] ]
then
internal \
"The bad '${image_id}' value of \${image_id} (the element don't exist in \${my_image_ids[@]} array)"
elif [[ "${my_params[${image_id}.status]}" != "ok" ]]
then
skipping \
"Problem with upload/checking the '${my_params[${image_id}.local_image_path]}' image (details see above ^^^)"
return 1
fi
fi
return 0
}
# The function for retrieving registered virtual machines list on specified hypervisors
#
# Input: ${1} - The type of retrieving ('full' with vm parameters, 'simple' and 'very simple')
# ${@} - The list esxi'es identifiers to
# ${temp_dir} - The temporary directory to save cache files if CACHE_DIR="-"
# ${CACHE_DIR} - GLOBAL (see description at top)
# ${CACHE_VALID} - GLOBAL (see description at top)
# Modify: ${my_options[@]} - GLOBAL (see description at top)
# ${my_params[@]} - GLOBAL (see description at top)
# ${my_params_last_id} - GLOBAL (see description at top)
# ${my_real_vm_list[@]} - GLOBAL (see description at top)
# Return: 0 - The retrieving information is complete successful
#
function get_real_vm_list {
local \
get_type="${1}"
shift
if [ "${get_type}" != "full" \
-a "${get_type}" != "simple" \
-a "${get_type}" != "very simple" ]
then
internal \
"Only 'full', 'simple' and 'very simple' values supported as first parameter"
fi
# The fucntion to update or not the cache file
#
# Input: ${1} - The path to cache file
# ${@} - The same as for 'run_on_hypervisor' parameters
# ${CACHE_VALID} - GLOBAL (see description at top)
# Return: 0 - If remote command is runned without errors
# 1 - Failed from 'run_on_hypervisor' function
#
function update_cachefile {
local \
cachefile_path="${1}" \
cachefile_mtime=""
shift
if [ -f "${cachefile_path}" \
-a -s "${cachefile_path}" ]
then
if ! \
cachefile_mtime=$(
stat \
--format "%Y" \
"${cachefile_path}"
)
then
skipping \
"Cannot get the status of cache file '${cachefile_path}'" \
"Please check file permissions or just remove this file and try again"
return 1
fi
if [ $((`printf "%(%s)T"`-cachefile_mtime)) -ge "${CACHE_VALID}" ]
then
if ! rm "${cachefile_path}"
then
skipping \
"Cannot the remove the old cache file '${cachefile_path}'" \
"Please check file permissions or just remove this file and try again"
return 1
fi
fi
fi
if [ -f "${cachefile_path}" \
-a -s "${cachefile_path}" ]
then
echo " Use the cache file '${cachefile_path}"
else
local \
cachefile_dir="${cachefile_path%/*}"
if ! \
mkdir \
--parents \
"${cachefile_dir}"
then
skipping \
"Failed to create directory '${cachefile_dir}' for saving cache files" \
"Please check file permissions or just remove this file and try again"
return 1
fi
run_on_hypervisor \
>"${cachefile_path}" \
"${@}" \
|| return 1
echo " Writed the cache file '${cachefile_path}'"
fi
return 0
}