-
-
Notifications
You must be signed in to change notification settings - Fork 602
/
run.py
executable file
·709 lines (623 loc) · 29.6 KB
/
run.py
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
#!/usr/bin/env python3
import subprocess
import sys
import argparse
import os
import tempfile
import errno
import re
stty_params = None
devnull = open('/dev/null', 'w')
osv_base = os.path.join(os.path.dirname(os.path.abspath(__file__)), '..')
host_arch = os.uname().machine
def stty_save():
global stty_params
p = subprocess.Popen(["stty", "-g"], stdout=subprocess.PIPE, stderr=devnull)
stty_params, err = p.communicate()
stty_params = stty_params.strip()
def stty_restore():
if stty_params:
subprocess.call(["stty", stty_params], stderr=devnull)
def cleanups():
"cleanups after execution"
stty_restore()
def format_args(args):
def format_arg(arg):
if ' ' in arg:
return '"%s"' % arg
elif arg[0] == '-':
return '\\\n' + arg
else:
return arg
return ' '.join(map(format_arg, args))
def find_qemu_tap_guest_ip_address(qemu_tap_ip_address):
fields = re.search(r'(\d+)\.(\d+)\.(\d+)\.(\d+)', qemu_tap_ip_address)
return "%s.%s.%s.%d" % (fields.group(1), fields.group(2), fields.group(3), int(fields.group(4)) + 1)
def set_imgargs(options):
execute = options.execute
if options.image and not execute:
return
if not execute:
with open("build/%s/cmdline" % (options.opt_path), "r") as cmdline:
execute = cmdline.read()
if options.verbose:
execute = "--verbose " + execute
if options.jvm_debug or options.jvm_suspend:
if '-agentlib:jdwp' in execute:
raise Exception('The command line already has debugger options')
if not 'java.so' in execute:
raise Exception('java.so is not part of the command line')
debug_options = '-agentlib:jdwp=transport=dt_socket,server=y,suspend=%s,address=5005' % \
('n', 'y')[options.jvm_suspend]
execute = execute.replace('java.so', 'java.so ' + debug_options)
if options.trace:
execute = ' '.join('--trace=%s' % name for name in options.trace) + ' ' + execute
if options.trace_backtrace:
execute = '--trace-backtrace ' + execute
if options.sampler:
execute = '--sampler=%d %s' % (int(options.sampler), execute)
if options.hypervisor == 'qemu_microvm':
execute = '--nopci ' + execute
if options.mount_fs:
execute = ' '.join('--mount-fs=%s' % m for m in options.mount_fs) + ' ' + execute
if options.networking and options.tap and hasattr(options, 'qemu_tap_ip_address'):
qemu_tap_guest_ip_address = find_qemu_tap_guest_ip_address(options.qemu_tap_ip_address)
execute = '--ip=eth0,%s,255.255.255.252 --defaultgw=%s --nameserver=%s %s' % \
(qemu_tap_guest_ip_address, options.qemu_tap_ip_address, options.qemu_tap_ip_address, execute)
elif options.ip:
execute = ' '.join('--ip=%s' % i for i in options.ip) + ' ' + execute
if options.bootchart:
execute = '--bootchart ' + execute
options.osv_cmdline = execute
if options.kernel or options.hypervisor == 'qemu_microvm' or options.arch == 'aarch64':
return
cmdline = [os.path.join(osv_base, "scripts/imgedit.py"), "setargs", options.image_file, execute]
if options.dry_run:
print(format_args(cmdline))
else:
subprocess.call(cmdline)
def is_direct_io_supported(path):
if not os.path.exists(path):
raise Exception('Path not found: ' + path)
try:
file = os.open(path, os.O_RDONLY | os.O_DIRECT)
os.close(file)
return True
except OSError as e:
if e.errno == errno.EINVAL:
return False
raise
def start_osv_qemu(options):
if not is_direct_io_supported(options.image_file):
aio = 'cache=unsafe,aio=threads'
elif options.block_device_cache != None:
aio = 'cache=%s,aio=threads'% options.block_device_cache
else:
aio = 'cache=none,aio=native'
args = [
"-m", options.memsize,
"-smp", options.vcpus]
if not options.novnc and options.hypervisor != 'qemu_microvm' and options.arch == 'x86_64':
args += [
"-vnc", options.vnc]
else:
args += [
"--nographic"]
if not options.nogdb:
args += [
"-gdb", "tcp::%s,server,nowait" % options.gdb]
if options.graphics:
args += [
"-display", "sdl"]
if options.kernel or options.hypervisor == 'qemu_microvm' or options.arch == 'aarch64':
boot_index = ""
args += [
"-kernel", options.kernel_file,
"-append", options.osv_cmdline]
else:
boot_index = ",bootindex=0"
if options.arch == 'aarch64':
if options.hypervisor == 'qemu':
args += ["-machine", "gic-version=max", "-cpu", "cortex-a57"]
args += [
"-machine", "virt",
"-device", "virtio-blk-pci,id=blk0,drive=hd0,scsi=off%s%s" % (boot_index, options.virtio_device_suffix),
"-drive", "file=%s,if=none,id=hd0,%s" % (options.image_file, aio)]
elif options.hypervisor == 'qemu_microvm':
args += [
"-M", "microvm,x-option-roms=off,pit=off,pic=off,rtc=off",
"-nodefaults", "-no-user-config", "-no-reboot", "-global", "virtio-mmio.force-legacy=off",
"-device", "virtio-blk-device,id=blk0,drive=hd0,scsi=off%s%s" % (boot_index, options.virtio_device_suffix),
"-drive", "file=%s,if=none,id=hd0,%s" % (options.image_file, aio)]
elif options.sata:
args += [
"-machine", "q35",
"-drive", "file=%s,if=none,id=hd0,media=disk,%s" % (options.image_file, aio),
"-device", "ide-hd,drive=hd0,id=idehd0,bus=ide.0"]
elif options.scsi:
args += [
"-device", "virtio-scsi-pci,id=scsi0%s" % options.virtio_device_suffix,
"-drive", "file=%s,if=none,id=hd0,media=disk,%s" % (options.image_file, aio),
"-device", "scsi-hd,bus=scsi0.0,drive=hd0,scsi-id=1,lun=0%s" % boot_index]
elif options.nvme:
args += [
"-device", "nvme,serial=deadbeef,drive=nvm%s" % (boot_index),
"-drive", "file=%s,if=none,id=nvm,%s" % (options.image_file, aio)]
elif options.ide:
args += [
"-hda", options.image_file]
else:
args += [
"-device", "virtio-blk-pci,id=blk0,drive=hd0,scsi=off%s%s" % (boot_index, options.virtio_device_suffix),
"-drive", "file=%s,if=none,id=hd0,%s" % (options.image_file, aio)]
if options.cloud_init_image:
args += [
"-device", "virtio-blk-pci,id=blk1,bootindex=1,drive=hd1,scsi=off%s" % options.virtio_device_suffix,
"-drive", "file=%s,if=none,id=hd1" % (options.cloud_init_image)]
if options.second_disk_image:
args += [
"-device", "virtio-blk-pci,id=blk1,drive=hd1,scsi=off%s" % options.virtio_device_suffix,
"-drive", "file=%s,if=none,id=hd1" % (options.second_disk_image)]
if options.virtio_fs_tag:
dax = (",cache-size=%s" % options.virtio_fs_dax) if options.virtio_fs_dax else ""
args += [
"-chardev", "socket,id=char0,path=/tmp/vhostqemu",
"-device", "vhost-user-fs-pci,queue-size=1024,chardev=char0,tag=%s%s" % (options.virtio_fs_tag, dax),
"-object", "memory-backend-file,id=mem,size=%s,mem-path=/dev/shm,share=on" % options.memsize,
"-numa", "node,memdev=mem"]
if options.second_nvme_image:
args += [
"-drive", "file=%s,if=none,id=nvm1" % (options.second_nvme_image),
"-device", "nvme,serial=deadbeef,drive=nvm1,"]
if options.pass_pci:
args += [
"-device", "vfio-pci,host=%s" % (options.pass_pci)]
if options.no_shutdown:
args += ["-no-reboot", "-no-shutdown"]
if options.wait:
args += ["-S"]
for idx in range(int(options.nics)):
if options.vmxnet3:
net_device_options = ['vmxnet3']
elif options.hypervisor == 'qemu_microvm':
net_device_options = ['virtio-net-device']
else:
net_device_options = ['virtio-net-pci']
if options.mac:
net_device_options.append('mac=%s' % options.mac)
if options.networking:
if options.tap:
args += ["-netdev", "tap,id=hn%d,ifname=%s,script=no,downscript=no" % (idx, options.tap)]
elif options.vhost:
args += ["-netdev", "tap,id=hn%d,script=%s,vhost=on" % (idx, os.path.join(osv_base, "scripts/qemu-ifup.sh"))]
else:
for bridge_helper_dir in ['/usr/libexec', '/usr/lib/qemu']:
bridge_helper = bridge_helper_dir + '/qemu-bridge-helper'
if os.path.exists(bridge_helper):
break
else:
print("Unable to find qemu-bridge-helper program", file=sys.stderr)
return
args += ["-netdev", "bridge,id=hn%d,br=%s,helper=%s" % (idx, options.bridge, bridge_helper)]
net_device_options.extend(['netdev=hn%d' % idx, 'id=nic%d' % idx])
else:
if options.api:
forward_options = ',hostfwd=tcp::8000-:8000'
else:
forward_options = ''
for rule in options.forward:
forward_options += ',hostfwd=%s' % rule
args += ["-netdev", "user,id=un%d,net=192.168.122.0/24,host=192.168.122.1%s" % (idx, forward_options)]
net_device_options.append("netdev=un%d" % idx)
net_device_options_str = ','.join(net_device_options)
if not options.vmxnet3:
net_device_options_str = net_device_options_str + options.virtio_device_suffix
args += ["-device", net_device_options_str]
if options.hypervisor != 'qemu_microvm':
args += ["-device", "virtio-rng-pci%s" % options.virtio_device_suffix]
if options.hypervisor == "kvm" or options.hypervisor == 'qemu_microvm':
if options.arch == 'aarch64':
args += ["-enable-kvm", "-cpu", "host", "-machine", "gic-version=max"]
else:
args += ["-enable-kvm", "-cpu", "host,+x2apic"]
elif options.hypervisor == "none" or options.hypervisor == "qemu":
pass
if options.hypervisor == 'qemu_microvm':
args += ["-serial", "stdio"]
elif options.detach:
args += ["-daemonize"]
elif options.arch == 'x86_64':
signal_option = ('off', 'on')[options.with_signals]
args += ["-chardev", "stdio,mux=on,id=stdio,signal=%s" % signal_option]
args += ["-mon", "chardev=stdio,mode=readline"]
args += ["-device", "isa-serial,chardev=stdio"]
else:
pass
for a in options.pass_args or []:
args += a.split()
virtiofsd = None
if options.virtio_fs_dir:
virtiofsd_cmdline = ["virtiofsd", "--socket-path=/tmp/vhostqemu", "-o",
"source=%s" % options.virtio_fs_dir]
if options.dry_run:
print(format_args(virtiofsd_cmdline))
else:
try:
virtiofsd = subprocess.Popen(virtiofsd_cmdline, stdout=devnull,
stderr=devnull)
except OSError as e:
if e.errno == errno.ENOENT:
print("virtiofsd binary not found. Please install the qemu-system-%s package "
"that comes with it (>= 4.2) and is in path." % options.arch,
file=sys.stderr)
else:
print("OS error(%d): \"%s\" while running virtiofsd %s" % \
(e.errno, e.strerror, " ".join(args)), file=sys.stderr)
sys.exit()
try:
# Save the current settings of the stty
stty_save()
# Launch qemu
qemu_env = os.environ.copy()
qemu_env['OSV_BRIDGE'] = options.bridge
qemu_path = options.qemu_path or qemu_env.get('QEMU_PATH') or ('qemu-system-%s' % options.arch)
cmdline = [qemu_path] + args
if options.dry_run:
print(format_args(cmdline))
else:
ret = subprocess.call(cmdline, env=qemu_env)
if ret != 0:
sys.exit("qemu failed.")
except OSError as e:
if e.errno == errno.ENOENT:
print("'%s' binary not found. Please install the qemu-system-%s package." % \
(qemu_path, options.arch), file=sys.stderr)
else:
print("OS error(%d): \"%s\" while running qemu-system-%s %s" %
(e.errno, e.strerror, options.arch, " ".join(args)), file=sys.stderr)
finally:
cleanups()
# Clean up the spawned virtiofsd, if any
if virtiofsd is not None:
if virtiofsd.poll() is None:
virtiofsd.terminate()
try:
virtiofsd.wait(5)
except subprocess.TimeoutExpired:
virtiofsd.kill()
def start_osv_xen(options):
if options.hypervisor == "xen":
args = [
"builder='hvm'",
"xen_platform_pci=1",
"acpi=1",
"apic=1",
"boot='c'",
]
else:
args = ["kernel='%s/build/%s/loader.elf'" % (os.getcwd(), options.opt_path)]
try:
memory = int(options.memsize)
except ValueError:
memory = options.memsize
if memory[-1:].upper() == "M":
memory = int(memory[:-1])
elif memory[-2:].upper() == "MB":
memory = int(memory[:-2])
elif memory[-1:].upper() == "G":
memory = 1024 * int(memory[:-1])
elif memory[-2:].upper() == "GB":
memory = 1024 * int(memory[:-2])
else:
print("Unrecognized memory size", file=sys.stderr)
return
disk_type = "qcow2" if options.image_file.endswith(".img") else "raw"
disk_value = "'%s,%s,hda,rw'" % (options.image_file, disk_type)
if cmdargs.second_disk_image:
second_disk_type = "qcow2" if options.second_disk_image.endswith(".img") else "raw"
disk_value = disk_value + ",'%s,%s,hda,rw'" % (options.second_disk_image, second_disk_type)
if not options.novnc:
vncoptions = re.match("^(?P<vncaddr>[^:]*):?(?P<vncdisplay>[0-9]*$)", options.vnc)
if not vncoptions:
raise Exception('Invalid vnc option format: \"' + options.vnc + "\"")
if vncoptions.group("vncaddr"):
args += ["vnclisten=%s" % (vncoptions.group("vncaddr"))]
if vncoptions.group("vncdisplay"):
args += ["vncdisplay=%s" % (vncoptions.group("vncdisplay"))]
args += [
"memory=%d" % (memory),
"vcpus=%s" % (options.vcpus),
"maxcpus=%s" % (options.vcpus),
"name='osv-%d'" % (os.getpid()),
"disk=[%s]" % (disk_value),
"serial='pty'",
"paused=0",
"on_crash='preserve'"
]
if options.networking:
net_device_options = "bridge=%s" % options.bridge
if options.mac:
net_device_options += ",mac=%s" % options.mac
if options.script:
net_device_options += ",script=%s" % options.script
args += ["vif=['%s']" % (net_device_options)]
# Using xm would allow us to get away with creating the file, but it comes
# with its set of problems as well. Stick to xl.
xenfile = tempfile.NamedTemporaryFile(mode="w")
xenfile.writelines("%s\n" % item for item in args)
xenfile.flush()
try:
# Save the current settings of the stty
stty_save()
# Launch qemu
cmdline = ["xl", "create"]
if not options.detach:
cmdline += ["-c"]
cmdline += [xenfile.name]
if options.dry_run:
print(format_args(cmdline))
print("\nContent of %s\n---------------------------" % xenfile.name)
for item in args:
print("%s" % item)
else:
subprocess.call(cmdline)
except:
pass
finally:
xenfile.close()
cleanups()
def start_osv_vmware(options):
args = [
'#!/usr/bin/vmware',
'.encoding = "UTF-8"',
'config.version = "8"',
'virtualHW.version = "8"',
'scsi0.present = "TRUE"',
'scsi0.virtualDev = "pvscsi"',
'scsi0:0.fileName = "osv.vmdk"',
'ethernet0.present = "TRUE"',
'ethernet0.connectionType = "nat"',
'ethernet0.virtualDev = "vmxnet3"',
'ethernet0.addressType = "generated"',
'pciBridge0.present = "TRUE"',
'pciBridge4.present = "TRUE"',
'pciBridge4.virtualDev = "pcieRootPort"',
'pciBridge4.functions = "8"',
'hpet0.present = "TRUE"',
'guestOS = "ubuntu-64"',
'scsi0:0.present = "TRUE"',
'floppy0.present = "FALSE"',
'serial0.present = "TRUE"',
'serial0.fileType = "network"',
'serial0.fileName = "telnet://127.0.0.1:10000"',
'debugStub.listen.guest64 = "TRUE"',
'debugStub.listen.guest64.remote = "TRUE"',
]
try:
memory = int(options.memsize)
except ValueError:
memory = options.memsize
if memory[-1:].upper() == "M":
memory = int(memory[:-1])
elif memory[-2:].upper() == "MB":
memory = int(memory[:-2])
elif memory[-1:].upper() == "G":
memory = 1024 * int(memory[:-1])
elif memory[-2:].upper() == "GB":
memory = 1024 * int(memory[:-2])
else:
print("Unrecognized memory size", file=sys.stderr)
return
args += [
'memsize = "%d"' % (memory),
'numvcpus = "%s"' % (options.vcpus),
'displayName = "osv-%d"' % (os.getpid()),
]
vmxfile = open("build/%s/osv.vmx" % options.opt_path, "w")
vmxfile.writelines("%s\n" % item for item in args)
vmxfile.flush()
try:
# Convert disk image to vmdk
subprocess.call(["qemu-img", "convert", "-O", "vmdk", options.image_file, "build/%s/osv.vmdk" % options.opt_path])
# Launch vmware
cmdline = ["vmrun", "start", vmxfile.name]
if options.graphics:
cmdline += ["gui"]
else:
cmdline += ["nogui"]
if options.dry_run:
print(format_args(cmdline))
else:
subprocess.call(cmdline)
# Connect serial console via TCP
subprocess.call(["telnet", "127.0.0.1", "10000"])
except:
pass
finally:
vmxfile.close()
cleanups()
def start_osv(options):
launchers = {
"xen" : start_osv_xen,
"xenpv" : start_osv_xen,
"none" : start_osv_qemu,
"qemu" : start_osv_qemu,
"qemu_microvm" : start_osv_qemu,
"kvm" : start_osv_qemu,
"vmware" : start_osv_vmware,
}
try:
launchers[options.hypervisor](options)
except KeyError:
print("Unrecognized hypervisor selected", file=sys.stderr)
return
def choose_hypervisor(external_networking, arch):
if os.path.exists('/dev/kvm') and arch == host_arch:
return 'kvm'
if (os.path.exists('/proc/xen/capabilities')
and 'control_d' in open('/proc/xen/capabilities', 'r').read()
and external_networking):
return 'xen'
return 'qemu'
def main(options):
set_imgargs(options)
start_osv(options)
if __name__ == "__main__":
# Parse arguments
parser = argparse.ArgumentParser(prog='run')
parser.add_argument("-d", "--debug", action="store_true",
help="start debug version")
parser.add_argument("-r", "--release", action="store_true",
help="start release version")
parser.add_argument("-w", "--wait", action="store_true",
help="don't start OSv till otherwise specified, e.g. through the QEMU monitor or a remote gdb")
parser.add_argument("-i", "--image", action="store", default=None, metavar="IMAGE",
help="path to disk image file. defaults to build/$mode/usr.img")
parser.add_argument("-N", "--nvme",action="store_true", default=False,
help="use NVMe instead of virtio-blk")
parser.add_argument("-S", "--scsi", action="store_true", default=False,
help="use virtio-scsi instead of virtio-blk")
parser.add_argument("-A", "--sata", action="store_true", default=False,
help="use AHCI instead of virtio-blk")
parser.add_argument("-I", "--ide", action="store_true", default=False,
help="use ide instead of virtio-blk")
parser.add_argument("-3", "--vmxnet3", action="store_true", default=False,
help="use vmxnet3 instead of virtio-net")
parser.add_argument("-n", "--networking", action="store_true",
help="needs root. tap networking, specify interface")
parser.add_argument("-b", "--bridge", action="store", default="virbr0",
help="bridge name for tap networking")
parser.add_argument("-v", "--vhost", action="store_true",
help="needs root. tap networking and vhost")
parser.add_argument("-t", "--tap", action="store",
help="tap interface name")
parser.add_argument("-m", "--memsize", action="store", default="2G",
help="specify memory: ex. 1G, 2G, ...")
parser.add_argument("-c", "--vcpus", action="store", default="4",
help="specify number of vcpus")
parser.add_argument("-e", "--execute", action="store", default=None, metavar="CMD",
help="edit command line before execution")
parser.add_argument("-p", "--hypervisor", action="store", default="auto",
help="choose hypervisor to run: kvm, qemu_microvm, xen, xenpv, vmware, none (plain qemu)")
parser.add_argument("-D", "--detach", action="store_true",
help="run in background, do not connect the console")
parser.add_argument("-H", "--no-shutdown", action="store_true",
help="don't restart qemu automatically (allow debugger to connect on early errors)")
parser.add_argument("-s", "--with-signals", action="store_true", default=False,
help="qemu only. handle signals instead of passing keys to the guest. pressing ctrl+c from console will kill the emulator")
parser.add_argument("--block-device-cache", action="store", default=None,
help="Set QEMU block device cache to: none, writethrough, writeback, directsync or unsafe.")
parser.add_argument("-g", "--graphics", action="store_true",
help="Enable graphics mode.")
parser.add_argument("-V", "--verbose", action="store_true",
help="pass --verbose to OSv, to display more debugging information on the console")
parser.add_argument("--forward", metavar="RULE", action="append", default=[],
help="add network forwarding RULE (QEMU syntax)")
parser.add_argument("--dry-run", action="store_true",
help="do not run, just print the command line")
parser.add_argument("--jvm-debug", action="store_true",
help="start JVM with a debugger server")
parser.add_argument("--jvm-suspend", action="store_true",
help="start JVM with a suspended debugger server")
parser.add_argument("--mac", action="store",
help="set MAC address for NIC")
parser.add_argument("--vnc", action="store", default=":1",
help="specify vnc port number")
parser.add_argument("--api", action="store_true",
help="redirect the API port (8000) for user-mode networking")
parser.add_argument("--pass-args", action="append",
help="pass arguments to underlying hypervisor (e.g. qemu)")
parser.add_argument("--trace", default=[], action='append',
help="enable tracepoints")
parser.add_argument("--trace-backtrace", action="store_true",
help="enable collecting of backtrace at tracepoints")
parser.add_argument("--sampler", action="store", nargs='?', const='1000',
help="start sampling profiler. optionally specify sampling frequency in Hz")
parser.add_argument("--qemu-path", action="store",
help="specify qemu command path")
parser.add_argument("--nics", action="store", default="1",
help="number of NICs configured for the VM")
parser.add_argument("--novnc", action="store_true",
help="disable vnc")
parser.add_argument("--nogdb", action="store_true",
help="disable gdb")
parser.add_argument("--gdb", action="store", default="1234",
help="specify gdb port number")
parser.add_argument("--script", action="store",
help="XEN define configuration script for vif")
parser.add_argument("--second-disk-image", action="store",
help="Path to the optional second disk image that should be attached to the instance")
parser.add_argument("--cloud-init-image", action="store",
help="Path to the optional cloud-init image that should be attached to the instance")
parser.add_argument("-k", "--kernel", action="store_true",
help="Run OSv in QEMU kernel mode as PVH.")
parser.add_argument("--kernel-path", action="store",
help="path to loader-stripped.elf. defaults to build/$mode/loader-stripped.elf")
parser.add_argument("--virtio", action="store", choices=["legacy","transitional","modern"], default="transitional",
help="specify virtio version: legacy, transitional or modern")
parser.add_argument("--arch", action="store", choices=["x86_64","aarch64"], default=host_arch,
help="specify QEMU architecture: x86_64, aarch64")
parser.add_argument("--virtio-fs-tag", action="store",
help="virtio-fs device tag")
parser.add_argument("--virtio-fs-dir", action="store",
help="path to the directory exposed via virtio-fs mount")
parser.add_argument("--virtio-fs-dax", action="store",
help="DAX window size for virtio-fs device (disabled if not specified)")
parser.add_argument("--mount-fs", default=[], action="append",
help="extra mounts (forwarded to respective kernel command line option)")
parser.add_argument("--ip", default=[], action="append",
help="static ip addresses (forwarded to respective kernel command line option)")
parser.add_argument("--bootchart", action="store_true",
help="bootchart mode (forwarded to respective kernel command line option")
parser.add_argument("--second-nvme-image", action="store",
help="Path to an optional disk image that should be attached to the instance as NVMe device")
parser.add_argument("--pass-pci", action="store",
help="passthrough a pci device in given slot if bound to vfio driver")
cmdargs = parser.parse_args()
cmdargs.opt_path = "debug" if cmdargs.debug else "release" if cmdargs.release else "last"
if cmdargs.arch == 'aarch64':
default_kernel_file_name = "loader.img"
default_image_file_name = "disk.img"
else:
default_kernel_file_name = "loader-stripped.elf"
default_image_file_name = "usr.img"
cmdargs.kernel_file = os.path.abspath(cmdargs.kernel_path or os.path.join(osv_base, "build/%s/%s" % (cmdargs.opt_path, default_kernel_file_name)))
cmdargs.image_file = os.path.abspath(cmdargs.image or os.path.join(osv_base, "build/%s/%s" % (cmdargs.opt_path, default_image_file_name)))
if not os.path.exists(cmdargs.image_file):
raise Exception('Image file %s does not exist.' % cmdargs.image_file)
if cmdargs.cloud_init_image:
cmdargs.cloud_init_image = os.path.abspath(cmdargs.cloud_init_image)
if not os.path.exists(cmdargs.cloud_init_image):
raise Exception('Cloud-init image %s does not exist.' % cmdargs.cloud_init_image)
if cmdargs.second_disk_image:
cmdargs.second_disk_image = os.path.abspath(cmdargs.second_disk_image)
if not os.path.exists(cmdargs.second_disk_image):
raise Exception('Second disk image %s does not exist.' % cmdargs.second_disk_image)
if cmdargs.virtio_fs_dir and not os.path.exists(cmdargs.virtio_fs_dir):
raise Exception('Directory %s to be exposed through virtio-fs does not exist.' % cmdargs.virtio_fs_dir)
if cmdargs.hypervisor == "auto":
cmdargs.hypervisor = choose_hypervisor(cmdargs.networking,cmdargs.arch)
if cmdargs.virtio == "legacy":
cmdargs.virtio_device_suffix = ",disable-legacy=off,disable-modern=on"
elif cmdargs.virtio == "modern":
cmdargs.virtio_device_suffix = ",disable-legacy=on,disable-modern=off"
else:
cmdargs.virtio_device_suffix = ""
if cmdargs.networking and cmdargs.tap and (cmdargs.execute == None or '--ip=' not in cmdargs.execute):
process = subprocess.run(["ip", "address", "show", cmdargs.tap], stdout=subprocess.PIPE)
if process.returncode != 0:
print("Please create tap device by calling", file=sys.stderr)
print(" ./scripts/create_tap_device.sh natted %s <ip_address>\n" % cmdargs.tap, file=sys.stderr)
raise Exception("Could not find the tap device %s" % cmdargs.tap)
output_lines = process.stdout.decode('utf-8').split('\n')
inet_line = next(filter(lambda line: "inet" in line, output_lines), None)
if inet_line and cmdargs.tap in inet_line:
ip_address = re.search(r'\d+\.\d+\.\d+\.\d+', inet_line)
if ip_address:
cmdargs.qemu_tap_ip_address = ip_address.group(0)
else:
raise Exception("Unable to find tap device %s with assigned IP address." % cmdargs.tap)
else:
raise Exception("Unable to find tap device %s with assigned IP address." % cmdargs.tap)
# Call main
main(cmdargs)