-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathpatch_vm.sh
101 lines (89 loc) · 2.2 KB
/
patch_vm.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
#!/bin/bash
#
# Script to patch manifest files for use in a VM with nested virtualization.
# [Bash Strict Mode](http://redsymbol.net/articles/unofficial-bash-strict-mode/)
set -euo pipefail
IFS=$'\n\t'
save_manifests() {
for file in ./templates/**/manifest.yml; do
cp -p "$file"{,.BKP}
done
}
restore_manifests() {
for file in ./templates/**/manifest.yml; do
mv "$file"{.BKP,}
done
}
nested_virt() {
# IFS=$'\n' prevents leading (and trailing) spaces from being removed
IFS=$'\n' read -r -d '' KEY <<'EOM'
qemuargs:
EOM
IFS=$'\n' read -r -d '' VAL <<'EOM'
- - "-cpu"
- "host"
- - "-enable-kvm"
- ""
EOM
for file in ./templates/**/manifest.yml; do
if ! grep -q 'qemuargs' "$file"; then
# insert $KEY after `type: qemu`
sed -i "/type: qemu/a \\${KEY//$'\n'/\\n}" "$file"
fi
# insert $VAL after `qemuargs:`
sed -i "/qemuargs:/a \\${VAL//$'\n'/\\n}" "$file"
done
}
patch_files() {
if grep -q 'hypervisor' /proc/cpuinfo; then # running inside a VM
if grep -qE '(vmx|svm)' /proc/cpuinfo; then # nested virtualization supported
save_manifests
nested_virt
fi
else
false
fi
}
compare_files() {
for file in ./templates/**/manifest.yml; do
diff --color -u "$file"{.BKP,} || true # diff return a non-zero value when there are differences
done
}
if ! ls ./templates/**/manifest.yml &>/dev/null; then
echo "Can't find manifest files."
false
fi
case ${1-} in
p | patch)
if ls ./templates/**/manifest.yml.BKP &>/dev/null; then
echo "Files have already been patched."
false
else
if patch_files; then
echo "Files have been patched successfully."
else
echo "Your system does not support nested virtualization or is not a VM."
false
fi
fi
compare_files
;;
r | restore)
if ls ./templates/**/manifest.yml.BKP &>/dev/null; then
restore_manifests
echo "Manifest files have been restored."
else
echo "There are no files to restore."
false
fi
;;
*)
cat <<'EOM'
Usage: patch_vm.sh <argument>
Argument:
p|patch: Patch the manifests files for use inside a VM with nested virtualization.
r|restore: Restore the original files.
EOM
false
;;
esac