-
Notifications
You must be signed in to change notification settings - Fork 19
/
kiss-vm
executable file
·4663 lines (4268 loc) · 153 KB
/
kiss-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
#!/usr/bin/env bash
# author: [email protected]
# test pass on RHEL-7/CentOS-7, RHEL-8/CentOS-8 RHEL-9/CentOS-9s and Fedora-{29..36}
#
# inspired by https://www.brianlinkletter.com/2019/02/build-a-network-emulator-using-libvirt/
# `and inspired by Red Hat traning Virtual Lab
LANG=C
PATH=~/bin:$PATH
#>================ for recall self if something happen ================
CPID=$$
PROG=$0
ARGS=("$@")
trap_retry() {
local cpu=Icelake-Server
echo "[Error] got a special issue($SA_SIGINFO) while create VM, try again:";
echo '----------------------------------------------------------------'
PATH=/usr/libexec:$PATH qemu-kvm -cpu ?|grep -q $cpu || cpu=Skylake-Server
VM_RETRY=yes exec $PROG "${ARGS[@]}" -f --qemucpu=$cpu;
}
trap trap_retry SIGALRM SIGUSR2
#<================ for recall self if something happen ================
P=$0; [[ $0 = /* ]] && P=${0##*/}
_repon=kiss-vm-ns
_confdir=/etc/$_repon
Distro=
Location=
Imageurl=
VM_OS_VARIANT=
OVERWRITE=no
KSPath=
ksauto=
MacvtapMode=bridge
VMName=
InstallType=import
VirtInstallTimeOut=600
VMUSER=$(whoami)
[[ $(id -u) = 0 && -n "$SUDO_USER" ]] && VMUSER=$SUDO_USER
eval VMSHOME=~$VMUSER/VMs
eval ImagePath=~$VMUSER/myimages
eval perConfDir=~$VMUSER/.config/${_repon}
eval oldperConfDir=~$VMUSER/.config/kiss-vm
VM_DOMAIN=lab.kissvm.net
RuntimeTmp=/tmp/vm-$$
INTERACT=yes
Intranet=yes
VIRT_READY=unkown
_MSIZE=1536
DSIZE=64
baudrate=115200
GRAPHICS_OPT="--graphics=vnc,listen=0.0.0.0"
HostARCH=$(uname -m)
GuestARCH=$HostARCH
VIDEO_OPT="--video=qxl"
SOUND_OPT=""
QEMU_OPTS=()
QEMU_ENV=()
_downhostname="download.devel.fedorahat.com"
downhostname=${_downhostname/fedora/red}
baseUrl=http://$downhostname/qa/rhts/lookaside/kiss-vm-ns
bkrClientImprovedUrl=http://$downhostname/qa/rhts/lookaside/bkr-client-improved
VCPUS=4,sockets=1,cores=4
DEFAULT_DISK_BUS=virtio
DEFAULT_IF_MODEL=virtio
defaultPasswd=redhat
defaultWindowsPasswd=Sesame~0pen
orig_disable_ipv6=$(/sbin/sysctl -n net.ipv6.conf.all.disable_ipv6 2>/dev/null)
{ QEMU_USER=qemu; id ${QEMU_USER} &>/dev/null || QEMU_USER=libvirt-qemu; }
quote() {
local at=$1
if [[ -z "$at" ]]; then
echo -n "'' "
elif [[ "$at" =~ [^[:print:]]+ || "$at" = *$'\t'* || "$at" = *$'\n'* ]]; then
builtin printf %q "$at"; echo -n " "
elif [[ "$at" =~ "'" && ! "$at" =~ ([\`\"$]+|\\\\) ]]; then
echo -n "\"$at\" "
else
echo -n "$at" | sed -r -e ':a;$!{N;ba};' \
-e "s/'+/'\"&\"'/g" -e "s/^/'/" -e "s/$/' /" \
-e "s/^''//" -e "s/'' $/ /"
fi
}
getReusableCommandLine() {
#if only one parameter, treat it as a piece of script
[[ $# = 1 ]] && { echo "$1"; return; }
local shpattern='^[][0-9a-zA-Z~@%^_+=:,./-]+$'
for at; do
if [[ "$at" =~ $shpattern ]]; then
echo -n "$at "
else
quote "$at"
fi
done
echo
}
run() {
#ref: https://superuser.com/questions/927544/run-command-in-detached-tmux-session-and-log-console-output-to-file
local _runtype= _debug= _rc=0
local _nohup= _nohuplogf=
local _user= _SUDO=
local _default_nohuplogf=${VMpath:-.}/nohup.log
local _tmuxSession= _tmuxlogf=
while true; do
case "$1" in
-d|-debug) _debug=yes; shift;;
-eval*) _runtype=eval; shift;;
-bash*) _runtype=bash; shift;;
-tmux*) _runtype=tmux;
[[ $1 = *=* ]] && _tmuxSession=${1#*=}
_tmuxSession=${_tmuxSession:-$$-${USER}}
_tmuxlogf=${VMpath:-/tmp}/run-tmux-${_tmuxSession}.log
shift;;
-nohu*) _nohup=yes
[[ $1 = *=* ]] && _nohuplogf=${1#*=}
_nohuplogf=${_nohuplogf:-$_default_nohuplogf}
shift;;
-as=*) _U=${1#*=}; [[ "$_U" = "$USER" ]] || _SUDO="sudo -u $_U"; shift;;
-*) shift;;
*) break;;
esac
done
[[ $# -eq 0 ]] && return 0
[[ $# -eq 1 && -z "$_runtype" ]] && _runtype=eval
[[ "${_runtype}" = eval && -n "$_SUDO" ]] && _SUDO+=\ -s
local _cmdl=$(getReusableCommandLine "$@")
local _cmdlx=
if [[ "$_debug" = yes ]]; then
_cmdlx=$_cmdl
if [[ "${_runtype}" = tmux ]]; then
_cmdlx="tmux new -s $_tmuxSession -d \"$_cmdl\" \\; pipe-pane \"cat >$_tmuxlogf\""
elif [[ "$_nohup" = yes ]]; then
_cmdlx="nohup $_cmdl &>${_nohuplogf} &"
fi
[[ -n "$_SUDO" ]] && _cmdlx="[$_SUDO] $_cmdlx"
echo $'\E[0;33;44m'"[${_runtype:-plat} run] $_cmdlx"$'\E[0m'
fi
case ${_runtype:-plat} in
plat)
if [[ -n "$_nohup" ]]; then
$_SUDO touch "${_nohuplogf}"
$_SUDO nohup "$@" &>${_nohuplogf} &
else
$_SUDO "$@"; _rc=$?
fi
;;
eval) $_SUDO eval "$_cmdl"; _rc=$?;;
bash) $_SUDO bash -c "$_cmdl"; _rc=$?;;
tmux) $_SUDO tmux new -s $_tmuxSession -d "$_cmdl" \; pipe-pane "cat >$_tmuxlogf"; _rc=$?;;
esac
return $_rc
}
is_ssh() {
local p=${1:-$PPID}
read pid name x ppid y < <(cat /proc/$p/stat)
# or: read pid name ppid < <(ps -o pid= -o comm= -o ppid= -p $p)
[[ "$name" =~ sshd ]] && { echo "Is SSH: $pid $name"; return 0; }
[ "$ppid" -le 1 ] && { echo "Root is $pid $name"; return 1; }
is_ssh $ppid
}
try_disable_ipv6() {
[[ $(id -u) != 0 ]] && return 1
who am i|grep -v '([0-9a-f:]\+)$' && /sbin/sysctl -w net.ipv6.conf.all.disable_ipv6=1
}
create_vmhome() {
local vmhome=${1%/}
if [[ -z "$vmhome" ]]; then
echo "{VM:ERROR} create_vmhost <vmhome>: argument vmhome is required"
return 1
fi
VMtmp=$vmhome/tmp
run -debug -as=$VMUSER mkdir -p $vmhome $VMtmp
run -as=$VMUSER "chmod 1777 $VMtmp; chcon --reference=/tmp $VMtmp 2>/dev/null"
setfacl -mu:${QEMU_USER}:rwx -mg:${QEMU_USER}:rwx ${vmhome%/*} ${vmhome} 2>/dev/null
#ensure files created in VMtmp can be accessed by others
setfacl -PRdm u::rwx,g::rwx,o::rx ${VMtmp}
}
at_exit() {
#echo -e "\n\n{VM:debug} Removing tmpdir: $RuntimeTmp"
[[ $(id -u) = 0 ]] && /sbin/sysctl -w net.ipv6.conf.all.disable_ipv6=$orig_disable_ipv6 &>/dev/null
rm -rf $RuntimeTmp
}
kill_installer_tmux_session() {
local _vmn=$1
[[ -z "$_vmn" ]] && return
while read session _ ; do
[[ "$session" = *_${_vmn}: ]] && tmux kill-session -t ${session%:}
done < <(tmux ls 2>/dev/null)
}
cleanup() {
if [[ -n "$VMpath" ]]; then
echo -e "\n{VM:clean} Removing VM dir: $VMpath"
rm -rfv "$VMpath"
rmdir -v "${VMpath%/*}" 2>/dev/null
echo -e "{VM:clean} kill installer assistant tmux session"
kill_installer_tmux_session ${VMpath##*/}
fi
exit
}
trap cleanup SIGINT SIGQUIT SIGTERM
trap at_exit EXIT
#-------------------------------------------------------------------------------
vcpuN() {
local _vcpus=$1
local _vcpun= _sockets=1 _cores=4 _threads=1
for _item in ${_vcpus//,/ }; do
case $_item in
[0-9]*) _vcpun=$_item;;
sockets=*) _sockets=${_item#*=};;
cores=*) _cores=${_item#*=};;
threads=*) _threads=${_item#*=};;
esac
done
if [[ -z "$_vcpun" ]]; then
_vcpun=$((_sockets * _cores * _threads))
fi
echo -n $_vcpun
}
vmname_gen() {
local distro=$1
local cname=$2
local name=${Distro//./}
local archsuffix=
name=${name,,}
if [[ -n "$cname" ]]; then
name=${cname//[._]/-}
else
[[ "$GuestARCH" != "$HostARCH" ]] && archsuffix="_$GuestARCH"
name=${VMUSER}-${name}$archsuffix
fi
echo -n $name
}
vmname_extract() {
local allopt=
[[ "$1" = -all || "$1" = --all ]] && { shift; allopt=--all; }
local i=0
for vm; do
let i=0
for _vm in $(virsh list --name ${allopt}); do
[[ "$_vm" = $vm ]] && { echo $_vm; let i++; }
done
[[ $i -eq 0 ]] && echo "$vm"
done
}
_vmblklist() {
local _vmname=$(vmname_extract -all "$1"|head -n1)
local _pat=${2:-.}
[[ -z "$_vmname" ]] && {
echo "Usage: vmblklist <vmname> [pattern]"
return 1
}
local blklist=$(virsh domblklist "$_vmname" --details | awk 'NR>2{print}' | sed -r '/^$/d')
if [[ -z "$(grep -E -v 'cdrom|ansf-usb.image' <<<"$blklist")" ]]; then
blklist+=$'\n'$(virsh dumpxml "$_vmname" |
sed -rn '/qemu:commandline/,/\/qemu:commandline/{/.*file=([^,]+),.*,id=NVME.*/I{s//file disk nvme \1/;p}}')
fi
echo "$blklist" | grep -E "/$_vmname/" | grep -E "$_pat"
echo "$blklist" | grep -E -v "/$_vmname/" | grep -E "$_pat"
}
vmrootdir() {
pushd $VMSHOME >/dev/null
pwd
ls -l
popd >/dev/null
}
vmhomedir() {
local _vmname=$(vmname_extract -all "$1")
local _vmdir= _image=
read _type _dev _target _image < <(_vmblklist $_vmname '\.(qcow2|qcow|raw)')
if test -n "$_image"; then
_vmdir=$(dirname $_image)
elif test -d $VMSHOME/PXE/$_vmname; then
_vmdir=$VMSHOME/PXE/$_vmname
else
echo "{VM:WARN} VM dir is empty, something is wrong!" >&2
return 1
fi
if pushd $_vmdir &>/dev/null; then
pwd
ls -lAhZ
popd >/dev/null
test -f $_vmdir/.kiss-vm ||
echo "{VM:NOTE} seems this VM is not created by kiss-vm($(command -v vm))" >&2
else
echo "$_vmdir"
ls -lAhZ "$_vmdir" ||
echo "{VM:WARN} current user($(whoami)) can not access the ^^ VM homedir ^^" >&2
fi
}
_vmdelete() {
local _vmname=$1
[[ -z "$_vmname" ]] && {
return 1
}
grep -E -q "^${_vmname//+/.}$" <(virsh list --name --all) || {
echo -e "{VM:WARN} VM '$_vmname' does not exist"
return 1
}
local userhome=$(getent passwd "$VMUSER" | cut -d: -f6)
blk=$(_vmblklist "$_vmname")
if test -n "$blk"; then
! grep -q "$userhome/VM[sS]/" <<<"$blk" && {
echo -e "{VM:DEBUG} blklist in '$_vmname':\n$blk"
echo -e "{VM:WARN} VM '$_vmname' was not created by current user($VMUSER); try:"
cat <<-EOF
virsh destroy $_vmname
virsh undefine $_vmname #--remove-all-storage --nvram
EOF
return 1
}
#pxe vms
elif [[ ! -d $userhome/VMs/PXE/$_vmname ]]; then
echo -e "{VM:WARN} VM '$_vmname' was not created by current user($VMUSER); try:"
cat <<-EOF
virsh destroy $_vmname
virsh undefine $_vmname #--remove-all-storage --nvram
EOF
return 1
fi
local _vmdir= _image=
read _type _dev _target _image < <(_vmblklist $_vmname '\.(qcow2|qcow|raw)')
if test -n "$_image"; then
_vmdir=$(dirname $_image)
elif test -d $VMSHOME/PXE/$_vmname; then
_vmdir=$VMSHOME/PXE/$_vmname
else
echo "{VM:WARN} VM dir is empty, something is wrong!" >&2
fi
echo -e "\n{VM:INFO} => dist removing VM $_vmname .."
{ virsh destroy $_vmname 2>/dev/null; sleep 0.5
virsh undefine $_vmname 2>/dev/null || virsh undefine $_vmname --nvram; } | sed '/^$/d'
if [[ "$_vmdir" = $VMSHOME/?*/$_vmname ]]; then
echo -e "{VM:INFO} kill tmux session ..."
kill_installer_tmux_session ${_vmname}
echo -e "{VM:INFO} removing VM folder $_vmdir ..."
rm -f $_vmdir/{url,nohup.log,ext4.qcow2,xfs.qcow2,vm.xml,qemu.argv,.kiss-vm}
rm -f $_vmdir/*.cfg $_vmdir/*.ks
rm -f $_vmdir/*.qcow2.xz $_vmdir/*.img $_vmdir/*.image
rm -f $_vmdir/nvdimm-*.dev
rm -f $(sed 's/^unix://' $_vmdir/tmp/monitor.unix 2>/dev/null)
rm -fr $_vmdir/tmp
rm -f $_vmdir/*
rmdir $_vmdir 2>/dev/null
rmdir ${_vmdir%/*} 2>/dev/null
fi
return 0
}
vmdialogchecklist() {
local cmdinfo=$1
local resfile=$2
local all=$3
local vmlist=$(virsh list --name ${all:+--all})
[[ -n "$VMUSER" ]] && vmlist=$(grep "^$VMUSER" <<<"$vmlist"; grep -v "^$VMUSER" <<<"$vmlist";)
local vmList=$(echo "$vmlist" | sed -e /^$/d -e 's/.*/"&" "" 1/')
[[ -z "${vmList}" ]] && {
echo -e "{VM:WARN} there is not any VM in your host .." >&2
return 1;
}
dialog --backtitle "$cmdinfo" --separate-output --checklist "${cmdinfo}: please select vms you want " 30 120 28 $vmList 2>$resfile; rc=$?
tput cup $(tput lines) 0
return $rc
}
vmdialogradiolist() {
local cmdinfo=$1
local resfile=$2
local all=$3
local vmlist=$(virsh list --name ${all:+--all})
[[ -n "$VMUSER" ]] && vmlist=$(grep "^$VMUSER" <<<"$vmlist"; grep -v "^$VMUSER" <<<"$vmlist";)
local vmList=$(echo "$vmlist" | sed -e /^$/d -e 's/.*/"&" "" 1/')
[[ -z "${vmList}" ]] && {
echo -e "{VM:WARN} there is not any VM in your host .." >&2
return 1;
}
dialog --backtitle "$cmdinfo" --radiolist "${cmdinfo}: please select vm you want " 30 60 28 $vmList 2>$resfile; rc=$?
tput cup $(tput lines) 0
return $rc
}
vmdelete() {
[[ $# = 0 ]] && {
resf=$RuntimeTmp/vmlist
vmdialogchecklist vm-delete $resf all && rmList=$(< $resf)
[[ -z "$rmList" ]] && { return; }
eval set $rmList
}
set -- $(vmname_extract -all "$@")
for vm; do _vmdelete $vm; done
}
vmifaddr() {
local GETENT=
local VERBOSEIF=
while :; do
case "$1" in
/x) GETENT=yes; shift;;
/v) VERBOSEIF=yes; shift;;
*) break;;
esac
done
local _vmname=$(vmname_extract -all "$1")
VERBOSEIF=${2:+yes}
[[ -z "$_vmname" ]] && {
resf=$RuntimeTmp/vmlist
vmdialogradiolist vm-ifaddr $resf && _vmname=$(sed 's/"//g' $resf)
[[ -z "$_vmname" ]] && { return; }
}
local addrs=
if [[ "$GETENT" = yes ]]; then
addrs=$(getent hosts "$_vmname"|awk '{print $1}'|tac)
else
addrs=$(virsh --quiet domifaddr "$_vmname" | awk '{print $4}')
if [[ -z "$VERBOSEIF" ]]; then
addrs=$(echo "$addrs" | awk -F/ '{print $1}')
fi
fi
[[ -n "$addrs" ]] && echo "$addrs"
}
vmviewer() {
echo "{VM:INFO} redirect to: virt-viewer -s -v -r ..."
local logf=$RuntimeTmp/vmviewer-$$.log
local waitopt=
[[ "$WAIT" = yes ]] && waitopt=-w
set -- $(vmname_extract "$@")
run -debug -nohup=$logf virt-viewer -s -v -r $waitopt "$@"
sleep 1; cat $logf 2>/dev/null
}
vncgetsc() {
local vncport=$1
local _vmname=$(vmname_extract -all "$2")
! command -v vncdo >/dev/null && {
echo "{VM:WARN} command vncdo is needed by 'vncgetsc/vncgetscreen' function!" >&2
return 1
}
local fname=$_vmname-screen-$(date +%F_%T_%N).png
vncdo -s $vncport capture $RuntimeTmp/_screen.png
if [[ -n "$INVERT" ]]; then
image_binarize $RuntimeTmp/_screen.png $fname $INVERT
else
mv $RuntimeTmp/_screen.png $fname
fi
ls -lh $fname
if [[ -n $DISPLAY ]]; then
RM=yes
if command -v eom &>/dev/null; then
run -debug eom $fname
elif command -v eog &>/dev/null; then
run -debug eog $fname
elif command -v qview &>/dev/null; then
run -debug qview $fname
else
RM=no
fi
[[ "$RM" = yes ]] && { sleep 0.1; rm -f $fname; }
fi
}
image_binarize() {
local srcf=${1}
local dstf=${2:-new-${srcf}}
local invert=${3}
GMFirst=${GMFirst:-no}
if [[ "$GMFirst" != yes ]] && command -v anytopnm >/dev/null; then
if [[ -n "$invert" ]]; then
anytopnm $srcf | ppmtopgm | pgmtopbm -threshold | pnminvert | pnmtopng > $dstf
else
anytopnm $srcf | ppmtopgm | pgmtopbm -threshold | pnmtopng > $dstf
fi
else
local ConvertCmd="gm convert"
[[ -n "$invert" ]] && negateOpt=-negate
! command -v gm >/dev/null && {
if ! command -v convert >/dev/null; then
echo "{VM:WARN} command gm or convert are needed by 'vncget' function!" >&2
return 1
else
ConvertCmd=convert
fi
}
$ConvertCmd $srcf -threshold 30% $negateOpt $dstf
fi
return 0
}
vncget() {
local vncport=$1
! command -v vncdo >/dev/null && {
echo "{VM:WARN} command vncdo is needed by 'vncget' function!" >&2
return 1
}
! command -v gocr >/dev/null && {
echo "{VM:WARN} command gocr is needed by 'vncget' function!" >&2
return 1
}
vncdo -s $vncport capture $RuntimeTmp/_screen.png
[[ ! -s $RuntimeTmp/_screen.png ]] && {
echo "{VM:WARN} vncdo capture fail, it might because that conflict with unshared 'virt-viewer'" >&2
}
image_binarize $RuntimeTmp/_screen.png $RuntimeTmp/_screen2.png $INVERT
gocr -i $RuntimeTmp/_screen2.png 2>/dev/null | GREP_COLORS='ms=30;47' grep --color .
}
vncput() {
local vncport=$1
shift
command -v vncdo >/dev/null || {
echo "{VM:WARN} vncdo is needed by 'vncput' function!" >&2
return 1
}
local msgArray=()
for msg; do
[[ -z "$msg" ]] && { msgArray+=(); continue; }
case "$msg" in
key:*|keyup:*|keydown:*)
msgArray+=("$msg")
;;
*)
regex='[~@#$%^&*()_+|}{":?><!]'
_msg="${msg#type:}"
if [[ "$_msg" =~ $regex ]]; then
while IFS= read -r line; do
if [[ "$line" = key:shift-? ]]; then
: #line=key:shift-$(tr ')~!@#$%^&*(+}{|:><?"' '0`123456789=][\\;.,/'"'" <<<"${line: -1}")
else
line="type:$line"
fi
msgArray+=("$line")
done < <(sed -r -e 's;[~!@#$%^&*()_+|}{":?><]+;&\n;g' -e 's;[~!@#$%^&*()_+|}{":?><];\nkey:shift-&;g' <<<"$_msg")
else
msgArray+=("$msg")
fi
;;
esac
msgArray+=("")
done
for msg in "${msgArray[@]}"; do
[[ -z "$msg" ]] && { sleep 0.5; continue; }
case "$msg" in
key:*) vncdo --force-caps -s $vncport key "${msg#key:}";;
keyup:*) vncdo --force-caps -s $vncport keyup "${msg#keyup:}";;
keydown:*) vncdo --force-caps -s $vncport keydown "${msg#keydown:}";;
*) vncdo --force-caps -s $vncport type "${msg#type:}";;
esac
done
}
_vmvncport() {
local _vmn=$1;
virsh dumpxml "$_vmn" | sed -rn "/.* type=.vnc. port=.([0-9]+).*/{s//\1/;p}";
}
vmvncproc() {
local _vmname=$(vmname_extract -all "$1")
[[ -z "$_vmname" ]] && {
resf=$RuntimeTmp/vmlist
vmdialogradiolist vm-vncproc $resf all && _vmname=$(sed 's/"//g' $resf)
[[ -z "$_vmname" ]] && { return; }
}
local port=$(_vmvncport $_vmname)
if [[ -n "${port}" ]]; then
if [[ -z "${VNCPUTS}" && -z "${VNCGET}" && -z "${VNCGETSC}" ]]; then
for _host in $(hostname -A|xargs -n 1|sort -u); do
ping -c 2 $_host &>/dev/null || continue
echo $_host:$port
done
return
fi
if [[ -n "${VNCPUTS}" ]]; then
vncput localhost::$port "${VNCPUTS[@]}"
echo "[vncput@$_vmname]> ${VNCPUTS[*]}"
fi
if [[ -n "${VNCGETSC}" ]]; then
[[ -t 1 || ! -p /dev/stdout ]] && echo "[vncgetsc@$_vmname]:" >&2
vncgetsc localhost::$port $_vmname
fi
if [[ -n "${VNCGET}" ]]; then
[[ -t 1 || ! -p /dev/stdout ]] && echo "[vncget@$_vmname]:" >&2
vncget localhost::$port $_vmname
fi
fi
}
vmxml() {
local _vmname=$(vmname_extract -all "$1")
[[ -z "$_vmname" ]] && {
resf=$RuntimeTmp/vmlist
vmdialogradiolist vm-dumpxml $resf all && _vmname=$(sed 's/"//g' $resf)
[[ -z "$_vmname" ]] && { return; }
}
virsh dumpxml "$_vmname"
}
vmedit() {
local _vmname=$(vmname_extract -all "$1")
[[ -z "$_vmname" ]] && {
resf=$RuntimeTmp/vmlist
vmdialogradiolist vm-edit $resf all && _vmname=$(sed 's/"//g' $resf)
[[ -z "$_vmname" ]] && { return; }
}
virsh edit "$_vmname"
}
port_available() {
nc $(grep -q -- '-z\>' < <(nc -h 2>&1) && echo -z) $1 $2 </dev/null &>/dev/null
}
vmreboot() {
local _vmname=$(vmname_extract -all "$1")
[[ -z "$_vmname" ]] && {
resf=$RuntimeTmp/vmlist
vmdialogradiolist vm-reboot $resf all && _vmname=$(sed 's/"//g' $resf)
[[ -z "$_vmname" ]] && { return; }
}
virsh destroy "$_vmname" 2>/dev/null
virsh start "$_vmname"
[[ "$WAIT" = yes ]] && {
echo -e "{VM:INFO} waiting restart finish ..."
read _addr < <(vmifaddr "$_vmname")
until port_available ${_addr} 22; do sleep 1; done
}
}
vmstop() {
local _vmname=$(vmname_extract "$1")
[[ -z "$_vmname" ]] && {
resf=$RuntimeTmp/vmlist
vmdialogchecklist vm-shutdown $resf all && vmList=$(< $resf)
[[ -z "$vmList" ]] && { return; }
eval set $vmList
}
set -- $(vmname_extract "$@")
for vm; do
virsh destroy "$vm"
done
}
vmstart() {
local _vmname=$(vmname_extract -all "$1")
[[ -z "$_vmname" ]] && {
resf=$RuntimeTmp/vmlist
vmdialogchecklist vm-start $resf all && vmList=$(< $resf)
[[ -z "$vmList" ]] && { return; }
eval set $vmList
}
set -- $(vmname_extract -all "$@")
for vm; do
virsh start "$vm"
done
}
vmstat() {
local _vmname=$(vmname_extract -all "$1")
[[ -z "$_vmname" ]] && {
resf=$RuntimeTmp/vmlist
vmdialogchecklist vm-stat $resf all && vmList=$(< $resf)
[[ -z "$vmList" ]] && { return; }
eval set $vmList
}
set -- $(vmname_extract -all "$@")
for vm; do
virsh domstate "$vm"
done
}
vmclone() {
[[ "$1" = /a ]] && {
shift
local APPEND=yes
}
is_invalid_vmname() {
local nvmname=$1
grep -E --color=always "[][~\!@#$^&()=,\":;{}|<>'\` ]" <<<"$nvmname"
}
echo -e "{VM:INFO} checking source and destination VM status ..."
local srcname=$(vmname_extract -all "$1"|head -1)
local dstname=$2
[[ -z "$srcname" ]] && {
resf=$RuntimeTmp/vmlist
vmdialogradiolist vm-clone $resf all && srcname=$(sed 's/"//g' $resf)
[[ -z "$srcname" ]] && {
return;
}
}
if [[ -z "$dstname" ]]; then
dstname=${srcname}-clone-$$
else
#verify invalid charactors
[[ "$APPEND" = yes ]] && dstname=${srcname}-${dstname}
fi
is_invalid_vmname "$dstname" && return 1
virsh desc $dstname &>/dev/null && {
echo -e "{VM:WARN} Guest $dstname has been there ..."
return 1
}
#get src vm path
srcpath=$(vmhomedir $srcname 2>/dev/null|head -n1)
[[ ! -r "${srcpath}" ]] && {
echo "homedir($srcname): $srcpath"
echo -e "{VM:WARN} Guest homedir is not readable for current user($(whoami)) ..."
return 1
}
[[ ! -f ${srcpath}/.kiss-vm || ${srcpath##*/} != ${srcname} ]] && {
echo -e "{VM:WARN} seems $srcname was not created by kiss-vm, can not use vm-clone; please use virt-clone instead ..."
return 1
}
[[ ! -r ${srcpath}/.kiss-vm ]] && {
vmhomedir $srcname
echo -e "{VM:WARN} Guest $srcname is not readable for current user($(whoami)) ..."
return 1
}
#virsh suspend "$srcname"
echo -e "{VM:INFO} stoping source VM '${srcname}' ..."
virsh destroy "$srcname" &>/dev/null
[[ "$(vmstat $srcname)" = running* ]] && {
echo -e "{VM:WARN} Guest $srcname is still running, please stop it before clone ..."
return 1
}
# do clone
echo -e "{VM:INFO} cloning $srcname to $dstname ..."
local distron=$(awk -F/ '{print $(NF-1)}' <<<"${srcpath}")
local dstpath=$VMSHOME/$distron/$dstname
create_vmhome $dstpath
rm -f $dstpath/*
if [[ "$VMSHARE" != yes ]]; then
setfacl -d -mg::--- -mo::--- $dstpath
fi
chcon --reference=${srcpath} $dstpath 2>/dev/null
run -as=$VMUSER touch $dstpath/.kiss-vm
fileopts=$(_vmblklist $srcname|sed -rn '/( -|\.iso)$/!{ s|^.* | --file |;'"s|$srcpath|$dstpath|;s%/${srcname}([^/]+)\$%/${dstname}\1%;"' p}'|xargs)
run -debug -as=$VMUSER bash -c "virt-clone -o ${srcname} --name ${dstname} $fileopts \
--check path_exists=off --check disk_size=off \
--print-xml >$dstpath/${dstname}.xml"
[[ -s $dstpath/${dstname}.xml ]] || return 1
sed -i "s|$srcpath|$dstpath|" $dstpath/${dstname}.xml
#Note: https://www.reddit.com/r/archlinux/comments/obn999/ownership_of_qcow2_images_created_by_virtmanager/
#^^^^ why don't use virt-clone directly
#copy file
for f in ${srcpath}/*; do
fname=${f##*/}
df=$dstpath/$fname
[[ "${fname}" = nohup.log ]] && continue
if [[ "${fname}" = ${srcname}[-.]* ]]; then
dfname=${fname/$srcname/$dstname}
df="$dstpath/${dfname}"
sed -i "s|/$fname|/$dfname|g" $dstpath/${dstname}.xml
fi
run -debug cp -p --sparse=always --preserve=all "$f" "$df"
#if the cp --preserve=context does not work, use:
#run -debug chcon --reference="$f" "$df" 2>/dev/null
done
#virt-clone get wrong nvram path/filename, fix it.
if grep -q "<nvram>$dstpath/" $dstpath/${dstname}.xml; then
nvramline=$(virsh dumpxml "$srcname"|sed -n "/<nvram>/{s#$srcpath#$dstpath#; p}")
sed -i "/<nvram>/s#^.*\$#${nvramline}#" $dstpath/${dstname}.xml
fi
if [[ $(id -u) = 0 ]]; then
chown $VMUSER:$(id -g -u $VMUSER) -R $dstpath
fi
run -debug -as=$VMUSER virsh define $dstpath/${dstname}.xml
vmhomedir ${dstname}
#--enable customize,user-account,ssh-hostkeys,net-hostname,net-hwaddr,machine-id \
LIBGUESTFS_BACKEND=direct run -debug virt-sysprep -d ${dstname} \
--enable customize,user-account,net-hostname,net-hwaddr,machine-id \
--hostname $dstname \
--remove-user-accounts bar \
--run-command "ls -l"
run -debug -as=$VMUSER virsh start $dstname
#virsh resume "$srcname"
#virsh start "$srcname"
}
sshtest() {
local target=$1
local sshOpts=${2:--o UserKnownHostsFile=/dev/null -o StrictHostKeyChecking=no -o GSSAPIAuthentication=no}
local result=255
local tmpf=${RuntimeTmp}/_sshtest
local KexAlgorithmsOpt=
[[ -z "${RuntimeTmp}" ]] && tmpf=$(mktemp)
local _cmd= #work-around for avoiding hang while test against windows openssh-server
[[ "${target,,}" = administrator@* ]] && _cmd=exit
ssh -v -n -o Batchmode=yes $sshOpts $target $_cmd &>$tmpf; sshrc=$?
[[ "$DEBUG" = yes ]] && {
echo "[sshtest:debug] sshrc=$sshrc" >&2
echo -e "\033[32m$(tail -n 20 $tmpf)\033[0m" >&2
}
if [[ $sshrc = 0 ]]; then
result=0 #can login or run command without password
elif grep -iq '^Bytes per second:' $tmpf; then
result=0 #freebsd "publickey" login
elif grep -v ^debug1: $tmpf|grep -iq "Permission denied (.*password.*)"; then
result=1 #can login or run command with password
elif grep -iq "no matching key exchange method found. Their offer:" $tmpf; then
local KexAlgorithmsOpt=-oKexAlgorithms=+$(sed -n '/^.*Their offer: /{s///;s/\r//;p}' $tmpf)
if [[ "$sshOpts" != *$KexAlgorithmsOpt ]]; then
sshOpts+=" $KexAlgorithmsOpt"
sshtest $target "$sshOpts"
result=$?
else
result=2 #can not connect to ssh
fi
fi
[[ -z "${RuntimeTmp}" ]] && rm -f $tmpf
[[ -z "$KexAlgorithmsOpt" ]] && echo "$sshOpts"
return $result
}
vmcopyto() {
[[ "$#" -lt 3 ]] && {
echo "Usage: vm cpto vmname <src files/dirs ...> <dst dir in vm>"
return 1
}
local _vmname=$(vmname_extract "$1"|head -1)
shift 1
local _addr=
local dstdir=${@: -1}
local srcarray=("${@:1: $#-1}")
read _addr < <(vmifaddr "$_vmname")
port_available $_addr 22 || {
echo -e "{VM:ERR} port $_vmname:22 is not available"
return 1
}
local sshstat=unavailable
local sshOpts="-o UserKnownHostsFile=/dev/null -o StrictHostKeyChecking=no -o GSSAPIAuthentication=no -o LogLevel=ERROR"
local U=root
vmhomedir $_vmname | grep -E -q -i -e windows && {
U=Administrator; defaultPasswd=$defaultWindowsPasswd;
}
sshOpts=$(sshtest $U@$_addr "$sshOpts")
case $? in 0) sshstat=yes;; 1) sshstat=passwd;; esac
if [[ $sshstat = yes ]]; then
scp $sshOpts -r "${srcarray[@]}" $U@${_addr}:$dstdir/.
rc=$?
[[ $rc = 0 ]] && {
flist=()
for f in "${srcarray[@]}"; do f=${f%/}; flist+=("$dstdir/${f##*/}"); done
ssh $sshOpts $U@${_addr} ls -ld "${flist[@]}"
}
elif [[ $sshstat = passwd ]]; then
expect <(cat <<-EOF
set timeout 120
spawn scp $sshOpts -r "${srcarray[@]}" $U@${_addr}:$dstdir/.
expect {
"password:" { send "$defaultPasswd\r"; exp_continue }
"Password for" { send "$defaultPasswd\r"; exp_continue }
eof
}
foreach {pid spawnid os_error_flag value} [wait] break
exit \$value
EOF
)
rc=$?
else
echo -e "{VM:WARN} ssh $_vmname is not available ..."
rc=1
fi
return $rc
}
vmcopyfrom() {
[[ "$#" -lt 3 ]] && {
echo "Usage: vm cpfrom vmname <file/dir> <dst dir>"
return 1
}
local _vmname=$(vmname_extract "$1"|head -1)
shift 1
local src=${1%/}
local dstf=${2}
[[ -d "$dstf" ]] && dstf=$(readlink -f $dstf)/.
read _addr < <(vmifaddr "$_vmname")
port_available $_addr 22 || {
echo -e "{VM:ERR} port $_vmname:22 is not available"
return 1
}
local sshstat=unavailable
local sshOpts="-o UserKnownHostsFile=/dev/null -o StrictHostKeyChecking=no -o GSSAPIAuthentication=no -o LogLevel=ERROR"
local U=root
vmhomedir $_vmname | grep -q -i windows && {
U=Administrator; defaultPasswd=$defaultWindowsPasswd;
}
sshOpts=$(sshtest $U@$_addr "$sshOpts")
case $? in 0) sshstat=yes;; 1) sshstat=passwd;; esac
if [[ $sshstat = yes ]]; then
scp $sshOpts -r $U@${_addr}:$src $dstf
rc=$?
elif [[ $sshstat = passwd ]]; then
expect <(cat <<-EOF
set timeout 120
spawn scp $sshOpts -r $U@${_addr}:$src $dstf
expect {
"password:" { send "$defaultPasswd\r"; exp_continue }
"Password for" { send "$defaultPasswd\r"; exp_continue }
eof
}
foreach {pid spawnid os_error_flag value} [wait] break
exit \$value
EOF
)
rc=$?
else
echo -e "{VM:WARN} ssh $_vmname is not available ..."
rc=1
fi
[[ $rc = 0 ]] && {
if [[ -f "$dstf" ]]; then
ls -l $dstf
else
ls -l -d ${dstf}/${src##*/}
fi
}
return $rc
}
vmport_available() {
local _vmname=$(vmname_extract -all "$1")
local _port=${2:-22}
local wait_opt=
[[ -z "$_vmname" ]] && {
resf=$RuntimeTmp/vmlist
vmdialogradiolist vm-console $resf && _vmname=$(sed 's/"//g' $resf)
[[ -z "$_vmname" ]] && { return; }
}
local _addr=$(vm ifaddr "$_vmname"|head -1)
if [[ "$WAIT" = yes ]]; then
while [[ -z "$_addr" ]]; do
sleep 8
_addr=$(vm ifaddr "$_vmname"|head -1)
done