Debian Codegraph @

ova-compose/ova-compose.py

raw symbols SCIP
1 #!/usr/bin/env python3
2
3 # Copyright (c) 2023 VMware, Inc. All Rights Reserved.
4 #
5 # Licensed under the Apache License, Version 2.0 (the “License”); you may not
6 # use this file except in compliance with the License. You may obtain a copy of
7 # the License at:
8 #
9 # http://www.apache.org/licenses/LICENSE-2.0
10 #
11 # Unless required by applicable law or agreed to in writing, software distributed
12 # under the License is distributed on an “AS IS” BASIS, without warranties or
13 # conditions of any kind, EITHER EXPRESS OR IMPLIED. See the License for the
14 # specific language governing permissions and limitations under the License.
15
16 import sys
17 import os
18 import subprocess
19 import getopt
20 import datetime
21 import yaml
22 import json
23 from lxml import etree as ET
24 import hashlib
25 import tempfile
26 import shutil
27 from concurrent.futures import ProcessPoolExecutor
28
29 APP_NAME = "ova-compose"
30
31 VMDK_CONVERT = "vmdk-convert"
32
33 NS_CIM = "http://schemas.dmtf.org/wbem/wscim/1/common"
34 NS_OVF = "http://schemas.dmtf.org/ovf/envelope/1"
35 NS_RASD = "http://schemas.dmtf.org/wbem/wscim/1/cim-schema/2/CIM_ResourceAllocationSettingData"
36 NS_VMW = "http://www.vmware.com/schema/ovf"
37 NS_VSSD = "http://schemas.dmtf.org/wbem/wscim/1/cim-schema/2/CIM_VirtualSystemSettingData"
38 NS_XSI = "http://www.w3.org/2001/XMLSchema-instance"
39
40 NS_MAP = {
41 None: NS_OVF,
42 "cim" : NS_CIM,
43 "ovf" : NS_OVF,
44 "rasd" : NS_RASD,
45 "vmw" : NS_VMW,
46 "vssd" : NS_VSSD,
47 "xsi" : NS_XSI
48 }
49
50
51 def xml_indent(elem, level=0):
52 i = "\n" + level*" "
53 if len(elem):
54 if not elem.text or not elem.text.strip():
55 elem.text = i + " "
56 if not elem.tail or not elem.tail.strip():
57 elem.tail = i
58 for elem in elem:
59 xml_indent(elem, level+1)
60 if not elem.tail or not elem.tail.strip():
61 elem.tail = i
62
63
64 def xml_text_element(tag, value):
65 elem = ET.Element(tag)
66 elem.text = value
67 return elem
68
69
70 def xml_config(key, value):
71 if type(value) is bool:
72 value = "true" if value else "false"
73 elif type(value) is not str:
74 value = str(value)
75 return ET.Element('{%s}Config' % NS_VMW, { '{%s}required' % NS_OVF: 'false', '{%s}key' % NS_VMW: key, '{%s}value' % NS_VMW: value})
76
77
78 def xml_configs(config):
79 ret = []
80 if config is not None:
81 for k,v in config.items():
82 if v is not None:
83 ret.append(xml_config(k, v))
84 return ret
85
86
87 class ValidationError(Exception):
88 pass
89
90
91 class VirtualHardware(object):
92 pass
93
94
95 class VssdSystem(VirtualHardware):
96
97 def __init__(self, identifier, type):
98 self.identifier = identifier
99 self.type = type
100
101
102 @classmethod
103 def from_dict(cls, d):
104 system = d['system']
105 return cls(system['name'], system['type'])
106
107
108 def new_text_element(self, tag, value):
109 elem = ET.Element(tag)
110 elem.text = value
111 return elem
112
113
114 def xml_element(self, tag, value):
115 return self.new_text_element("{%s}%s" % (NS_VSSD, tag), str(value))
116
117
118 def xml_item(self, element_name):
119 attrs = {}
120 item = ET.Element('{%s}System' % NS_OVF, attrs)
121
122 item.append(self.xml_element('ElementName', element_name))
123 item.append(self.xml_element('InstanceID', 0))
124 item.append(self.xml_element('VirtualSystemIdentifier', self.identifier))
125 item.append(self.xml_element('VirtualSystemType', self.type))
126
127 return item
128
129
130 class RasdItem(VirtualHardware):
131 last_instance_id = 0
132 description = "Virtual Hardware Item"
133 config = None
134 connectable = False
135 configuration = None
136
137
138 def __init__(self, subtype=None, config=None):
139 RasdItem.last_instance_id += 1
140 self.instance_id = RasdItem.last_instance_id
141 if config is not None:
142 if self.config is None:
143 self.config = {}
144 self.config.update(config)
145
146
147 @classmethod
148 def from_dict(cls, d):
149 return cls(config=d.get('config'))
150
151
152 def connect(self, ovf):
153 pass
154
155
156 def xml_references(self):
157 return None
158
159
160 def xml_disks(self):
161 return None
162
163
164 def new_text_element(self, tag, value):
165 elem = ET.Element(tag)
166 elem.text = value
167 return elem
168
169
170 def xml_element(self, tag, value):
171 return self.new_text_element("{%s}%s" % (NS_RASD, tag), str(value))
172
173
174 def xml_item(self, required, element_name):
175 attrs = {}
176
177 if not required:
178 attrs["{%s}required" % NS_OVF] = 'false'
179 if self.configuration:
180 attrs["{%s}configuration" % NS_OVF] = self.configuration
181
182 item = ET.Element('{%s}Item' % NS_OVF, attrs)
183
184 item.append(self.xml_element('ResourceType', self.resource_type))
185 item.append(self.xml_element('InstanceID', self.instance_id))
186 item.append(self.xml_element('Description', self.description))
187 item.append(self.xml_element('ElementName', element_name))
188
189 item.extend(xml_configs(self.config))
190
191 if self.connectable:
192 item.append(self.xml_element('AutomaticAllocation', "true" if self.connected else "false"))
193
194 return item
195
196
197 class RasdCpus(RasdItem):
198 resource_type = 3
199 description = "Virtual CPUs"
200
201
202 def __init__(self, num, config=None):
203 super().__init__(config=config)
204 self.num = int(num)
205
206
207 @classmethod
208 def from_dict(cls, d):
209 if type(d) is int:
210 item = cls(d)
211 else:
212 item = cls(d['number'], config=d.get('config'))
213 return item
214
215
216 def xml_item(self, required, element_name):
217 item = super().xml_item(required, element_name)
218 item.append(self.xml_element('AllocationUnits', 'hertz * 10^6'))
219 item.append(self.xml_element('VirtualQuantity', self.num))
220
221 return item
222
223
224 class RasdMemory(RasdItem):
225 resource_type = 4
226 description = "Virtual Memory"
227
228
229 def __init__(self, size, config=None):
230 super().__init__(config=config)
231 self.size = int(size)
232
233
234 @classmethod
235 def from_dict(cls, d):
236 if type(d) is int:
237 item = cls(d)
238 else:
239 item = cls(d['size'], config=d.get('config'))
240 return item
241
242
243 def xml_item(self, required, element_name):
244 item = super().xml_item(required, element_name)
245 item.append(self.xml_element('AllocationUnits', 'byte * 2^20'))
246 item.append(self.xml_element('VirtualQuantity', self.size))
247
248 return item
249
250
251 class RasdController(RasdItem):
252
253 def __init__(self, subtype, config=None):
254 super().__init__(config=config)
255 self.next_child_address = 0
256 self.subtype = subtype
257
258
259 @classmethod
260 def from_dict(cls, d):
261 item = cls(d.get('subtype', None), config=d.get('config'))
262 return item
263
264
265 def add_child(self, child):
266 child.address_on_parent = self.next_child_address
267 self.next_child_address += 1
268
269
270 class RasdScsiController(RasdController):
271 resource_type = 6
272 description = "SCSI Controller"
273
274
275 def __init__(self, subtype, config=None):
276 super().__init__(subtype, config=config)
277 self.next_child_address = 0
278 # TODO: maintain valid settings in a structure instead of code:
279 if self.subtype is None:
280 self.subtype = 'VirtualSCSI'
281 elif self.subtype.lower() in ['virtualscsi', 'lsilogic']:
282 self.subtype = subtype
283 else:
284 raise Exception(f"invalid SCSI subtype '{self.subtype}'")
285
286
287 def xml_item(self, required, element_name):
288 item = super().xml_item(required, element_name)
289 item.append(self.xml_element('ResourceSubType', self.subtype))
290
291 return item
292
293
294 class RasdSataController(RasdController):
295 resource_type = 20
296 description = "SATA Controller"
297
298
299 def xml_item(self, required, element_name):
300 item = super().xml_item(required, element_name)
301 item.append(self.xml_element('ResourceSubType', 'vmware.sata.ahci'))
302
303 return item
304
305
306 class RasdNvmeController(RasdController):
307 resource_type = 20
308 description = "NVME Controller"
309
310
311 def xml_item(self, required, element_name):
312 item = super().xml_item(required, element_name)
313 item.append(self.xml_element('ResourceSubType', 'vmware.nvme.controller'))
314
315 return item
316
317
318 class RasdIdeController(RasdController):
319 resource_type = 5
320 description = "IDE Controller"
321
322
323 class RasdControllerItem(RasdItem):
324
325 def __init__(self, parent_id, config=None):
326 super().__init__(config=config)
327 self.parent_id = parent_id
328 self.rasd_parent = None
329
330
331 @classmethod
332 def from_dict(cls, d):
333 item = cls(d['parent'], config=d.get('config'))
334 return item
335
336
337 def connect(self, ovf):
338 self.rasd_parent = ovf.rasd_items[self.parent_id]
339 self.rasd_parent.add_child(self)
340
341
342 def xml_item(self, required, element_name):
343 item = super().xml_item(required, element_name)
344 item.append(self.xml_element('Parent', self.rasd_parent.instance_id))
345 item.append(self.xml_element('AddressOnParent', self.address_on_parent))
346
347 return item
348
349
350 class RasdCdDrive(RasdControllerItem):
351 resource_type = 15
352 description = "CD Drive"
353 DEFAULT_CONFIG = {
354 "connectable.allowGuestControl":"true"
355 }
356 connectable = True
357
358
359 def __init__(self, parent_id, image, connected=False, config=None):
360 self.config = self.DEFAULT_CONFIG.copy()
361 super().__init__(parent_id, config=config)
362 self.image = image
363 self.connected = connected
364
365
366 @classmethod
367 def from_dict(cls, d):
368 item = cls(d['parent'], d.get('image', None), connected=d.get('connected', False), config=d.get('config'))
369 return item
370
371
372 def xml_item(self, required, element_name):
373 item = super().xml_item(required, element_name)
374 item.append(self.xml_element('ResourceSubType', 'vmware.cdrom.remotepassthrough'))
375 if self.image is not None:
376 item.append(self.xml_element('HostResource', self.image.host_resource()))
377
378 return item
379
380
381 class RasdUsbController(RasdItem):
382 resource_type = 23
383 description = "USB Controller"
384
385
386 def xml_item(self, required, element_name):
387 item = super().xml_item(required, element_name)
388 item.append(self.xml_element('ResourceSubType', 'vmware.usb.ehci'))
389 item.append(xml_config('ehciEnabled', 'true'))
390 return item
391
392
393 class RasdUsb3Controller(RasdItem):
394 resource_type = 23
395 description = "USB3 Controller"
396
397
398 def xml_item(self, required, element_name):
399 item = super().xml_item(required, element_name)
400 item.append(self.xml_element('ResourceSubType', 'vmware.usb.xhci'))
401 return item
402
403
404 class RasdVmci(RasdItem):
405 resource_type = 1
406 description = "VMCI"
407
408
409 def xml_item(self, required, element_name):
410 item = super().xml_item(required, element_name)
411 item.append(self.xml_element('ResourceSubType', 'vmware.vmci'))
412 return item
413
414
415 class RasdFloppy(RasdItem):
416 resource_type = 14
417 description = "Floppy Drive"
418 DEFAULT_CONFIG = {
419 "connectable.allowGuestControl":"true"
420 }
421 connectable = True
422
423
424 def __init__(self, image, connected=False, config=None):
425 self.config = self.DEFAULT_CONFIG.copy()
426 super().__init__(config=config)
427 self.image = image
428 self.connected = connected
429
430
431 @classmethod
432 def from_dict(cls, d):
433 item = cls(d.get('image', None), d.get('connected', False), config=d.get('config'))
434 return item
435
436
437 def xml_item(self, required, element_name):
438 item = super().xml_item(required, element_name)
439 if self.image is not None:
440 item.append(self.xml_element('HostResource', self.image.host_resource()))
441
442 return item
443
444
445 class RasdVideoCard(RasdItem):
446 resource_type = 24
447 description = "Video Card"
448 DEFAULT_CONFIG = {
449 "useAutoDetect" : "false",
450 "videoRamSizeInKB" : "4096",
451 "enable3DSupport" : "false",
452 "use3dRenderer" : "automatic"
453 }
454 connectable = True
455 connected = False
456
457
458 def __init__(self, config=None):
459 self.config = RasdVideoCard.DEFAULT_CONFIG.copy()
460 super().__init__(config=config)
461
462
463 def xml_item(self, required, element_name):
464 item = super().xml_item(required, element_name)
465
466 return item
467
468
469 class RasdHardDisk(RasdControllerItem):
470 resource_type = 17
471 description = "Hard Disk"
472
473
474 def __init__(self, parent_id, disk, config=None):
475 if config is None or 'virtualDiskFormat' not in config:
476 if disk.sector_size is not None:
477 if config is None:
478 config = {}
479 try:
480 config['virtualDiskFormat'] = {512: "native_512", 4096: "native_4k"}[disk.sector_size]
481 except KeyError:
482 print(f"invalid sector size {disk.sector_size}")
483 raise
484 super().__init__(parent_id, config=config)
485 self.disk = disk
486
487
488 @classmethod
489 def from_dict(cls, d):
490 item = cls(d['parent'], d['disk'], config=d.get('config'))
491 return item
492
493
494 def xml_item(self, required, element_name):
495 item = super().xml_item(required, element_name)
496 item.append(self.xml_element('HostResource', self.disk.host_resource()))
497
498 return item
499
500
501 class RasdEthernet(RasdItem):
502 resource_type = 10
503 description = "Ethernet Adapter"
504 DEFAULT_CONFIG = {
505 "wakeOnLanEnabled":"false",
506 "connectable.allowGuestControl":"true"
507 }
508 connectable = True
509
510
511 def __init__(self, network_id, subtype, connected=True, address=None, config=None):
512 self.config = RasdEthernet.DEFAULT_CONFIG.copy()
513 super().__init__(config=config)
514 self.network_id = network_id
515 self.subtype = subtype
516 self.connected = connected
517 self.address = address
518
519
520 @classmethod
521 def from_dict(cls, d):
522 item = cls(d['network'], d['subtype'], connected=d.get('connected', True), address=d.get('address'), config=d.get('config'))
523 return item
524
525
526 def connect(self, ovf):
527 self.network = ovf.networks[self.network_id]
528
529
530 def xml_item(self, required, element_name):
531 item = super().xml_item(required, element_name)
532 item.append(self.xml_element('ResourceSubType', self.subtype))
533 item.append(self.xml_element('Connection', self.network.name))
534 if self.address:
535 item.append(self.xml_element('Address', self.address))
536
537 return item
538
539
540 class OVFNetwork(object):
541
542 def __init__(self, name, description):
543 self.name = name
544
545
546 @classmethod
547 def from_dict(cls, d):
548 item = cls(d['name'], d['description'])
549 return item
550
551
552 def xml_item(self):
553 item = ET.Element('{%s}Network' % NS_OVF, {'{%s}name' % NS_OVF : self.name})
554 item_desc = ET.Element('{%s}Description' % NS_OVF)
555 item_desc.text = f"The {self.name} Network"
556 item.append(item_desc)
557
558 return item
559
560
561 class OVFFile(object):
562 next_id = 0
563
564 def __init__(self, path, file_id=None):
565 self.path = os.path.abspath(path)
566 if file_id is None:
567 self.id = f"file{OVFFile.next_id}"
568 OVFFile.next_id += 1
569 else:
570 self.id = file_id
571 self.size = os.path.getsize(self.path)
572
573
574 def host_resource(self):
575 return f"ovf:/file/{self.id}"
576
577
578 def xml_item(self):
579 return ET.Element('{%s}File' % NS_OVF, {
580 '{%s}href' % NS_OVF: os.path.basename(self.path),
581 '{%s}id' % NS_OVF: self.id,
582 '{%s}size' % NS_OVF: str(self.size)
583 })
584
585
586 class OVFDisk(object):
587 next_id = 0
588
589 allocation_units_map = {
590 'byte' : "byte",
591 'KB' : "byte * 2^10",
592 'MB' : "byte * 2^20",
593 'GB' : "byte * 2^30",
594 'TB' : "byte * 2^40",
595 }
596
597 allocation_factors = {
598 'byte' : 1,
599 'byte * 2^10' : 2 ** 10,
600 'byte * 2^20' : 2 ** 20,
601 'byte * 2^30' : 2 ** 30,
602 'byte * 2^40' : 2 ** 40,
603 }
604
605 def __init__(self, path, units=None, disk_id=None, file_id=None, raw_image=None, sector_size=None):
606 if disk_id is None:
607 self.id = f"vmdisk{OVFDisk.next_id}"
608 OVFDisk.next_id += 1
609 else:
610 self.id = disk_id
611
612 # units can be unspecified (default: byte),
613 # one of KB, MB, ...
614 # or byte * 2^10, ... with exponents 10-40
615 if units is None:
616 units = "byte"
617 elif units in self.allocation_units_map:
618 units = self.allocation_units_map[units]
619 elif units in self.allocation_factors:
620 pass
621 else:
622 assert False, "invalid units used"
623 self.units = units
624
625 self.sector_size = int(sector_size) if sector_size is not None else None
626
627 if raw_image is not None:
628 if os.path.exists(raw_image):
629 # check if the vmdk exists, and if it does if it's newer than the raw image
630 # if not, create vmdk from raw image
631 if not os.path.exists(path) or os.path.getctime(raw_image) > os.path.getctime(path):
632 command = [VMDK_CONVERT, raw_image, path]
633 if sector_size is not None:
634 command += ["--sector-size", str(sector_size)]
635 subprocess.check_call(command)
636 else:
637 print(f"warning: raw image file {raw_image} does not exist, using {path}")
638
639 self.file = OVFFile(path, file_id=file_id)
640 disk_info = OVF._disk_info(path)
641 self.capacity = int(disk_info['capacity'] / self.allocation_factors[self.units])
642 self.used = disk_info['used']
643
644 if 'descriptorFile' in disk_info and 'ddb.logicalSectorSize' in disk_info['descriptorFile']:
645 sector_size = int(disk_info['descriptorFile']['ddb.logicalSectorSize'])
646 if self.sector_size is not None:
647 assert self.sector_size == sector_size
648 else:
649 self.sector_size = sector_size
650 elif self.sector_size is None:
651 self.sector_size = 512
652
653
654 def host_resource(self):
655 return f"ovf:/disk/{self.id}"
656
657
658 def xml_item(self):
659 return ET.Element('{%s}Disk' % NS_OVF, {
660 '{%s}diskId' % NS_OVF: self.id,
661 '{%s}capacity' % NS_OVF: str(self.capacity),
662 '{%s}capacityAllocationUnits' % NS_OVF: self.units,
663 '{%s}fileRef' % NS_OVF: self.file.id,
664 '{%s}populatedSize' % NS_OVF: str(self.used),
665 '{%s}format' % NS_OVF: 'http://www.vmware.com/interfaces/specifications/vmdk.html#streamOptimized'
666 })
667
668
669 class OVFEmptyDisk(OVFDisk):
670
671 def __init__(self, capacity, units="MB", disk_id=None):
672 if disk_id is None:
673 self.id = f"vmdisk{OVFDisk.next_id}"
674 OVFDisk.next_id += 1
675 else:
676 self.id = disk_id
677 self.capacity = capacity
678 if units in self.allocation_units_map:
679 units = self.allocation_units_map[units]
680 self.units = units
681 self.sector_size = None
682
683 def xml_item(self):
684 return ET.Element('{%s}Disk' % NS_OVF, {
685 '{%s}capacity' % NS_OVF: str(self.capacity),
686 '{%s}capacityAllocationUnits' % NS_OVF: self.units,
687 '{%s}diskId' % NS_OVF: self.id,
688 '{%s}format' % NS_OVF: 'http://www.vmware.com/interfaces/specifications/vmdk.html#streamOptimized'
689 })
690
691
692 def to_camel_case(snake_str):
693 return ''.join(x.title() for x in snake_str.split('_'))
694
695
696 class OVFProperty(object):
697
698 def __init__(self, key, type,
699 password = False,
700 value=None,
701 user_configurable=False, qualifiers=None,
702 label=None, description=None, category=None, required=None, configuration=None):
703
704 self.category = category
705 self.configuration = configuration
706 self.description = description
707 self.key = key
708 self.label = label
709 self.password = password
710 self.qualifiers = qualifiers
711 self.required = required
712 self.type = type
713 self.user_configurable = user_configurable
714 self.value = value
715
716
717 @classmethod
718 def from_dict(cls, key, type, d):
719 item = cls(key, type, **d)
720 return item
721
722
723 def xml_item(self):
724 xml_attrs = {
725 '{%s}key' % NS_OVF: self.key,
726 '{%s}type' % NS_OVF: self.type
727 }
728
729 # Handle the default value for the property
730 # DSP0243 2.1.1 line 1026
731 if self.value is not None:
732 # Simple string value (backward compatible)
733 if not isinstance(self.value, dict):
734 xml_attrs['{%s}value' % NS_OVF] = str(self.value)
735 # Dictionary with configuration-specific values
736 elif 'default' in self.value:
737 xml_attrs['{%s}value' % NS_OVF] = str(self.value['default'])
738
739 # Add other standard attributes
740 if self.qualifiers is not None:
741 xml_attrs['{%s}qualifiers' % NS_OVF] = self.qualifiers
742 if self.user_configurable:
743 xml_attrs['{%s}userConfigurable' % NS_OVF] = "true"
744 if self.configuration is not None:
745 xml_attrs['{%s}configuration' % NS_OVF] = self.configuration
746 if self.password:
747 xml_attrs['{%s}password' % NS_OVF] = "true"
748 if self.required is not None:
749 xml_attrs['{%s}required' % NS_OVF] = "true" if self.required else "false"
750
751 xml_property = ET.Element('{%s}Property' % NS_OVF, xml_attrs)
752
753 # Add label and description
754 if self.label is not None:
755 xml_property.append(xml_text_element('{%s}Label' % NS_OVF, self.label))
756 if self.description is not None:
757 xml_property.append(xml_text_element('{%s}Description' % NS_OVF, self.description))
758
759 # Add configuration-specific values if present
760 # DSP0243 2.1.1 line 1026
761 if isinstance(self.value, dict) and 'configurations' in self.value:
762 for config_id, config_value in self.value['configurations'].items():
763 config_elem = ET.Element('{%s}Value' % NS_OVF, {
764 '{%s}value' % NS_OVF: str(config_value),
765 '{%s}configuration' % NS_OVF: config_id
766 })
767 xml_property.append(config_elem)
768
769 return xml_property
770
771
772 class OVFProduct(object):
773 # snake case will be converted to camel case in XML
774 keys = ['info', 'product', 'vendor', 'version', 'full_version']
775 attr_keys = ['class', 'instance', 'required']
776
777 def __init__(self, **kwargs):
778 self.info = "Information about the installed software"
779 self.__dict__.update((k, v) for k, v in kwargs.items() if k in self.keys)
780 self.__dict__.update((k, v) for k, v in kwargs.items() if k in self.attr_keys)
781
782 self.properties = []
783 if 'properties' in kwargs:
784 props = kwargs['properties']
785 if props is not None:
786 for k, v in props.items():
787 self.properties.append(OVFProperty(k, **v))
788
789 self.transports = kwargs.get('transports', [])
790 self.categories = kwargs.get('categories', {})
791
792 # if a property references a non-existing category it will be dropped
793 for prop in self.properties:
794 assert prop.category is None or prop.category in self.categories,\
795 f"property '{prop.key}' references unknown category '{prop.category}'"
796
797
798 @classmethod
799 def from_dict(cls, d):
800 item = cls(**d)
801 return item
802
803
804 def xml_item(self):
805 xml_attrs = {}
806 for k in self.attr_keys:
807 if hasattr(self, k) and getattr(self, k) is not None:
808 xml_attrs['{%s}%s' % (NS_OVF, k)] = getattr(self, k)
809 xml_product = ET.Element('{%s}ProductSection' % NS_OVF, xml_attrs)
810
811 for k in self.keys:
812 if hasattr(self, k) and getattr(self, k) is not None:
813 xml_name = to_camel_case(k)
814 xml_product.append(xml_text_element('{%s}%s' % (NS_OVF, xml_name), getattr(self, k)))
815
816 # append category-less properties first
817 for prop in self.properties:
818 if prop.category is None:
819 xml_product.append(prop.xml_item())
820 # then go through all categories, and append matching props
821 for cat_id, cat_name in self.categories.items():
822 xml_product.append(xml_text_element('{%s}Category' % NS_OVF, cat_name))
823 for prop in self.properties:
824 if prop.category == cat_id:
825 xml_product.append(prop.xml_item())
826
827 return xml_product
828
829
830 # abstract base class for OVFAnnotation and OVFEula
831 class OVFTextBlock(object):
832 # snake case will be converted to camel case in XML
833 keys = ['info', 'text', 'file']
834 info_text = ""
835 xml_name = "TextBlock"
836 xml_text_name = "TextBlock"
837
838
839 def __init__(self, **kwargs):
840 self.info = "Information about the installed software"
841 self.__dict__.update((k, v) for k, v in kwargs.items() if k in self.keys)
842 if hasattr(self, 'file'):
843 file_name = self.file
844 with open(file_name, 'rt') as f:
845 self.text = f.read()
846 self.file = None
847
848
849 @classmethod
850 def from_dict(cls, d):
851 item = cls(**d)
852 return item
853
854
855 def _xml_element(self):
856 return ET.Element('{%s}%s' % (NS_OVF, self.xml_name))
857
858
859 def xml_item(self):
860 item = self._xml_element()
861 for k in self.keys:
862 if hasattr(self, k):
863 if k == 'text':
864 xml_name = self.xml_text_name
865 item.append(xml_text_element('{%s}%s' % (NS_OVF, xml_name), getattr(self, k)))
866 elif getattr(self, k) is not None:
867 xml_name = to_camel_case(k)
868 item.append(xml_text_element('{%s}%s' % (NS_OVF, xml_name), getattr(self, k)))
869 return item
870
871
872 class OVFAnnotation(OVFTextBlock):
873 info = "Description of the Product"
874 xml_name = "AnnotationSection"
875 xml_text_name = "Annotation"
876
877
878 class OVFEula(OVFTextBlock):
879 info = "End User License Agreement"
880 xml_name = "EulaSection"
881 xml_text_name = "License"
882
883
884 def _xml_element(self):
885 return ET.Element('{%s}%s' % (NS_OVF, self.xml_name), { '{%s}msgid' % NS_OVF: "eula"})
886
887
888 class OVFConfiguration(object):
889 keys = ['label', 'description', 'default']
890
891 def __init__(self, id, **kwargs):
892 self.id = id
893 self.default = False
894 self.info = "Information about the installed software"
895 self.__dict__.update((k, v) for k, v in kwargs.items() if k in self.keys)
896
897
898 @classmethod
899 def from_dict(cls, d):
900 item = cls(**d)
901 return item
902
903
904 def xml_item(self):
905 attrs = {'{%s}id' % NS_OVF: self.id}
906 if self.default:
907 attrs['{%s}default' % NS_OVF] = "true"
908 elem = ET.Element('{%s}Configuration' % NS_OVF, attrs)
909 elem.append(xml_text_element('{%s}%s' % (NS_OVF, 'Label'), getattr(self, 'label')))
910 elem.append(xml_text_element('{%s}%s' % (NS_OVF, 'Description'), getattr(self, 'description')))
911 return elem
912
913
914 class VmwExtraConfigItem(object):
915
916 def __init__(self, key, value, required=None):
917 self.key = key
918 self.value = value
919 self.required = required
920
921
922 @classmethod
923 def from_dict(cls, d):
924 item = cls(**d)
925 return item
926
927
928 def xml_item(self):
929 value = self.value
930 if type(value) is bool:
931 value = "true" if value else "false"
932 elif type(value) is not str:
933 value = str(value)
934
935 attrs = {'{%s}key' % NS_VMW: self.key, '{%s}value' % NS_VMW: value}
936 if self.required is not None:
937 attrs['{%s}required' % NS_OVF] = "true" if self.required else "false"
938 elem = ET.Element('{%s}ExtraConfig' % NS_VMW, attrs)
939 return elem
940
941
942 class OVF(object):
943
944 CONFIG_DEFAULTS = {
945 "cpuHotAddEnabled": "false",
946 "cpuHotRemoveEnabled": "false",
947 "memoryHotAddEnabled": "false",
948 "firmware": "bios",
949 "tools.syncTimeWithHost": "false",
950 "tools.afterPowerOn": "true",
951 "tools.afterResume": "true",
952 "tools.beforeGuestShutdown": "true",
953 "tools.beforeGuestStandby": "true",
954 "tools.toolsUpgradePolicy": "manual",
955 "powerOpInfo.powerOffType": "soft",
956 "powerOpInfo.resetType": "soft",
957 "powerOpInfo.suspendType": "hard",
958 "nestedHVEnabled": "false",
959 "virtualICH7MPresent": "false",
960 "virtualSMCPresent": "false",
961 "flags.vvtdEnabled": "false",
962 "flags.vbsEnabled": "false",
963 "bootOptions.efiSecureBootEnabled": "false",
964 "powerOpInfo.standbyAction": "checkpoint"
965 }
966
967
968 def __init__(self,
969 system, hardware_config,
970 files, disks,
971 networks,
972 vssd_system, rasd_items, extra_configs,
973 products, annotation, eula,
974 configurations):
975 self.hardware_config = {}
976 if not system.get('no_default_configs', False):
977 self.hardware_config.update(OVF.CONFIG_DEFAULTS)
978
979 if hardware_config:
980 self.hardware_config.update(hardware_config)
981
982 self.name = system['name']
983 self.os_cim = system.get('os_cim', 100)
984 self.os_vmw = system.get('os_vmw', "other4xLinux64Guest")
985 if 'os_name' in system:
986 self.os_name = system['os_name']
987 if 'firmware' in system:
988 if system['firmware'] not in ['bios','efi']:
989 raise ValidationError("os.firmware must be 'bios' or 'efi'")
990 self.hardware_config['firmware'] = system['firmware']
991 if 'secure_boot' in system:
992 if type(system['secure_boot']) is not bool:
993 raise ValidationError("os.secure_boot must be boolean")
994 self.hardware_config['bootOptions.efiSecureBootEnabled'] = "true" if system['secure_boot'] else "false"
995 self.files = files
996 self.disks = disks
997 self.networks = networks
998 self.vssd_system = vssd_system
999 self.rasd_items = rasd_items
1000 self.extra_configs = extra_configs
1001 self.products = products
1002 self.annotation = annotation
1003 self.eula = eula
1004 self.configurations = configurations
1005
1006 if 'default_configuration' in system:
1007 dflt_cfg = system['default_configuration']
1008 self.configurations[dflt_cfg].default = True
1009
1010 self.connect()
1011
1012
1013 @classmethod
1014 def from_dict(cls, config):
1015
1016 # search for files and disks in hardware config:
1017 files = []
1018 disks = []
1019 product = None
1020 annotation = None
1021 eula = None
1022 hardware_config = {}
1023
1024 assert 'hardware' in config, "config needs a 'hardware' section"
1025
1026 hardware = config['hardware']
1027 for hw_id, hw in hardware.items():
1028 if isinstance(hw, dict):
1029 if 'image' in hw:
1030 file = OVFFile(hw['image'],
1031 file_id=hw.get('file_id', None))
1032 files.append(file)
1033 hw['image'] = file
1034 elif 'disk_image' in hw or 'raw_image' in hw:
1035 if 'disk_image' not in hw:
1036 # if vmdk file is unset, use the raw image name and replace the extension
1037 hw['disk_image'] = os.path.splitext(hw['raw_image'])[0] + ".vmdk"
1038 disk = OVFDisk(hw['disk_image'],
1039 units=hw.get('units', None),
1040 raw_image=hw.get('raw_image', None),
1041 disk_id=hw.get('disk_id', None),
1042 file_id=hw.get('file_id', None),
1043 sector_size=hw.get('sector_size', None))
1044 disks.append(disk)
1045 files.append(disk.file)
1046 hw['disk'] = disk
1047 elif 'disk_capacity' in hw:
1048 disk = OVFEmptyDisk(hw['disk_capacity'],
1049 disk_id=hw.get('disk_id', None))
1050 disks.append(disk)
1051 hw['disk'] = disk
1052
1053 hardware_config = hardware.get('config', {})
1054
1055 networks = {}
1056 if 'networks' in config:
1057 for nw_id, nw in config['networks'].items():
1058 network = OVFNetwork.from_dict(nw)
1059 networks[nw_id] = network
1060
1061 vssd_system = VssdSystem.from_dict(config)
1062 rasd_items = cls.rasd_items_from_dict(config)
1063 extra_configs = cls.vmw_extra_config_items_from_dict(config)
1064
1065 products = []
1066 assert not ('product' in config and 'product_sections' in config), "can only have one of 'product' or 'product_sections'"
1067
1068 # we want properties in their own section ('environment')
1069 # but in OVF they are part of the ProductSection, so copy it
1070 if 'environment' in config:
1071 env = config['environment']
1072 if 'product' not in config:
1073 config['product'] = {}
1074 for cfg in ['transports', 'properties', 'categories']:
1075 if cfg in env:
1076 config['product'][cfg] = env[cfg]
1077
1078 if 'product' in config:
1079 product = OVFProduct.from_dict(config['product'])
1080
1081 if product:
1082 products.append(product)
1083
1084 if 'product_sections' in config:
1085 for p in config['product_sections']:
1086 products.append(OVFProduct.from_dict(p))
1087
1088 if 'annotation' in config:
1089 annotation = OVFAnnotation.from_dict(config['annotation'])
1090
1091 if 'eula' in config:
1092 eula = OVFEula.from_dict(config['eula'])
1093
1094 configurations = {}
1095 if 'configurations' in config:
1096 for k, v in config['configurations'].items():
1097 configurations[k] = OVFConfiguration(k, **v)
1098
1099 ovf = cls(config['system'], hardware_config, files, disks,
1100 networks, vssd_system, rasd_items, extra_configs,
1101 products, annotation, eula,
1102 configurations)
1103
1104 return ovf
1105
1106
1107 @classmethod
1108 def rasd_items_from_dict(cls, config):
1109 rasd_items = {}
1110 hardware = config['hardware']
1111 for hw_id, hw_config in hardware.items():
1112 if hw_id == 'config':
1113 continue
1114 elif hw_id == 'memory':
1115 cl_name = "RasdMemory"
1116 elif hw_id == 'cpus':
1117 cl_name = "RasdCpus"
1118 else:
1119 hw_type = hw_config['type']
1120 cl_name = "Rasd" + hw_type.title().replace("_", "")
1121 try:
1122 cl = getattr(sys.modules[__name__], cl_name)
1123 rasd_item = cl.from_dict(hw_config)
1124 if type(hw_config) is dict:
1125 rasd_item.configuration = hw_config.get('configuration', None)
1126 rasd_items[hw_id] = rasd_item
1127 except AttributeError:
1128 print(f"no class {cl_name}")
1129 raise
1130 return rasd_items
1131
1132
1133 @classmethod
1134 def vmw_extra_config_items_from_dict(cls, config):
1135 xtra_cfgs = []
1136 xconfigs = config.get('extra_configs', None)
1137 if xconfigs is None:
1138 return []
1139 for key, cfg in xconfigs.items():
1140 cfg['key'] = key
1141 xtra_cfg_item = VmwExtraConfigItem.from_dict(cfg)
1142 xtra_cfgs.append(xtra_cfg_item)
1143 return xtra_cfgs
1144
1145
1146 def connect(self):
1147 for hw_id, rasd_item in self.rasd_items.items():
1148 rasd_item.connect(self)
1149
1150
1151 @staticmethod
1152 def _disk_info(filename):
1153 out = subprocess.check_output([VMDK_CONVERT, "-i", "--detailed", filename]).decode("UTF-8")
1154 return json.loads(out)
1155
1156
1157 def to_xml(self):
1158 envelope = ET.Element('{%s}Envelope' % NS_OVF, nsmap=NS_MAP)
1159
1160 # References (files)
1161 references = ET.Element('{%s}References' % NS_OVF)
1162 for file in self.files:
1163 references.append(file.xml_item())
1164 envelope.append(references)
1165
1166 # DiskSection
1167 disk_section = ET.Element('{%s}DiskSection' % NS_OVF)
1168 disk_section.append(xml_text_element('{%s}Info' % NS_OVF, "Virtual disk information"))
1169
1170 for disk in self.disks:
1171 disk_section.append(disk.xml_item())
1172 envelope.append(disk_section)
1173
1174 if self.configurations:
1175 dos = ET.Element('{%s}DeploymentOptionSection' % NS_OVF)
1176 dos.append(xml_text_element('{%s}Info' % NS_OVF, "List of profiles"))
1177 for id, config in self.configurations.items():
1178 dos.append(config.xml_item())
1179 envelope.append(dos)
1180
1181 # NetworkSection
1182 network_section = ET.Element('{%s}NetworkSection' % NS_OVF)
1183 network_section.append(xml_text_element('{%s}Info' % NS_OVF, "Virtual Networks"))
1184 for nw_id, nw in self.networks.items():
1185 network_section.append(nw.xml_item())
1186 envelope.append(network_section)
1187
1188 # VirtualSystem
1189 virtual_system = ET.Element('{%s}VirtualSystem' % NS_OVF, { '{%s}id' % NS_OVF: 'vm' })
1190 virtual_system.append(xml_text_element('{%s}Info' % NS_OVF, "Virtual System"))
1191 envelope.append(virtual_system)
1192
1193 virtual_system.append(xml_text_element('{%s}Name' % NS_OVF, self.vssd_system.identifier))
1194 oss = ET.Element('{%s}OperatingSystemSection' % NS_OVF, { '{%s}id' % NS_OVF: str(self.os_cim), '{%s}osType' % NS_VMW: self.os_vmw })
1195 oss.append(xml_text_element('{%s}Info' % NS_OVF, "Operating System"))
1196 if hasattr(self, 'os_name'):
1197 oss.append(xml_text_element('{%s}Description' % NS_OVF, self.os_name))
1198 virtual_system.append(oss)
1199
1200 hw_attrs = None
1201 if self.products:
1202 transports = []
1203 for p in self.products:
1204 if p.transports:
1205 transports.extend(p.transports)
1206 transports = list(set(transports))
1207 hw_attrs = {'{%s}transport' % NS_OVF: " ".join(transports)}
1208
1209 hw = ET.Element('{%s}VirtualHardwareSection' % NS_OVF, hw_attrs)
1210
1211 hw.append(xml_text_element('{%s}Info' % NS_OVF, "Virtual Hardware"))
1212 virtual_system.append(hw)
1213
1214 hw.append(self.vssd_system.xml_item("Virtual Hardware Family"))
1215 for hw_id, rasd_item in self.rasd_items.items():
1216 xml_item = rasd_item.xml_item(True, hw_id)
1217 # sort rasd elements by tag:
1218 xml_item[:] = sorted(xml_item, key=lambda child: child.tag)
1219 hw.append(xml_item)
1220
1221 for xcfg in self.extra_configs:
1222 hw.append(xcfg.xml_item())
1223
1224 hw.extend(xml_configs(self.hardware_config))
1225
1226 if self.products:
1227 for p in self.products:
1228 virtual_system.append(p.xml_item())
1229
1230 if self.annotation:
1231 virtual_system.append(self.annotation.xml_item())
1232 if self.eula:
1233 virtual_system.append(self.eula.xml_item())
1234
1235 xml_indent(envelope)
1236 doc = ET.ElementTree(envelope)
1237 ET.cleanup_namespaces(doc)
1238 return doc
1239
1240
1241 def write_xml(self, ovf_file=None):
1242 if ovf_file == None:
1243 ovf_file = f"{self.name}.ovf"
1244 doc = self.to_xml()
1245 with open(ovf_file, "wb") as f:
1246 doc.write(f, pretty_print=True, exclusive=True, xml_declaration=True, encoding="UTF-8")
1247
1248 # if you know an easier way to produce a time stamp with the local tz, please fix:
1249 timestamp = datetime.datetime.now(
1250 datetime.datetime.now(datetime.timezone.utc).astimezone().tzinfo).strftime("%d-%m-%Y %H:%M:%S %z")
1251
1252 # ugly hack to insert a comment (there should be a better way)
1253 with open(ovf_file, "rt") as f:
1254 with open(f"{ovf_file}.tmp", "wt") as fout:
1255 line = f.readline()
1256 fout.write(line)
1257 fout.write(f"<!-- Generated by {APP_NAME} {timestamp} -->\n")
1258 for line in f.readlines():
1259 fout.write(line)
1260 os.rename(f"{ovf_file}.tmp", ovf_file)
1261
1262
1263 @staticmethod
1264 def _get_hash(args):
1265 filename, hash_type = args
1266 blocksz = 1024 * 1024
1267 hash = hashlib.new(hash_type)
1268 with open(filename, "rb") as f:
1269 while True:
1270 buf = f.read(blocksz)
1271 if not buf:
1272 break
1273 hash.update(buf)
1274 return hash.hexdigest()
1275
1276
1277 def write_manifest(self, ovf_file=None, mf_file=None, hash_type="sha512"):
1278 if ovf_file == None:
1279 ovf_file = f"{self.name}.ovf"
1280 if mf_file == None:
1281 mf_file = f"{self.name}.mf"
1282 filenames = [ovf_file]
1283
1284 for file in self.files:
1285 filenames.append(file.path)
1286
1287 with ProcessPoolExecutor() as executor:
1288 hash_results = list(zip(filenames, executor.map(OVF._get_hash, [(fname, hash_type) for fname in filenames])))
1289
1290 with open(mf_file, "wt") as f:
1291 for fname, hash in hash_results:
1292 fname = os.path.basename(fname)
1293 f.write(f"{hash_type.upper()}({fname})= {hash}\n")
1294
1295
1296 def sign_manifest(self, keyfile, ovf_file=None, mf_file=None, sign_alg="sha512"):
1297 if ovf_file == None:
1298 ovf_file = f"{self.name}.ovf"
1299 if mf_file == None:
1300 mf_file = f"{self.name}.mf"
1301 cert_file = os.path.splitext(ovf_file)[0] + ".cert"
1302
1303 with open(cert_file, "wt") as f:
1304 signature = subprocess.check_output(["openssl", "dgst", f"-{sign_alg}", "-sign", keyfile, "-out", "-", mf_file])
1305 f.write(f"{sign_alg.upper()}({mf_file})= {signature.hex()}\n")
1306
1307 with open(keyfile, "rt") as fin:
1308 do_copy = False
1309 for line in fin:
1310 if (line.startswith("-----BEGIN CERTIFICATE")):
1311 do_copy = True
1312 if do_copy:
1313 f.write(line)
1314 if (line.startswith("-----END CERTIFICATE")):
1315 break
1316 assert do_copy, f"no certificate found in {keyfile}"
1317
1318
1319 def sign_manifest_external(self, script_format, keyfile, ovf_file=None, mf_file=None, sign_alg="sha512"):
1320 if ovf_file == None:
1321 ovf_file = f"{self.name}.ovf"
1322 if mf_file == None:
1323 mf_file = f"{self.name}.mf"
1324 cert_file = os.path.splitext(ovf_file)[0] + ".cert"
1325
1326 script = script_format.format(ovf_file=ovf_file, mf_file=mf_file, sign_alg=sign_alg, cert_file=cert_file, keyfile=keyfile)
1327 subprocess.check_call(script, shell=True)
1328 assert os.path.isfile(cert_file), f"certificate file {cert_file} not created"
1329 assert os.path.getsize(cert_file) > 0, f"certificate file {cert_file} is empty"
1330
1331
1332 def usage():
1333 print(f"Usage: {sys.argv[0]} -i|--input-file <input file> -o|--output-file <output file> [--format ova|ovf|dir] [-q] [-h]")
1334 print("")
1335 print("Options:")
1336 print(" -i, --input-file <file> input file")
1337 print(" -o, --output-file <file> output file or directory name")
1338 print(" -f, --format ova|ovf|dir output format")
1339 print(" -m, --manifest create manifest file along with ovf (default true for output formats ova and dir)")
1340 print(" --checksum-type sha1|sha256|sha512 set the checksum type for the manifest. Must be sha1, sha256 or sha512.")
1341 print(" --sign <keyfile> sign the manifest file with the given keyfile")
1342 print(" --sign-alg sha1|sha256|sha512 set the signature algorithm for the manifest. Must be sha1, sha256 or sha512. Default is the same as the checksum-type.")
1343 print(" --sign-script <script> sign the manifest file with the given script")
1344 print(" --tar-format gnu|posix set the tar format for the ova file. Must be gnu or posix. Default is gnu.")
1345 print(" --vmdk-convert <path> set the path to the vmdk-convert tool (optional)")
1346 print(" -q quiet mode")
1347 print(" -h print help")
1348 print("")
1349 print("Output formats:")
1350 print(" ova: create an OVA file")
1351 print(" ovf: create OVF file only")
1352 print(" dir: create a directory with the OVF file, the manifest and symlinks to the referenced files (hard disk(s) and iso image(s))")
1353 print("")
1354 print("Specifying the format is optional if the output file name ends with '.ovf' or '.ova'")
1355 print("")
1356 print("Sign options:")
1357 print(" To sign the manifest file, you can use the --sign option to provide a keyfile, or the --sign-script option to provide a script.")
1358 print(" The keyfile should be a PEM encoded certificate and key file.")
1359 print(" Optionally, the signature algorithm (sha1, sha256, sha512) can be set with the --sign-alg option. Default is the same as the checksum-type.")
1360 print(" If no sign-script is given, ova-compose will use the keyfile to sign the manifest using openssl.")
1361 print(" If a sign-script is given, it should be a shell python style format string that takes the following arguments:")
1362 print(" - {ovf_file}: the path to the ovf file")
1363 print(" - {mf_file}: the path to the manifest file")
1364 print(" - {sign_alg}: the signature algorithm")
1365 print(" - {cert_file}: the path to the certificate file (the signature to be included)")
1366 print(" - {keyfile}: the path to the keyfile")
1367 print(" These arguments will be set by the ova-compose tool and passed to the script.")
1368 print(" It is expected that the script signs the file given by {mf_file} and writes the signature to {cert_file}.")
1369 print(" Refer to the DMTF DSP2434 specification for more details on the signature format.")
1370 print(" The script should be executable and should be in the PATH or the full path to the script should be provided.")
1371 print("")
1372 print("Example usage:")
1373 print(f" {sys.argv[0]} -i photon.yaml -o photon.ova")
1374
1375
1376 def yaml_param(loader, node):
1377 params = loader.app_params
1378 default = None
1379 key = node.value
1380
1381 assert type(key) is str, f"param name {key} must be a string"
1382
1383 if '=' in key:
1384 key, default = [t.strip() for t in key.split('=', maxsplit=1)]
1385 default = yaml.safe_load(default)
1386 value = params.get(key, default)
1387
1388 assert value is not None, f"no param set for '{key}', and there is no default"
1389
1390 return value
1391
1392
1393 def main():
1394 config_file = None
1395 output_file = None
1396 output_format = None
1397 basename = None
1398 do_quiet = False
1399 do_manifest = False
1400 params = {}
1401 checksum_type = "sha256"
1402 sign_keyfile = None
1403 sign_alg = None
1404 sign_script = None
1405 tar_format = "gnu"
1406
1407 try:
1408 opts, args = getopt.getopt(sys.argv[1:],
1409 'f:hi:mo:q',
1410 longopts=['format=', 'input-file=', 'manifest', 'output-file=', 'param=', 'checksum-type=', 'sign=', 'sign-alg=', 'sign-script=', 'tar-format=', 'vmdk-convert='])
1411 except:
1412 print ("invalid option")
1413 sys.exit(2)
1414
1415 for o, a in opts:
1416 if o in ['-i', '--input-file']:
1417 config_file = a
1418 elif o in ['-o', '--output-file']:
1419 output_file = a
1420 elif o in ['-f', '--format']:
1421 output_format = a
1422 elif o in ['-m', '--manifest']:
1423 do_manifest = True
1424 elif o in ['--checksum-type']:
1425 checksum_type = a
1426 elif o in ['--param']:
1427 k,v = a.split('=', maxsplit=1)
1428 params[k] = yaml.safe_load(v)
1429 elif o in ['--tar-format']:
1430 tar_format = a
1431 elif o in ['--vmdk-convert']:
1432 global VMDK_CONVERT
1433 VMDK_CONVERT = a
1434 elif o in ['-q']:
1435 do_quiet = True
1436 elif o in ['-s', '--sign']:
1437 sign_keyfile = a
1438 elif o in ['--sign-alg']:
1439 sign_alg = a
1440 elif o in ['--sign-script']:
1441 sign_script = a
1442 elif o in ['-h']:
1443 usage()
1444 sys.exit(0)
1445 else:
1446 assert False, f"unhandled option {o}"
1447
1448 assert config_file != None, "no input file specified"
1449 assert output_file != None, "no output file/directory specified"
1450
1451 assert checksum_type in ["sha1", "sha512", "sha256"], f"checksum-type '{checksum_type}' is invalid"
1452 if sign_alg is None:
1453 sign_alg = checksum_type
1454 assert sign_alg in ["sha1", "sha512", "sha256"], f"checksum-type '{sign_alg}' is invalid"
1455
1456 if sign_keyfile is not None:
1457 sign_keyfile = os.path.abspath(sign_keyfile)
1458
1459 if config_file != None:
1460 f = open(config_file, 'r')
1461
1462 yaml_loader = yaml.SafeLoader
1463 yaml_loader.app_params = params
1464 yaml.add_constructor("!param", yaml_param, Loader=yaml_loader)
1465
1466 config = yaml.load(f, Loader=yaml_loader)
1467 if f != sys.stdin:
1468 f.close()
1469
1470 ovf = OVF.from_dict(config)
1471
1472 if output_format is None:
1473 if output_file.endswith(".ova"):
1474 # create an ova file
1475 output_format = "ova"
1476 elif output_file.endswith(".ovf"):
1477 # create just ovf (and maybe mf) file
1478 output_format = "ovf"
1479
1480 assert output_format != None, "no output format specified"
1481 assert output_format in ['ova', 'ovf', 'dir'], f"invalid output_format '{output_format}'"
1482
1483 if not do_quiet:
1484 print (f"creating '{output_file}' with format '{output_format}' from '{config_file}'")
1485
1486 if output_format != "dir":
1487 basename = os.path.basename(output_file)[:-4]
1488 else:
1489 basename = os.path.basename(output_file)
1490 mf_file = f"{basename}.mf"
1491
1492 if output_format == "ovf":
1493 ovf_file = output_file
1494 ovf.write_xml(ovf_file=ovf_file)
1495 if do_manifest:
1496 ovf.write_manifest(ovf_file=ovf_file, mf_file=mf_file, hash_type=checksum_type)
1497 if sign_keyfile is not None or sign_script is not None:
1498 if sign_script is None:
1499 ovf.sign_manifest(sign_keyfile, ovf_file=ovf_file, mf_file=mf_file, sign_alg=sign_alg)
1500 else:
1501 ovf.sign_manifest_external(sign_script, sign_keyfile, ovf_file=ovf_file, mf_file=mf_file, sign_alg=sign_alg)
1502 elif output_format == "ova" or output_format == "dir":
1503 pwd = os.getcwd()
1504 tmpdir = tempfile.mkdtemp(prefix=f"{basename}-", dir=pwd)
1505 try:
1506 os.chdir(tmpdir)
1507 ovf_file = f"{basename}.ovf"
1508 ovf.write_xml(ovf_file=ovf_file)
1509
1510 all_files = [ovf_file, mf_file]
1511 for file in ovf.files:
1512 dst = os.path.basename(file.path)
1513 os.symlink(os.path.join(pwd, file.path), dst)
1514 all_files.append(dst)
1515
1516 ovf.write_manifest(ovf_file=ovf_file, mf_file=mf_file, hash_type=checksum_type)
1517 if sign_keyfile is not None or sign_script is not None:
1518 if sign_script is None:
1519 ovf.sign_manifest(sign_keyfile, ovf_file=ovf_file, mf_file=mf_file, sign_alg=sign_alg)
1520 else:
1521 ovf.sign_manifest_external(sign_script, sign_keyfile, ovf_file=ovf_file, mf_file=mf_file, sign_alg=sign_alg)
1522 cert_file = os.path.splitext(ovf_file)[0] + ".cert"
1523 all_files.append(cert_file)
1524
1525 if output_format == "ova":
1526 ret = subprocess.check_call(["tar", f"--format={tar_format}", "-h",
1527 "--owner=0", "--group=0", "--mode=0644",
1528 "-cf",
1529 os.path.join(pwd, output_file)] + all_files)
1530 os.chdir(pwd)
1531 shutil.rmtree(tmpdir)
1532 else:
1533 os.chdir(pwd)
1534 shutil.move(tmpdir, output_file)
1535 except Exception as e:
1536 os.chdir(pwd)
1537 if os.path.isdir(tmpdir):
1538 shutil.rmtree(tmpdir)
1539 raise e
1540
1541 if not do_quiet:
1542 print ("done.")
1543
1544
1545 if __name__ == "__main__":
1546 main()