summaryrefslogtreecommitdiffstats
path: root/kvm-wrapper.sh
blob: 5028921004bd40e7073222f389087ba61d38760b (plain)
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
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
#!/bin/bash
#
# KVM Wrapper Script
# Copyright (C) 2011 Benjamin Cohen <bencoh@codewreck.org>
#                    Dominique Martinet <asmadeus@codewreck.org>
# Published under the WTFPLv2 (see LICENSE)

SCRIPT_PATH="${BASH_SOURCE[0]}"
SCRIPT_NAME=$(basename "$SCRIPT_PATH")
ROOTDIR=$(readlink -m "$SCRIPT_PATH")
ROOTDIR=$(dirname "$ROOTDIR")
[[ -r "$ROOTDIR/kvm-wrapper.conf" ]] || ROOTDIR="/etc/kvm-wrapper"
CONFFILE="$ROOTDIR/kvm-wrapper.conf"

function canonpath ()
{
	readlink -e "$1"
}

# Exit on fail and print a nice message
function fail_exit ()
{
	echo -ne '\n'
	echo -e "$1"
	[[ -n "$KVM_SCREEN" ]] && (
		local USE_PID_FILE=""
		test_exist "$PID_FILE" || USE_PID_FILE="true"
		[[ -n "$USE_PID_FILE" ]] && echo "error" > "$PID_FILE"
		echo ""
		stty sane
		echo "Press ^D (EOF) or enter to exit"
		read
		[[ -n "$USE_PID_FILE" ]] && rm -f "$PID_FILE"
		stty sane
		reset
	)
	echo "Exiting."
	exit 1
}

# FS node testers
function test_exist ()
{
	local NODE="$1"
	[[ -e "$NODE" ]]
}

function test_dir ()
{
	local DIR="$1"
	[[ -d "$DIR" && -r "$DIR" ]]
}

function test_dir_rw ()
{
	local DIR="$1"
	[[ -d "$DIR" && -r "$DIR" && -w "$DIR" ]]
}

function test_file ()
{
	local FILE="$1"
	[[ -f "$FILE" && -r "$FILE" ]]
}

function test_file_rw ()
{
	local FILE="$1"
	[[ -f "$FILE" && -r "$FILE" && -w "$FILE" ]]
}

function test_pid ()
{
	local PID="$1"
	ps "$PID" >& /dev/null
}

function test_pid_from_file ()
{
	local PID_FILE="$1"
	test_file "$PID_FILE" && test_pid "$(cat "$PID_FILE")"
}

function test_socket ()
{
	local FILE="$1"
	[[ -S "$FILE" && -r "$FILE" ]]
}

function test_socket_rw ()
{
	local FILE="$1"
	[[ -S "$FILE" && -r "$FILE" && -w "$FILE" ]]
}

function test_blockdev ()
{
	local FILE="$1"
	[[ -b "$FILE" && -r "$FILE" ]]
}

function test_blockdev_rw ()
{
	local FILE="$1"
	[[ -b "$FILE" && -r "$FILE" && -w "$FILE" ]]
}

function test_exec ()
{
	local FILE="$1"
	[[ -x "$FILE" && -r "$FILE" ]]
}

function test_nodename ()
{
	local NODE="$1"
	[[ -n "$NODE" && "$NODE" != "$(hostname -s)" && -n "$(get_cluster_host "$NODE")" ]]
}

function require_exec ()
{
	test_exec "$(which "$1")" || fail_exit "$1 not found or not executable"
}

function check_create_dir ()
{
	local DIR="$1"
	test_dir_rw "$DIR" || mkdir -p "$DIR"
	test_dir_rw "$DIR" || fail_exit "Couldn't read/write VM PID directory:\n$DIR"
}

function wait_test_timelimit ()
{
	local PROPER=0
	local ELAPSED=0
	local TIMELIMIT=$1
	local EVAL_EXPR=$2
	while [[ $ELAPSED -le $TIMELIMIT ]]
	do
		ELAPSED=$((ELAPSED+1))
		eval "$EVAL_EXPR" && PROPER=1;
		[[ $PROPER -eq 1 ]] && break
		sleep 1
	done
	echo $ELAPSED
	[[ $PROPER -eq 1 ]] && return 0
	return 1
}

function kvm_init_env ()
{
	VM_NAME="$1"
	KVM_CLUSTER_NODE=local
	VM_DESCRIPTOR="$VM_DIR/$VM_NAME-vm"
	MONITOR_FILE="$MONITOR_DIR/$VM_NAME.unix"
	SERIAL_FILE="$SERIAL_DIR/$VM_NAME.unix"

	local vmnamehash
	vmnamehash=$(hash_string "$VM_NAME")
	vmnamehash=${vmnamehash:0:5}
	SCREEN_SESSION_NAME="${SCREEN_NAME_PREFIX}kvm-$VM_NAME-$vmnamehash"

	unset PID_FILE
	if [[ -z "$KVM_RUNDISK" ]]; then
		test_file "$VM_DESCRIPTOR" || fail_exit "Couldn't open VM $VM_NAME descriptor:\n$VM_DESCRIPTOR"
		source "$VM_DESCRIPTOR"
	fi
	PID_FILE=${PID_FILE:-"$PID_DIR/${KVM_CLUSTER_NODE:-*}:$VM_NAME-vm.pid"}

}

function random_mac ()
{
	local MACADDR
	BASE_MAC=${BASE_MAC:-"52:54:00:ff"}
	MACADDR=$(printf "$BASE_MAC:%02x:%02x" $((RANDOM % 256)) $((RANDOM % 256)))
	# check if it's not already used..
	grep -qre "KVM_MACADDR.*=\"$MACADDR\"" "$VM_DIR" \
		&& random_mac \
		|| echo -n "$MACADDR"
}

# stores FD in global variable LOCKFD_${VARIANT}
# the lock will automatically be released when shell exits,
# but calling unlock lets us unlink lock file safely
function lock ()
{
	local VARIANT="${1//-/_}"
	local LOCKFILE="/tmp/kvm-wrapper-$VARIANT.lock"
	local LOCKFD

	while :; do
		exec {LOCKFD}<>"$LOCKFILE"
		flock ${LOCKFD}

		# Check if file has changed since opening
		# if it has, drop lock and try again
		FD_INO=$(stat -c "%i" -L "/proc/$$/fd/${LOCKFD}")
		FILE_INO=$(stat -c "%i" "${LOCKFILE}" 2>/dev/null)

		[[ "$FD_INO" == "$FILE_INO" ]] && break

		exec {LOCKFD}<&-
	done

	eval "export LOCKFD_${VARIANT}=${LOCKFD}"
}

function unlock ()
{
	local VARIANT="${1//-/_}"
	local LOCKFILE="/tmp/kvm-wrapper-$VARIANT.lock"
	local LOCKFD

	# remove lockfile then close (unlock) fd
	rm -f "$LOCKFILE"

	eval "LOCKFD=\$LOCKFD_${VARIANT}"
	eval "exec $LOCKFD<&-"
	eval "unset LOCKFD_${VARIANT}"
}

# cluster helpers
hash_string ()
{
	echo "$1"|md5sum|awk '{print $1}'
}

set_cluster_host ()
{
	eval KVM_CLUSTER_HOSTS_$(hash_string $1)="$2"
}

get_cluster_host ()
{
	eval echo '${KVM_CLUSTER_HOSTS_'$(hash_string "$1")'}'
}

run_remote ()
{
	HOST="`get_cluster_host $1`"
	[[ -z "$HOST" ]] && fail_exit "Error: Unknown host $1!"
	shift
	require_exec ssh
	SSH_OPTS=${SSH_OPTS-"-t"}
	[[ -n "$KVM_CLUSTER_IDENT" ]] && SSH_OPTS+=" -i $KVM_CLUSTER_IDENT"
	echo ssh $SSH_OPTS "$HOST" $@
	ssh $SSH_OPTS "$HOST" $@
}
# NBD helpers
function nbd_img_link ()
{
	KVM_IMAGE="$1"
	echo "$NBD_IMG_LINK_DIR/$(basename "$KVM_IMAGE")-$(hash_string "$(canonpath "$KVM_IMAGE")")"
}

function kvm_nbd_connect ()
{
	require_exec "$KVM_NBD_BIN"
	check_create_dir $NBD_IMG_LINK_DIR
	local KVM_IMAGE="$1"

	local KVM_IMAGE_NBD_LINK=$(nbd_img_link "$KVM_IMAGE")
	[[ -h "$KVM_IMAGE_NBD_LINK" ]] && fail_exit "Image disk $KVM_IMAGE seems to be connected already."

	local SUCCESS=0
	local NBD_BLOCKDEV
	for NBD_BLOCKDEV in /dev/nbd*; do
		local NBD_SOCKET_LOCK="/var/lock/qemu-nbd-nbd$i"

		test_blockdev_rw "$NBD_BLOCKDEV" || continue
		test_socket "$NBD_SOCKET_LOCK" && continue

		$KVM_NBD_BIN -c "$NBD_BLOCKDEV" "$KVM_IMAGE"
		ln -s "$NBD_BLOCKDEV" "$KVM_IMAGE_NBD_LINK"

		echo "Connected: $KVM_IMAGE to $NBD_BLOCKDEV."
		SUCCESS=1
		break
	done
	[[ $SUCCESS -eq 1 ]] || fail_exit "Couldn't connect image disk for some reason."
}

function kvm_nbd_disconnect ()
{
	require_exec "$KVM_NBD_BIN"
	check_create_dir $NBD_IMG_LINK_DIR
	local KVM_IMAGE="$1"

	local KVM_IMAGE_NBD_LINK=$(nbd_img_link "$KVM_IMAGE")
	[[ -h "$KVM_IMAGE_NBD_LINK" ]] || fail_exit "Image disk $KVM_IMAGE does not seem to be connected."
	$KVM_NBD_BIN -d "$KVM_IMAGE_NBD_LINK"
	rm -f "$KVM_IMAGE_NBD_LINK"
}

# LVM helpers
function prepare_disks ()
{
	case "$KVM_MANAGE_DISKS" in
		"ACTIVATE_LV")
			for DISK in "${KVM_DISK[@]}"; do
				[[ "$DISK" == "/dev/"*"/"* ]] && lvchange -ay "$DISK" || true
			done
			;;
		"USER_DEFINED")
			eval "$USER_PREPARE_DISKS"
			;;
	esac;
}

function unprepare_disks ()
{
	case "$KVM_MANAGE_DISKS" in
		"ACTIVATE_LV")
			for DISK in "${KVM_DISK[@]}"; do
				[[ "$DISK" == "/dev/"*"/"* ]] && lvchange -an "$DISK" || true
			done
			;;
		"USER_DEFINED")
			eval "$USER_UNPREPARE_DISKS"
			;;
	esac;
}

function lvm_create_disk ()
{
	require_exec "$LVM_LVCREATE_BIN"

	LVM_LV_NAME="${LVM_LV_NAME:-"vm.$VM_NAME"}"
	local LVM_LV_SIZE=$(($ROOT_SIZE+${SWAP_SIZE:-0}))

	eval "$LVM_LVCREATE_BIN --name $LVM_LV_NAME --size $LVM_LV_SIZE $LVM_VG_NAME $LVM_PV_NAME"
	desc_update_setting "KVM_DISK[0]" "/dev/$LVM_VG_NAME/$LVM_LV_NAME"
}

function qcow_create_disk()
{
	local KVM_IMG_DISKNAME="$1"
	local KVM_IMG_DISKSIZE="$2"
	"$KVM_IMG_BIN" create -f "$KVM_IMG_FORMAT" "$KVM_IMG_DISKNAME" "$KVM_IMG_DISKSIZE"

	if [[ "x$?" == "x0" ]]
	then
		[[ -n "$KVM_USER" ]] && chown $KVM_USER: "$KVM_IMG_DISKNAME"
		desc_update_setting "KVM_DISK[0]" "$KVM_IMG_DISKNAME"
	else
		echo "Failed creating disk. Continuing anyway"
	fi
}

function map_disk()
{
	local DISKDEV=$1
	kpartx -a -p- "$DISKDEV" > /dev/null
	echo /dev/mapper/`kpartx -l -p- $DISKDEV | grep -m 1 -- "-1.*$DISKDEV" | awk '{print $1}'`
}

function unmap_disk()
{
	local DISKDEV=$1
	kpartx -d -p- "$DISKDEV"
}

function lvm_mount_disk()
{
	set -e

	test_exist "$PID_FILE" && fail_exit "VM $VM_NAME seems to be running! (PID file $PID_FILE exists)\nYou cannot mount disk on a running VM"

	echo "Attempting to mount first partition of ${KVM_DISK[0]}"
	prepare_disks
	PART=`map_disk "${KVM_DISK[0]}"`
	mkdir -p "/mnt/$VM_NAME"
	mount "$PART" "/mnt/$VM_NAME"
	set +e
}

function lvm_umount_disk()
{
	set -e
	echo "unmounting ${KVM_DISK[0]}"
	umount "/mnt/$VM_NAME" 
	rmdir "/mnt/$VM_NAME"
	unmap_disk "${KVM_DISK[0]}"
	unprepare_disks
	set +e
}

# PCI rebind helper
function pci_bind_driver ()
{
	local BIND_DRIVER_NAME=$1
	local PCIDOMAIN=$2
	[[ "$(echo "$PCIDOMAIN" | tr -dc ":" | wc -c)" == "1" ]] && PCIDOMAIN="0000:$PCIDOMAIN"

	local PCI_BIND_DRIVER="/sys/bus/pci/drivers/$BIND_DRIVER_NAME"

	# drivers don't like parallel bind/unbind, lock through.
	lock "$BIND_DRIVER_NAME"

	# In case driver is not loaded
	test_file_rw "$PCI_BIND_DRIVER/new_id" || modprobe "$BIND_DRIVER_NAME"
	test_file_rw "$PCI_BIND_DRIVER/new_id" || fail_exit "$BIND_DRIVER_NAME driver not available"

	# Retrieve vendor/device id
	local PCIVENDOR="$(cat "/sys/bus/pci/devices/$PCIDOMAIN/vendor" |sed 's/^0x//')"
	PCIVENDOR+=" $(cat "/sys/bus/pci/devices/$PCIDOMAIN/device" |sed 's/^0x//')"

	echo "Unbinding pci device ($PCIDOMAIN [$PCIVENDOR]) and binding to $BIND_DRIVER_NAME"

	# Add id, unbind, and bind
	echo "$PCIVENDOR" > "$PCI_BIND_DRIVER/new_id" || fail_exit "couldn't add new_id"
	[[ -w "/sys/bus/pci/devices/$PCIDOMAIN/driver/unbind" ]] && \
		{ echo "$PCIDOMAIN" > "/sys/bus/pci/devices/$PCIDOMAIN/driver/unbind" || fail_exit "couldn't unbind"; }
	echo "$PCIDOMAIN" > "$PCI_BIND_DRIVER/bind" || fail_exit "couldn't bind"

	unlock "$BIND_DRIVER_NAME"
}

function pci_unbind_driver()
{
	local BIND_DRIVER_NAME=$1
	local PCIDOMAIN=$2
	[[ "$(echo "$PCIDOMAIN" | tr -dc ":" | wc -c)" == "1" ]] && PCIDOMAIN="0000:$PCIDOMAIN"

	local PCI_BIND_DRIVER="/sys/bus/pci/drivers/$BIND_DRIVER_NAME"

	echo "$PCIDOMAIN" > $PCI_BIND_DRIVER/unbind
}

# PCI assign helper (pci-stub)
function pci_stubify()
{
	pci_bind_driver "pci-stub" "$1"
}

function pci_unstubify()
{
	pci_unbind_driver "pci-stub" "$1"
}

# PCI vfio helper (vfio-pci)
function pci_vfiofy()
{
	pci_bind_driver "vfio-pci" "$1"

	if [[ -n "$KVM_USER" ]]; then
		local IOMMU_GROUP=$(readlink "/sys/bus/pci/drivers/vfio-pci/"*"$1/iommu_group")
		IOMMU_GROUP=${IOMMU_GROUP##*/}
		chown $KVM_USER: /dev/vfio/$IOMMU_GROUP
	fi
}

function pci_unvfiofy()
{
	pci_unbind_driver "vfio-pci" "$1"
}

# helper for sriov
# for mlx4 cards, we can force pkeys just like we'd force vlan at host level
function ib_sriov_pkeys()
{
	local DEV="$1"
	local PCIDOMAIN="$2"
	local PKEYS="$3"

	# set pkey if able
	if [[ -e  /sys/class/infiniband/$DEV/iov/$PCIDOMAIN/ports/1/pkey_idx ]]; then
		PKIDX=0
		[[ -z "$PKEYS" ]] || for PKEY in $PKEYS; do
			local PKEY_IDX=$(basename "$(grep -lZw 0x8$PKEY /sys/class/infiniband/$DEV/ports/1/pkeys/*)")
			[[ -z "$PKEY_IDX" ]] && fail_exit "pkey $PKEY not found for $DEV"
			echo $PKEY_IDX > /sys/class/infiniband/$DEV/iov/$PCIDOMAIN/ports/1/pkey_idx/$PKIDX || fail_exit "couldn't set pkey"
			PKIDX=$((PKIDX+1))
		done
		PKEY_IDX=$(basename "$(grep -lZw 0x7fff /sys/class/infiniband/$DEV/ports/1/pkeys/*)")
		echo $PKEY_IDX > /sys/class/infiniband/$DEV/iov/$PCIDOMAIN/ports/1/pkey_idx/$PKIDX
	fi
}

function ib_unsriov_pkeys()
{
	local DEV="$1"
	local PCIDOMAIN="$2"

	test -e "/sys/class/infiniband/$DEV/iov/$PCIDOMAIN" || continue
	grep -lZv none "/sys/class/infiniband/$DEV/iov/$PCIDOMAIN/ports/1/pkey_idx/"* | \
		tr '\0' '\n' | \
		while read file; do
			echo none > $file
		done
}

# for mlx5, we don't force pkeys but we force node guid to let opensm handle it
function ib_sriov_guid()
{
	local DEV="$1"
	local VIRTFN_IDX="$2"
	local CHILD_GUID="$3"

	if [[ "$DEV" =~ "mlx5_"* ]]; then
		local GUID=$(sed -e 's/\([a-f0-9]\{2\}\)\([a-f0-9]\{2\}\)/\1:\2/g' < /sys/class/infiniband/$DEV/node_guid)
		echo Follow > /sys/class/infiniband/$DEV/device/sriov/$VIRTFN_IDX/policy
		echo $GUID > /sys/class/infiniband/$DEV/device/sriov/$VIRTFN_IDX/node
		[[ -n "$CHILD_GUID" ]] && \
			echo "$CHILD_GUID" > /sys/class/infiniband/$DEV/device/sriov/$VIRTFN_IDX/port || \
			printf "%s:%x\n" "${GUID%:*}" $((0x${GUID##*:}+$VIRTFN_IDX+1)) > /sys/class/infiniband/$DEV/device/sriov/$VIRTFN_IDX/port
	fi
}


# main sriov function - returns two values in PCIDOMAIN and VFNUM variables
function sriov()
{
	local BR="$1"
	local DEVDIR=inval
	local FLOCK
	local VIRTFN
	PCIDOMAIN=inval

	[[ -e "/sys/class/net/${BR}/device" ]] && DEVDIR="/sys/class/net/${BR}/device"
	[[ -e "/sys/class/infiniband/${BR}/device" ]] && DEVDIR="/sys/class/infiniband/${BR}/device"
	[[ "$DEVDIR" = "inval" ]] && fail_exit "could not find device for $BR"

	# following is racy, lock through.
	lock "$BR"

	if [[ -e "$DEVDIR/sriov_numvfs" && ! -e "$DEVDIR/virtfn0" ]]; then
		# arbitrary number: create all vfs available
		cat "$DEVDIR/sriov_totalvfs" > "$DEVDIR/sriov_numvfs"
	fi

	# pick a virtfn
	for VIRTFN in $DEVDIR/virtfn*; do
		PCIDOMAIN=$(basename $(readlink $VIRTFN))
		[[ -e /sys/bus/pci/drivers/vfio-pci/$PCIDOMAIN ]] || break
		PCIDOMAIN=inval
	done
	[[ $PCIDOMAIN = inval ]] && { unlock "$BR"; fail_exit "no vfio virtfn available for $BR"; }
	VFNUM=${VIRTFN##*virtfn}

	# hack - register everything to pci-stub first so we can tell appart which are used or not
	local PCIVENDOR="$(cat "/sys/bus/pci/devices/$PCIDOMAIN/vendor" |sed 's/^0x//')"
	PCIVENDOR+=" $(cat "/sys/bus/pci/devices/$PCIDOMAIN/device" |sed 's/^0x//')"
	echo "$PCIVENDOR" > "/sys/bus/pci/drivers/pci-stub/new_id" || { unlock "$BR"; fail_exit "couldn't add new_id (pci-stub)"; }

	pci_vfiofy "$PCIDOMAIN"

	unlock "$BR"
}

# Change perms. Meant to run forked.
function serial_perms_forked()
{
	while [[ ! -e "$SERIAL_FILE" ]];
	do
		! ps "$$"  >& /dev/null && return
		sleep 1
	done
	if [[ -n "$SERIAL_USER" ]]; then
		chown "$SERIAL_USER" "$SERIAL_FILE"
		chmod 600 "$SERIAL_FILE"
	fi
	if [[ -n "$SERIAL_GROUP" ]]; then
		chgrp "$SERIAL_GROUP" "$SERIAL_FILE"
		chmod g+rw "$SERIAL_FILE"
	fi
}

# VM descriptor helpers
# Overwrite (or create) descriptor setting
function desc_update_setting ()
{
	local KEY="$1"
	local VALUE="$2"

	local MATCH=$(printf "^#*%q" "$KEY")
	local NEW="$KEY=\"$VALUE\""
	sed -i -e "0,/$MATCH/ {
		s@$MATCH=\?\(.*\)@$NEW ## \1@g
		$ t
		$ a$NEW
		}" "$VM_DESCRIPTOR"
}

# Revert descriptor setting modified by this script
function desc_revert_setting()
{
	local KEY="$1"
	sed -i -e "s/^$KEY=[^#]*## /$KEY=/" "$VM_DESCRIPTOR"
}

function desc_remove_setting()
{
	local KEY="$1"
	sed -i -e "/^$KEY/d" "$VM_DESCRIPTOR"
}

function desc_comment_setting()
{
	local KEY="$1"
	sed -i -e "s/^$KEY/#$KEY/" "$VM_DESCRIPTOR"
}

function monitor_send_cmd ()
{
	echo "$1" | socat STDIN unix:"$MONITOR_FILE"
}

function monitor_send_cmd_read ()
{
	echo "$1" | socat - unix:"$MONITOR_FILE"
}

function monitor_send_sysrq ()
{
	local SYSRQ="$1"
	monitor_send_cmd "sendkey ctrl-alt-sysrq-$SYSRQ"
}

# VM Status
function kvm_status_from_pid
{
	local VM_PID=$@
	test_nodename "$KVM_CLUSTER_NODE" && run_remote "$KVM_CLUSTER_NODE" ps wwp "$VM_PID" || ps wwp "$VM_PID"
}

function kvm_status_vm ()
{
	kvm_init_env "$1"
	test_exist "$PID_FILE" || fail_exit "Error: $VM_NAME doesn't seem to be running."

	local VM_PID="`cat "$PID_FILE"`"

	[[ "$VM_PID" = "error" ]] \
		&& echo "VM $VM_NAME is in error state, attach it for more info" \
		|| kvm_status_from_pid "$VM_PID"
}

function kvm_status ()
{
	if [[ ! "$1" == "all" ]];
	then
		kvm_status_vm "$1"
	else
		# Check that there actually are VMs first.
		ls "$PID_DIR"/*-vm.pid >&/dev/null || fail_exit "No VM yet"

		for KVM_CLUSTER_NODE in `ls -1 $PID_DIR/*-vm.pid|cut -d: -f1|sed -e 's:.*/::'|uniq`
		do
			echo "VMs on $KVM_CLUSTER_NODE:"
			kvm_status_from_pid `cat "$PID_DIR/$KVM_CLUSTER_NODE:"*-vm.pid|grep -v error`

			echo

			grep -l error "$PID_DIR/$KVM_CLUSTER_NODE:"*-vm.pid | sed -e 's!.*:\(.*\)-vm.pid!\1!' | while read VM_NAME; do
				echo "VM $VM_NAME is in error state, attach it for more info"
				echo
			done
		done
	fi
}

function kvm_top ()
{
	local nodelist="{local,$KVM_CLUSTER_NODE}"
	local pattern="$PID_DIR/$nodelist:*-vm.pid"
	pidlist=$(eval cat $pattern 2>/dev/null | sed -e ':a;N;s/\n/,/;ta')
	top -d 2 -cp $pidlist
}

function kvm_cleanup ()
{
	# wait for mount...
	while ! [[ -d "$PID_DIR" ]]; do
		echo "$PID_DIR doesn't exist, waiting..."
		sleep 1
	done

	[[ -n "$PID_DIR" ]] && rm -f "$PID_DIR/$(hostname -s):"*-vm.pid
}

function kvm_shutdown ()
{
	# This function could implement automigrate on host shutdown or similar...
	# We're not really good at knowing what host is up in the cluster and stuff
	# like that though, just a proper stopall is a good start.
	kvm-wrapper list | awk "/Running on $(hostname -s)/ "'{ print $1 }' | \
		while read vm; do
			kvm_init_env "$vm"
			kvm_stop_vm
		done
}

function cleanup ()
{
	local LAST_ELEMENT
	local FD
	local i

	echo "Cleaning up"
	for FD in "${CLEANUP_FD[@]}"; do
		eval "exec $FD<&-"
	done
	while read -r i; do
		eval ${CLEANUP[i]}
	done < <(printf "%s\n" "${!FOO[@]}" | tac)
}

function kvm_start_vm_prep ()
{
	CLEANUP=( )
	CLEANUP_FD=( )

	trap cleanup EXIT

	check_create_dir "$PID_DIR"
	check_create_dir "$MONITOR_DIR"
	check_create_dir "$SERIAL_DIR"
	[[ -n "$KVM_USER" ]] && chown "$KVM_USER" "$PID_DIR" "$MONITOR_DIR" "$SERIAL_DIR"

	[[ -z "$KVM_BIN" ]] && KVM_BIN="/usr/bin/kvm"
	require_exec "$KVM_BIN"

	# More sanity checks: VM running, monitor socket existing, etc.
	if [[ -z "$FORCE" ]]; then
		test_pid_from_file "$PID_FILE" && fail_exit "VM $VM_NAME seems to be running already.\nPID file $PID_FILE exists"
		rm -rf "$MONITOR_FILE"
		rm -rf "$SERIAL_FILE"
		test_socket "$MONITOR_FILE" && fail_exit "Monitor socket $MONITOR_FILE already existing and couldn't be removed"
		test_socket "$SERIAL_FILE" && fail_exit "Serial socket $SERIAL_FILE already existing and couldn't be removed"

		# Fork change_perms
		[[ -n "$SERIAL_USER" ]] || [[ -n "$SERIAL_GROUP" ]] && serial_perms_forked &
	fi

	# backward compatibility transforms
	if [[ -n "$KVM_PREPEND_PARAMS" && -z "${KVMARG_PREPEND_PARAMS[*]}" ]]; then
		read -ra KVMARG_PREPEND_PARAMS <<< "$KVM_PREPEND_PARAMS"
	fi
	if [[ -n "$KVM_ADDITIONNAL_PARAMS" && -z "${KVMARG_ADDITIONNAL_PARAMS[*]}" ]]; then
		read -ra KVMARG_ADDITIONNAL_PARAMS <<< "$KVM_ADDITIONNAL_PARAMS"
	fi

	# build KVM_EXEC_CMD -- wrappers first
	KVM_EXEC_CMD=( )
	[[ -n "$KVM_PIN_PCI" ]] && {
		KVM_PIN_NODE=$(cat /sys/bus/pci/devices/*${KVM_PIN_PCI}/numa_node)
		[[ "$KVM_PIN_NODE" == "-1" || "$KVM_PIN_NODE" == *$'\n'* ]] && \
			fail_exit "$KVM_PIN_PCI does not look like a valid PCI to pin to (cat /sys/bus/pci/devices/*${KVM_PIN_PCI}/numa_node)"
	}

	[[ -n "$KVM_PIN_NODE" && -z "$KVM_NUMACTL_OPT" ]] && \
		KVM_NUMACTL_OPT=( -N "$KVM_PIN_NODE" )

	[[ -n "$KVM_NUMACTL_OPT" ]] && {
		require_exec "$KVM_NUMACTL_BIN"
		KVM_EXEC_CMD+=( "$KVM_NUMACTL_BIN" "${KVM_NUMACTL_OPT[@]}" -- )
	}

	# actual qemu command
	KVM_EXEC_CMD+=( "$KVM_BIN" -name "$VM_NAME,process=\"kvm-$VM_NAME\"" )
	KVM_EXEC_CMD+=( "${KVMARG_PREPEND_PARAMS[@]}" )

	# Build KVM Drives (hdd, cdrom) parameters
	KVM_DRIVE_IF="${KVM_DRIVE_IF:-ide-hd}"

	# backward compatibility
	[[ -n "$KVM_DISK1" ]] && KVM_EXEC_CMD+=( -drive "if=none,id=disk1,file=\"$KVM_DISK1\"$KVM_DRIVE_OPT" -device "${KVM_DRIVE1_IF:-$KVM_DRIVE_IF},drive=disk1" )
	[[ -n "$KVM_DISK2" ]] && KVM_EXEC_CMD+=( -drive "if=none,id=disk2,file=\"$KVM_DISK2\"$KVM_DRIVE_OPT" -device "${KVM_DRIVE2_IF:-$KVM_DRIVE_IF},drive=disk2" )
	[[ -n "$KVM_DISK3" ]] && KVM_EXEC_CMD+=( -drive "if=none,id=disk3,file=\"$KVM_DISK3\"$KVM_DRIVE_OPT" -device "${KVM_DRIVE3_IF:-$KVM_DRIVE_IF},drive=disk3" )
	[[ -n "$KVM_DISK4" ]] && KVM_EXEC_CMD+=( -drive "if=none,id=disk4,file=\"$KVM_DISK4\"$KVM_DRIVE_OPT" -device "${KVM_DRIVE4_IF:-$KVM_DRIVE_IF},drive=disk4" )
	KVM_DISK_IF[0]=${KVM_DISK_IF[0]-$KVM_DRIVE_IF}

	for i in ${!KVM_DISK[@]}; do
		KVM_EXEC_CMD+=( -drive "if=none,id=disk${i},file=${KVM_DISK[i]}${KVM_DISK_OPT[i]-${KVM_DISK_OPT[@]:0:1}}" -device "${KVM_DISK_IF[i]:-${KVM_DISK_IF[@]:0:1}},drive=disk${i}" )
	done

	[[ -n "$KVM_CDROM" ]] && KVM_EXEC_CMD+=( -cdrom "$KVM_CDROM" )
	[[ -n "$KVM_KERNEL" ]] && KVM_EXEC_CMD+=( -kernel "$KVM_KERNEL" )
	[[ -n "$KVM_INITRD" ]] && KVM_EXEC_CMD+=( -initrd "$KVM_INITRD" )
	[[ -n "$KVM_APPEND" ]] && KVM_EXEC_CMD+=( -append "$KVM_APPEND" )

	# If drive is a lv in the main vg, activate the lv
	prepare_disks
	CLEANUP+=("unprepare_disks")

	# backward compatibility - prioritize old values because new ones can come from the global config
	[[ -n "$KVM_MACADDRESS" ]] && {
		KVM_MACADDR=("$KVM_MACADDRESS")
		KVM_IF=("${KVM_NETWORK_MODEL-${KVM_IF[0]}}")
		KVM_BR=("${KVM_BRIDGE-${KVM_BR[0]}}")
	}
	[[ "${KVM_IF[0]}" = "vhost_net" ]] && (KVM_NET_OPT[0]=",vhost=on"; KVM_IF[0]="virtio-net-pci")

	# Iterately build kvmnet string and create tuntaps
	[[ "${#KVM_MACADDR[@]}" != 0 ]] && {
		# not checking KVM_NET_OPT because it _can_ be empty... others will raise an error
		[[ -z "${KVM_BR[@]:0:1}" ]] && fail_exit "No KVM_BR defined"
		[[ -z "${KVM_IF[@]:0:1}" ]] && fail_exit "No KVM_IF defined"
		for i in ${!KVM_MACADDR[@]}; do
			KVM_BR[$i]="${KVM_BR[i]:-${KVM_BR[@]:0:1}}"
			KVM_IF[$i]="${KVM_IF[i]:-${KVM_IF[@]:0:1}}"
			KVM_NET_OPT[$i]="${KVM_NET_OPT[i]-${KVM_NET_OPT[@]:0:1}}"
			KVM_NET_MTU[$i]="${KVM_NET_MTU[i]-${KVM_NET_MTU[@]:0:1}}"

			# handle special cases first
			case "${KVM_IF[i]}" in
			sriov)
				local PCIDOMAIN
				local VFNUM

				sriov "${KVM_BR[i]}"
				CLEANUP+=("pci_unvfiofy \"$PCIDOMAIN\"")

				ip link set "${KVM_BR[i]}" vf "$VFNUM" mac "${KVM_MACADDR[i]}" || fail_exit "Could not set MAC address for vf $VFNUM device ${KVM_BR[i]}"
				CLEANUP+=("ip link set \"${KVM_BR[i]}\" vf \"$VFNUM\" mac 02:00:00:00:00:00")

				KVM_EXEC_CMD+=( -device "vfio-pci,id=net${i},host=${PCIDOMAIN}" )

				continue
				;;

			mlx*-sriov)
				local PCIDOMAIN
				local VFNUM

				sriov "${KVM_BR[i]}"
				CLEANUP+=("pci_unvfiofy \"$PCIDOMAIN\"")

				if [[ "${KVM_IF[i]}" == "mlx4-sriov" ]]; then
					# KVM_MACADDR reused for pkeys as we can't (?) set guid
					ib_sriov_pkeys "${KVM_BR[i]}" "$PCIDOMAIN" "${KVM_MACADDR[i]}"
					CLEANUP+=("ib_unsriov_pkeys \"${KVM_BR[i]}\" \"$PCIDOMAIN\"")
				else
					# KVM_MACADDR relates to child guid
					ib_sriov_guid "${KVM_BR[i]}" "$VFNUM" "${KVM_MACADDR[i]}"
				fi

				KVM_EXEC_CMD+=( -device "vfio-pci,id=net${i},host=${PCIDOMAIN}" )

				continue
				;;
			user:*)
				KVM_EXEC_CMD+=( -netdev user,id=net${i} -device "${KVM_IF[i]#user:},netdev=net${i},mac=${KVM_MACADDR[i]}" )
				continue
				;;
			esac

			local TAPDEV=""
			local VHOSTFD_OPT=""

			# tapdev can only be 15 chars long, if VM_NAME is too long keep start + last 2 chars
			# and pray for no collision...
			[[ $(( ${#VM_NAME} + ${#i} )) -le 10 ]] && \
				TAPDEV=tap-${VM_NAME:0:$((10-${#i}))}-${i} || \
				TAPDEV=tap-${VM_NAME:0:$((8-${#i}))}${VM_NAME:(-2)}-${i}

			if [[ "${KVM_NET_OPT[i]}" == *"vhost=on"* ]] && [[ -n "$KVM_USER" ]]; then
				exec {VHOSTFD}<>/dev/vhost-net
				VHOSTFD_OPT=",vhostfd=${VHOSTFD}"
				CLEANUP_FD+=("${VHOSTFD}")
			fi

			if [[ -n "$KVM_MACVTAP" ]]; then
				local TAPFILE
				local TAPFD

				ip link add link ${KVM_BR[i]} name $TAPDEV address ${KVM_MACADDR[i]} type macvtap mode bridge
				ip link set $TAPDEV ${KVM_NET_MTU[$i]:+mtu ${KVM_NET_MTU[$i]}} up
				CLEANUP+=("ip link del $TAPDEV")

				[[ -e "/sys/class/net/$TAPDEV/ifindex" ]] || fail_exit "Could not create interface $TAPDEV"
				TAPFILE=/dev/tap$(cat "/sys/class/net/$TAPDEV/ifindex")
				exec {TAPFD}<>${TAPFILE}

				CLEANUP_FD+=("${TAPFD}")
				KVM_EXEC_CMD+=( -netdev "type=tap,id=guest${i},fd=${TAPFD}${KVM_NET_OPT[i]}${VHOSTFD_OPT}" -device "${KVM_IF[i]},netdev=guest${i},mac=${KVM_MACADDR[i]}" )
			else
				ip tuntap add dev $TAPDEV mode tap ${KVM_USER+user $KVM_USER}
				ip link set $TAPDEV ${KVM_NET_MTU[$i]:+mtu ${KVM_NET_MTU[$i]}} up
				brctl addif ${KVM_BR[i]} $TAPDEV

				CLEANUP+=("ip tuntap del dev $TAPDEV mode tap")
				KVM_EXEC_CMD+=( -netdev "type=tap,id=guest${i},ifname=${TAPDEV},script=no,downscript=no${KVM_NET_OPT[i]}${VHOSTFD_OPT}" -device "${KVM_IF[i]},netdev=guest${i},mac=${KVM_MACADDR[i]}" )
			fi
		done

		# XXX use -nodefaults instead
		[[ "${KVM_EXEC_CMD[*]}" == *"-net"* ]] || KVM_EXEC_CMD+=( -net none )
	}

	# PCI passthrough assignement
	for i in ${!KVM_PCIASSIGN_DOMAIN[@]}; do
		pci_stubify "${KVM_PCIASSIGN_DOMAIN[$i]}"
		CLEANUP+=("pci_unstubify \"${KVM_PCIASSIGN_DOMAIN[$i]}\"")
		KVM_EXEC_CMD+=( -device "pci-assign,id=${KVM_PCIASSIGN_ID[$i]:-pciassign${i}},host=${KVM_PCIASSIGN_DOMAIN[$i]}" )
	done

	# vfio assignement
	for i in ${!KVM_VFIO_DOMAIN[@]}; do
		pci_vfiofy "${KVM_VFIO_DOMAIN[$i]}"
		CLEANUP+=("pci_unvfiofy \"${KVM_VFIO_DOMAIN[$i]}\"")
		KVM_EXEC_CMD+=( -device "vfio-pci,id=${KVM_VFIO_ID[$i]:-vfio${i}},host=${KVM_VFIO_DOMAIN[$i]}" )
	done

	[[ -n "$KVM_MEM_POLICY" ]] && {
		KVM_EXEC_CMD+=( -m "$KVM_MEM" -object "memory-backend-ram,size=${KVM_MEM},policy=$KVM_MEM_POLICY,id=ram-0${KVM_PIN_NODE:+,host-nodes=$KVM_PIN_NODE}" )
	} || {
		KVM_EXEC_CMD+=( -m "$KVM_MEM" )
	}

	# Monitor/serial devices
	KVM_EXEC_CMD+=( -monitor "unix:$MONITOR_FILE,server,nowait" )
	KVM_EXEC_CMD+=( -pidfile "$PID_FILE" )
	KVM_EXEC_CMD+=( -serial chardev:char1 -chardev "socket,id=char1,path=$SERIAL_FILE,server,nowait,telnet" )
	KVM_EXEC_CMD+=( -device virtio-rng-pci,max-bytes=1024,period=1000 )

	# Backward compat: support full arg with space or short option only
	if [[ "$KVM_BOOTDEVICE" == *" "* ]]; then
		local KVMARG_BOOTDEVICE=( )
		read -ra KVMARG_BOOTDEVICE <<< "$KVM_BOOTDEVICE"
		KVM_EXEC_CMD+=( "${KVMARG_BOOTDEVICE[@]}" )
	elif [[ -n "$KVM_BOOTDEVICE" ]]; then
		KVM_EXEC_CMD+=( -boot "order=$KVM_BOOTDEVICE" )
	fi
	if [[ "$KVM_KEYMAP" == *" "* ]]; then
		local KVMARG_KEYMAP=( )
		read -ra KVMARG_KEYMAP <<< "$KVM_KEYMAP"
		KVM_EXEC_CMD+=( "${KVMARG_KEYMAP[@]}" )
	elif [[ -n "$KVM_KEYMAP" ]]; then
		KVM_EXEC_CMD+=( -k "$KVM_KEYMAP" )
	fi
	if [[ -n "$KVM_OUTPUT" ]]; then
		local KVMARG_OUTPUT=( )
		read -ra KVMARG_OUTPUT <<< "$KVM_OUTPUT"
		KVM_EXEC_CMD+=( "${KVMARG_OUTPUT[@]}" )
	fi
	[[ -n "$KVM_SANDBOX" ]] && KVM_EXEC_CMD+=( -sandbox "$KVM_SANDBOX" )

	KVM_EXEC_CMD+=( "${KVMARG_ADDITIONNAL_PARAMS[@]}" )

	CLEANUP+=("rm -f \"$PID_FILE\" \"$MONITOR_FILE\" \"$SERIAL_FILE\"")
}

function kvm_start_vm_here()
{
	# Now run kvm
	echo "${KVM_EXEC_CMD[*]}"
	echo ""
	echo ""
	if [[ -n "$KVM_USER" ]]; then
		su $KVM_USER -s /bin/sh -c "$(printf "%q " "${KVM_EXEC_CMD[@]}")"
	else
		"${KVM_EXEC_CMD[@]}"
	fi

	local KVM_RETURN_VALUE="$?"

	[[ "$KVM_RETURN_VALUE" != "0" ]] && fail_exit "qemu returned $KVM_RETURN_VALUE, read above"

	return $KVM_RETURN_VALUE
}

# Main function: start a virtual machine
function kvm_start_vm ()
{
	local KVM_EXEC_CMD

	kvm_start_vm_prep
	kvm_start_vm_here
}

function kvm_stop_vm ()
{
	test_exist "$PID_FILE" || fail_exit "VM $VM_NAME doesn't seem to be running.\nPID file $PID_FILE not found"
	test_socket_rw "$MONITOR_FILE" || fail_exit "Monitor socket $MONITOR_FILE not existing or not writable"

	KVM_WAIT_SHUTDOWN=${KVM_WAIT_SHUTDOWN:-20}

	# Send monitor command through unix socket
	echo "Trying to powerdown the VM $VM_NAME first, might take some time (up to $KVM_WAIT_SHUTDOWN sec)"
	monitor_send_cmd "system_powerdown"
	echo -n "Waiting ..."

	# Now wait for it
	local ELAPSED=0
	ELAPSED=$(wait_test_timelimit $KVM_WAIT_SHUTDOWN "! test_file $PID_FILE")
	local PROPER=$?
	echo " elapsed time: $ELAPSED sec"

	if [[ $PROPER -eq 0 ]];
	then
		echo "VM powerdown properly :)"
	else

		echo "Trying with magic-sysrq ... (10sec)"
		monitor_send_sysrq r && sleep 2
		monitor_send_sysrq e && sleep 2
		monitor_send_sysrq i && sleep 2
		monitor_send_sysrq s && sleep 2
		monitor_send_sysrq u && sleep 2
		monitor_send_sysrq o && sleep 2

		if test_file "$PID_FILE"
		then
			echo "Trying to monitor-quit the qemu instance."
			monitor_send_cmd "quit" && sleep 2

			if test_file "$PID_FILE"
			then
				# kill - SIGTERM
				local KVM_PID="`cat $PID_FILE`"
				echo "Now trying to terminate (SIGTERM) $VM_NAME, pid $KVM_PID"
				kill "$KVM_PID"
			fi
		fi
	fi

	! test_file "PID_FILE" && echo "VM $VM_NAME is now down."

	return 0
}

function kvm_run_disk ()
{
	KVM_RUNDISK=1 kvm_init_env "run_disk_$$"
	KVM_DISK[0]="$1"
	KVM_IF[0]="user:virtio-net-pci"
	KVM_MACADDR[0]=$(random_mac)

	kvm_start_vm
}

function kvm_start_screen ()
{
	check_create_dir "$RUN_DIR"
	eval KVM_SCREEN="yes" $SCREEN_START_ATTACHED "$SCREEN_SESSION_NAME" $SCREEN_EXTRA_OPTS "$SCRIPT_PATH" start-here "$VM_NAME"
}

function kvm_start_screen_detached ()
{
	eval KVM_SCREEN="yes" $SCREEN_START_DETACHED "$SCREEN_SESSION_NAME" $SCREEN_EXTRA_OPTS "$SCRIPT_PATH" start-here "$VM_NAME"
}

function kvm_attach_screen ()
{
	! test_exist "$PID_FILE" && fail_exit "Error: $VM_NAME doesn't seem to be running."
	$SCREEN_ATTACH "$SCREEN_SESSION_NAME" $SCREEN_EXTRA_OPTS
}

function kvm_monitor ()
{
	! test_exist "$PID_FILE" && fail_exit "Error: $VM_NAME doesn't seem to be running."
	! test_socket_rw "$MONITOR_FILE" && fail_exit "Error: could not open monitor socket $MONITOR_FILE."
	echo "Attaching monitor unix socket (using socat). Press ^D (EOF) to exit" >&2
	local socatin="-"
	tty >/dev/null 2>&1 && socatin="READLINE"
	socat $socatin unix:"$MONITOR_FILE"
	echo "Monitor exited" >&2
}

function kvm_serial ()
{
	! test_exist "$PID_FILE" && fail_exit "Error: $VM_NAME doesn't seem to be running."
	! test_socket_rw "$SERIAL_FILE" && fail_exit "Error: could not open serial socket $SERIAL_FILE."
	echo "Attaching serial console unix socket (using socat)." >&2
	tty >/dev/null 2>&1 && echo "You might want to run this after logging in: $(stty -a | awk '/rows/ { print "stty rows " $5 " cols "$7 }' | tr -d ';')" >&2
	echo "Press ^] to exit" >&2
	local socatin="-"
	tty >/dev/null 2>&1 && socatin="-,IGNBRK=0,BRKINT=0,PARMRK=0,ISTRIP=0,INLCR=0,IGNCR=0,ICRNL=0,IXON=0,OPOST=1,ECHO=0,ECHONL=0,ICANON=0,ISIG=0,IEXTEN=0,CSIZE=0,PARENB=0,CS8,escape=0x1d" 
	socat $socatin unix:"$SERIAL_FILE"
	[[ "xx$?" != "xx0" ]] && fail_exit "socat must be of version > 1.7.0 to work"
	stty sane
	echo "Serial console exited" >&2
}

function kvm_list ()
{
	# Check that there actually are VMs first.
	ls "$VM_DIR"/*-vm >&/dev/null || fail_exit "No VM to list yet"

	echo "Available VM descriptors:"
	for file in "$VM_DIR"/*-vm
	do
		kvm_init_env `basename "${file%"-vm"}"`
		if [[ -z "$1" || "$1" == "$KVM_CLUSTER_NODE" ]]; then
			local VM_STATUS="Halted"

			# We check if it exists first if no read access
			test_exist "$PID_FILE" && VM_STATUS="Running"
			test_file "$PID_FILE" && [[ "$(cat "$PID_FILE")" = "error" ]] \
				&& VM_STATUS="Error"

			printf "\t%-20s\t$VM_STATUS\ton ${KVM_CLUSTER_NODE:-local}\n" "$VM_NAME"
		fi
	done
}

function kvm_edit_descriptor ()
{
	EDITOR=${EDITOR-vim}
	kvm_init_env "$1"
	test_file "$VM_DESCRIPTOR" && "$EDITOR" "$VM_DESCRIPTOR"
}

function kvm_create_descriptor ()
{
	VM_NAME="$1"
	VM_DESCRIPTOR="$VM_DIR/$VM_NAME-vm"
	test_exist "$VM_DESCRIPTOR" && fail_exit "Error: $VM_NAME already exists ($VM_DESCRIPTOR found)"

	touch "$VM_DESCRIPTOR"
	test_exist "$VM_DESCRIPTOR" || fail_exit "Error: Could not create $VM_NAME descriptor ($VM_DSECRIPTOR)"
	echo "# VM $VM_NAME file descriptor" 			>> "$VM_DESCRIPTOR"
	echo "# Created: `date` on $HOSTNAME by $USER" >> "$VM_DESCRIPTOR"
	echo "" 										>> "$VM_DESCRIPTOR"


	awk '/#xxDEFAULTxx#/,0 { print "#" $0}' $CONFFILE|grep -v "#xxDEFAULTxx#" >> "$VM_DESCRIPTOR"

	sed -i 's/#KVM_MACADDR\[0\]="`random_mac`/KVM_MACADDR[0]="'`random_mac`'/g' "$VM_DESCRIPTOR"
	#sed -i 's/#KVM_CLUSTER_NODE="`hostname -s`/KVM_CLUSTER_NODE="'`hostname -s`'/g' "$VM_DESCRIPTOR"
	local NODENAME=$(grep KVM_CLUSTER_NODE "$VM_DESCRIPTOR" | cut -d= -f2)
	sed -i 's/#KVM_CLUSTER_NODE=.*/KVM_CLUSTER_NODE="'$(eval echo "$NODENAME")'"/g' "$VM_DESCRIPTOR"

	if [[ -n "$3" ]]; then
		qcow_create_disk "$2" "$3"
	elif [[ -n "$2" ]]; then
		desc_update_setting "KVM_DISK[0]" "$2"
	fi


	echo "VM $VM_NAME created. Descriptor: $VM_DESCRIPTOR"
}

function kvm_bootstrap_vm ()
{

	cleanup()
	{
		set +e
		echo "Cleaning up the mess"
		if [ ${#CLEANUP[*]} -gt 0 ]; then
			LAST_ELEMENT=$((${#CLEANUP[*]}-1))
			for i in `seq $LAST_ELEMENT -1 0`; do
				eval ${CLEANUP[$i]}
			done
		fi
	}

	CLEANUP=( )

	set -e
	trap cleanup EXIT

	require_exec "kpartx"
	check_create_dir "$BOOT_IMAGES_DIR"
	check_create_dir "$CACHE_DIR"
	check_create_dir "$LOGDIR"

	kvm_init_env "$1"
	test_exist "$PID_FILE" && fail_exit "Error: $VM_NAME seems to be running. Please stop it before trying to bootstrap it."

	if [[ -n "$2" ]]; then
		BOOTSTRAP_DISTRIB="$2"   # The variable is already set in the config file otherwise.
	fi
	BOOTSTRAP_SCRIPT="$BOOTSTRAP_DIR/$BOOTSTRAP_DISTRIB/bootstrap.sh"
	test_file "$BOOTSTRAP_SCRIPT" || fail_exit "Couldn't read $BOOTSTRAP_SCRIPT to bootstrap $VM_NAME as $BOOTSTRAP_DISTRIB"
	source "$BOOTSTRAP_SCRIPT"

	prepare_disks
	CLEANUP+=("unprepare_disks")
	if ! test_blockdev "${KVM_DISK[0]}"
	then
		require_exec "$KVM_NBD_BIN"
		test_file "${KVM_DISK[0]}" || fail_exit "\"${KVM_DISK[0]}\" appears to be neither a blockdev nor a regular file."
		echo "Attempting to connect the disk image to an nbd device."
		kvm_nbd_connect "${KVM_DISK[0]}"
		CLEANUP+=("kvm_nbd_disconnect \"${KVM_DISK[0]}\"")
		local BOOTSTRAP_DEVICE=$(nbd_img_link "${KVM_DISK[0]}")
		sleep 1 #needed to give time to the nbd to really connect
	else
		local BOOTSTRAP_DEVICE="${KVM_DISK[0]}"
	fi

	echo "Starting to bootstrap $VM_NAME as $BOOTSTRAP_DISTRIB on disk $BOOTSTRAP_DEVICE"
	bootstrap_fs "$BOOTSTRAP_DEVICE"
	sync

	cleanup
	trap - EXIT
	set +e

	echo "Bootstrap ended."
	return 0
}

function kvm_migrate_vm ()
{
	local REMOTE_NODE="$2"

	! test_file "$PID_FILE" && fail_exit "Error: $VM_NAME doesn't seem to be running."
	! test_socket_rw "$MONITOR_FILE" && fail_exit "Error: could not open monitor socket $MONITOR_FILE."
	[[ "$KVM_CLUSTER_NODE" == "$REMOTE_NODE" ]] && fail_exit "Error: $VM_NAME already runs on $REMOTE_NODE!"
	[[ -z "`get_cluster_host $REMOTE_NODE`" ]] && fail_exit "Error: Unknown host $REMOTE_NODE!"

	[[ -n "${KVM_PCIASSIGN_DOMAIN[@]}" ]] && fail_exit "Cannot migrate vm with pci passthrough!"

	# Update VM configuration with new node
	desc_update_setting "KVM_CLUSTER_NODE" "$REMOTE_NODE"
	PORT=$((RANDOM%1000+4000))

	# Launch new instance (on pre-configured node)
	if ! "$SCRIPT_PATH" receive-migrate "$VM_NAME" "$PORT"; then
		desc_revert_setting "KVM_CLUSTER_NODE"
		fail_exit "Could not receive migrate on remote host"
	fi

	sleep 0.5

	# default speed is 32MiB/s, apparently. Set it higher.
	monitor_send_cmd "migrate_set_speed 100g"
#	monitor_send_cmd "migrate \"exec: ssh `get_cluster_host $REMOTE_NODE` socat - unix:$RUN_DIR/migrate-$REMOTE_NODE.sock\""
	monitor_send_cmd "migrate ${KVM_MIGRATE_TRANSPORT:-tcp}:`get_cluster_host $REMOTE_NODE`:$PORT"
	while ! echo "info migrate" | socat - unix:"$MONITOR_FILE" | grep -q "Migration status: completed"; do
		sleep 1
	done
	monitor_send_cmd "quit"
}

function kvm_receive_migrate_vm ()
{
	local PORT="$2"

	eval KVM_SCREEN="yes" $SCREEN_START_DETACHED "$SCREEN_SESSION_NAME" $SCREEN_EXTRA_OPTS "$SCRIPT_PATH" receive-migrate-here "$VM_NAME" "$PORT"

	# Wait for the receiving qemu is ready.
	while ! monitor_send_cmd "info status" >&/dev/null; do
		sleep 0.1
	done
}

function kvm_receive_migrate_here_vm ()
{
	local PORT="$2"

	test_exec "$(which firewall-cmd)" && firewall-cmd --add-port $2/tcp --timeout=1h

#	KVM_ADDITIONNAL_PARAMS+=" -incoming unix:$RUN_DIR/migrate-$VM_NAME.sock"
	KVM_ADDITIONNAL_PARAMS+=" -incoming ${KVM_MIGRATE_TRANSPORT:-tcp}:`get_cluster_host $(hostname -s)`:$PORT"
	FORCE="yes"
	kvm_start_vm "$VM_NAME"
}

kvm_save_state_vm ()
{
	! test_exist "$PID_FILE" && fail_exit "Error: $VM_NAME doesn't seem to be running."
	! test_socket_rw "$MONITOR_FILE" && fail_exit "Error: could not open monitor socket $MONITOR_FILE."
	monitor_send_cmd "stop"
	monitor_send_cmd "migrate_set_speed 100g"
	monitor_send_cmd "migrate \"exec:gzip -c > $CACHE_DIR/$VM_NAME-state.gz\""
	while ! echo "info migrate" | socat - unix:"$MONITOR_FILE" | grep -q "Migration status: completed"; do
		sleep 1
	done
	monitor_send_cmd "quit"
}

kvm_load_state_vm ()
{
	KVM_ADDITIONNAL_PARAMS+=" -incoming \"exec: gzip -c -d $CACHE_DIR/$VM_NAME-state.gz\""
	FORCE="yes"
	kvm_start_vm "$2"
}


function kvm_build_vm ()
{
	local USER_OPTIONS=( )

	while [[ "$#" -gt 1 ]]; do
		case "$1" in
			"-s"|"--size")
				USER_OPTIONS+=("ROOT_SIZE")
				USER_OPTIONS+=("$2")
				shift; shift
				;;
			"-m"|"--mem"|"--memory")
				USER_OPTIONS+=("KVM_MEM")
				USER_OPTIONS+=("$2")
				shift; shift
				;;
			"-c"|"--cpu"|"--smp")
				USER_OPTIONS+=("KVM_CPU_NUM")
				USER_OPTIONS+=("$2")
				shift; shift
				;;
			"--swap")
				USER_OPTIONS+=("SWAP_SIZE")
				USER_OPTIONS+=("$2")
				shift; shift
				;;
			"-f"|"--flavor")
				USER_OPTIONS+=("BOOTSTRAP_FLAVOR")
				USER_OPTIONS+=("$2")
				shift; shift
				;;
			"-e"|"--edit"|"--edit-conf")
				local EDIT_CONF="yes"
				shift
				;;
			"--no-bootstrap")
				local DISABLE_BOOTSTRAP="yes"
				shift
				;;
			*)
				echo "Unknown argument: $1"
				echo "Exiting"
				print_help "create"
				return 1
				;;
		esac
	done
	if [[ ! "$#" -eq 1 ]]; then print_help "create"; return 1; fi

	VM_NAME="$1"

	if [[ "$VM_NAME" == -* ]]; then
		echo "VM name $VM_NAME starts with a dash, you probably didn't want that"
		print_help "create"
		return 1
	fi

	test_file "$AUTOCONF_SCRIPT" || fail_exit "Couldn't read autoconfiguration script $AUTOCONF_SCRIPT\n"

	kvm_create_descriptor "$VM_NAME"

	source "$AUTOCONF_SCRIPT"

	if [ ${#USER_OPTIONS[*]} -gt 0 ]; then
		LAST_ELEMENT=$((${#USER_OPTIONS[*]}-2))
		for i in `seq 0 2 $LAST_ELEMENT`; do
			desc_update_setting "${USER_OPTIONS[$i]}" "${USER_OPTIONS[$((i+1))]}"
		done
	fi

	if [[ -n "$EDIT_CONF" ]]; then
		kvm_edit_descriptor "$VM_NAME"
	fi

	kvm_init_env "$VM_NAME"

	if [[ -n "$BOOTSTRAP_DISK_DIR" ]]; then
		qcow_create_disk "$BOOTSTRAP_DISK_DIR/vm-$VM_NAME" "$ROOT_SIZE"
	else
		lvm_create_disk "$VM_NAME"
	fi
	if [[ -z "$DISABLE_BOOTSTRAP" ]]; then
		# PREBOOTSTRAP_SCRIPT="$BOOTSTRAP_DIR/$BOOTSTRAP_DISTRIB/prebootstrap.sh"
		# test_file "$PREBOOTSTRAP_SCRIPT" && source "$PREBOOTSTRAP_SCRIPT" && prebootstrap

		kvm_bootstrap_vm "$VM_NAME"

		echo "Will now start VM $VM_NAME"
		"$SCRIPT_PATH" start "$VM_NAME"
	else
		echo "VM created."
	fi
}

function kvm_balloon_vm ()
{
	! test_exist "$PID_FILE" && fail_exit "Error: $VM_NAME doesn't seem to be running."
	! test_socket_rw "$MONITOR_FILE" && fail_exit "Error: could not open monitor socket $MONITOR_FILE."
	monitor_send_cmd "balloon $1"
}

function kvm_pci_assign_vm ()
{
	! test_exist "$PID_FILE" && fail_exit "Error: $VM_NAME doesn't seem to be running."
	! test_socket_rw "$MONITOR_FILE" && fail_exit "Error: could not open monitor socket $MONITOR_FILE."

	local DOMAIN="$1"
	pci_stubify "$DOMAIN"
	local devid=""
	[[ -n "$2" ]] && devid=",id=$2"

	monitor_send_cmd "device_add pci-assign${devid},host=$DOMAIN"
}

function kvm_remove_vm ()
{

	test_exist "$PID_FILE" && fail_exit "Error: $VM_NAME seems to be running. Please stop it before trying to remove it."

	[[ -n "$KVM_DISK1" ]] && KVM_DISK+=("$KVM_DISK1")
	[[ -n "$KVM_DISK2" ]] && KVM_DISK+=("$KVM_DISK2")
	[[ -n "$KVM_DISK3" ]] && KVM_DISK+=("$KVM_DISK3")
	[[ -n "$KVM_DISK4" ]] && KVM_DISK+=("$KVM_DISK4")
	for i in ${!KVM_DISK[@]}; do
		if lvdisplay "${KVM_DISK[i]}" >&/dev/null; then
			if lvremove "${KVM_DISK[i]}"; then
				unset KVM_DISK[$i]
			fi
		fi
	done

	if [ ${#KVM_DISK[*]} -gt 0 ]; then
		echo "The VM $VM_NAME used the following disks (NOT removed by $SCRIPT_NAME):"
		for DRIVE in "${KVM_DISK[@]}"; do
			echo $DRIVE
		done
	fi
	rm -f "$VM_DESCRIPTOR"
	test_exist "$VM_DESCRIPTOR" && fail_exit "Failed to remove descriptor $VM_DSCRIPTOR."
}

function kvm_vncviewer_vm ()
{
	local PORT LOCALPORT SSHPID
	kvm_init_env "$1"

	! test_exist "$PID_FILE" && fail_exit "Error: $VM_NAME doesn't seem to be running."

	PORT=$(echo "info vnc" | kvm-wrapper monitor $VM_NAME 2>&1 | sed -ne 's/.*address: .*:\([0-9]*\).*/\1/p' | head -n 1 )

	[[ -z "$PORT" ]] && fail_exit "Error: couldn't find vnc port used"

	if test_nodename "$KVM_CLUSTER_NODE"; then
		while
			LOCALPORT=$((RANDOM%1000+4000))
			ss -nplt \( sport = :$LOCALPORT \) | grep -q $LOCALPORT
		do :; done

		SSH_OPTS="-L $LOCALPORT:localhost:$PORT -N" run_remote "$KVM_CLUSTER_NODE" &
		SSHPID=$!

		trap "kill $SSHPID" EXIT
		while ! ss -nplt \( sport = :$LOCALPORT \) | grep -q $LOCALPORT; do
			sleep 0.1
		done
		vncviewer localhost:$LOCALPORT || fail_exit "Error: couldn't start vncviewer"

		kill $SSHPID
	else
		vncviewer localhost:$PORT
	fi
}

function kvm_edit_conf ()
{
	EDITOR=${EDITOR-vim}
	eval "$EDITOR" "$CONFFILE"
}

function print_help ()
{
	case "$1" in
		"create")
	echo -e "Usage $SCRIPT_NAME create [flags] virtual-machine"
	echo
	echo -e "Flags are:"
	echo -e "   -m size, --mem size:    Specify how much RAM you want the system to have"
	echo -e "   -s size, --size size:   Specify how big the disk should be in MB"
	echo -e "   -e, --edit:             If you want to edit the descriptor after autoconfiguration"
	echo -e "   --no-bootstrap:         Do not run bootstrap"
	echo -e "   -c num, --cpu num:      Number of cpu the system should have"
	echo -e "   --swap size:            Size of the swap in MB"
	echo -e "   --flavor name, -f name: Flavor of the debian release (lenny, squeeze..)"
	echo
	echo -e " More to come ?"
	;;
		*)
	echo -e "Usage: $SCRIPT_NAME {start|screen|stop} virtual-machine"
	echo -e "       $SCRIPT_NAME {attach|monitor|serial} virtual-machine"
	echo -e "       $SCRIPT_NAME {save-state|load-state} virtual-machine"
	echo -e "       $SCRIPT_NAME migrate virtual-machine dest-node"
	echo -e ""
	echo -e "       $SCRIPT_NAME status [virtual-machine]"
	echo -e "       $SCRIPT_NAME list [node]"
	echo -e "       $SCRIPT_NAME top"
	echo -e "       $SCRIPT_NAME conf"
	echo
	echo -e "       $SCRIPT_NAME balloon virtual-machine target_RAM"
	echo -e "       $SCRIPT_NAME pci-assign virtual-machine pci-domain [devname]"

	echo -e "       $SCRIPT_NAME create [flags] virtual-machine #for flag list, try $SCRIPT_NAME help create"
	echo -e "       $SCRIPT_NAME create-desc virtual-machine [diskimage [size]]"
	echo -e "       $SCRIPT_NAME bootstrap virtual-machine"
	echo -e "       $SCRIPT_NAME edit virtual-machine"
	echo -e "       $SCRIPT_NAME remove virtual-machine"
	;;
	esac
	exit 2
}

test_dir "$ROOTDIR" || fail_exit "Couldn't open kvm-wrapper's root directory:\n$ROOTDIR"
test_file "$CONFFILE" || fail_exit "Couldn't open kvm-wrapper's configuration file:\n$CONFFILE"

# Load default configuration file
source "$CONFFILE"

test_file "$CLUSTER_CONF" && source "$CLUSTER_CONF"

# Check VM descriptor directory
test_dir "$VM_DIR" || fail_exit "Couldn't open VM descriptor directory:\n$VM_DIR"

# if we're being sourced, don't parse arguments
[[ $(caller | cut -d' ' -f1) != "0" ]] && return 0

if [[ $# -eq 0 ]]; then
	print_help;
	exit 0;
fi

case "$1" in
	list)
		kvm_list "$2"
		exit 0
		;;
	status)
		if [[ -n "$2" ]]; then 
			kvm_status "$2"
		else kvm_status "all"; fi
		exit 0
		;;
	top)
		kvm_top
		exit 0
		;;
	rundisk)
		if [[ $# -eq 2 ]]; then
			kvm_run_disk "$2"
		else print_help; fi
		exit 0
		;;
	edit)
		if [[ $# -eq 2 ]]; then
			kvm_edit_descriptor "$2"
		else print_help; fi
		exit 0
		;;
	create-desc*)
		if [[ $# -ge 2 ]]; then
			kvm_create_descriptor "$2" "$3" "$4"
		else print_help; fi
		exit 0
		;;
	create|build)
		if [[ $# -ge 2 ]]; then
			shift
			kvm_build_vm $@
		else print_help; fi
		exit 0
		;;
	conf)
		kvm_edit_conf
		exit 0
		;;
	vncviewer)
		if [[ $# -ge 2 ]]; then
			kvm_vncviewer_vm "$2" "$3"
		else print_help; fi
		exit 0
		;;
	cleanup)
		kvm_cleanup
		exit 0
		;;
	shutdown)
		kvm_shutdown
		exit 0
		;;
	help)
		shift
		print_help $@
		exit 0
		;;
esac

if [[ $# -le 1 ]]; then
	print_help
	exit 0
fi
kvm_init_env "$2"

test_nodename "$KVM_CLUSTER_NODE" && { run_remote $KVM_CLUSTER_NODE kvm-wrapper $@; exit $?; }

# Argument parsing
case "$1" in
	remove)
		if [[ $# -eq 2 ]]; then
			kvm_remove_vm "$2"
		else print_help; fi
		;;
	migrate)
		if [[ $# -eq 3 ]]; then
			kvm_migrate_vm "$2" "$3"
		else print_help; fi
		;;
	receive-migrate-here)
		if [[ $# -eq 3 ]]; then
			kvm_receive_migrate_here_vm "$2" "$3"
		else print_help; fi
		;;
	receive-migrate)
		if [[ $# -eq 3 ]]; then
			kvm_receive_migrate_vm "$VM_NAME" "$3"
		else print_help; fi
		;;
	save-state)
		if [[ $# -eq 2 ]]; then
			kvm_save_state_vm "$2"
		else print_help; fi
		;;
	load-state)
		if [[ $# -eq 2 ]]; then
			check_create_dir "$RUN_DIR"
			eval KVM_SCREEN="yes" $SCREEN_START_ATTACHED "$SCREEN_SESSION_NAME" $SCREEN_EXTRA_OPTS "$SCRIPT_PATH" load-state-here "$VM_NAME"
		else print_help; fi
		;;
	load-state-here)
		if [[ $# -eq 2 ]]; then
			kvm_load_state_vm "$2"
		else print_help; fi
		;;
	balloon)
		if [[ $# -eq 3 ]]; then
			kvm_balloon_vm "$3"
		else print_help; fi
		;;
	pci-assign)
		if [[ $# -eq 3 ]]; then
			kvm_pci_assign_vm "$3"
		elif [[ $# -eq 4 ]]; then
			kvm_pci_assign_vm "$3" "$4"
		else print_help; fi
		;;

	restart)
		if [[ $# -eq 2 ]]; then
			kvm_stop_vm "$2"
			kvm_start_screen "$2"
		else print_help; fi
		;;
	start)
		if [[ $# -eq 2 ]]; then
			kvm_start_screen "$2"
		else print_help; fi
		;;
	start-here)
		if [[ $# -eq 2 ]]; then
			kvm_start_vm "$2"
		else print_help; fi
		;;
	screen)
		if [[ $# -eq 2 ]]; then
			kvm_start_screen_detached "$2"
		else print_help; fi
		;;
	attach)
		if [[ $# -eq 2 ]]; then
			kvm_attach_screen "$2"
		else print_help; fi
		;;
	monitor)
		if [[ $# -eq 2 ]]; then
			kvm_monitor "$2"
		else print_help; fi
		;;
	serial)
		if [[ $# -eq 2 ]]; then
			kvm_serial "$2"
		else print_help; fi
		;;
	stop)
		if [[ $# -eq 2 ]]; then
			kvm_stop_vm "$2"
		else print_help; fi
		;;
	diag)
		monitor_send_cmd "nmi"
		;;
	bootstrap)
		if [[ $# -ge 2 ]]; then
			kvm_bootstrap_vm "$2" "$3"
		else print_help; fi
		;;
	create-disk)
		lvm_create_disk "$2"
		;;
	mount-disk)
		lvm_mount_disk "$2"
		;;
	umount-disk)
		lvm_umount_disk "$2"
		;;
	*)
		print_help
		;;
esac