summaryrefslogtreecommitdiffstats
path: root/remote/modules/vmchooser/data/opt/openslx/scripts/vmchooser-run_virt
blob: 2f3a94036db18510a5d55d6176738c32ea0ce999 (plain) (blame)
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
#!/bin/bash
# Full bash required
# -----------------------------------------------------------------------------
# Copyright (c) 2007..2010 - RZ Uni FR
# Copyright (c) 2007..2013 - OpenSLX GmbH
#
# This program is free software distributed under the GPL version 2.
# See http://openslx.org/COPYING
#
# If you have any feedback please consult http://openslx.org/feedback and
# send your suggestions, praise, or complaints to feedback@openslx.org
#
# General information about OpenSLX can be found at http://openslx.org/
# -----------------------------------------------------------------------------
# run-virt.sh
#    - This is the generic wrapper for the several virtualization solutions.
#      The idea is to setup a set of variables used by at least two different
#      tools and then include the specific plugin which configures the speci-
#      fied virtualization tool.
################################################################################

################################################################################
### Define default dirs / get configs
################################################################################

VMCHOOSER_DIR="/opt/openslx/vmchooser"
VMCHOOSER_CONF_DIR="$VMCHOOSER_DIR/config"

# include general configuration from vmchooser
[ -f "$VMCHOOSER_CONF_DIR/vmchooser.conf" ] && . "$VMCHOOSER_CONF_DIR/vmchooser.conf"
# load general virtualization information
[ -f "$VMCHOOSER_CONF_DIR/virtualization.conf" ] && . "$VMCHOOSER_CONF_DIR/virtualization.conf"
# Load general openslx config
[ -f "/opt/openslx/config" ] && . "/opt/openslx/config"

################################################################################
### Functions used throughout the script
################################################################################

# function to write to stdout and logfile
LOGFILE="/var/log/openslx/run-virt.${USER}.$$.log"
writelog () {
	# write to stdout
	echo -e "$1"
	# log into file
	echo -e "$1" >> "${LOGFILE}"
}

# Clean exit will be called at the end of this script
cleanexit () {
	sleep 1
	# remove config dirs when exit
	if echo "${RMDIRS}" 2>/dev/null | grep -q "${xmlvirt}"; then
		writelog "${xmlvirt} exited. Cleaning up... \c"
		rm -rf -- ${RMDIRS} >/dev/null 2>&1
		writelog "done"
	fi
	# Disconnect dnbd3 device
	if [ -n "$dnbd3" ]; then
		for timeout in 1 1 2; do
			dnbd3-client -d "$dnbd3" -c -d "$dnbd3" -c && break
			writelog "dnbd3 still busy...."
			sleep "$timeout"
		done
	fi
	# Kill LPD
	kill "$PID_LPD"
	# Remove spool directory for printjobs from VM
	[ -n "${SPOOLDIR}" ] && rm -rf -- "${SPOOLDIR}"
	
	[ $# -gt 0 ] && exit "$1"
	exit 129 # No exit code was given :/
}

function rv_clean_string ()
{
	if [ "$#" -ge 1 ]; then
		echo "$@" | tr '[A-Z]' '[a-z]' | tr -d -c '[a-z0-9]'
	else
		tr '[A-Z]' '[a-z]' | tr -d -c '[a-z0-9]'
	fi
}

trap cleanexit SIGINT SIGTERM

# check for important files used
filecheck ()
{
	filecheck=$(LANG=us ls -lh ${diskfile} 2>&1)
	writelog "Filecheck:\n${filecheck}\n"
	noimage=$(echo ${filecheck} | grep -i "no such file or directory" | wc -l)
	rightsfile=${diskfile}
	
	# check if link
	if [ -L "${diskfile}" ]; then
		# take link target
		rightsfile=$(ls -lh ${diskfile} 2>&1 | awk -F '-> *' '{print $2}')
		rightsfile=${vmdir}/${rightsfile}
		filecheck=$(LANG=us ls -lh ${rightsfile} 2>&1)
	fi
	
	# does file exist
	if [ "${noimage}" -ge "1" ]; then
		writelog "Virtual Machine Image Problem:\c "
		writelog "\tThe image you've specified doesn't exist."
		writelog "Filecheck says:\c "
		writelog "\t\t${diskfile}:\n\t\t\tNo such file or directory"
		writelog "Hint:\c "
		writelog "\t\t\tCompare spelling of the image with your options.\n"
		exit 1
	fi
	
	# readable by calling user
	if ! [ -r "${diskfile}" >/dev/null 2>&1 \
		-o -r "${diskfile}" >/dev/null 2>&1 ]; then
		writelog "Vmware Image Problem:\c "
		writelog "\tThe image you've specified has wrong rights."
		writelog "Filecheck says:\t\t$(echo ${filecheck} \
		| awk '{print $1" "$3" "$4}') ${rightsfile}"
		writelog "Hint:\t\t\tChange rights with: chmod a+r ${rightsfile}\n"
		exit 1
	fi
	
	# writable (for persistent-mode)?
	if ! [ -w "${diskfile}" >/dev/null 2>&1 \
	-o -w "${diskfile}" >/dev/null 2>&1 ] \
	&& [ "${np}" = "independent-persistent" ]; then
		writelog "Vmware Image Problem:\c "
		writelog "\tThe image you have specified has wrong rights."
		writelog "Filecheck says:\t\t$(echo ${filecheck} \
		| awk '{print $1" "$3" "$4}') ${rightsfile}"
		writelog "Hint:\t\t\tUse nonpersistent-mode or change rights to rw\n"
		exit 1
	fi
}

################################################################################
### Get XML file and dir
################################################################################

## Added for persistent support.
diskmode='nonpersistent'
if [[ "$(grep --extended-regexp \
      '< *short_description *param=".+ --persistent--"' "$1")" ]]; then
    diskmode='persistent'
    imageFilePath="$(grep -io '<image_path param=.*"' "$1" | sed -e "s/&.*;/; /g" | awk -F '"' '{ print $2 }')"
    [ -z "$imageFilePath" ] && imageFilePath="$(grep -io '<image_name param=.*"' "$1" | sed -e "s/&.*;/; /g" | awk -F '"' '{ print $2 }')"
    originalXMLFilePath="$(grep -io '<original_xml_file_path param=.*"' "$1" \
        | sed -e "s/&.*;/; /g" | awk -F '"' '{ print $2 }')"
    originalImageFileName="$(grep -io '<image_name param=.*"' \
        "$originalXMLFilePath" | sed -e "s/&.*;/; /g" | awk -F '"' \
        '{ print $2 }')"
    originalVMDKFilePath="$(dirname \
        "$originalXMLFilePath")/${originalImageFileName}"
    # Added to workaround path prefix coming from temporary generated xml file
    # by vmchooser.
    if [[ "$(grep --extended-regexp '^/tmp/tmp\.[^\/]+/' <<< \
          "$imageFilePath")" ]]; then
        imageFilePath=$(sed -r 's/^\/?tmp\/[^\/]+\///g' \
            <<< "$imageFilePath")
        sed -ir \
            "s/(<image_name param=\")[^\"]*(\")/\\1$(sed -e \
            's/\\/\\\\/g' -e 's/\//\\\//g' -e \
            's/&/\\\&/g' <<< "$imageFilePath")\\2/g" "$1"
    fi
    # Create linked clone if not exists.
    if [ ! -f "$imageFilePath" ]; then
        mkdir -p "$(dirname "$imageFilePath")" && \
        bash "$(dirname "$0")/vmchooser-clc" "$originalXMLFilePath" \
            "$imageFilePath" --debug --verbose &>"${LOGFILE}"
    fi
fi
##

# absolute or relative path?
xmlfile=$1
if ls "${xmlfile}" 2>/dev/null | grep '/' >/dev/null 2>&1; then
	xmlpath=$(dirname "${xmlfile}")
	xmlfile=$(basename "${xmlfile}")
else
	xmlpath=${vmchooser_xmlpath}
fi
# full path
xmlfile="${xmlpath}/${xmlfile%.xml}.xml"

DO_PROFILE="$(grep -c -E -i '<\s*profile\s*param="?(true|yes)"?' "$xmlfile")"

################################################################################
### Sanity checks
################################################################################

# test if the xml file is valid
if ! [ -r "${xmlfile}" ]; then
	writelog "${xmlfile} not a readable XML file!"
	slxlog "virt-nonreadable-xml" "XML file not readable: $xmlfile"
	exit 1
fi

# test if XML file
if ! grep -q '<?xml' "${xmlfile}"; then
	writelog "Submitted configuration file ${xmlfile} seems to have wrong XML format"
	slxlog "virt-invalid-xml" "Malformed XML file: $xmlfile" "$xmlfile"
	exit 1
fi

# check for running in graphical environment otherwise no much use here
if [ -z "$DISPLAY" ]; then
	echo -e "\n\tStart only within a graphical desktop!\n"
	exit 1
fi

################################################################################
###  Logo for console
################################################################################

cat <<EOL
                                             __        __   
                .----.--.--.-----.___.--.--.|__|.----.|  |_ 
                |   _|  |  |     |___|  |  ||  ||   _||   _|
                |__| |_____|__|__|    \___/ |__||__|  |____|
          OpenSLX virtual machine environment preparation script ...

EOL

################################################################################
### Read needed variables from XML file
################################################################################

writelog "Starting configuration..."
writelog "\tLogfile:\t\t${LOGFILE}"
writelog "\t/tmp info:\t\t$(df -h | grep " /tmp$" | awk '{print $2}') \c"
writelog "$(grep "/tmp " /proc/mounts | awk '{print $1" "$2" "$3" "$4}')"
writelog "\tVM XML dir:\t\t$(dirname "${xmlfile}")"
writelog "\tXML file:\t\t${xmlfile}"
writelog "Enable 3D:\t\t${enable3d}"
writelog "VM config:"

# Name of the virt image
imgname=$(grep -io '<image_path param=.*"' "${xmlfile}" | sed -e "s/&.*;/; /g" | awk -F '"' '{ print $2 }')
imgrelpath=$(grep -io '<image_name param=.*"' "${xmlfile}" | sed -e "s/&.*;/; /g" | awk -F '"' '{ print $2 }')
[ -z "$imgname" ] && imgname="${imgrelpath}"

## Added for persistent support.
if [[ "$userBranchFilePath" ]]; then
	imgname="$userBranchFilePath"
fi
##

# Imagename w/ full path
if echo "${imgname}" | grep -q '^/'; then
	imgpath="$(dirname "${imgname}")"
	imgname="$(basename "${imgname}")"
	vmpath="${imgpath}/${imgname}"
	# If old vmchooser binary stuff
	# We do not need folder name as it is already included by vmchooser
elif echo "${xmlfile}" | grep -q '^/tmp/'; then
	vmpath="$imgname"
	imgname="$(basename "${imgname}")"
## Added for persistent support.
elif [[ "$userBranchFilePath" ]]; then
	vmpath="$userBranchFilePath"
##
	# Else use same path as xml
else
	imgpath="${xmlpath}"
	vmpath="${imgpath}/${imgname}"
fi


# Name of the virt machine, sed because of Windows formatting
vm_name=$(grep -o 'short_description param=.*"' "${xmlfile}" \
| sed -e "s/&.*;/; /g" | awk -F '"' '{print $2}')
# If ${vm_name} not defined use ${xmlfile}
vm_name="${vm_name:-${xmlfile%.xml}}"

# Define vm_shortname since vm_name can be very long
vm_shortname="$(basename "${xmlfile%.xml}" | sed -e "s, ,-,g")"

# vm_name = displayname, define for old scripts
displayname="${vm_name}"

# image is for the following virtual machine
xmlvirt=$(grep -o 'virtualmachine param=.*"' "${xmlfile}" \
| sed -e "s/&.*;/; /g" | awk -F '"' '{print $2}')

# choose the proper virtualization/emulator plugin
[ "x${xmlvirt}" != "x" -a "x${xmlvirt}" != "xqemukvm" -a "x${xmlvirt}" != "xvirtualbox" -a "x${xmlvirt}" != "xvmware" ] && xmlvirt="emufe"

# make a guess from the filename extension if ${xmlvirt} is empty
# (not set within the XML file)
# TODO: implement possibility to submit own configuration files
if [ -z "${xmlvirt}" ] && [ -n "${additional_config}" ]; then
	writelog "No virtual machine parameter defined in ${xmlfile}"
	writelog "Trying to guess VM...\c"
	case "$(cat ${additional_config} | tr \"[A-Z]\" \"[a-z]\")" in
		*config.version*|*virtualhw.version*|*independent-nonpersistent*|*vmdk*)
			xmlvirt="vmware"
		;;
		*innotek*|*virtualbox*)
			xmlvirt="virtualbox"
		;;
		*qemu*|*kvm*)
			xmlvirt="qemukvm"
		;;
		*)
			xmlvirt="none"
		;;
	esac
	elif [ -z "${xmlvirt}" ]; then
	case "$(echo ${imgname##*.} | tr \"[A-Z]\" \"[a-z]\")" in
		vmdk)
			xmlvirt="vmware"
		;;
		vbox|vdi)
			xmlvirt="virtualbox"
		;;
		qcow*)
			xmlvirt="qemukvm"
		;;
		*)
			xmlvirt="emufe"
		;;
	esac
	writelog "result:\t${xmlvirt}"
fi

# Definition of the client system
vmostype=$(grep -io '<os param=.*"' "${xmlfile}" | awk -F '"' '{ print $2 }' | tr "[A-Z]" "[a-z]")

# Definition of the networking the client system is connected to
network_kind=$(grep -io '<network param=.*"' "${xmlfile}" | awk -F '"' '{ print $2 }' | tr "[A-Z]" "[a-z]")
network_card=$(grep -io '<netcard param=.*"' "${xmlfile}" | awk -F '"' '{ print $2 }'| tr "[A-Z]" "[a-z]")
override_hddtype=$(grep -io '<hddtype param=.*"' "${xmlfile}" | awk -F '"' '{ print $2 }'| tr "[A-Z]" "[a-z]")

# Set redirects to 0, see vmgrid if you want to define some
redirects=0

# Serial/parallel ports defined (e.g. "ttyS0" or "autodetect")
serial=$(grep -io '<serialport param=.*"' "${xmlfile}" | awk -F '"' '{ print $2 }')
parallel=$(grep -io '<parport param=.*"' "${xmlfile}" | awk -F '"' '{ print $2 }')

writelog "\tVirtualization:\t\t$xmlvirt"
writelog "\tVM name:\t\t$vm_name"
writelog "\tVM short name:\t\t$vm_shortname"

###############################################################################
### Declaration of default variables
###############################################################################

# take last two digits of current pid...
VM_ID=$(expr substr $$ $(expr ${#$} - 1) 2)

# Make sure cpu_cores is not empty
cpu_cores=${cpu_cores:-"1"}

# Amount of memory for the VM. Be generous if diff is written to HDD
if mount | grep -q '^/dev/sd.*on.*/tmp'; then
	reserve=20
	min=768
	max=1536
else
	reserve=65
	min=768
	max=8192
fi

# Calculate absulute amount of RAM that should stay available to the host
reserve="$[ ( $totalmem * $reserve ) / 100 ]"
# Respect some upper and lower bounds for the host amount
[ "$reserve" -lt "$min" ] && reserve="$min"
[ "$reserve" -gt "$max" ] && reserve="$max"

# Get a result which can be divided by 4
mem="$[ ( ( $totalmem - $reserve ) / 4 ) * 4 ]"
if [ -n "$mainvirtmem" ]; then
	forcemem="$[ "$mainvirtmem" / 4 * 4 ]"
	mem="$forcemem"
fi
hostmem="$[ $totalmem - $mem ]"

# TODO: We should only generate the suffix here (last 3 octets) as the first 3 are
# dependant on the virtualizer/emulator. Check if any run-virt.include still relies on
# $macguestpart/$macaddr. If so, fix it to use its specific first 3 bytes
# and append $macaddrssuffix
macguestpart="00:50:56:${VM_ID}"
machostpart=$(echo "${hostmacaddr}" | awk -F ":" '{print $(NF-1)":"$NF}')
macaddr=$(echo "${macguestpart}:${machostpart}" | tr "[a-z]" "[A-Z]")
macaddrsuffix=$(echo "${VM_ID}:${machostpart}" | tr "[a-z]" "[A-Z]")

if ! echo "$macaddrsuffix" | grep -q -E '^[0-9A-F]{2}:[0-9A-F]{2}:[0-9A-F]{2}$'; then
	slxlog "virt-mac" "Could not properly generate mac address suffix (got $macaddrsuffix)"
fi

# Virtual fd/cd/dvd and drive devices, floppy b: for configuration
# if $floppy_0 from virtualization.conf set then fdtest="TRUE"
fdtest=${floppy_0:+"TRUE"}
# if $fdtest not set floppy0="FALSE", else "TRUE"
floppy0=${fdtest:-"FALSE"}
floppy1="TRUE"
floppy1name="$VMCHOOSER_DIR/data/loopimg/fd.img"
# if $cdrom_0 from virtualization.conf set then cdtest="TRUE"
cdtest=${cdrom_0:+"TRUE"}
# if $cdtest not set cdrom0="FALSE", else "TRUE"
cdrom0=${cdtest:-"FALSE"}
# if $cdrom_1 from virtualization.conf set then cdtest="TRUE"
cdtest=${cdrom_1:+"TRUE"}
# if $cdtest not set cdrom1="FALSE", else "TRUE"
cdrom1=${cdtest:-"FALSE"}
# IDE is expected default, test for the virtual disk image type should
# be done while creating the runscripts ...
# TODO enable SCSI support instead of just disabling it.
ide="TRUE"
scsi="FALSE"
hddrv="ide"
audio="true"
remotedesktopport="590${VM_ID}"


# Enable 3D
enable3d=$(grep -i -o "<enable3d param=.*" "${xmlfile}" | awk -F '"' '{print $2}' | rv_clean_string)

# Add rw share
sharepath="${HOME}/PERSISTENT"
sharename="home"

# Set hostname: using original hostname and adding string
hostname="virt-$(hostname)"

writelog "\tVM Hostname:\t\t$hostname"

################################################################################
### Setup the rest of the environment and run the configured vm
################################################################################
# 8086:1e20
if lspci -n | grep -E -i '8086:1e20( |$)'; then
	VOL="100%" # bwPC 4: Speaker too quiet :-(
else
	VOL="85%"
fi
if true; then
	# detecting which card is to be used
	echo "Detecting which sound card to use ..."
	PROC="/proc/asound/cards"	
	if [ ! -r "$PROC" ]; then
		echo "'${PROC}' not found or not readable."
		SOUND_CARD_INDEX=0
	else
		# Try to filter HDMI cards first
		SOUND_CARD_INDEX=$(grep -v -i 'HDMI' "${PROC}" | grep -E -o '^[[:space:]]*[0-9]+[[:space:]]+' | head -n 1)
		# If empty, try again with all
		[ -z "${SOUND_CARD_INDEX}" ] && SOUND_CARD_INDEX=$(cat "${PROC}" | grep -E -o '^[[:space:]]*[0-9]+[[:space:]]+' | head -n 1)
		
		if [ -z "${SOUND_CARD_INDEX}" ]; then
			echo "No sound card found."
			SOUND_CARD_INDEX=0
		fi
	fi

	# Adjust sound volume (playback)... Random mixer names we have encountered during testing
	echo "Setting up volume..."
	amixer -q -c "$SOUND_CARD_INDEX" sset 'Master' "$VOL" unmute
	amixer -q -c "$SOUND_CARD_INDEX" sset 'PCM' "$VOL" unmute
	amixer -q -c "$SOUND_CARD_INDEX" sset 'CD' "$VOL" unmute
	amixer -q -c "$SOUND_CARD_INDEX" sset 'Headphone' "$VOL" unmute
	amixer -q -c "$SOUND_CARD_INDEX" sset 'Front' "$VOL" unmute
	amixer -q -c "$SOUND_CARD_INDEX" sset 'Speaker' "$VOL" unmute
	# Recording. It seems that (most) devices need the volume set to 0, so you
	# don't hear your own mic input, but should be unmuted. Also on some cards,
	# you need to set the cap option on the mic you want to use, while other cards
	# will just ignore that option.
	# Plus, most cards have a Capture mixer, which needs to be set to cap too, and
	# have its volume turned up. (There'll probably be some cards that need yet
	# another setup, but this works for now on 4 tested cards)
	amixer -q -c "$SOUND_CARD_INDEX" sset 'Rear Mic Boost' "50%" cap unmute
	amixer -q -c "$SOUND_CARD_INDEX" sset 'Rear Mic' "0%" cap unmute
	amixer -q -c "$SOUND_CARD_INDEX" sset 'Front Mic Boost' "50%" cap unmute
	amixer -q -c "$SOUND_CARD_INDEX" sset 'Front Mic' "0%" cap unmute
	amixer -q -c "$SOUND_CARD_INDEX" sset 'Mic Boost' "50%" cap unmute
	amixer -q -c "$SOUND_CARD_INDEX" sset 'Mic' "0%" cap unmute
	amixer -q -c "$SOUND_CARD_INDEX" sset 'Capture' "100%" cap unmute
	amixer -q -c "$SOUND_CARD_INDEX" sset 'Input Source' 'Front Mic' # Let's hope nobody uses rear mic...
	# fix random static noise when starting vmplayer when module snd_pcsp (not pcspkr) is loaded
	amixer -q -c pcsp sset Master "0%" mute
	echo "Done setting up volume."
fi >> "${LOGFILE}" 2>&1

# Start printer daemon
QUEUE="STANDARD" # This has to match the queue you configured in your VM
USER="$(whoami)"
SPOOLDIR=
### Disabled: 100megs is not enough, some jobs are HUGE, try to use temp which should be on disk
## Try using user's tmpfs home first, as it gets wiped on logout
#if [ -n "${HOME}" ] && [ -w "${HOME}" ]; then
#	SPOOLDIR="${HOME}/.spool"
#	mkdir -p "${SPOOLDIR}/${QUEUE}"
#fi
# If failed, try to fall back to /tmp
if [ -z "${SPOOLDIR}" ] || [ ! -w "${SPOOLDIR}/${QUEUE}" ]; then
	SPOOLDIR="/tmp/printergui-${USER}-$$-${RANDOM}"
	rm -rf -- "${SPOOLDIR}"
	if ! mkdir -p "${SPOOLDIR}/${QUEUE}"; then
		slxlog "virt-spooldir" "Could not create spool directory ($SPOOLDIR) for $USER - printing will not work!"
		# TODO: Warn user
	fi
	chmod 0700 "${SPOOLDIR}/${QUEUE}"
fi

# Start the lpdaemon listening on the given port
# TODO: externalize with something like runtvirt.d (other parts might benefit from that too)
tcpsvd -E 192.168.101.1 5515 \
	lpd "$SPOOLDIR" \
	ash -c "/opt/openslx/cups/printergui '${USER}' \"${SPOOLDIR}/${QUEUE}/\$DATAFILE\"" &

# PID to kill the process
PID_LPD="$!"

# Copy guest configuration (with added information) config.xml to be accessed
# via virtual floppy
cp "$xmlfile" "$VMCHOOSER_DIR/fd-loop/config.xml"
# Add another file with resolution information
xrandr | grep -o -E 'connected\s*(primary)?\s*[0-9]+x[0-9]+\+0\+0' | grep -o -E '[0-9]+x[0-9]+' | head -n 1 > "$VMCHOOSER_DIR/fd-loop/hostres.txt"
# Add our magic openslx binary that sets the correct guest resolution
cp "$VMCHOOSER_DIR/data/openslx.exe" "$VMCHOOSER_DIR/fd-loop/"

# Try to use dnbd3 to access the image
unset vm_diskfile
unset vm_revision
unset dnbd3
unset dnbd3error
if [ -n "$SLX_DNBD3_SERVERS" -o -n "$SLX_DNBD3_PRIO_SERVERS" ] && [ "x$SLX_VM_DNBD3" = "xyes" ]; then
	if [ -e "/dev/dnbd0" -a -e "/var/run/dnbd3.socket" ]; then
		# Shuffle server list
		[ -n "$SLX_DNBD3_SERVERS" ] && TMP_SERVERS=$(for SRV in $SLX_DNBD3_SERVERS; do echo "$RANDOM $SRV"; done | sort -u | sed -r 's/^[0-9]+ //')
		for SRV in $SLX_DNBD3_PRIO_SERVERS $TMP_SERVERS; do
			dnbd3=$(dnbd3-client -h "$SRV" -i "${imgrelpath}" -r 0)
			RET=$?
			if [ "$RET" = "0" ]; then
				vm_revision=$(cat "/sys/block/${dnbd3#/dev/}/net/rid")
				writelog "DNBD3: $vm_diskfile on $dnbd3 with rid $vm_revision"
				vm_diskfile="$dnbd3"
				vmpath="$vm_diskfile"
				break
			fi
			dnbd3error="$dnbd3error ($RET/$dnbd3)"
			usleep 200000
		done
		if [ -z "$vm_diskfile" ]; then
			slxlog "virt-dnbd3" "No dnbd3 server for ${imgrelpath} found ($SLX_DNBD3_PRIO_SERVERS $TMP_SERVERS $dnbd3error), trying NFS/CIFS..."
			writelog "No working dnbd3 server found :-("
		fi
	else
		writelog "Won't use dnbd3 as it's not loaded, or the daemon is not running..."
	fi
else
	writelog "Won't use dnbd3 as no servers are given in config"
fi

# $vm_diskfile will be empty if dnbd3 is not used or failed. Let's try to fall back to NFS/CIFS via file system
if [ -z "$vm_diskfile" ]; then
	new_vmpath=$(ls "${vmpath}.r"* | grep -E -o '\.r[0-9]+$' | grep -o -E '[0-9]+' | sort -n | tail -1)
	[ -n "$new_vmpath" ] && vmpath="${vmpath}.r${new_vmpath}"
	vm_diskfile="$vmpath"
fi

# Check if virtual machine container file exists
if ! [ -e "${vmpath}" ]; then
	slxlog "virt-image-missing" "VM image $vmpath not found!"
	writelog "Virtual machine image ${vmpath} not found!"
	cleanexit 1
fi

writelog "Used diskfile: $vm_diskfile"

# Get all virtual machine specific stuff from the respective include file
if [ ! -e "$VMCHOOSER_DIR/$xmlvirt/run-virt.include" ] ; then
	# TODO: Tell user
	slxlog "virt-plugin-missing" "Could not find run-virt.include for $xmlvirt ($VMCHOOSER_DIR/$xmlvirt/run-virt.include)"
	writelog "Failed because of missing ${xmlvirt} plugin."
	cleanexit 1
fi

self="${xmlvirt}"
if ! . "$VMCHOOSER_DIR/$xmlvirt/run-virt.include"; then
	slxlog "virt-plugin-error" "run-virt.include for $xmlvirt could not be sourced (contains syntax errors?)" "$xmlvirt"
	writelog "Erroneous run-virt.include for $xmlvirt"
fi

# start a windowmanager for easier handling
# (expect problems w/ windows opening in background w/ vmware without wm)
for dm in openbox kwin xfwm4 metacity blackbox twm fvwm2 ; do
	if which $dm >/dev/null 2>&1 ; then
		if [ "$dm" = "fvwm2" ] ; then
			echo "EdgeScroll 0 0" > ${redodir}/fvwm
			fvwm2 -f ${redodir}/fvwm >/dev/null 2>&1 &
		else
			$dm >/dev/null 2>&1 &
		fi
		break
	fi
done

# Start poolvideoswitch if we find the autostarter file
#if [ -e /etc/xdg/autostart/pvsgui.desktop ]; then
#  /usr/local/bin/pvsgui -p 2 -b >/dev/null 2>&1 &
#fi

if [[ "$DO_PROFILE" -ge "1" ]]; then
	wget "http://132.230.8.113/profile/do.php?action=start" &
fi

# Check if tcpsvd is running. Do this down here so we do not check immediately after trying to spawn it,
# as this could result in success even if it's not really working
if ! kill -0 "$PID_LPD"; then
	slxlog "virt-lpd" "Could not start tcpsvd/lpd for virtual machine session"
fi

# Configure and start samba service to provide user's home directory
#if [ -f /usr/sbin/smbd ] ; then
#	sudo /opt/openslx/bin/sed -i /opt/openslx/vmchooser/smb.conf -e "s,USER,$USER,"
#	sudo /usr/sbin/nmbd -s /opt/openslx/vmchooser/config/smb.conf
#	sudo /usr/sbin/smbd -s /opt/openslx/vmchooser/config/smb.conf
#fi

# This will start the VM
writelog "VM command: eval ${VIRTCMD} ${VIRTCMDOPTS}"
eval ${VIRTCMD} ${VIRTCMDOPTS}
#
writelog "Bye."

# Postrun for commands after virtualization finishes
if [ -n "${POSTRUN}" ]; then
	eval ${POSTRUN}  >/dev/null 2>&1
fi


cleanexit 0