aos_version.py 8.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204
  1. #!/usr/bin/python
  2. '''
  3. Ansible module for yum-based systems determining if multiple releases
  4. of an OpenShift package are available, and if the release requested
  5. (if any) is available down to the given precision.
  6. For Enterprise, multiple releases available suggest that multiple repos
  7. are enabled for the different releases, which may cause installation
  8. problems. With Origin, however, this is a normal state of affairs as
  9. all the releases are provided in a single repo with the expectation that
  10. only the latest can be installed.
  11. Code in the openshift_version role contains a lot of logic to pin down
  12. the exact package and image version to use and so does some validation
  13. of release availability already. Without duplicating all that, we would
  14. like the user to have a helpful error message if we detect things will
  15. not work out right. Note that if openshift_release is not specified in
  16. the inventory, the version comparison checks just pass.
  17. '''
  18. from ansible.module_utils.basic import AnsibleModule
  19. IMPORT_EXCEPTION = None
  20. try:
  21. import yum # pylint: disable=import-error
  22. except ImportError as err:
  23. IMPORT_EXCEPTION = err # in tox test env, yum import fails
  24. class AosVersionException(Exception):
  25. '''Base exception class for package version problems'''
  26. def __init__(self, message, problem_pkgs=None):
  27. Exception.__init__(self, message)
  28. self.problem_pkgs = problem_pkgs
  29. def main():
  30. """Entrypoint for this Ansible module"""
  31. module = AnsibleModule(
  32. argument_spec=dict(
  33. package_list=dict(type="list", required=True),
  34. ),
  35. supports_check_mode=True
  36. )
  37. if IMPORT_EXCEPTION:
  38. module.fail_json(msg="aos_version module could not import yum: %s" % IMPORT_EXCEPTION)
  39. # determine the packages we will look for
  40. package_list = module.params['package_list']
  41. if not package_list:
  42. module.fail_json(msg="package_list must not be empty")
  43. # generate set with only the names of expected packages
  44. expected_pkg_names = [p["name"] for p in package_list]
  45. # gather packages that require a multi_minor_release check
  46. multi_minor_pkgs = [p for p in package_list if p["check_multi"]]
  47. # generate list of packages with a specified (non-empty) version
  48. # should look like a version string with possibly many segments e.g. "3.4.1"
  49. versioned_pkgs = [p for p in package_list if p["version"]]
  50. # get the list of packages available and complain if anything is wrong
  51. try:
  52. pkgs = _retrieve_available_packages(expected_pkg_names)
  53. if versioned_pkgs:
  54. _check_precise_version_found(pkgs, _to_dict(versioned_pkgs))
  55. _check_higher_version_found(pkgs, _to_dict(versioned_pkgs))
  56. if multi_minor_pkgs:
  57. _check_multi_minor_release(pkgs, _to_dict(multi_minor_pkgs))
  58. except AosVersionException as excinfo:
  59. module.fail_json(msg=str(excinfo))
  60. module.exit_json(changed=False)
  61. def _to_dict(pkg_list):
  62. return {pkg["name"]: pkg for pkg in pkg_list}
  63. def _retrieve_available_packages(expected_pkgs):
  64. # search for package versions available for openshift pkgs
  65. yb = yum.YumBase() # pylint: disable=invalid-name
  66. # The openshift excluder prevents unintended updates to openshift
  67. # packages by setting yum excludes on those packages. See:
  68. # https://wiki.centos.org/SpecialInterestGroup/PaaS/OpenShift-Origin-Control-Updates
  69. # Excludes are then disabled during an install or upgrade, but
  70. # this check will most likely be running outside either. When we
  71. # attempt to determine what packages are available via yum they may
  72. # be excluded. So, for our purposes here, disable excludes to see
  73. # what will really be available during an install or upgrade.
  74. yb.conf.disable_excludes = ['all']
  75. try:
  76. pkgs = yb.pkgSack.returnPackages(patterns=expected_pkgs)
  77. except yum.Errors.PackageSackError as excinfo:
  78. # you only hit this if *none* of the packages are available
  79. raise AosVersionException('\n'.join([
  80. 'Unable to find any OpenShift packages.',
  81. 'Check your subscription and repo settings.',
  82. str(excinfo),
  83. ]))
  84. return pkgs
  85. class PreciseVersionNotFound(AosVersionException):
  86. """Exception for reporting packages not available at given version"""
  87. def __init__(self, not_found):
  88. msg = ['Not all of the required packages are available at their requested version']
  89. msg += ['{}:{} '.format(pkg["name"], pkg["version"]) for pkg in not_found]
  90. msg += ['Please check your subscriptions and enabled repositories.']
  91. AosVersionException.__init__(self, '\n'.join(msg), not_found)
  92. def _check_precise_version_found(pkgs, expected_pkgs_dict):
  93. # see if any packages couldn't be found at requested release version
  94. # we would like to verify that the latest available pkgs have however specific a version is given.
  95. # so e.g. if there is a package version 3.4.1.5 the check passes; if only 3.4.0, it fails.
  96. pkgs_precise_version_found = set()
  97. for pkg in pkgs:
  98. if pkg.name not in expected_pkgs_dict:
  99. continue
  100. # does the version match, to the precision requested?
  101. # and, is it strictly greater, at the precision requested?
  102. expected_pkg_version = expected_pkgs_dict[pkg.name]["version"]
  103. match_version = '.'.join(pkg.version.split('.')[:expected_pkg_version.count('.') + 1])
  104. if match_version == expected_pkg_version:
  105. pkgs_precise_version_found.add(pkg.name)
  106. not_found = []
  107. for name, pkg in expected_pkgs_dict.items():
  108. if name not in pkgs_precise_version_found:
  109. not_found.append(pkg)
  110. if not_found:
  111. raise PreciseVersionNotFound(not_found)
  112. class FoundHigherVersion(AosVersionException):
  113. """Exception for reporting that a higher version than requested is available"""
  114. def __init__(self, higher_found):
  115. msg = ['Some required package(s) are available at a version',
  116. 'that is higher than requested']
  117. msg += [' ' + name for name in higher_found]
  118. msg += ['This will prevent installing the version you requested.']
  119. msg += ['Please check your enabled repositories or adjust openshift_release.']
  120. AosVersionException.__init__(self, '\n'.join(msg), higher_found)
  121. def _check_higher_version_found(pkgs, expected_pkgs_dict):
  122. expected_pkg_names = list(expected_pkgs_dict)
  123. # see if any packages are available in a version higher than requested
  124. higher_version_for_pkg = {}
  125. for pkg in pkgs:
  126. if pkg.name not in expected_pkg_names:
  127. continue
  128. expected_pkg_version = expected_pkgs_dict[pkg.name]["version"]
  129. req_release_arr = [int(segment) for segment in expected_pkg_version.split(".")]
  130. version = [int(segment) for segment in pkg.version.split(".")]
  131. too_high = version[:len(req_release_arr)] > req_release_arr
  132. higher_than_seen = version > higher_version_for_pkg.get(pkg.name, [])
  133. if too_high and higher_than_seen:
  134. higher_version_for_pkg[pkg.name] = version
  135. if higher_version_for_pkg:
  136. higher_found = []
  137. for name, version in higher_version_for_pkg.items():
  138. higher_found.append(name + '-' + '.'.join(str(segment) for segment in version))
  139. raise FoundHigherVersion(higher_found)
  140. class FoundMultiRelease(AosVersionException):
  141. """Exception for reporting multiple minor releases found for same package"""
  142. def __init__(self, multi_found):
  143. msg = ['Multiple minor versions of these packages are available']
  144. msg += [' ' + name for name in multi_found]
  145. msg += ["There should only be one OpenShift release repository enabled at a time."]
  146. AosVersionException.__init__(self, '\n'.join(msg), multi_found)
  147. def _check_multi_minor_release(pkgs, expected_pkgs_dict):
  148. # see if any packages are available in more than one minor version
  149. pkgs_by_name_version = {}
  150. for pkg in pkgs:
  151. # keep track of x.y (minor release) versions seen
  152. minor_release = '.'.join(pkg.version.split('.')[:2])
  153. if pkg.name not in pkgs_by_name_version:
  154. pkgs_by_name_version[pkg.name] = set()
  155. pkgs_by_name_version[pkg.name].add(minor_release)
  156. multi_found = []
  157. for name in expected_pkgs_dict:
  158. if name in pkgs_by_name_version and len(pkgs_by_name_version[name]) > 1:
  159. multi_found.append(name)
  160. if multi_found:
  161. raise FoundMultiRelease(multi_found)
  162. if __name__ == '__main__':
  163. main()