openshift_master.py 20 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535
  1. #!/usr/bin/python
  2. # -*- coding: utf-8 -*-
  3. # vim: expandtab:tabstop=4:shiftwidth=4
  4. '''
  5. Custom filters for use in openshift-master
  6. '''
  7. import copy
  8. import sys
  9. import yaml
  10. from ansible import errors
  11. from ansible.runner.filter_plugins.core import bool as ansible_bool
  12. class IdentityProviderBase(object):
  13. """ IdentityProviderBase
  14. Attributes:
  15. name (str): Identity provider Name
  16. login (bool): Is this identity provider a login provider?
  17. challenge (bool): Is this identity provider a challenge provider?
  18. provider (dict): Provider specific config
  19. _idp (dict): internal copy of the IDP dict passed in
  20. _required (list): List of lists of strings for required attributes
  21. _optional (list): List of lists of strings for optional attributes
  22. _allow_additional (bool): Does this provider support attributes
  23. not in _required and _optional
  24. Args:
  25. api_version(str): OpenShift config version
  26. idp (dict): idp config dict
  27. Raises:
  28. AnsibleFilterError:
  29. """
  30. # disabling this check since the number of instance attributes are
  31. # necessary for this class
  32. # pylint: disable=too-many-instance-attributes
  33. def __init__(self, api_version, idp):
  34. if api_version not in ['v1']:
  35. raise errors.AnsibleFilterError("|failed api version {0} unknown".format(api_version))
  36. self._idp = copy.deepcopy(idp)
  37. if 'name' not in self._idp:
  38. raise errors.AnsibleFilterError("|failed identity provider missing a name")
  39. if 'kind' not in self._idp:
  40. raise errors.AnsibleFilterError("|failed identity provider missing a kind")
  41. self.name = self._idp.pop('name')
  42. self.login = ansible_bool(self._idp.pop('login', False))
  43. self.challenge = ansible_bool(self._idp.pop('challenge', False))
  44. self.provider = dict(apiVersion=api_version, kind=self._idp.pop('kind'))
  45. mm_keys = ('mappingMethod', 'mapping_method')
  46. mapping_method = None
  47. for key in mm_keys:
  48. if key in self._idp:
  49. mapping_method = self._idp.pop(key)
  50. if mapping_method is None:
  51. mapping_method = self.get_default('mappingMethod')
  52. self.mapping_method = mapping_method
  53. valid_mapping_methods = ['add', 'claim', 'generate', 'lookup']
  54. if self.mapping_method not in valid_mapping_methods:
  55. raise errors.AnsibleFilterError("|failed unkown mapping method "
  56. "for provider {0}".format(self.__class__.__name__))
  57. self._required = []
  58. self._optional = []
  59. self._allow_additional = True
  60. @staticmethod
  61. def validate_idp_list(idp_list):
  62. ''' validates a list of idps '''
  63. login_providers = [x.name for x in idp_list if x.login]
  64. if len(login_providers) > 1:
  65. raise errors.AnsibleFilterError("|failed multiple providers are "
  66. "not allowed for login. login "
  67. "providers: {0}".format(', '.join(login_providers)))
  68. names = [x.name for x in idp_list]
  69. if len(set(names)) != len(names):
  70. raise errors.AnsibleFilterError("|failed more than one provider configured with the same name")
  71. for idp in idp_list:
  72. idp.validate()
  73. def validate(self):
  74. ''' validate an instance of this idp class '''
  75. pass
  76. @staticmethod
  77. def get_default(key):
  78. ''' get a default value for a given key '''
  79. if key == 'mappingMethod':
  80. return 'claim'
  81. else:
  82. return None
  83. def set_provider_item(self, items, required=False):
  84. ''' set a provider item based on the list of item names provided. '''
  85. for item in items:
  86. provider_key = items[0]
  87. if item in self._idp:
  88. self.provider[provider_key] = self._idp.pop(item)
  89. break
  90. else:
  91. default = self.get_default(provider_key)
  92. if default is not None:
  93. self.provider[provider_key] = default
  94. elif required:
  95. raise errors.AnsibleFilterError("|failed provider {0} missing "
  96. "required key {1}".format(self.__class__.__name__, provider_key))
  97. def set_provider_items(self):
  98. ''' set the provider items for this idp '''
  99. for items in self._required:
  100. self.set_provider_item(items, True)
  101. for items in self._optional:
  102. self.set_provider_item(items)
  103. if self._allow_additional:
  104. for key in self._idp.keys():
  105. self.set_provider_item([key])
  106. else:
  107. if len(self._idp) > 0:
  108. raise errors.AnsibleFilterError("|failed provider {0} "
  109. "contains unknown keys "
  110. "{1}".format(self.__class__.__name__, ', '.join(self._idp.keys())))
  111. def to_dict(self):
  112. ''' translate this idp to a dictionary '''
  113. return dict(name=self.name, challenge=self.challenge,
  114. login=self.login, mappingMethod=self.mapping_method,
  115. provider=self.provider)
  116. class LDAPPasswordIdentityProvider(IdentityProviderBase):
  117. """ LDAPPasswordIdentityProvider
  118. Attributes:
  119. Args:
  120. api_version(str): OpenShift config version
  121. idp (dict): idp config dict
  122. Raises:
  123. AnsibleFilterError:
  124. """
  125. def __init__(self, api_version, idp):
  126. IdentityProviderBase.__init__(self, api_version, idp)
  127. self._allow_additional = False
  128. self._required += [['attributes'], ['url'], ['insecure']]
  129. self._optional += [['ca'],
  130. ['bindDN', 'bind_dn'],
  131. ['bindPassword', 'bind_password']]
  132. self._idp['insecure'] = ansible_bool(self._idp.pop('insecure', False))
  133. if 'attributes' in self._idp and 'preferred_username' in self._idp['attributes']:
  134. pref_user = self._idp['attributes'].pop('preferred_username')
  135. self._idp['attributes']['preferredUsername'] = pref_user
  136. def validate(self):
  137. ''' validate this idp instance '''
  138. IdentityProviderBase.validate(self)
  139. if not isinstance(self.provider['attributes'], dict):
  140. raise errors.AnsibleFilterError("|failed attributes for provider "
  141. "{0} must be a dictionary".format(self.__class__.__name__))
  142. attrs = ['id', 'email', 'name', 'preferredUsername']
  143. for attr in attrs:
  144. if attr in self.provider['attributes'] and not isinstance(self.provider['attributes'][attr], list):
  145. raise errors.AnsibleFilterError("|failed {0} attribute for "
  146. "provider {1} must be a list".format(attr, self.__class__.__name__))
  147. unknown_attrs = set(self.provider['attributes'].keys()) - set(attrs)
  148. if len(unknown_attrs) > 0:
  149. raise errors.AnsibleFilterError("|failed provider {0} has unknown "
  150. "attributes: {1}".format(self.__class__.__name__, ', '.join(unknown_attrs)))
  151. class KeystonePasswordIdentityProvider(IdentityProviderBase):
  152. """ KeystoneIdentityProvider
  153. Attributes:
  154. Args:
  155. api_version(str): OpenShift config version
  156. idp (dict): idp config dict
  157. Raises:
  158. AnsibleFilterError:
  159. """
  160. def __init__(self, api_version, idp):
  161. IdentityProviderBase.__init__(self, api_version, idp)
  162. self._allow_additional = False
  163. self._required += [['url'], ['domainName', 'domain_name']]
  164. self._optional += [['ca'], ['certFile', 'cert_file'], ['keyFile', 'key_file']]
  165. class RequestHeaderIdentityProvider(IdentityProviderBase):
  166. """ RequestHeaderIdentityProvider
  167. Attributes:
  168. Args:
  169. api_version(str): OpenShift config version
  170. idp (dict): idp config dict
  171. Raises:
  172. AnsibleFilterError:
  173. """
  174. def __init__(self, api_version, idp):
  175. IdentityProviderBase.__init__(self, api_version, idp)
  176. self._allow_additional = False
  177. self._required += [['headers']]
  178. self._optional += [['challengeURL', 'challenge_url'],
  179. ['loginURL', 'login_url'],
  180. ['clientCA', 'client_ca']]
  181. def validate(self):
  182. ''' validate this idp instance '''
  183. IdentityProviderBase.validate(self)
  184. if not isinstance(self.provider['headers'], list):
  185. raise errors.AnsibleFilterError("|failed headers for provider {0} "
  186. "must be a list".format(self.__class__.__name__))
  187. class AllowAllPasswordIdentityProvider(IdentityProviderBase):
  188. """ AllowAllPasswordIdentityProvider
  189. Attributes:
  190. Args:
  191. api_version(str): OpenShift config version
  192. idp (dict): idp config dict
  193. Raises:
  194. AnsibleFilterError:
  195. """
  196. def __init__(self, api_version, idp):
  197. IdentityProviderBase.__init__(self, api_version, idp)
  198. self._allow_additional = False
  199. class DenyAllPasswordIdentityProvider(IdentityProviderBase):
  200. """ DenyAllPasswordIdentityProvider
  201. Attributes:
  202. Args:
  203. api_version(str): OpenShift config version
  204. idp (dict): idp config dict
  205. Raises:
  206. AnsibleFilterError:
  207. """
  208. def __init__(self, api_version, idp):
  209. IdentityProviderBase.__init__(self, api_version, idp)
  210. self._allow_additional = False
  211. class HTPasswdPasswordIdentityProvider(IdentityProviderBase):
  212. """ HTPasswdPasswordIdentity
  213. Attributes:
  214. Args:
  215. api_version(str): OpenShift config version
  216. idp (dict): idp config dict
  217. Raises:
  218. AnsibleFilterError:
  219. """
  220. def __init__(self, api_version, idp):
  221. IdentityProviderBase.__init__(self, api_version, idp)
  222. self._allow_additional = False
  223. self._required += [['file', 'filename', 'fileName', 'file_name']]
  224. @staticmethod
  225. def get_default(key):
  226. if key == 'file':
  227. return '/etc/origin/htpasswd'
  228. else:
  229. return IdentityProviderBase.get_default(key)
  230. class BasicAuthPasswordIdentityProvider(IdentityProviderBase):
  231. """ BasicAuthPasswordIdentityProvider
  232. Attributes:
  233. Args:
  234. api_version(str): OpenShift config version
  235. idp (dict): idp config dict
  236. Raises:
  237. AnsibleFilterError:
  238. """
  239. def __init__(self, api_version, idp):
  240. IdentityProviderBase.__init__(self, api_version, idp)
  241. self._allow_additional = False
  242. self._required += [['url']]
  243. self._optional += [['ca'], ['certFile', 'cert_file'], ['keyFile', 'key_file']]
  244. class IdentityProviderOauthBase(IdentityProviderBase):
  245. """ IdentityProviderOauthBase
  246. Attributes:
  247. Args:
  248. api_version(str): OpenShift config version
  249. idp (dict): idp config dict
  250. Raises:
  251. AnsibleFilterError:
  252. """
  253. def __init__(self, api_version, idp):
  254. IdentityProviderBase.__init__(self, api_version, idp)
  255. self._allow_additional = False
  256. self._required += [['clientID', 'client_id'], ['clientSecret', 'client_secret']]
  257. def validate(self):
  258. ''' validate this idp instance '''
  259. IdentityProviderBase.validate(self)
  260. if self.challenge:
  261. raise errors.AnsibleFilterError("|failed provider {0} does not "
  262. "allow challenge authentication".format(self.__class__.__name__))
  263. class OpenIDIdentityProvider(IdentityProviderOauthBase):
  264. """ OpenIDIdentityProvider
  265. Attributes:
  266. Args:
  267. api_version(str): OpenShift config version
  268. idp (dict): idp config dict
  269. Raises:
  270. AnsibleFilterError:
  271. """
  272. def __init__(self, api_version, idp):
  273. IdentityProviderOauthBase.__init__(self, api_version, idp)
  274. self._required += [['claims'], ['urls']]
  275. self._optional += [['ca'],
  276. ['extraScopes'],
  277. ['extraAuthorizeParameters']]
  278. if 'claims' in self._idp and 'preferred_username' in self._idp['claims']:
  279. pref_user = self._idp['claims'].pop('preferred_username')
  280. self._idp['claims']['preferredUsername'] = pref_user
  281. if 'urls' in self._idp and 'user_info' in self._idp['urls']:
  282. user_info = self._idp['urls'].pop('user_info')
  283. self._idp['urls']['userInfo'] = user_info
  284. if 'extra_scopes' in self._idp:
  285. self._idp['extraScopes'] = self._idp.pop('extra_scopes')
  286. if 'extra_authorize_parameters' in self._idp:
  287. self._idp['extraAuthorizeParameters'] = self._idp.pop('extra_authorize_parameters')
  288. if 'extraAuthorizeParameters' in self._idp:
  289. if 'include_granted_scopes' in self._idp['extraAuthorizeParameters']:
  290. val = ansible_bool(self._idp['extraAuthorizeParameters'].pop('include_granted_scopes'))
  291. self._idp['extraAuthorizeParameters']['include_granted_scopes'] = val
  292. def validate(self):
  293. ''' validate this idp instance '''
  294. IdentityProviderOauthBase.validate(self)
  295. if not isinstance(self.provider['claims'], dict):
  296. raise errors.AnsibleFilterError("|failed claims for provider {0} "
  297. "must be a dictionary".format(self.__class__.__name__))
  298. for var, var_type in (('extraScopes', list), ('extraAuthorizeParameters', dict)):
  299. if var in self.provider and not isinstance(self.provider[var], var_type):
  300. raise errors.AnsibleFilterError("|failed {1} for provider "
  301. "{0} must be a {2}".format(self.__class__.__name__,
  302. var,
  303. var_type.__class__.__name__))
  304. required_claims = ['id']
  305. optional_claims = ['email', 'name', 'preferredUsername']
  306. all_claims = required_claims + optional_claims
  307. for claim in required_claims:
  308. if claim in required_claims and claim not in self.provider['claims']:
  309. raise errors.AnsibleFilterError("|failed {0} claim missing "
  310. "for provider {1}".format(claim, self.__class__.__name__))
  311. for claim in all_claims:
  312. if claim in self.provider['claims'] and not isinstance(self.provider['claims'][claim], list):
  313. raise errors.AnsibleFilterError("|failed {0} claims for "
  314. "provider {1} must be a list".format(claim, self.__class__.__name__))
  315. unknown_claims = set(self.provider['claims'].keys()) - set(all_claims)
  316. if len(unknown_claims) > 0:
  317. raise errors.AnsibleFilterError("|failed provider {0} has unknown "
  318. "claims: {1}".format(self.__class__.__name__, ', '.join(unknown_claims)))
  319. if not isinstance(self.provider['urls'], dict):
  320. raise errors.AnsibleFilterError("|failed urls for provider {0} "
  321. "must be a dictionary".format(self.__class__.__name__))
  322. required_urls = ['authorize', 'token']
  323. optional_urls = ['userInfo']
  324. all_urls = required_urls + optional_urls
  325. for url in required_urls:
  326. if url not in self.provider['urls']:
  327. raise errors.AnsibleFilterError("|failed {0} url missing for "
  328. "provider {1}".format(url, self.__class__.__name__))
  329. unknown_urls = set(self.provider['urls'].keys()) - set(all_urls)
  330. if len(unknown_urls) > 0:
  331. raise errors.AnsibleFilterError("|failed provider {0} has unknown "
  332. "urls: {1}".format(self.__class__.__name__, ', '.join(unknown_urls)))
  333. class GoogleIdentityProvider(IdentityProviderOauthBase):
  334. """ GoogleIdentityProvider
  335. Attributes:
  336. Args:
  337. api_version(str): OpenShift config version
  338. idp (dict): idp config dict
  339. Raises:
  340. AnsibleFilterError:
  341. """
  342. def __init__(self, api_version, idp):
  343. IdentityProviderOauthBase.__init__(self, api_version, idp)
  344. self._optional += [['hostedDomain', 'hosted_domain']]
  345. class GitHubIdentityProvider(IdentityProviderOauthBase):
  346. """ GitHubIdentityProvider
  347. Attributes:
  348. Args:
  349. api_version(str): OpenShift config version
  350. idp (dict): idp config dict
  351. Raises:
  352. AnsibleFilterError:
  353. """
  354. def __init__(self, api_version, idp):
  355. IdentityProviderOauthBase.__init__(self, api_version, idp)
  356. self._optional += [['organizations']]
  357. class FilterModule(object):
  358. ''' Custom ansible filters for use by the openshift_master role'''
  359. @staticmethod
  360. def translate_idps(idps, api_version):
  361. ''' Translates a list of dictionaries into a valid identityProviders config '''
  362. idp_list = []
  363. if not isinstance(idps, list):
  364. raise errors.AnsibleFilterError("|failed expects to filter on a list of identity providers")
  365. for idp in idps:
  366. if not isinstance(idp, dict):
  367. raise errors.AnsibleFilterError("|failed identity providers must be a list of dictionaries")
  368. cur_module = sys.modules[__name__]
  369. idp_class = getattr(cur_module, idp['kind'], None)
  370. idp_inst = idp_class(api_version, idp) if idp_class is not None else IdentityProviderBase(api_version, idp)
  371. idp_inst.set_provider_items()
  372. idp_list.append(idp_inst)
  373. IdentityProviderBase.validate_idp_list(idp_list)
  374. return yaml.safe_dump([idp.to_dict() for idp in idp_list], default_flow_style=False)
  375. @staticmethod
  376. def validate_pcs_cluster(data, masters=None):
  377. ''' Validates output from "pcs status", ensuring that each master
  378. provided is online.
  379. Ex: data = ('...',
  380. 'PCSD Status:',
  381. 'master1.example.com: Online',
  382. 'master2.example.com: Online',
  383. 'master3.example.com: Online',
  384. '...')
  385. masters = ['master1.example.com',
  386. 'master2.example.com',
  387. 'master3.example.com']
  388. returns True
  389. '''
  390. if not issubclass(type(data), basestring):
  391. raise errors.AnsibleFilterError("|failed expects data is a string or unicode")
  392. if not issubclass(type(masters), list):
  393. raise errors.AnsibleFilterError("|failed expects masters is a list")
  394. valid = True
  395. for master in masters:
  396. if "{0}: Online".format(master) not in data:
  397. valid = False
  398. return valid
  399. @staticmethod
  400. def certificates_to_synchronize(hostvars):
  401. ''' Return certificates to synchronize based on facts. '''
  402. if not issubclass(type(hostvars), dict):
  403. raise errors.AnsibleFilterError("|failed expects hostvars is a dict")
  404. certs = ['admin.crt',
  405. 'admin.key',
  406. 'admin.kubeconfig',
  407. 'master.kubelet-client.crt',
  408. 'master.kubelet-client.key',
  409. 'openshift-registry.crt',
  410. 'openshift-registry.key',
  411. 'openshift-registry.kubeconfig',
  412. 'openshift-router.crt',
  413. 'openshift-router.key',
  414. 'openshift-router.kubeconfig',
  415. 'serviceaccounts.private.key',
  416. 'serviceaccounts.public.key']
  417. if bool(hostvars['openshift']['common']['version_gte_3_1_or_1_1']):
  418. certs += ['master.proxy-client.crt',
  419. 'master.proxy-client.key']
  420. if not bool(hostvars['openshift']['common']['version_gte_3_2_or_1_2']):
  421. certs += ['openshift-master.crt',
  422. 'openshift-master.key',
  423. 'openshift-master.kubeconfig']
  424. return certs
  425. def filters(self):
  426. ''' returns a mapping of filters to methods '''
  427. return {"translate_idps": self.translate_idps,
  428. "validate_pcs_cluster": self.validate_pcs_cluster,
  429. "certificates_to_synchronize": self.certificates_to_synchronize}