sanity_checks.py 8.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198
  1. """
  2. Ansible action plugin to ensure inventory variables are set
  3. appropriately and no conflicting options have been provided.
  4. """
  5. import re
  6. from ansible.plugins.action import ActionBase
  7. from ansible import errors
  8. # Valid values for openshift_deployment_type
  9. VALID_DEPLOYMENT_TYPES = ('origin', 'openshift-enterprise')
  10. # Tuple of variable names and default values if undefined.
  11. NET_PLUGIN_LIST = (('openshift_use_openshift_sdn', True),
  12. ('openshift_use_flannel', False),
  13. ('openshift_use_nuage', False),
  14. ('openshift_use_contiv', False),
  15. ('openshift_use_calico', False))
  16. ENTERPRISE_TAG_REGEX_ERROR = """openshift_image_tag must be in the format
  17. v#.#[.#[.#]]. Examples: v1.2, v3.4.1, v3.5.1.3,
  18. v3.5.1.3.4, v1.2-1, v1.2.3-4, v1.2.3-4.5, v1.2.3-4.5.6
  19. You specified openshift_image_tag={}"""
  20. ORIGIN_TAG_REGEX_ERROR = """openshift_image_tag must be in the format
  21. v#.#.#[-optional.#]. Examples: v1.2.3, v3.5.1-alpha.1
  22. You specified openshift_image_tag={}"""
  23. ORIGIN_TAG_REGEX = {'re': '(^v?\\d+\\.\\d+\\.\\d+(-[\\w\\-\\.]*)?$)',
  24. 'error_msg': ORIGIN_TAG_REGEX_ERROR}
  25. ENTERPRISE_TAG_REGEX = {'re': '(^v\\d+\\.\\d+(\\.\\d+)*(-\\d+(\\.\\d+)*)?$)',
  26. 'error_msg': ENTERPRISE_TAG_REGEX_ERROR}
  27. IMAGE_TAG_REGEX = {'origin': ORIGIN_TAG_REGEX,
  28. 'openshift-enterprise': ENTERPRISE_TAG_REGEX}
  29. CONTAINERIZED_NO_TAG_ERROR_MSG = """To install a containerized Origin release,
  30. you must set openshift_release or openshift_image_tag in your inventory to
  31. specify which version of the OpenShift component images to use.
  32. (Suggestion: add openshift_release="x.y" to inventory.)"""
  33. def to_bool(var_to_check):
  34. """Determine a boolean value given the multiple
  35. ways bools can be specified in ansible."""
  36. # http://yaml.org/type/bool.html
  37. yes_list = (True, 1, "True", "1", "true", "TRUE",
  38. "Yes", "yes", "Y", "y", "YES",
  39. "on", "ON", "On")
  40. return var_to_check in yes_list
  41. class ActionModule(ActionBase):
  42. """Action plugin to execute sanity checks."""
  43. def template_var(self, hostvars, host, varname):
  44. """Retrieve a variable from hostvars and template it.
  45. If undefined, return None type."""
  46. # We will set the current host and variable checked for easy debugging
  47. # if there are any unhandled exceptions.
  48. # pylint: disable=W0201
  49. self.last_checked_var = varname
  50. # pylint: disable=W0201
  51. self.last_checked_host = host
  52. res = hostvars[host].get(varname)
  53. if res is None:
  54. return None
  55. return self._templar.template(res)
  56. def check_openshift_deployment_type(self, hostvars, host):
  57. """Ensure a valid openshift_deployment_type is set"""
  58. openshift_deployment_type = self.template_var(hostvars, host,
  59. 'openshift_deployment_type')
  60. if openshift_deployment_type not in VALID_DEPLOYMENT_TYPES:
  61. type_strings = ", ".join(VALID_DEPLOYMENT_TYPES)
  62. msg = "openshift_deployment_type must be defined and one of {}".format(type_strings)
  63. raise errors.AnsibleModuleError(msg)
  64. return openshift_deployment_type
  65. def check_python_version(self, hostvars, host, distro):
  66. """Ensure python version is 3 for Fedora and python 2 for others"""
  67. ansible_python = self.template_var(hostvars, host, 'ansible_python')
  68. if distro == "Fedora":
  69. if ansible_python['version']['major'] != 3:
  70. msg = "openshift-ansible requires Python 3 for {};".format(distro)
  71. msg += " For information on enabling Python 3 with Ansible,"
  72. msg += " see https://docs.ansible.com/ansible/python_3_support.html"
  73. raise errors.AnsibleModuleError(msg)
  74. else:
  75. if ansible_python['version']['major'] != 2:
  76. msg = "openshift-ansible requires Python 2 for {};".format(distro)
  77. def check_image_tag_format(self, hostvars, host, openshift_deployment_type):
  78. """Ensure openshift_image_tag is formatted correctly"""
  79. openshift_image_tag = self.template_var(hostvars, host, 'openshift_image_tag')
  80. if not openshift_image_tag or openshift_image_tag == 'latest':
  81. return None
  82. regex_to_match = IMAGE_TAG_REGEX[openshift_deployment_type]['re']
  83. res = re.match(regex_to_match, str(openshift_image_tag))
  84. if res is None:
  85. msg = IMAGE_TAG_REGEX[openshift_deployment_type]['error_msg']
  86. msg = msg.format(str(openshift_image_tag))
  87. raise errors.AnsibleModuleError(msg)
  88. def no_origin_image_version(self, hostvars, host, openshift_deployment_type):
  89. """Ensure we can determine what image version to use with origin
  90. fail when:
  91. - openshift_is_containerized
  92. - openshift_deployment_type == 'origin'
  93. - openshift_release is not defined
  94. - openshift_image_tag is not defined"""
  95. if not openshift_deployment_type == 'origin':
  96. return None
  97. oic = self.template_var(hostvars, host, 'openshift_is_containerized')
  98. if not to_bool(oic):
  99. return None
  100. orelease = self.template_var(hostvars, host, 'openshift_release')
  101. oitag = self.template_var(hostvars, host, 'openshift_image_tag')
  102. if not orelease and not oitag:
  103. raise errors.AnsibleModuleError(CONTAINERIZED_NO_TAG_ERROR_MSG)
  104. def network_plugin_check(self, hostvars, host):
  105. """Ensure only one type of network plugin is enabled"""
  106. res = []
  107. # Loop through each possible network plugin boolean, determine the
  108. # actual boolean value, and append results into a list.
  109. for plugin, default_val in NET_PLUGIN_LIST:
  110. res_temp = self.template_var(hostvars, host, plugin)
  111. if res_temp is None:
  112. res_temp = default_val
  113. res.append(to_bool(res_temp))
  114. if sum(res) != 1:
  115. plugin_str = list(zip([x[0] for x in NET_PLUGIN_LIST], res))
  116. msg = "Host Checked: {} Only one of must be true. Found: {}".format(host, plugin_str)
  117. raise errors.AnsibleModuleError(msg)
  118. def check_hostname_vars(self, hostvars, host):
  119. """Checks to ensure openshift_hostname
  120. and openshift_public_hostname
  121. conform to the proper length of 63 characters or less"""
  122. for varname in ('openshift_public_hostname', 'openshift_hostname'):
  123. var_value = self.template_var(hostvars, host, varname)
  124. if var_value and len(var_value) > 63:
  125. msg = '{} must be 63 characters or less'.format(varname)
  126. raise errors.AnsibleModuleError(msg)
  127. def run_checks(self, hostvars, host):
  128. """Execute the hostvars validations against host"""
  129. distro = self.template_var(hostvars, host, 'ansible_distribution')
  130. odt = self.check_openshift_deployment_type(hostvars, host)
  131. self.check_python_version(hostvars, host, distro)
  132. self.check_image_tag_format(hostvars, host, odt)
  133. self.no_origin_image_version(hostvars, host, odt)
  134. self.network_plugin_check(hostvars, host)
  135. self.check_hostname_vars(hostvars, host)
  136. def run(self, tmp=None, task_vars=None):
  137. result = super(ActionModule, self).run(tmp, task_vars)
  138. # self.task_vars holds all in-scope variables.
  139. # Ignore settting self.task_vars outside of init.
  140. # pylint: disable=W0201
  141. self.task_vars = task_vars or {}
  142. # pylint: disable=W0201
  143. self.last_checked_host = "none"
  144. # pylint: disable=W0201
  145. self.last_checked_var = "none"
  146. # self._task.args holds task parameters.
  147. # check_hosts is a parameter to this plugin, and should provide
  148. # a list of hosts.
  149. check_hosts = self._task.args.get('check_hosts')
  150. if not check_hosts:
  151. msg = "check_hosts is required"
  152. raise errors.AnsibleModuleError(msg)
  153. # We need to access each host's variables
  154. hostvars = self.task_vars.get('hostvars')
  155. if not hostvars:
  156. msg = hostvars
  157. raise errors.AnsibleModuleError(msg)
  158. # We loop through each host in the provided list check_hosts
  159. for host in check_hosts:
  160. try:
  161. self.run_checks(hostvars, host)
  162. except Exception as uncaught_e:
  163. msg = "last_checked_host: {}, last_checked_var: {};"
  164. msg = msg.format(self.last_checked_host, self.last_checked_var)
  165. msg += str(uncaught_e)
  166. raise errors.AnsibleModuleError(msg)
  167. result["changed"] = False
  168. result["failed"] = False
  169. result["msg"] = "Sanity Checks passed"
  170. return result