openshift_master.py 22 KB

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