Revision 2cfbc784 lib/ovf.py

b/lib/ovf.py
1 1
#!/usr/bin/python
2 2
#
3 3

  
4
# Copyright (C) 2011 Google Inc.
4
# Copyright (C) 2011, 2012 Google Inc.
5 5
#
6 6
# This program is free software; you can redistribute it and/or modify
7 7
# it under the terms of the GNU General Public License as published by
......
152 152
  """
153 153
  if not constants.QEMUIMG_PATH:
154 154
    raise errors.OpPrereqError("qemu-img not found at build time, unable"
155
                               " to continue")
155
                               " to continue", errors.ECODE_STATE)
156 156

  
157 157

  
158 158
def LinkFile(old_path, prefix=None, suffix=None, directory=None):
......
191 191
        counter += 1
192 192
      else:
193 193
        raise errors.OpPrereqError("Error moving the file %s to %s location:"
194
                                   " %s" % (old_path, new_path, err))
194
                                   " %s" % (old_path, new_path, err),
195
                                   errors.ECODE_ENVIRON)
195 196
  return new_path
196 197

  
197 198

  
......
228 229
      self.tree.parse(input_path)
229 230
    except (ParseError, xml.parsers.expat.ExpatError), err:
230 231
      raise errors.OpPrereqError("Error while reading %s file: %s" %
231
                                 (OVF_EXT, err))
232
                                 (OVF_EXT, err), errors.ECODE_ENVIRON)
232 233

  
233 234
    # Create a list of all files in the OVF package
234 235
    (input_dir, input_file) = os.path.split(input_path)
......
245 246
    for file_name in files_list:
246 247
      file_path = utils.PathJoin(input_dir, file_name)
247 248
      if not os.path.exists(file_path):
248
        raise errors.OpPrereqError("File does not exist: %s" % file_path)
249
        raise errors.OpPrereqError("File does not exist: %s" % file_path,
250
                                   errors.ECODE_ENVIRON)
249 251
    logging.info("Files in the OVF package: %s", " ".join(files_list))
250 252
    self.files_list = files_list
251 253
    self.input_dir = input_dir
......
360 362
      for file_name, value in manifest_files.iteritems():
361 363
        if sha1_sums.get(utils.PathJoin(self.input_dir, file_name)) != value:
362 364
          raise errors.OpPrereqError("SHA1 checksum of %s does not match the"
363
                                     " value in manifest file" % file_name)
365
                                     " value in manifest file" % file_name,
366
                                     errors.ECODE_ENVIRON)
364 367
      logging.info("SHA1 checksums verified")
365 368

  
366 369
  def GetInstanceName(self):
......
451 454
      matching_units = [units for units, variants in
452 455
        ALLOCATION_UNITS.iteritems() if alloc_units.lower() in variants]
453 456
      if matching_units == []:
454
        raise errors.OpPrereqError("Unit %s for RAM memory unknown",
455
          alloc_units)
457
        raise errors.OpPrereqError("Unit %s for RAM memory unknown" %
458
                                   alloc_units, errors.ECODE_INVAL)
456 459
      units = matching_units[0]
457 460
      memory_raw = int(memory.findtext("{%s}VirtualQuantity" % RASD_SCHEMA,
458 461
            default=constants.VALUE_AUTO))
......
579 582
      disk_elem = self._GetElementMatchingAttr(disk_search, disk_match)
580 583
      if disk_elem is None:
581 584
        raise errors.OpPrereqError("%s file corrupted - disk %s not found in"
582
                                   " references" % (OVF_EXT, disk))
585
                                   " references" % (OVF_EXT, disk),
586
                                   errors.ECODE_ENVIRON)
583 587
      disk_name = disk_elem.get("{%s}href" % OVF_SCHEMA)
584 588
      disk_compression = disk_elem.get("{%s}compression" % OVF_SCHEMA)
585 589
      results.append((disk_name, disk_compression))
......
860 864
    """
861 865
    input_path = os.path.abspath(input_path)
862 866
    if not os.path.isfile(input_path):
863
      raise errors.OpPrereqError("File does not exist: %s" % input_path)
867
      raise errors.OpPrereqError("File does not exist: %s" % input_path,
868
                                 errors.ECODE_ENVIRON)
864 869
    self.options = options
865 870
    self.temp_file_manager = utils.TemporaryFileManager()
866 871
    self.temp_dir = None
......
896 901
    # For now we only support gzip, as it is used in ovftool
897 902
    if compression != COMPRESSION_TYPE:
898 903
      raise errors.OpPrereqError("Unsupported compression type: %s"
899
                                 % compression)
904
                                 % compression, errors.ECODE_INVAL)
900 905
    disk_file = os.path.basename(disk_path)
901 906
    if action == DECOMPRESS:
902 907
      (disk_name, _) = os.path.splitext(disk_file)
......
910 915
    run_result = utils.RunCmd(args, output=new_path)
911 916
    if run_result.failed:
912 917
      raise errors.OpPrereqError("Disk %s failed with output: %s"
913
                                 % (action, run_result.stderr))
918
                                 % (action, run_result.stderr),
919
                                 errors.ECODE_ENVIRON)
914 920
    logging.info("The %s of the disk is completed", action)
915 921
    return (COMPRESSION_EXT, new_path)
916 922

  
......
948 954
    run_result = utils.RunCmd(args, cwd=os.getcwd())
949 955
    if run_result.failed:
950 956
      raise errors.OpPrereqError("Convertion to %s failed, qemu-img output was"
951
                                 ": %s" % (disk_format, run_result.stderr))
957
                                 ": %s" % (disk_format, run_result.stderr),
958
                                 errors.ECODE_ENVIRON)
952 959
    return (".%s" % disk_format, new_disk_path)
953 960

  
954 961
  @staticmethod
......
970 977
    run_result = utils.RunCmd(args, cwd=os.getcwd())
971 978
    if run_result.failed:
972 979
      raise errors.OpPrereqError("Gathering info about the disk using qemu-img"
973
                                 " failed, output was: %s" % run_result.stderr)
980
                                 " failed, output was: %s" % run_result.stderr,
981
                                 errors.ECODE_ENVIRON)
974 982
    result = run_result.output
975 983
    regexp = r"%s" % regexp
976 984
    match = re.search(regexp, result)
......
978 986
      disk_format = match.group(1)
979 987
    else:
980 988
      raise errors.OpPrereqError("No file information matching %s found in:"
981
                                 " %s" % (regexp, result))
989
                                 " %s" % (regexp, result),
990
                                 errors.ECODE_ENVIRON)
982 991
    return disk_format
983 992

  
984 993
  def Parse(self):
......
1063 1072
      self._UnpackOVA(input_path)
1064 1073
    else:
1065 1074
      raise errors.OpPrereqError("Unknown file extension; expected %s or %s"
1066
                                 " file" % (OVA_EXT, OVF_EXT))
1075
                                 " file" % (OVA_EXT, OVF_EXT),
1076
                                 errors.ECODE_INVAL)
1067 1077
    assert ((input_extension == OVA_EXT and self.temp_dir) or
1068 1078
            (input_extension == OVF_EXT and not self.temp_dir))
1069 1079
    assert self.input_dir in self.input_path
......
1095 1105
    input_name = None
1096 1106
    if not tarfile.is_tarfile(input_path):
1097 1107
      raise errors.OpPrereqError("The provided %s file is not a proper tar"
1098
                                 " archive", OVA_EXT)
1108
                                 " archive" % OVA_EXT, errors.ECODE_ENVIRON)
1099 1109
    ova_content = tarfile.open(input_path)
1100 1110
    temp_dir = tempfile.mkdtemp()
1101 1111
    self.temp_dir = temp_dir
......
1105 1115
        utils.PathJoin(temp_dir, file_normname)
1106 1116
      except ValueError, err:
1107 1117
        raise errors.OpPrereqError("File %s inside %s package is not safe" %
1108
                                   (file_name, OVA_EXT))
1118
                                   (file_name, OVA_EXT), errors.ECODE_ENVIRON)
1109 1119
      if file_name.endswith(OVF_EXT):
1110 1120
        input_name = file_name
1111 1121
    if not input_name:
1112 1122
      raise errors.OpPrereqError("No %s file in %s package found" %
1113
                                 (OVF_EXT, OVA_EXT))
1123
                                 (OVF_EXT, OVA_EXT), errors.ECODE_ENVIRON)
1114 1124
    logging.warning("Unpacking the %s archive, this may take a while",
1115 1125
      input_path)
1116 1126
    self.input_dir = temp_dir
......
1126 1136
        extract(self.temp_dir)
1127 1137
    except tarfile.TarError, err:
1128 1138
      raise errors.OpPrereqError("Error while extracting %s archive: %s" %
1129
                                 (OVA_EXT, err))
1139
                                 (OVA_EXT, err), errors.ECODE_ENVIRON)
1130 1140
    logging.info("OVA package extracted to %s directory", self.temp_dir)
1131 1141

  
1132 1142
  def Parse(self):
......
1142 1152
    self.results_name = self._GetInfo("instance name", self.options.name,
1143 1153
      self._ParseNameOptions, self.ovf_reader.GetInstanceName)
1144 1154
    if not self.results_name:
1145
      raise errors.OpPrereqError("Name of instance not provided")
1155
      raise errors.OpPrereqError("Name of instance not provided",
1156
                                 errors.ECODE_INVAL)
1146 1157

  
1147 1158
    self.output_dir = utils.PathJoin(self.output_dir, self.results_name)
1148 1159
    try:
1149 1160
      utils.Makedirs(self.output_dir)
1150 1161
    except OSError, err:
1151 1162
      raise errors.OpPrereqError("Failed to create directory %s: %s" %
1152
                                 (self.output_dir, err))
1163
                                 (self.output_dir, err), errors.ECODE_ENVIRON)
1153 1164

  
1154 1165
    self.results_template = self._GetInfo("disk template",
1155 1166
      self.options.disk_template, self._ParseTemplateOptions,
......
1167 1178
    self.results_os = self._GetInfo("OS", self.options.os,
1168 1179
      self._ParseOSOptions, self.ovf_reader.GetOSData)
1169 1180
    if not self.results_os.get("os_name"):
1170
      raise errors.OpPrereqError("OS name must be provided")
1181
      raise errors.OpPrereqError("OS name must be provided",
1182
                                 errors.ECODE_INVAL)
1171 1183

  
1172 1184
    self.results_backend = self._GetInfo("backend", self.options.beparams,
1173 1185
      self._ParseBackendOptions, self.ovf_reader.GetBackendData)
......
1194 1206

  
1195 1207
    if not self.results_disk and not self.results_network:
1196 1208
      raise errors.OpPrereqError("Either disk specification or network"
1197
                                 " description must be present")
1209
                                 " description must be present",
1210
                                 errors.ECODE_STATE)
1198 1211

  
1199 1212
  @staticmethod
1200 1213
  def _GetInfo(name, cmd_arg, cmd_function, nocmd_function,
......
1340 1353
          disk_size = utils.ParseUnit(disk_desc["size"])
1341 1354
        except ValueError:
1342 1355
          raise errors.OpPrereqError("Invalid disk size for disk %s: %s" %
1343
                                     (disk_id, disk_desc["size"]))
1356
                                     (disk_id, disk_desc["size"]),
1357
                                     errors.ECODE_INVAL)
1344 1358
        new_path = utils.PathJoin(self.output_dir, str(disk_id))
1345 1359
        args = [
1346 1360
          constants.QEMUIMG_PATH,
......
1353 1367
        run_result = utils.RunCmd(args)
1354 1368
        if run_result.failed:
1355 1369
          raise errors.OpPrereqError("Creation of disk %s failed, output was:"
1356
                                     " %s" % (new_path, run_result.stderr))
1370
                                     " %s" % (new_path, run_result.stderr),
1371
                                     errors.ECODE_ENVIRON)
1357 1372
        results["disk%s_size" % disk_id] = str(disk_size)
1358 1373
        results["disk%s_dump" % disk_id] = "disk%s.raw" % disk_id
1359 1374
      else:
1360 1375
        raise errors.OpPrereqError("Disks created for import must have their"
1361
                                   " size specified")
1376
                                   " size specified",
1377
                                   errors.ECODE_INVAL)
1362 1378
    results["disk_count"] = str(len(self.options.disks))
1363 1379
    return results
1364 1380

  
......
1376 1392
    for (counter, (disk_name, disk_compression)) in enumerate(disks_list):
1377 1393
      if os.path.dirname(disk_name):
1378 1394
        raise errors.OpPrereqError("Disks are not allowed to have absolute"
1379
                                   " paths or paths outside main OVF directory")
1395
                                   " paths or paths outside main OVF"
1396
                                   " directory", errors.ECODE_ENVIRON)
1380 1397
      disk, _ = os.path.splitext(disk_name)
1381 1398
      disk_path = utils.PathJoin(self.input_dir, disk_name)
1382 1399
      if disk_compression not in NO_COMPRESSION:
......
1451 1468
    try:
1452 1469
      utils.WriteFile(output_file_name, data=output_contents)
1453 1470
    except errors.ProgrammerError, err:
1454
      raise errors.OpPrereqError("Saving the config file failed: %s" % err)
1471
      raise errors.OpPrereqError("Saving the config file failed: %s" % err,
1472
                                 errors.ECODE_ENVIRON)
1455 1473

  
1456 1474
    self.Cleanup()
1457 1475

  
......
1531 1549
      self.config_parser.read(input_path)
1532 1550
    except ConfigParser.MissingSectionHeaderError, err:
1533 1551
      raise errors.OpPrereqError("Error when trying to read %s: %s" %
1534
                                 (input_path, err))
1552
                                 (input_path, err), errors.ECODE_ENVIRON)
1535 1553
    if self.options.ova_package:
1536 1554
      self.temp_dir = tempfile.mkdtemp()
1537 1555
      self.packed_dir = self.output_dir
......
1553 1571
    else:
1554 1572
      name = self.config_parser.get(constants.INISECT_INS, NAME)
1555 1573
    if name is None:
1556
      raise errors.OpPrereqError("No instance name found")
1574
      raise errors.OpPrereqError("No instance name found",
1575
                                 errors.ECODE_ENVIRON)
1557 1576
    return name
1558 1577

  
1559 1578
  def _ParseVCPUs(self):
......
1567 1586
    """
1568 1587
    vcpus = self.config_parser.getint(constants.INISECT_BEP, VCPUS)
1569 1588
    if vcpus == 0:
1570
      raise errors.OpPrereqError("No CPU information found")
1589
      raise errors.OpPrereqError("No CPU information found",
1590
                                 errors.ECODE_ENVIRON)
1571 1591
    return vcpus
1572 1592

  
1573 1593
  def _ParseMemory(self):
......
1581 1601
    """
1582 1602
    memory = self.config_parser.getint(constants.INISECT_BEP, MEMORY)
1583 1603
    if memory == 0:
1584
      raise errors.OpPrereqError("No memory information found")
1604
      raise errors.OpPrereqError("No memory information found",
1605
                                 errors.ECODE_ENVIRON)
1585 1606
    return memory
1586 1607

  
1587 1608
  def _ParseGaneti(self):
......
1596 1617
    results["hypervisor"] = {}
1597 1618
    hyp_name = self.config_parser.get(constants.INISECT_INS, HYPERV)
1598 1619
    if hyp_name is None:
1599
      raise errors.OpPrereqError("No hypervisor information found")
1620
      raise errors.OpPrereqError("No hypervisor information found",
1621
                                 errors.ECODE_ENVIRON)
1600 1622
    results["hypervisor"]["name"] = hyp_name
1601 1623
    pairs = self.config_parser.items(constants.INISECT_HYP)
1602 1624
    for (name, value) in pairs:
......
1605 1627
    results["os"] = {}
1606 1628
    os_name = self.config_parser.get(constants.INISECT_EXP, OS)
1607 1629
    if os_name is None:
1608
      raise errors.OpPrereqError("No operating system information found")
1630
      raise errors.OpPrereqError("No operating system information found",
1631
                                 errors.ECODE_ENVIRON)
1609 1632
    results["os"]["name"] = os_name
1610 1633
    pairs = self.config_parser.items(constants.INISECT_OSP)
1611 1634
    for (name, value) in pairs:
......
1648 1671
      })
1649 1672
      if results[counter]["mode"] not in constants.NIC_VALID_MODES:
1650 1673
        raise errors.OpPrereqError("Network mode %s not recognized"
1651
                                   % results[counter]["mode"])
1674
                                   % results[counter]["mode"],
1675
                                   errors.ECODE_INVAL)
1652 1676
      counter += 1
1653 1677
    return results
1654 1678

  
......
1666 1690
    disk_path = utils.PathJoin(self.input_dir, disk_file)
1667 1691
    results = {}
1668 1692
    if not os.path.isfile(disk_path):
1669
      raise errors.OpPrereqError("Disk image does not exist: %s" % disk_path)
1693
      raise errors.OpPrereqError("Disk image does not exist: %s" % disk_path,
1694
                                 errors.ECODE_ENVIRON)
1670 1695
    if os.path.dirname(disk_file):
1671 1696
      raise errors.OpPrereqError("Path for the disk: %s contains a directory"
1672
                                 " name" % disk_path)
1697
                                 " name" % disk_path, errors.ECODE_ENVIRON)
1673 1698
    disk_name, _ = os.path.splitext(disk_file)
1674 1699
    ext, new_disk_path = self._ConvertDisk(self.options.disk_format, disk_path)
1675 1700
    results["format"] = self.options.disk_format
......
1715 1740
      utils.Makedirs(self.output_dir)
1716 1741
    except OSError, err:
1717 1742
      raise errors.OpPrereqError("Failed to create directory %s: %s" %
1718
                                 (self.output_dir, err))
1743
                                 (self.output_dir, err), errors.ECODE_ENVIRON)
1719 1744

  
1720 1745
    self.references_files = []
1721 1746
    self.results_name = self._ParseName()
......
1749 1774
    try:
1750 1775
      utils.WriteFile(path, data=data)
1751 1776
    except errors.ProgrammerError, err:
1752
      raise errors.OpPrereqError("Saving the manifest file failed: %s" % err)
1777
      raise errors.OpPrereqError("Saving the manifest file failed: %s" % err,
1778
                                 errors.ECODE_ENVIRON)
1753 1779

  
1754 1780
  @staticmethod
1755 1781
  def _PrepareTarFile(tar_path, files_list):
......
1808 1834
        utils.Makedirs(self.packed_dir)
1809 1835
      except OSError, err:
1810 1836
        raise errors.OpPrereqError("Failed to create directory %s: %s" %
1811
                                   (self.packed_dir, err))
1837
                                   (self.packed_dir, err),
1838
                                   errors.ECODE_ENVIRON)
1812 1839
      self._PrepareTarFile(packed_path, files_list)
1813 1840
    logging.info("Creation of the OVF package was successfull")
1814 1841
    self.Cleanup()

Also available in: Unified diff