-
Notifications
You must be signed in to change notification settings - Fork 14
/
fast-vm
executable file
·1097 lines (998 loc) · 45.1 KB
/
fast-vm
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
#!/bin/sh
DEBUG_LOG_CMD="logger -p debug -t fast-vm-dbg"
FASTVM_HELPER=/usr/libexec/fast-vm-helper.sh
FASTVM_USER_CONF_DIR="$HOME/.fast-vm"
FASTVM_SYSTEM_CONF_DIR="/etc/fast-vm"
CURL_OPTS=""
TASKSET_CPULIST="0"
LOG_LEVEL=7
DISPLAY_LEVEL=7
FVM=$(basename "$0")
## terminal colors
c_red=$(tput setaf 1)
c_yellow=$(tput setaf 3)
c_green=$(tput setaf 2)
c_cyan=$(tput setaf 6)
c_normal=$(tput sgr0)
## LOG priorities
P_DEBUG=7
P_INFO=6
P_WARNING=4
P_ERROR=3
#### start common functions
# function for message output to display&logs based on LOG/DISPLAY level
pmsg () {
priority="$1"
message="$2"
vmn=${3:-__}
if [ "$LOG_LEVEL" -ge "$priority" ]; then
printf "%s |%s| %s" "$USER" "$vmn" "$message"|logger -p "$priority" --id -t fast-vm
fi
if [ "$DISPLAY_LEVEL" -ge "$priority" ]; then
case "$priority" in
"$P_DEBUG")
# shellcheck disable=SC2059
printf "[${c_cyan}inf${c_normal}] %b" "$message" | sed -e "s/^/\[$vmn\]/"
;;
"$P_INFO")
# shellcheck disable=SC2059
printf "[${c_green}ok${c_normal}] %b" "$message" | sed -e "s/^/\[$vmn\]/"
;;
"$P_WARNING")
# shellcheck disable=SC2059
printf "[${c_yellow}wrn${c_normal}] %b" "$message" | sed -e "s/^/\[$vmn\]/"
;;
"$P_ERROR")
# shellcheck disable=SC2059
printf "[${c_red}err${c_normal}] %b" "$message" | sed -e "s/^/\[$vmn\]/"
;;
*)
printf "[unk] %s" "$message" | sed -e "s/^/\[$vmn\]/"
;;
esac
fi
}
# helper function for loading and checking configuration
check_empty () {
var_name="$1"
var_value="$2"
if [ -z "$var_value" ]; then
pmsg $P_ERROR "variable $var_name not declared in global configuration run configure-fast-vm again or fix manually\n"
exit 2
fi
}
wait_for_ssh () {
vm_number="$1"
pmsg $P_DEBUG "checking the 192.168.$SUBNET_NUMBER.$vm_number for active SSH connection (ctrl+c to interrupt)\n" "$vm_number"
ssh_ready=$(ssh-keyscan -T 1 "192.168.$SUBNET_NUMBER.$vm_number" 2>/dev/null|grep -c -E '(ssh-|ecdsa-)')
while [ "$ssh_ready" -eq "0" ];
do
if [ "$DISPLAY_LEVEL" = "$P_DEBUG" ]; then printf "."; fi
ssh_ready=$(ssh-keyscan -T 1 "192.168.$SUBNET_NUMBER.$vm_number" 2>/dev/null|grep -c -E '(ssh-|ecdsa-)')
sleep 1
done
pmsg $P_DEBUG "\nSSH ready\n" "$vm_number"
}
check_file () {
file_path="$1"
file_size=0
file_local=0
error_prefix="$2"
if [ -z "$file_path" ]; then pmsg $P_DEBUG "provided empty file path\n"; fi
if [ "$curl_ok" -eq 0 ] && [ "$(echo "$file_path" | awk '{ s=substr($0, 0, 4); print s; }' )" = "http" ]; then
curl_data=$(curl $CURL_OPTS --head "$file_path" 2>/dev/null)
curl_exit="$?"
curl_httpok=$(echo "$curl_data"|grep -c -E "(HTTP.*200 OK|HTTP/2 200)")
if [ "$curl_httpok" -eq "1" ]; then
file_size=$(echo "$curl_data"|grep -i "Content-Length:"|awk '{print $2}'|sed 's/[^0-9]*//g')
if [ -z "$file_size" ]; then
file_size=0
pmsg $P_DEBUG "Unable to detect remote file. Using '$file_size' instead.\n"
else
pmsg $P_DEBUG "Detected remote file with size '$file_size'.\n"
fi
else
pmsg $P_ERROR "$error_prefix: error checking remote file on the server.\nCURL exited with code $curl_exit and we got following information from server\n$curl_data\n"
return 2
fi
else
if [ -f "$file_path" ]; then
file_local=1
else
pmsg $P_ERROR "$error_prefix: local file '$file_path' not found\n"
return 2
fi
fi
}
download_file () {
file_url="$1"
tmp_file=$(mktemp)
pmsg $P_DEBUG "downloading $file_url\ninto $tmp_file\n" >&2
if curl $CURL_OPTS -o "$tmp_file" -s "$file_url"; then
echo "$tmp_file"
else
pmsg $P_ERROR "Download failed\n" >&2
exit 1
fi
}
list_vm () {
vm_state="$1"
case $vm_state in
inactive)
vm_option='--inactive'
;;
active)
vm_option='--state-running'
;;
*)
vm_option='--all'
;;
esac
virsh --connect qemu:///system list "$vm_option"|awk '{print $2}'|grep -E "^${VM_PREFIX}.*-[0-9]+$"|sed 's/.*-\([0-9]\+\)$/\1/'|sort -n
}
check_vm_number () {
vm_number="$1"
vm_state="$2"
if [ "$(list_vm all|grep -c -E "^$vm_number$")" -eq 0 ]; then
pmsg $P_ERROR "no VM with number '$vm_number' found\n" "$vm_number"
exit 1
fi
if [ -n "$vm_state" ] && [ "$(list_vm "$vm_state"|grep -c -E "^$vm_number$")" -eq 1 ]; then
pmsg $P_ERROR "VM with number '$vm_number' is $vm_state\n" "$vm_number"
exit 1
fi
}
config_file_operation () {
cmd="$1"
options="$2"
if [ "$(whoami)" = 'root' ]; then
$cmd "$FASTVM_SYSTEM_CONF_DIR/$options" 2>&1|$DEBUG_LOG_CMD
else
$cmd "$FASTVM_USER_CONF_DIR/$options" 2>&1|$DEBUG_LOG_CMD
fi
}
handle_multiple_requests () {
# this function wraps the request to do same operation on multiple VMs
# if fast-vm is called from this handler, then there will be variable MULTI_OPERATION=1
fast_vm_bin=$0
# determine operation that we handle
operation="$1"
# VM number is in other position in 'create' operation, change the operation so we don't loose the image_name
if [ "$operation" = 'create' ]; then operation="$operation $2"; fi
if [ "$operation" = 'scp' ] || [ "$operation" = 'rsync' ] || [ "$operation" = "keydist" ]; then SERIALIZE=1; fi
# get the rest of the command line for calling it later
original_arguments=$(echo "$@"|sed -e "s/$operation $vm_number//")
pmsg $P_DEBUG "Starting to handle multiple operations\n"
all_pids=''
for vm in $vm_number; do
pmsg $P_DEBUG "Calling operation: ./fast-vm $operation $vm $original_arguments\n"
if [ -z "$SERIALIZE" ]; then
MULTI_OPERATION=1 $fast_vm_bin $operation $vm $original_arguments &
else
MULTI_OPERATION=1 $fast_vm_bin $operation $vm $original_arguments
fi
all_pids="$all_pids $!"
done
errors=0
for pid in $all_pids; do
wait "$pid"
if [ "$?" != '0' ]; then errors=$((errors+1)); fi
done
if [ "$errors" -gt '0' ]; then
pmsg $P_ERROR "Some ($errors) operations reported errors\n"
exit 1
else
pmsg $P_INFO "All operations returned successfully\n"
exit 0
fi
}
update_access_time () {
# Update the time of 'note' file for VM.
# This can be used to track if the VM is actively used/accessed.
vm_number="$1"
update_vm_metadata "$vm_number"
}
calculate_day_difference () {
# receive 2 UNIX timestamps and return whole number difference in days between them (floor)
start="$1"
end="$2"
echo "$(((end-start)/86400))d"
}
## VM metadata handling functions, metadata are stored in description field of VM in libvirt
# version 1 Metadata format
# 1 , 2 , 3 , 4 , 5
# version,vm_owner_name,last_action_unix_timestamp,profile_name_or_---,freeform_description
get_vm_metadata () {
vm_name="$1"
desc_data=$(virsh --connect qemu:///system desc --config "$vm_name")
if [ "$desc_data" = "No description for domain: $vm_name" ]; then
desc_data="1,--unknown--,$(date '+%s'),---,--metadata-missing--"
fi
# parse the metadata into variables that can be used later including the raw format of them
metadata_user=$(echo "$desc_data"|cut -d, -f 2)
metadata_last_action=$(echo "$desc_data"|cut -d, -f 3)
metadata_profile=$(echo "$desc_data"|cut -d, -f 4)
metadata_description=$(echo "$desc_data"|cut -d, -f 5-)
metadata_raw="$desc_data"
}
update_vm_metadata () {
vm_number="$1"
vm_name=$(virsh --connect qemu:///system list --all |grep "$VM_PREFIX"|awk '{print $2}'|grep -E "\-$vm_number$")
profile_name="$2"
description_text="$3"
get_vm_metadata "$vm_name"
if [ -n "$profile_name" ] && [ "$profile_name" != '*no_change*' ]; then
metadata_profile=$profile_name
fi
if [ -n "$description_text" ]; then
metadata_description=$description_text
fi
if [ "$metadata_user" = '--unknown--' ]; then
metadata_user='root'
pmsg $P_WARNING "VM without valid metadata! Creating empty metadata and changing ownership of VM to 'root'\n" "$vm_number"
fi
# actually update the VM description
virsh --connect qemu:///system desc --config "$vm_name" -- "1,$metadata_user,$(date '+%s'),$metadata_profile,$metadata_description" 2>&1|$DEBUG_LOG_CMD
}
check_appliance_presence () {
# export LIBGUESTFS_PATH to custom appliance if it looks to be present
# this doesn't check if appliance is usable (configure-fast-vm does that)
ap_path="/var/lib/fast-vm/appliance"
if [ -f "$ap_path/kernel" ] && [ -f "$ap_path/initrd" ] && [ -f "$ap_path/root" ]; then
export LIBGUESTFS_PATH="$ap_path"
pmsg $P_DEBUG "Using system appliance ($ap_path) with following capabilities:\n"
ls "$ap_path"/capability_* 2>/dev/null
fi
}
usage () {
part="$1"
case $part in
create)
echo "$FVM create <ImageName|ProfileName> <base|VmNumber|'VmNumber1 VmNumber2 ...'> [PathToLibvirtXML] [PathToHacksFile]"
;;
start)
echo "$FVM start <VmNumber|'VmNumber1 VmNumber2 ...'> [console|keydist|ssh [/path/to/custom/script]]"
;;
stop)
echo "$FVM stop <VmNumber|'VmNumber1 VmNumber2 ...'> [graceful]"
;;
console)
echo "$FVM console VmNumber"
;;
ssh)
echo "$FVM ssh <VmNumber|'VmNumber1 VmNumber2 ...'> [/path/to/custom/script]"
;;
scp)
echo "$FVM scp <VmNumber|'VmNumber1 VmNumber2 ...'> < vm:/remote/sourcefile|/local/sourcefile /local/destfile|vm:/remote/destfile ...>"
;;
rsync)
echo "$FVM rsync <VmNumber|'VmNumber1 VmNumber2 ...'> < vm:/remote/sourcefile|/local/sourcefile /local/destfile|vm:/remote/destfile ...>"
;;
keydist)
echo "$FVM keydist <VmNumber|'VmNumber1 VmNumber2 ...'>"
;;
delete)
echo "$FVM delete <VmNumber|'VmNumber1 VmNumber2 ...'> [PathToDeleteHackFile]"
;;
edit_note)
echo "$FVM edit_note <VmNumber|'VmNumber1 VmNumber2 ...'> [NoteText]"
;;
resize)
echo "$FVM resize <VmNumber|'VmNumber1 VmNumber2 ...'> NewSizeInGiB"
;;
info)
echo "$FVM info <VmNumber|'VmNumber1 VmNumber2 ...'>"
;;
list)
echo "$FVM list [all|active|inactive [short]]"
;;
disk_usage)
echo "$FVM disk_usage [ <all|VmNumber > ]"
;;
compact)
echo "$FVM compact <VmNumber|'VmNumber1 VmNumber2 ...'>"
;;
*)
echo "== fast-vm version 1.7 <ondrej-xa2iel8u@famera.cz> =="
echo "$FVM <action> <options>"
for cmd in create delete edit_note resize info list start stop console keydist ssh scp rsync disk_usage compact;
do
usage $cmd noexit
done
;;
esac
# exit only when second parameter is not specified, otherwise just return and continue
if [ -z "$2" ]; then exit 1; fi
}
#### end common functions
# first parameter is compulsory
if [ -z "$1" ]; then usage; fi
# locate and load fast-vm configuration
if [ -f "/etc/fast-vm.conf" ]; then
# load and verify configuration
# shellcheck source=fast-vm.conf.defaults
. /etc/fast-vm.conf
check_empty "VM_PREFIX" "$VM_PREFIX"
check_empty "LIBVIRT_NETWORK" "$LIBVIRT_NETWORK"
check_empty "THINPOOL_VG" "$THINPOOL_VG"
check_empty "THINPOOL_LV" "$THINPOOL_LV"
check_empty "SUBNET_NUMBER" "$SUBNET_NUMBER"
check_empty "FASTVM_GROUP" "$FASTVM_GROUP"
else
pmsg $P_ERROR "no global configuration file /etc/fast-vm.conf not found please run configure-fast-vm as root before using fast-vm\n"
exit 1
fi
# check if we are in $FASTVM_GROUP group or if we are root
if [ "$(id |grep -c "($FASTVM_GROUP)")" -eq 0 ] && [ "$(whoami)" != "root" ]; then
pmsg $P_ERROR "User running fast-vm must be member of group '$FASTVM_GROUP'. You can easily add user to this group using command below\n # usermod -a -G $FASTVM_GROUP $(whoami)\n"
exit 1
fi
## try to detect if the defined thin pool is available
double_dash_lv=$(echo "$THINPOOL_LV"|sed 's/-/--/g') # LVM uses double dash in the /dev/mapper
double_dash_vg=$(echo "$THINPOOL_VG"|sed 's/-/--/g') # also for VGs
if [ -b "/dev/mapper/${double_dash_vg}-${double_dash_lv}-tpool" ];then
THINPOOL_PATH="/dev/mapper/${double_dash_vg}-${double_dash_lv}-tpool"
fi
if [ -b "/dev/mapper/${double_dash_vg}-${double_dash_lv}_tdata" ] && [ -b "/dev/mapper/${double_dash_vg}-${double_dash_lv}_tmeta" ];then
THINPOOL_PATH="/dev/mapper/${double_dash_vg}-${double_dash_lv}"
fi
if [ -z "$THINPOOL_PATH" ]; then
pmsg $P_ERROR "thinpool $THINPOOL_VG/$THINPOOL_LV not found or not a thinpool LV, try running configure-fast-vm as root to check/correct\n"
exit 1
fi
# create local configuration directory if it doesn't exists
if [ ! -d "$FASTVM_USER_CONF_DIR" ]; then
mkdir "$FASTVM_USER_CONF_DIR" 2>&1 |$DEBUG_LOG_CMD
fi
if [ ! -d "$FASTVM_SYSTEM_CONF_DIR" ] && [ "$(whoami)" = "root" ]; then
mkdir "$FASTVM_SYSTEM_CONF_DIR" 2>&1 |$DEBUG_LOG_CMD
fi
## check if there is curl available so we can fetch images from http/https
command -v curl >/dev/null 2>&1
curl_ok="$?"
#### main script
case "$1" in
create)
image_name="$2"
if [ -z "$image_name" ]; then pmsg $P_ERROR "missing image or profile name\n"; usage create; fi
vm_number="$3"
if $(echo "$vm_number"|grep -q ' '); then handle_multiple_requests $@; fi
tmp_files=""
# if the image_name looks like ProfileName
profile_name=$image_name
for profile_base_image in "$FASTVM_USER_CONF_DIR/${profile_name}/base_image" "$FASTVM_SYSTEM_CONF_DIR/${profile_name}/base_image"
do
if [ -f "$profile_base_image" ]; then
profile_name=$image_name
image_name=$(cat "$profile_base_image")
pmsg $P_DEBUG "using image $image_name with profile $profile_name\n" "$vm_number"
break
fi
done
if [ ! -b "/dev/$THINPOOL_VG/$VM_PREFIX$image_name" ]; then
pmsg $P_ERROR "Missing image for ${image_name}.\n/dev/$THINPOOL_VG/$VM_PREFIX$image_name not found.\nFirst import image using 'fast-vm image_import $image_name'\n" "$vm_number"
exit 2
fi
image_xml_path=""
for path in "$4" "$FASTVM_USER_CONF_DIR/${profile_name}/config.xml" "$FASTVM_SYSTEM_CONF_DIR/${profile_name}/config.xml" "$FASTVM_USER_CONF_DIR/config-${image_name}.xml" "$FASTVM_SYSTEM_CONF_DIR/config-${image_name}.xml"
do
check_file "$path" "test XML file" >/dev/null 2>&1
if [ "$?" != 2 ]; then
if [ "$file_local" = '0' ]; then
image_xml_path=$(download_file "$path")
tmp_files="$tmp_files $image_xml_path"
else
image_xml_path="$path"
fi
pmsg $P_DEBUG "using file $path as libvirt XML\n" "$vm_number"
break
fi
done
if [ -z "$image_xml_path" ]; then
pmsg $P_ERROR "no VM XML definition for image ${image_name}. Import image again or supply alternative xml\n" "$vm_number"
usage create
fi
hack_file=""
for path in "$5" "$FASTVM_USER_CONF_DIR/${profile_name}/hacks.sh" "$FASTVM_SYSTEM_CONF_DIR/${profile_name}/hacks.sh" "$FASTVM_USER_CONF_DIR/hacks-${image_name}.sh" "$FASTVM_SYSTEM_CONF_DIR/hacks-${image_name}.sh"
do
check_file "$path" "hack file at $path" >/dev/null 2>&1
if [ "$?" != 2 ]; then
if [ "$file_local" = '0' ]; then
hack_file=$(download_file "$path")
tmp_files="$tmp_files $hack_file"
else
hack_file="$path"
fi
pmsg $P_DEBUG "using file $path as hack file\n" "$vm_number"
break
fi
done
# NOTE: if profile doesn't contain hacks file the one from base image of that profile is used!
# validate vm_number is a 'number'
$(echo "$vm_number" | grep -Eq '^[+-]?[0-9]+$')
if [ "$?" -eq '0' ]
then
if [ "$vm_number" -lt 20 ] || [ "$vm_number" -gt 220 ];then
pmsg $P_ERROR "VM number out of range (20-220)\n" "$vm_number"
usage create
fi
if [ $(list_vm all|grep -c -E "^$vm_number$") -gt 0 ]; then
pmsg $P_ERROR "VM with this VM number already exists\n" "$vm_number"
exit 1
fi
else
if [ "$vm_number" = "base" ]; then
pmsg $P_DEBUG "creating base image VM for $image_name\n" "$vm_number"
else
pmsg $P_ERROR "only numbers from range 20-220 and word 'base' permitted here\n" "$vm_number"
usage create
fi
fi
# change group of LV so we can use it for locking
echo "chgrp" "/dev/$THINPOOL_VG/$VM_PREFIX$image_name" | sudo -n $FASTVM_HELPER
(
# beginning of locked section - FIXME: maybe only part with 'lvcreate' should be protected by lock
flock -s -n 9 || exit 4
# special case for creating only base image
if [ "$vm_number" = "base" ]; then
VM_NAME="$VM_PREFIX$image_name"
VM_HEX_NUMBER='01'
tmp_xml=$(mktemp --suffix=.xml)
sed -e "s/VM_NAME/$VM_PREFIX$image_name/g; s/THINPOOL_VG/$THINPOOL_VG/g; s/LIBVIRT_NETWORK/$LIBVIRT_NETWORK/g; s/VM_NUMBER/$vm_number/g; s/VM_HEX_NUMBER/$VM_HEX_NUMBER/g; s/IMAGE_NAME/$image_name/g;" "$image_xml_path" > "$tmp_xml"
virsh --connect qemu:///system define "$tmp_xml"
if [ ! "$?" -eq '0' ]; then
pmsg $P_ERROR "defining base VM for $image_name failed, doesn't it exists already?\n" "$vm_number"
exit 2
else
rm -f "$tmp_xml"
fi
# source file with hacks and apply them
if [ -n "$hack_file" ]; then
hack_file=$(echo "$hack_file"|sed 's/^\([^\/]\)/\.\/\1/g')
# check if we have any libguest appliance
check_appliance_presence
pmsg $P_DEBUG "applying hacks from $hack_file\n" "$vm_number"
. $hack_file
if [ ! "$?" -eq "0" ]; then
pmsg $P_WARNING "there was issue applying hacks to this machine, check syslog for more details\n" "$vm_number"
fi
pmsg $P_DEBUG "applying hacks finished\n" "$vm_number"
fi
rm -f -- $tmp_files # cleanup temporary files
pmsg $P_DEBUG "base image VM created, to start this VM use 'virsh --connect qemu:///system start $VM_PREFIX$image_name'.\n This VM is used for customizing the base image of '$image_name' VMs.\n All changes you make to this VM would be available in newly created VMs of that version, this will not affect already existing VMs of same version\n" "$vm_number"
exit 0
fi
## check if the machine doesn't exists already
vm_disk_test=$(ls /dev/${THINPOOL_VG}/${VM_PREFIX}*-${vm_number} 2>/dev/null|wc -l )
if [ "$vm_disk_test" -gt 0 ]; then
pmsg $P_ERROR "there is already disk for machine ${vm_number}, VM creation aborted\n" "$vm_number"
exit 1
fi
## create regular machine
VM_NAME="$VM_PREFIX$image_name-$vm_number"
VM_HEX_NUMBER=$(printf "%2x" "$vm_number")
pmsg $P_DEBUG "defining virtual machine '$VM_PREFIX$image_name-$vm_number' in libvirt\n" "$vm_number"
tmp_xml=$(mktemp --suffix=.xml)
sed -e "s/VM_NAME/$VM_PREFIX$image_name-$vm_number/g; s/THINPOOL_VG/$THINPOOL_VG/g; s/LIBVIRT_NETWORK/$LIBVIRT_NETWORK/g; s/VM_NUMBER/$vm_number/g; s/VM_HEX_NUMBER/$VM_HEX_NUMBER/g; s/IMAGE_NAME/$image_name/g;" "$image_xml_path" > "$tmp_xml"
virsh --connect qemu:///system define "$tmp_xml"
if [ ! "$?" -eq '0' ]; then
pmsg $P_ERROR "Unable to define virtual machine from $tmp_xml. Check syslog for more details\n" "$vm_number"
exit 2
else
rm -f "$tmp_xml"
fi
metadata_profile='---'
if [ "$profile_name" != "$image_name" ]; then metadata_profile=$profile_name; fi
# update libvirt XML with VM description
virsh --connect qemu:///system desc --config "$VM_NAME" --title --new-desc "$(printf '%03d' "$vm_number") $(whoami)"
# create metadata for the new VM
virsh --connect qemu:///system desc --config "$VM_NAME" -- "1,$(whoami),$(date '+%s'),$metadata_profile," 2>&1|$DEBUG_LOG_CMD
pmsg $P_DEBUG "creating disk '$VM_PREFIX$image_name-$vm_number'\n" "$vm_number"
echo "lvcreate" "newvm" "$image_name" "$image_name-$vm_number" | sudo -n $FASTVM_HELPER
echo "chgrp" "/dev/$THINPOOL_VG/$VM_PREFIX$image_name-$vm_number" | sudo -n $FASTVM_HELPER
## add DHCP reservation only if the VM has the interface for fast-vm network
VM_MAC=$(virsh --connect qemu:///system dumpxml "$VM_PREFIX$image_name-$vm_number"|xmllint --xpath "//interface[.//source[@network='$LIBVIRT_NETWORK']]/mac/@address" - 2>/dev/null|cut -d\" -f 2|head -1)
if [ -n "$VM_MAC" ]; then
pmsg $P_DEBUG "adding static lease for 192.168.$SUBNET_NUMBER.$vm_number into libvirts DHCP\n" "$vm_number"
virsh --connect qemu:///system net-update "$LIBVIRT_NETWORK" add-last ip-dhcp-host --xml "<host mac='$VM_MAC' ip='192.168.$SUBNET_NUMBER.$vm_number'/>" --live --config 2>&1|$DEBUG_LOG_CMD
fi
# source file with hacks and apply them
if [ -n "$hack_file" ]; then
hack_file=$(echo "$hack_file"|sed 's/^\([^\/]\)/\.\/\1/g')
# check if we have any libguest appliance
check_appliance_presence
pmsg $P_DEBUG "applying hacks from $hack_file\n" "$vm_number"
. $hack_file
if [ ! "$?" -eq "0" ]; then
pmsg $P_WARNING "there was issue applying hacks to this machine, check syslog for more details\n" "$vm_number"
fi
pmsg $P_DEBUG "applying hacks finished\n" "$vm_number"
fi
pmsg $P_INFO "VM '$VM_NAME' created\n" "$vm_number"
# end of locked section
) 9<"/dev/$THINPOOL_VG/$VM_PREFIX$image_name"
if [ "$?" != "0" ]; then
pmsg $P_ERROR "It is not possible to use image $image_name for creating VM now as it is being used by fast-vm or other process at the moment\n" "$vm_number"
exit 1
else
rm -f "/tmp/fast-vm.img.${image_name}.lock"
rm -f -- $tmp_files # cleanup temporary files
fi
;;
start)
vm_number="$2"
if [ -z "$vm_number" ]; then pmsg $P_ERROR "VM number missing\n"; usage start; fi
if $(echo "$vm_number"|grep -q ' '); then handle_multiple_requests $@; fi
check_vm_number "$vm_number" "active"
update_access_time "$vm_number"
vm_name=$(virsh --connect qemu:///system list --all |grep "$VM_PREFIX"|awk '{print $2}'|grep -E "\-$vm_number$")
# if there is any third argument start VM and console after
if [ -z "$3" ]; then
pmsg $P_DEBUG "starting VM $vm_name (192.168.$SUBNET_NUMBER.$vm_number)\n" "$vm_number"
virsh --connect qemu:///system start "$vm_name"
if [ "$?" != '0' ]; then
pmsg $P_ERROR "failed to start VM, check syslog for more information\n" "$vm_number"
fi
else
case "$3" in
console)
if [ -n "$MULTI_OPERATION" ] && [ "$MULTI_OPERATION" = 1 ]; then
pmsg $P_ERROR "When running start as part of multiple operations the console option is not available.\n" "$vm_number"
exit 1
fi
pmsg $P_DEBUG "starting VM $vm_name and connecting to it serial console ...\n" "$vm_number"
virsh --connect qemu:///system start "$vm_name"
if [ "$?" != '0' ]; then
pmsg $P_ERROR "failed to start VM $vm_name, check syslog for more information\n" "$vm_number"
else
virsh --connect qemu:///system console "$vm_name"
fi
;;
ssh)
if [ -z "$4" ] && [ -n "$MULTI_OPERATION" ] && [ "$MULTI_OPERATION" = 1 ]; then
pmsg $P_ERROR "When running start with ssh as part of multiple operations, script for SSH must be specified.\n" "$vm_number"
exit 1
fi
pmsg $P_DEBUG "starting VM $vm_name\n" "$vm_number"
virsh --connect qemu:///system start "$vm_name"
if [ "$?" != '0' ]; then
pmsg $P_ERROR "failed to start VM $vm_name, check syslog for more information\n" "$vm_number"
else
wait_for_ssh "$vm_number"
if [ -n "$4" ] && [ -x "$4" ]; then
eval "$4 192.168.$SUBNET_NUMBER.$vm_number" | sed -e "s/^/\[$vmn\]/"
else
ssh -i "$FASTVM_USER_CONF_DIR/id_fastvm" -o GlobalKnownHostsFile=/dev/null -o UserKnownHostsFile=/dev/null -o StrictHostKeyChecking=no "root@192.168.$SUBNET_NUMBER.$vm_number"
fi
fi
;;
keydist)
pmsg $P_DEBUG "starting VM $vm_name\n" "$vm_number"
virsh --connect qemu:///system start "$vm_name"
if [ "$?" != '0' ]; then
pmsg $P_ERROR "failed to start VM $vm_name, check syslog for more information\n" "$vm_number"
else
if [ ! -f "$FASTVM_USER_CONF_DIR/id_fastvm" ]; then
pmsg $P_WARNING "Generating new ssh key with empty passphrase for fast-vm use at $FASTVM_USER_CONF_DIR/id_fastvm\n" "$vm_number"
ssh-keygen -P '' -f "$FASTVM_USER_CONF_DIR/id_fastvm"
fi
wait_for_ssh "$vm_number"
pmsg $P_DEBUG "Adding SSH key fingerprints of VM to ~/.ssh/known_hosts\n" "$vm_number"
ssh-keyscan -T 1 "192.168.$SUBNET_NUMBER.$vm_number" 2>/dev/null|grep -E '(ssh-|ecdsa-)' >> ~/.ssh/known_hosts
pmsg $P_DEBUG "Copy SSH key to VM\n" "$vm_number"
if [ -n "$FASTVM_KEYDIST_PASSWORD" ]; then
pmsg $P_DEBUG "Attempting to use password from /etc/fast-vm.conf\n" "$vm_number"
if sshpass -p"$FASTVM_KEYDIST_PASSWORD" -- ssh-copy-id -i "$FASTVM_USER_CONF_DIR/id_fastvm"\
-o GlobalKnownHostsFile=/dev/null -o UserKnownHostsFile=/dev/null -o StrictHostKeyChecking=no\
"root@192.168.$SUBNET_NUMBER.$vm_number" >/dev/null 2>&1; then
pmsg $P_INFO "Installed SSH key using default password.\n Now try logging into the machine with: '$FVM ssh $vm_number'\n" "$vm_number"
exit 0
else
pmsg $P_DEBUG "Couldn't copy SSH key using password from /etc/fast-vm.conf (FASTVM_KEYDIST_PASSWORD)\n" "$vm_number"
fi
fi
ssh-copy-id -i "$FASTVM_USER_CONF_DIR/id_fastvm" \
-o GlobalKnownHostsFile=/dev/null -o UserKnownHostsFile=/dev/null -o StrictHostKeyChecking=no \
"root@192.168.$SUBNET_NUMBER.$vm_number" | grep -E '(password|Now try logging into the machine)' | sed "s@with:.*@with: $FVM ssh $vm_number@"
fi
;;
*)
usage start
;;
esac
fi
;;
stop)
vm_number="$2"
if [ -z "$vm_number" ]; then pmsg $P_ERROR "VM number missing\n"; usage stop; fi
if $(echo "$vm_number"|grep -q ' '); then handle_multiple_requests $@; fi
check_vm_number "$vm_number" "inactive"
update_access_time "$vm_number"
vm_name=$(virsh --connect qemu:///system list --all |grep "$VM_PREFIX"|awk '{print $2}'|grep -E "\-$vm_number$")
if [ -n "$3" ] && [ "$3" = "graceful" ]; then
pmsg $P_DEBUG "Sending ACPI shutdown event to $vm_name\n" "$vm_number"
virsh --connect qemu:///system shutdown "$vm_name"
if [ "$?" != '0' ]; then
pmsg $P_ERROR "failed to send graceful shutdown to VM $vm_name, check syslog for more information\n" "$vm_number"
exit 1
fi
else
pmsg $P_DEBUG "Stopping VM $vm_name now\n" "$vm_number"
virsh --connect qemu:///system destroy "$vm_name"
if [ "$?" != '0' ]; then
pmsg $P_ERROR "failed to forcefully shutdown VM $vm_name, check syslog for more information\n" "$vm_number"
exit 1
fi
fi
;;
ssh)
vm_number="$2"
if [ -z "$vm_number" ]; then pmsg $P_ERROR "VM number missing\n"; usage ssh; fi
if $(echo "$vm_number"|grep -q ' '); then handle_multiple_requests $@; fi
if [ -z "$3" ] && [ -n "$MULTI_OPERATION" ] && [ "$MULTI_OPERATION" = 1 ]; then
pmsg $P_ERROR "When running ssh as part of multiple operations, script for SSH must be specified.\n" "$vm_number"
exit 1
fi
check_vm_number "$vm_number" "inactive"
update_access_time "$vm_number"
wait_for_ssh "$vm_number"
if [ -n "$3" ]; then
if [ -x "$3" ]; then
eval "$3 192.168.$SUBNET_NUMBER.$vm_number" | sed -e "s/^/\[$vmn\]/"
else
pmsg $P_ERROR "$3 not executable\n" "$vm_number"
fi
else
ssh -i "$FASTVM_USER_CONF_DIR/id_fastvm" -o GlobalKnownHostsFile=/dev/null -o UserKnownHostsFile=/dev/null -o StrictHostKeyChecking=no "root@192.168.$SUBNET_NUMBER.$vm_number"
fi
;;
scp)
vm_number="$2"
if [ -z "$vm_number" ]; then pmsg $P_ERROR "VM number missing\n"; usage scp; fi
if $(echo "$vm_number"|grep -q ' '); then handle_multiple_requests $@; fi
check_vm_number "$vm_number" "inactive"
update_access_time "$vm_number"
if [ -z "$4" ]; then
pmsg $P_ERROR "scp requires a sourcepath and destination path to copy\n" "$vm_number"
exit 1
fi
wait_for_ssh "$vm_number"
shift 2
arguments=$(echo "$@"|sed "s/\bvm:/root@192.168.$SUBNET_NUMBER.$vm_number:/g")
scp -i "$FASTVM_USER_CONF_DIR/id_fastvm" -o GlobalKnownHostsFile=/dev/null -o UserKnownHostsFile=/dev/null -o StrictHostKeyChecking=no -r $arguments
;;
rsync)
vm_number="$2"
if [ -z "$vm_number" ]; then pmsg $P_ERROR "VM number missing\n"; usage rsync; fi
if $(echo "$vm_number"|grep -q ' '); then handle_multiple_requests $@; fi
check_vm_number "$vm_number" "inactive"
update_access_time "$vm_number"
if [ -z "$4" ]; then
pmsg $P_ERROR "rsync requires a sourcepath and destination path to copy\n" "$vm_number"
exit 1
fi
wait_for_ssh "$vm_number"
shift 2
arguments=$(echo "$@"|sed "s/\bvm:/root@192.168.$SUBNET_NUMBER.$vm_number:/g")
rsync --progress -avhe "ssh -i "$FASTVM_USER_CONF_DIR/id_fastvm" -o GlobalKnownHostsFile=/dev/null -o UserKnownHostsFile=/dev/null -o StrictHostKeyChecking=no" $arguments
;;
keydist)
vm_number="$2"
if [ -z "$vm_number" ]; then pmsg $P_ERROR "VM number missing\n"; usage keydist; fi
if $(echo "$vm_number"|grep -q ' '); then handle_multiple_requests $@; fi
check_vm_number "$vm_number" "inactive"
update_access_time "$vm_number"
if [ ! -f "$FASTVM_USER_CONF_DIR/id_fastvm" ]; then
pmsg $P_WARNING "Generating new ssh key with empty passphrase for fast-vm use at $FASTVM_USER_CONF_DIR/id_fastvm\n" "$vm_number"
ssh-keygen -P '' -f "$FASTVM_USER_CONF_DIR/id_fastvm"
fi
wait_for_ssh "$vm_number"
pmsg $P_DEBUG "Adding SSH key fingerprints of VM to ~/.ssh/known_hosts\n" "$vm_number"
ssh-keyscan -T 1 "192.168.$SUBNET_NUMBER.$vm_number" 2>/dev/null|grep -E '(ssh-|ecdsa-)' >> ~/.ssh/known_hosts
pmsg $P_DEBUG "Copy SSH key to VM\n" "$vm_number"
if [ -n "$FASTVM_KEYDIST_PASSWORD" ]; then
pmsg $P_DEBUG "Attempting to use password from /etc/fast-vm.conf\n" "$vm_number"
if sshpass -p"$FASTVM_KEYDIST_PASSWORD" -- ssh-copy-id -i "$FASTVM_USER_CONF_DIR/id_fastvm"\
-o GlobalKnownHostsFile=/dev/null -o UserKnownHostsFile=/dev/null -o StrictHostKeyChecking=no\
"root@192.168.$SUBNET_NUMBER.$vm_number" >/dev/null 2>&1; then
pmsg $P_INFO "Installed SSH key using default password.\n Now try logging into the machine with: '$FVM ssh $vm_number'\n" "$vm_number"
exit 0
else
pmsg $P_DEBUG "Couldn't copy SSH key using password from /etc/fast-vm.conf (FASTVM_KEYDIST_PASSWORD)\n" "$vm_number"
fi
fi
ssh-copy-id -i "$FASTVM_USER_CONF_DIR/id_fastvm" \
-o GlobalKnownHostsFile=/dev/null -o UserKnownHostsFile=/dev/null -o StrictHostKeyChecking=no \
"root@192.168.$SUBNET_NUMBER.$vm_number" | grep -E '(password|Now try logging into the machine)' | sed "s@with:.*@with: $FVM ssh $vm_number@"
;;
console)
vm_number="$2"
if [ -z "$vm_number" ]; then pmsg $P_ERROR "VM number missing\n"; usage console; fi
check_vm_number "$vm_number" "inactive"
update_access_time "$vm_number"
vm_name=$(virsh --connect qemu:///system list --all |grep "$VM_PREFIX"|awk '{print $2}'|grep -E "\-$vm_number$")
virsh --connect qemu:///system console "$vm_name"
;;
delete)
vm_number="$2"
if [ -z "$vm_number" ]; then pmsg $P_ERROR "VM number missing\n"; usage delete; fi
if $(echo "$vm_number"|grep -q ' '); then handle_multiple_requests $@; fi
tmp_files=""
if [ $(list_vm all|grep -c -E "^$vm_number$") -eq 0 ]; then
pmsg $P_ERROR "no VM with number '$vm_number' found\n" "$vm_number"
exit 1
fi
vm_name=$(virsh --connect qemu:///system list --all |grep "$VM_PREFIX"|awk '{print $2}'|grep -E "\-$vm_number$")
get_vm_metadata "$vm_name"
if [ "$metadata_profile" != '---' ]; then
profile_name=$metadata_profile
fi
# determine image name of VM
image_name=$(virsh --connect qemu:///system list --all|awk '{print $2,$3,$4}'|grep -E "^${VM_PREFIX}.*-[0-9]+ "|sed "s/${VM_PREFIX}\(.\+\)-\([0-9]\+\) \(.\+\)$/\2 \1 \3/"|awk "\$1==$vm_number {printf \"%s\",\$2}")
delete_hack_file=""
for path in "$3" "$FASTVM_USER_CONF_DIR/${profile_name}/delete-hacks.sh" "$FASTVM_SYSTEM_CONF_DIR/${profile_name}/delete-hacks.sh" "$FASTVM_USER_CONF_DIR/delete-hacks-${image_name}.sh" "$FASTVM_SYSTEM_CONF_DIR/delete-hacks-${image_name}.sh"
do
check_file "$path" "delete hack file at $path" >/dev/null 2>&1
if [ "$?" != 2 ]; then
if [ "$file_local" = '0' ]; then
delete_hack_file=$(download_file "$path")
tmp_files="$tmp_files $delete_hack_file"
else
delete_hack_file="$path"
fi
pmsg $P_DEBUG "using file $path as delete hack file\n" "$vm_number"
break
fi
done
if [ "$FASTVM_OWNER_ONLY_DELETE" = "yes" ]; then
if [ "$(whoami)" != "root" ] && [ "$(whoami)" != "$metadata_user" ]; then
if [ -z "$metadata_user" ]; then
pmsg $P_ERROR "only 'root' is allowed to delete this VM\n" "$vm_number"
else
pmsg $P_ERROR "only 'root' and '$metadata_user' are allowed to delete this VM\n" "$vm_number"
fi
exit 1
fi
fi
if [ "$(list_vm active|grep -c -E "^$vm_number$")" -eq 1 ]; then
pmsg $P_WARNING "VM $vm_name is active, forcefully stopping it\n" "$vm_number"
virsh --connect qemu:///system destroy "$vm_name"
if [ "$?" != '0' ]; then
pmsg $P_ERROR "failed to stop VM $vm_name, check syslog for more information\n" "$vm_number"
exit 1
fi
fi
VM_MAC=$(virsh --connect qemu:///system dumpxml "$vm_name"|xmllint --xpath "//interface[.//source[@network='$LIBVIRT_NETWORK']]/mac/@address" - 2>/dev/null|cut -d\" -f 2|head -1)
if [ -n "$VM_MAC" ]; then
pmsg $P_DEBUG "removing DHCP reservation 192.168.$SUBNET_NUMBER.$vm_number for $VM_MAC\n" "$vm_number"
virsh --connect qemu:///system net-update "$LIBVIRT_NETWORK" delete ip-dhcp-host --xml "<host mac='$VM_MAC' ip='192.168.$SUBNET_NUMBER.$vm_number'/>" --live --config
if [ "$?" != '0' ]; then
pmsg $P_WARNING "failed to remove DHCP reservation 192.168.$SUBNET_NUMBER.$vm_number for $VM_MAC from libvirt, check syslog for more information\n" "$vm_number"
fi
PATH="$PATH:/usr/sbin" command -v dhcp_release >/dev/null 2>&1
if [ "$?" -eq '0' ]; then
echo "dhcp_release" "$LIBVIRT_NETWORK" "$vm_number" "$VM_MAC" | sudo -n $FASTVM_HELPER
else
pmsg $P_WARNING "dhcp_release not found, to reuse the same VM number you would need to delete DHCP leases file for $LIBVIRT_NETWORK network and restart this network in the libvirt.\nhttp://lists.thekelleys.org.uk/pipermail/dnsmasq-discuss/2007q1/001094.html\n" "$vm_number"
fi
fi
pmsg $P_DEBUG "removing VM drive\n" "$vm_number"
echo "lvremove" "/dev/$THINPOOL_VG/$vm_name" | sudo -n $FASTVM_HELPER
pmsg $P_DEBUG "removing SSH keys for this machine from ~/.ssh/known_hosts\n" "$vm_number"
sed -i "/^192\.168\.$SUBNET_NUMBER\.$vm_number /d" ~/.ssh/known_hosts
## apply delete hack file
if [ -n "$delete_hack_file" ]; then
delete_hack_file=$(echo "$delete_hack_file"|sed 's/^\([^\/]\)/\.\/\1/g')
# check if we have any libguest appliance
check_appliance_presence
pmsg $P_DEBUG "applying delete hacks from $delete_hack_file\n" "$vm_number"
. $delete_hack_file
if [ ! "$?" -eq "0" ]; then
pmsg $P_WARNING "there was issue applying delete hacks to this machine, check syslog for more details\n" "$vm_number"
fi
pmsg $P_DEBUG "applying delete hacks finished\n" "$vm_number"
fi
pmsg $P_DEBUG "undefining VM $vm_name from libvirt\n" "$vm_number"
virsh --connect qemu:///system undefine "$vm_name" --nvram --managed-save
if [ "$?" != '0' ]; then
pmsg $P_ERROR "failed to undefine VM $vm_name, check syslog for more information\n" "$vm_number"
exit 1
else
rm -f "$tmp_files" # cleanup temporary files
pmsg $P_INFO "VM '$vm_name' deleted\n" "$vm_number"
fi
;;
edit_note)
vm_number="$2"
if [ -z "$vm_number" ]; then pmsg $P_ERROR "VM number missing\n"; usage edit_note; fi
if $(echo "$vm_number"|grep -q ' '); then handle_multiple_requests $@; fi
if [ $(list_vm all|grep -c -E "^$vm_number$") -eq 0 ]; then
pmsg $P_ERROR "no VM with number '$vm_number' found\n"
exit 1
fi
if [ -z "$3" ] && [ -n "$MULTI_OPERATION" ] && [ "$MULTI_OPERATION" = 1 ]; then
pmsg $P_ERROR "When running edit_note as part of multiple operations the note must be specified as argument.\n" "$vm_number"
exit 1
fi
vm_name=$(virsh --connect qemu:///system list --all |grep "$VM_PREFIX"|awk '{print $2}'|grep -E "\-$vm_number$")
content=''
owner=$(whoami)
get_vm_metadata "$vm_name"
if [ -z "$3" ]; then
tmp_file=$(mktemp)
if [ -n "$metadata_description" ]; then
echo "$metadata_description" > "$tmp_file"
fi
$EDITOR "$tmp_file"
content=$(cat "$tmp_file")
rm "$tmp_file"
else
# get the whole content of note (do not care in how many arguments it seems to be splitted)
shift 2
content="$@"
fi
# edit also title in libvirt XMl definition so applications like virt-manager can show same notes as seen in 'fast-vm list'
owner=$metadata_user
virsh --connect qemu:///system desc --config "$vm_name" --title --new-desc "$(printf '%03d' "$vm_number") $owner $content"
update_vm_metadata "$vm_number" '*no_change*' "$content"
;;
resize)
vm_number="$2"
if [ -z "$vm_number" ]; then pmsg $P_ERROR "VM number missing\n"; usage resize; fi
if $(echo "$vm_number"|grep -q ' '); then handle_multiple_requests $@; fi
check_vm_number "$vm_number" "active"
update_access_time "$vm_number"
vm_name=$(virsh --connect qemu:///system list --all |grep "$VM_PREFIX"|awk '{print $2}'|grep -E "\-$vm_number$")
new_size=$(echo "$3"|grep -E '^[0-9]+$')
if [ -z "$new_size" ]; then pmsg $P_ERROR "invalid size. Use only whole decimal numbers\n"; usage resize; fi
#FIXME due to handling of logging in fast-vm-helper we might not receive error code if something went wrong
pmsg $P_DEBUG "resizing $vm_name disk to ${new_size}G\n" "$vm_number"
echo "lvresize" "/dev/$THINPOOL_VG/$vm_name" "$new_size" | sudo -n $FASTVM_HELPER
if [ "$?" = 0 ]; then
pmsg $P_INFO "VM $vm_number resize to ${new_size}G succeeded.\n" "$vm_number"
else
pmsg $P_ERROR "Resize failed. Check logs for more details\n" "$vm_number"
fi
;;
disk_usage)
vm_number="$2"
if [ -z "$vm_number" ] || [ "$vm_number" = "all" ]; then
vm_list=$(list_vm 'all')
else
check_vm_number "$vm_number"
vm_list="$vm_number"
fi
pmsg $P_WARNING "This is EXPERIMENTAL feature, usage data might not be 100%% accurate.\n"
# gather data
lvs_out=$(echo 'lvs'|LANG=C sudo -n $FASTVM_HELPER)
thin_out=$(echo 'thin_dump'|LANG=C sudo -n $FASTVM_HELPER)
raw_data=$(virsh --connect qemu:///system list --all|awk '{print $2}'|grep -E "^${VM_PREFIX}.*-[0-9]+$")
all_metadata=$(echo "vm_desc"|sudo -n $FASTVM_HELPER )
# process data and print relevant information on disk usage
echo "$lvs_out"|grep -E " $THINPOOL_LV "|awk '{printf "=== Thinpool space used: %6s%% of %7s\n",$3,$2}'
echo "VM# Image name User Size( %aloc ) Shared Unshared ('.'-Shared, '#'-Unshared)"
# get thinpool block size
thin_block_size=$(echo "$thin_out"| xmllint --xpath "//superblock/@data_block_size" -|cut -d\" -f 2)
for vm in $vm_list;
do
vm_name=$(echo "$raw_data"|grep -E "\-$vm$")
# get metadata from fast-vm-helper instead of libvirt API (this is much faster on systems with many VMs)
desc_data=$(echo "$all_metadata" | grep "$vm_name.xml:" | sed "s#/etc/libvirt/qemu/$vm_name.xml:##" | xmllint --xpath '//description/text()' -)
metadata_user=$(echo "$desc_data"|cut -d, -f 2)
# get dev_id that we will work on
dev_id=$(echo "$lvs_out"|grep snapshot|grep -E " ${VM_PREFIX}.*-[0-9]+ "|grep "\-$vm "|awk '{printf $5}')
image_lv_name=$(echo "$vm_name"|sed 's/-[0-9]\+$//')
# get dev_id of image this VM is using
image_dev_id=$(echo "$lvs_out"|grep -E " $image_lv_name "|awk '{printf $5}')
image_dev_creation_time=$(echo "$thin_out"| xmllint --xpath "//device[@dev_id=$image_dev_id]/@creation_time" -|cut -d\" -f 2)
# check if the 'creation_time' and 'snap_time' of VM dev_id are same
dev_creation_time=$(echo "$thin_out"| xmllint --xpath "//device[@dev_id=$dev_id]/@creation_time" -|cut -d\" -f 2)
dev_snap_time=$(echo "$thin_out"| xmllint --xpath "//device[@dev_id=$dev_id]/@snap_time" -|cut -d\" -f 2)
if [ "$dev_creation_time" != "$dev_snap_time" ]; then
pmsg $P_WARNING "Device $dev_id contain modifications that this cannot account for, results may be inaccurate!\n"
fi
# get device allocation and size
dev_size=$(echo "$lvs_out"|grep snapshot|grep -E " ${VM_PREFIX}.*-[0-9]+ "|grep "\-$vm "|sed 's/\.00g//'|awk '{printf "%3sg(%6s%%)",$2,$3}')
#dev_mapped_blocks=$(echo "$thin_out"|xmllint --xpath "//device[@dev_id=${dev_id}]/@mapped_blocks" -|cut -d\" -f 2)
#dev_allocated_gb=$(echo "scale=3; $dev_mapped_blocks*$thin_block_size/1024/1024/2"|bc)
# count the blocks that are shared and unique from thinpool metadata
shared_range_blocks=$( echo "$thin_out" | xmllint --xpath "sum( //device[@dev_id=${dev_id}]/range_mapping[@time=${image_dev_creation_time}]/@length )" -)
shared_simple_blocks=$( echo "$thin_out" | xmllint --xpath "count( //device[@dev_id=${dev_id}]/single_mapping[@time=${image_dev_creation_time}])" -)
unique_range_blocks=$( echo "$thin_out" | xmllint --xpath "sum( //device[@dev_id=${dev_id}]/range_mapping[@time!=${image_dev_creation_time}]/@length )" -)
unique_simple_blocks=$( echo "$thin_out" | xmllint --xpath "count( //device[@dev_id=${dev_id}]/single_mapping[@time!=${image_dev_creation_time}])" -)
shared_blocks=$(echo "$shared_range_blocks+$shared_simple_blocks"|bc)
unique_blocks=$(echo "$unique_range_blocks+$unique_simple_blocks"|bc)
dev_shared_gb=$(echo "scale=3; $shared_blocks*$thin_block_size/1024/1024/2"|bc|sed 's/^\./0./;s/^0$/0.000/')
dev_unique_gb=$(echo "scale=3; $unique_blocks*$thin_block_size/1024/1024/2"|bc|sed 's/^\./0./;s/^0$/0.000/')
# print text results
printf "%-3d %-12s %-8s %8s %7sg %7sg " "$vm" "$(echo "$image_lv_name"|sed "s/${VM_PREFIX}//")" "$metadata_user" "$dev_size" "$dev_shared_gb" "$dev_unique_gb"
# visual space usage representation (20 segment bar)
dev_size2=$(echo "$lvs_out"|grep snapshot|grep -E " ${VM_PREFIX}.*-[0-9]+ "|grep "\-$vm "|sed 's/\.00g//'|awk '{printf "%3s",$2}')