oo_filters.py 41 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998
  1. #!/usr/bin/python
  2. # -*- coding: utf-8 -*-
  3. # vim: expandtab:tabstop=4:shiftwidth=4
  4. """
  5. Custom filters for use in openshift-ansible
  6. """
  7. import json
  8. import os
  9. import pdb
  10. import random
  11. import re
  12. from collections import Mapping
  13. # pylint no-name-in-module and import-error disabled here because pylint
  14. # fails to properly detect the packages when installed in a virtualenv
  15. from distutils.util import strtobool # pylint:disable=no-name-in-module,import-error
  16. from distutils.version import LooseVersion # pylint:disable=no-name-in-module,import-error
  17. from operator import itemgetter
  18. import pkg_resources
  19. import yaml
  20. from ansible import errors
  21. from ansible.parsing.yaml.dumper import AnsibleDumper
  22. # ansible.compat.six goes away with Ansible 2.4
  23. try:
  24. from ansible.compat.six import string_types, u
  25. from ansible.compat.six.moves.urllib.parse import urlparse
  26. except ImportError:
  27. from ansible.module_utils.six import string_types, u
  28. from ansible.module_utils.six.moves.urllib.parse import urlparse
  29. HAS_OPENSSL = False
  30. try:
  31. import OpenSSL.crypto
  32. HAS_OPENSSL = True
  33. except ImportError:
  34. pass
  35. def oo_pdb(arg):
  36. """ This pops you into a pdb instance where arg is the data passed in
  37. from the filter.
  38. Ex: "{{ hostvars | oo_pdb }}"
  39. """
  40. pdb.set_trace()
  41. return arg
  42. def get_attr(data, attribute=None):
  43. """ This looks up dictionary attributes of the form a.b.c and returns
  44. the value.
  45. If the key isn't present, None is returned.
  46. Ex: data = {'a': {'b': {'c': 5}}}
  47. attribute = "a.b.c"
  48. returns 5
  49. """
  50. if not attribute:
  51. raise errors.AnsibleFilterError("|failed expects attribute to be set")
  52. ptr = data
  53. for attr in attribute.split('.'):
  54. if attr in ptr:
  55. ptr = ptr[attr]
  56. else:
  57. ptr = None
  58. break
  59. return ptr
  60. def oo_flatten(data):
  61. """ This filter plugin will flatten a list of lists
  62. """
  63. if not isinstance(data, list):
  64. raise errors.AnsibleFilterError("|failed expects to flatten a List")
  65. return [item for sublist in data for item in sublist]
  66. def oo_merge_dicts(first_dict, second_dict):
  67. """ Merge two dictionaries where second_dict values take precedence.
  68. Ex: first_dict={'a': 1, 'b': 2}
  69. second_dict={'b': 3, 'c': 4}
  70. returns {'a': 1, 'b': 3, 'c': 4}
  71. """
  72. if not isinstance(first_dict, dict) or not isinstance(second_dict, dict):
  73. raise errors.AnsibleFilterError("|failed expects to merge two dicts")
  74. merged = first_dict.copy()
  75. merged.update(second_dict)
  76. return merged
  77. def oo_merge_hostvars(hostvars, variables, inventory_hostname):
  78. """ Merge host and play variables.
  79. When ansible version is greater than or equal to 2.0.0,
  80. merge hostvars[inventory_hostname] with variables (ansible vars)
  81. otherwise merge hostvars with hostvars['inventory_hostname'].
  82. Ex: hostvars={'master1.example.com': {'openshift_variable': '3'},
  83. 'openshift_other_variable': '7'}
  84. variables={'openshift_other_variable': '6'}
  85. inventory_hostname='master1.example.com'
  86. returns {'openshift_variable': '3', 'openshift_other_variable': '7'}
  87. hostvars=<ansible.vars.hostvars.HostVars object> (Mapping)
  88. variables={'openshift_other_variable': '6'}
  89. inventory_hostname='master1.example.com'
  90. returns {'openshift_variable': '3', 'openshift_other_variable': '6'}
  91. """
  92. if not isinstance(hostvars, Mapping):
  93. raise errors.AnsibleFilterError("|failed expects hostvars is dictionary or object")
  94. if not isinstance(variables, dict):
  95. raise errors.AnsibleFilterError("|failed expects variables is a dictionary")
  96. if not isinstance(inventory_hostname, string_types):
  97. raise errors.AnsibleFilterError("|failed expects inventory_hostname is a string")
  98. ansible_version = pkg_resources.get_distribution("ansible").version # pylint: disable=maybe-no-member
  99. merged_hostvars = {}
  100. if LooseVersion(ansible_version) >= LooseVersion('2.0.0'):
  101. merged_hostvars = oo_merge_dicts(
  102. hostvars[inventory_hostname], variables)
  103. else:
  104. merged_hostvars = oo_merge_dicts(
  105. hostvars[inventory_hostname], hostvars)
  106. return merged_hostvars
  107. def oo_collect(data, attribute=None, filters=None):
  108. """ This takes a list of dict and collects all attributes specified into a
  109. list. If filter is specified then we will include all items that
  110. match _ALL_ of filters. If a dict entry is missing the key in a
  111. filter it will be excluded from the match.
  112. Ex: data = [ {'a':1, 'b':5, 'z': 'z'}, # True, return
  113. {'a':2, 'z': 'z'}, # True, return
  114. {'a':3, 'z': 'z'}, # True, return
  115. {'a':4, 'z': 'b'}, # FAILED, obj['z'] != obj['z']
  116. ]
  117. attribute = 'a'
  118. filters = {'z': 'z'}
  119. returns [1, 2, 3]
  120. """
  121. if not isinstance(data, list):
  122. raise errors.AnsibleFilterError("|failed expects to filter on a List")
  123. if not attribute:
  124. raise errors.AnsibleFilterError("|failed expects attribute to be set")
  125. if filters is not None:
  126. if not isinstance(filters, dict):
  127. raise errors.AnsibleFilterError("|failed expects filter to be a"
  128. " dict")
  129. retval = [get_attr(d, attribute) for d in data if (
  130. all([d.get(key, None) == filters[key] for key in filters]))]
  131. else:
  132. retval = [get_attr(d, attribute) for d in data]
  133. retval = [val for val in retval if val is not None]
  134. return retval
  135. def oo_select_keys_from_list(data, keys):
  136. """ This returns a list, which contains the value portions for the keys
  137. Ex: data = { 'a':1, 'b':2, 'c':3 }
  138. keys = ['a', 'c']
  139. returns [1, 3]
  140. """
  141. if not isinstance(data, list):
  142. raise errors.AnsibleFilterError("|failed expects to filter on a list")
  143. if not isinstance(keys, list):
  144. raise errors.AnsibleFilterError("|failed expects first param is a list")
  145. # Gather up the values for the list of keys passed in
  146. retval = [oo_select_keys(item, keys) for item in data]
  147. return oo_flatten(retval)
  148. def oo_select_keys(data, keys):
  149. """ This returns a list, which contains the value portions for the keys
  150. Ex: data = { 'a':1, 'b':2, 'c':3 }
  151. keys = ['a', 'c']
  152. returns [1, 3]
  153. """
  154. if not isinstance(data, Mapping):
  155. raise errors.AnsibleFilterError("|failed expects to filter on a dict or object")
  156. if not isinstance(keys, list):
  157. raise errors.AnsibleFilterError("|failed expects first param is a list")
  158. # Gather up the values for the list of keys passed in
  159. retval = [data[key] for key in keys if key in data]
  160. return retval
  161. def oo_prepend_strings_in_list(data, prepend):
  162. """ This takes a list of strings and prepends a string to each item in the
  163. list
  164. Ex: data = ['cart', 'tree']
  165. prepend = 'apple-'
  166. returns ['apple-cart', 'apple-tree']
  167. """
  168. if not isinstance(data, list):
  169. raise errors.AnsibleFilterError("|failed expects first param is a list")
  170. if not all(isinstance(x, string_types) for x in data):
  171. raise errors.AnsibleFilterError("|failed expects first param is a list"
  172. " of strings")
  173. retval = [prepend + s for s in data]
  174. return retval
  175. def oo_combine_key_value(data, joiner='='):
  176. """Take a list of dict in the form of { 'key': 'value'} and
  177. arrange them as a list of strings ['key=value']
  178. """
  179. if not isinstance(data, list):
  180. raise errors.AnsibleFilterError("|failed expects first param is a list")
  181. rval = []
  182. for item in data:
  183. rval.append("%s%s%s" % (item['key'], joiner, item['value']))
  184. return rval
  185. def oo_combine_dict(data, in_joiner='=', out_joiner=' '):
  186. """Take a dict in the form of { 'key': 'value', 'key': 'value' } and
  187. arrange them as a string 'key=value key=value'
  188. """
  189. if not isinstance(data, dict):
  190. # pylint: disable=line-too-long
  191. raise errors.AnsibleFilterError("|failed expects first param is a dict [oo_combine_dict]. Got %s. Type: %s" % (str(data), str(type(data))))
  192. return out_joiner.join([in_joiner.join([k, str(v)]) for k, v in data.items()])
  193. def oo_dict_to_list_of_dict(data, key_title='key', value_title='value'):
  194. """Take a dict and arrange them as a list of dicts
  195. Input data:
  196. {'region': 'infra', 'test_k': 'test_v'}
  197. Return data:
  198. [{'key': 'region', 'value': 'infra'}, {'key': 'test_k', 'value': 'test_v'}]
  199. Written for use of the oc_label module
  200. """
  201. if not isinstance(data, dict):
  202. # pylint: disable=line-too-long
  203. raise errors.AnsibleFilterError("|failed expects first param is a dict. Got %s. Type: %s" % (str(data), str(type(data))))
  204. rval = []
  205. for label in data.items():
  206. rval.append({key_title: label[0], value_title: label[1]})
  207. return rval
  208. def oo_ami_selector(data, image_name):
  209. """ This takes a list of amis and an image name and attempts to return
  210. the latest ami.
  211. """
  212. if not isinstance(data, list):
  213. raise errors.AnsibleFilterError("|failed expects first param is a list")
  214. if not data:
  215. return None
  216. else:
  217. if image_name is None or not image_name.endswith('_*'):
  218. ami = sorted(data, key=itemgetter('name'), reverse=True)[0]
  219. return ami['ami_id']
  220. else:
  221. ami_info = [(ami, ami['name'].split('_')[-1]) for ami in data]
  222. ami = sorted(ami_info, key=itemgetter(1), reverse=True)[0][0]
  223. return ami['ami_id']
  224. def oo_ec2_volume_definition(data, host_type, docker_ephemeral=False):
  225. """ This takes a dictionary of volume definitions and returns a valid ec2
  226. volume definition based on the host_type and the values in the
  227. dictionary.
  228. The dictionary should look similar to this:
  229. { 'master':
  230. { 'root':
  231. { 'volume_size': 10, 'device_type': 'gp2',
  232. 'iops': 500
  233. },
  234. 'docker':
  235. { 'volume_size': 40, 'device_type': 'gp2',
  236. 'iops': 500, 'ephemeral': 'true'
  237. }
  238. },
  239. 'node':
  240. { 'root':
  241. { 'volume_size': 10, 'device_type': 'io1',
  242. 'iops': 1000
  243. },
  244. 'docker':
  245. { 'volume_size': 40, 'device_type': 'gp2',
  246. 'iops': 500, 'ephemeral': 'true'
  247. }
  248. }
  249. }
  250. """
  251. if not isinstance(data, dict):
  252. # pylint: disable=line-too-long
  253. raise errors.AnsibleFilterError("|failed expects first param is a dict [oo_ec2_volume_def]. Got %s. Type: %s" % (str(data), str(type(data))))
  254. if host_type not in ['master', 'node', 'etcd']:
  255. raise errors.AnsibleFilterError("|failed expects etcd, master or node"
  256. " as the host type")
  257. root_vol = data[host_type]['root']
  258. root_vol['device_name'] = '/dev/sda1'
  259. root_vol['delete_on_termination'] = True
  260. if root_vol['device_type'] != 'io1':
  261. root_vol.pop('iops', None)
  262. if host_type in ['master', 'node'] and 'docker' in data[host_type]:
  263. docker_vol = data[host_type]['docker']
  264. docker_vol['device_name'] = '/dev/xvdb'
  265. docker_vol['delete_on_termination'] = True
  266. if docker_vol['device_type'] != 'io1':
  267. docker_vol.pop('iops', None)
  268. if docker_ephemeral:
  269. docker_vol.pop('device_type', None)
  270. docker_vol.pop('delete_on_termination', None)
  271. docker_vol['ephemeral'] = 'ephemeral0'
  272. return [root_vol, docker_vol]
  273. elif host_type == 'etcd' and 'etcd' in data[host_type]:
  274. etcd_vol = data[host_type]['etcd']
  275. etcd_vol['device_name'] = '/dev/xvdb'
  276. etcd_vol['delete_on_termination'] = True
  277. if etcd_vol['device_type'] != 'io1':
  278. etcd_vol.pop('iops', None)
  279. return [root_vol, etcd_vol]
  280. return [root_vol]
  281. def oo_split(string, separator=','):
  282. """ This splits the input string into a list. If the input string is
  283. already a list we will return it as is.
  284. """
  285. if isinstance(string, list):
  286. return string
  287. return string.split(separator)
  288. def oo_haproxy_backend_masters(hosts, port):
  289. """ This takes an array of dicts and returns an array of dicts
  290. to be used as a backend for the haproxy role
  291. """
  292. servers = []
  293. for idx, host_info in enumerate(hosts):
  294. server = dict(name="master%s" % idx)
  295. server_ip = host_info['openshift']['common']['ip']
  296. server['address'] = "%s:%s" % (server_ip, port)
  297. server['opts'] = 'check'
  298. servers.append(server)
  299. return servers
  300. def oo_filter_list(data, filter_attr=None):
  301. """ This returns a list, which contains all items where filter_attr
  302. evaluates to true
  303. Ex: data = [ { a: 1, b: True },
  304. { a: 3, b: False },
  305. { a: 5, b: True } ]
  306. filter_attr = 'b'
  307. returns [ { a: 1, b: True },
  308. { a: 5, b: True } ]
  309. """
  310. if not isinstance(data, list):
  311. raise errors.AnsibleFilterError("|failed expects to filter on a list")
  312. if not isinstance(filter_attr, string_types):
  313. raise errors.AnsibleFilterError("|failed expects filter_attr is a str or unicode")
  314. # Gather up the values for the list of keys passed in
  315. return [x for x in data if filter_attr in x and x[filter_attr]]
  316. def oo_nodes_with_label(nodes, label, value=None):
  317. """ Filters a list of nodes by label and value (if provided)
  318. It handles labels that are in the following variables by priority:
  319. openshift_node_labels, cli_openshift_node_labels, openshift['node']['labels']
  320. Examples:
  321. data = ['a': {'openshift_node_labels': {'color': 'blue', 'size': 'M'}},
  322. 'b': {'openshift_node_labels': {'color': 'green', 'size': 'L'}},
  323. 'c': {'openshift_node_labels': {'size': 'S'}}]
  324. label = 'color'
  325. returns = ['a': {'openshift_node_labels': {'color': 'blue', 'size': 'M'}},
  326. 'b': {'openshift_node_labels': {'color': 'green', 'size': 'L'}}]
  327. data = ['a': {'openshift_node_labels': {'color': 'blue', 'size': 'M'}},
  328. 'b': {'openshift_node_labels': {'color': 'green', 'size': 'L'}},
  329. 'c': {'openshift_node_labels': {'size': 'S'}}]
  330. label = 'color'
  331. value = 'green'
  332. returns = ['b': {'labels': {'color': 'green', 'size': 'L'}}]
  333. Args:
  334. nodes (list[dict]): list of node to node variables
  335. label (str): label to filter `nodes` by
  336. value (Optional[str]): value of `label` to filter by Defaults
  337. to None.
  338. Returns:
  339. list[dict]: nodes filtered by label and value (if provided)
  340. """
  341. if not isinstance(nodes, list):
  342. raise errors.AnsibleFilterError("failed expects to filter on a list")
  343. if not isinstance(label, string_types):
  344. raise errors.AnsibleFilterError("failed expects label to be a string")
  345. if value is not None and not isinstance(value, string_types):
  346. raise errors.AnsibleFilterError("failed expects value to be a string")
  347. def label_filter(node):
  348. """ filter function for testing if node should be returned """
  349. if not isinstance(node, dict):
  350. raise errors.AnsibleFilterError("failed expects to filter on a list of dicts")
  351. if 'openshift_node_labels' in node:
  352. labels = node['openshift_node_labels']
  353. elif 'cli_openshift_node_labels' in node:
  354. labels = node['cli_openshift_node_labels']
  355. elif 'openshift' in node and 'node' in node['openshift'] and 'labels' in node['openshift']['node']:
  356. labels = node['openshift']['node']['labels']
  357. else:
  358. return False
  359. if isinstance(labels, string_types):
  360. labels = yaml.safe_load(labels)
  361. if not isinstance(labels, dict):
  362. raise errors.AnsibleFilterError(
  363. "failed expected node labels to be a dict or serializable to a dict"
  364. )
  365. return label in labels and (value is None or labels[label] == value)
  366. return [n for n in nodes if label_filter(n)]
  367. def oo_parse_heat_stack_outputs(data):
  368. """ Formats the HEAT stack output into a usable form
  369. The goal is to transform something like this:
  370. +---------------+-------------------------------------------------+
  371. | Property | Value |
  372. +---------------+-------------------------------------------------+
  373. | capabilities | [] | |
  374. | creation_time | 2015-06-26T12:26:26Z | |
  375. | description | OpenShift cluster | |
  376. | … | … |
  377. | outputs | [ |
  378. | | { |
  379. | | "output_value": "value_A" |
  380. | | "description": "This is the value of Key_A" |
  381. | | "output_key": "Key_A" |
  382. | | }, |
  383. | | { |
  384. | | "output_value": [ |
  385. | | "value_B1", |
  386. | | "value_B2" |
  387. | | ], |
  388. | | "description": "This is the value of Key_B" |
  389. | | "output_key": "Key_B" |
  390. | | }, |
  391. | | ] |
  392. | parameters | { |
  393. | … | … |
  394. +---------------+-------------------------------------------------+
  395. into something like this:
  396. {
  397. "Key_A": "value_A",
  398. "Key_B": [
  399. "value_B1",
  400. "value_B2"
  401. ]
  402. }
  403. """
  404. # Extract the “outputs” JSON snippet from the pretty-printed array
  405. in_outputs = False
  406. outputs = ''
  407. line_regex = re.compile(r'\|\s*(.*?)\s*\|\s*(.*?)\s*\|')
  408. for line in data['stdout_lines']:
  409. match = line_regex.match(line)
  410. if match:
  411. if match.group(1) == 'outputs':
  412. in_outputs = True
  413. elif match.group(1) != '':
  414. in_outputs = False
  415. if in_outputs:
  416. outputs += match.group(2)
  417. outputs = json.loads(outputs)
  418. # Revamp the “outputs” to put it in the form of a “Key: value” map
  419. revamped_outputs = {}
  420. for output in outputs:
  421. revamped_outputs[output['output_key']] = output['output_value']
  422. return revamped_outputs
  423. # pylint: disable=too-many-branches
  424. def oo_parse_named_certificates(certificates, named_certs_dir, internal_hostnames):
  425. """ Parses names from list of certificate hashes.
  426. Ex: certificates = [{ "certfile": "/root/custom1.crt",
  427. "keyfile": "/root/custom1.key",
  428. "cafile": "/root/custom-ca1.crt" },
  429. { "certfile": "custom2.crt",
  430. "keyfile": "custom2.key",
  431. "cafile": "custom-ca2.crt" }]
  432. returns [{ "certfile": "/etc/origin/master/named_certificates/custom1.crt",
  433. "keyfile": "/etc/origin/master/named_certificates/custom1.key",
  434. "cafile": "/etc/origin/master/named_certificates/custom-ca1.crt",
  435. "names": [ "public-master-host.com",
  436. "other-master-host.com" ] },
  437. { "certfile": "/etc/origin/master/named_certificates/custom2.crt",
  438. "keyfile": "/etc/origin/master/named_certificates/custom2.key",
  439. "cafile": "/etc/origin/master/named_certificates/custom-ca-2.crt",
  440. "names": [ "some-hostname.com" ] }]
  441. """
  442. if not isinstance(named_certs_dir, string_types):
  443. raise errors.AnsibleFilterError("|failed expects named_certs_dir is str or unicode")
  444. if not isinstance(internal_hostnames, list):
  445. raise errors.AnsibleFilterError("|failed expects internal_hostnames is list")
  446. if not HAS_OPENSSL:
  447. raise errors.AnsibleFilterError("|missing OpenSSL python bindings")
  448. for certificate in certificates:
  449. if 'names' in certificate.keys():
  450. continue
  451. else:
  452. certificate['names'] = []
  453. if not os.path.isfile(certificate['certfile']) or not os.path.isfile(certificate['keyfile']):
  454. raise errors.AnsibleFilterError("|certificate and/or key does not exist '%s', '%s'" %
  455. (certificate['certfile'], certificate['keyfile']))
  456. try:
  457. st_cert = open(certificate['certfile'], 'rt').read()
  458. cert = OpenSSL.crypto.load_certificate(OpenSSL.crypto.FILETYPE_PEM, st_cert)
  459. certificate['names'].append(str(cert.get_subject().commonName.decode()))
  460. for i in range(cert.get_extension_count()):
  461. if cert.get_extension(i).get_short_name() == 'subjectAltName':
  462. for name in str(cert.get_extension(i)).replace('DNS:', '').split(', '):
  463. certificate['names'].append(name)
  464. except Exception:
  465. raise errors.AnsibleFilterError(("|failed to parse certificate '%s', " % certificate['certfile'] +
  466. "please specify certificate names in host inventory"))
  467. certificate['names'] = list(set(certificate['names']))
  468. if 'cafile' not in certificate:
  469. certificate['names'] = [name for name in certificate['names'] if name not in internal_hostnames]
  470. if not certificate['names']:
  471. raise errors.AnsibleFilterError(("|failed to parse certificate '%s' or " % certificate['certfile'] +
  472. "detected a collision with internal hostname, please specify " +
  473. "certificate names in host inventory"))
  474. for certificate in certificates:
  475. # Update paths for configuration
  476. certificate['certfile'] = os.path.join(named_certs_dir, os.path.basename(certificate['certfile']))
  477. certificate['keyfile'] = os.path.join(named_certs_dir, os.path.basename(certificate['keyfile']))
  478. if 'cafile' in certificate:
  479. certificate['cafile'] = os.path.join(named_certs_dir, os.path.basename(certificate['cafile']))
  480. return certificates
  481. def oo_pretty_print_cluster(data, prefix='tag_'):
  482. """ Read a subset of hostvars and build a summary of the cluster
  483. in the following layout:
  484. "c_id": {
  485. "master": {
  486. "default": [
  487. { "name": "c_id-master-12345", "public IP": "172.16.0.1", "private IP": "192.168.0.1" }
  488. ]
  489. "node": {
  490. "infra": [
  491. { "name": "c_id-node-infra-23456", "public IP": "172.16.0.2", "private IP": "192.168.0.2" }
  492. ],
  493. "compute": [
  494. { "name": "c_id-node-compute-23456", "public IP": "172.16.0.3", "private IP": "192.168.0.3" },
  495. ...
  496. ]
  497. }
  498. """
  499. def _get_tag_value(tags, key):
  500. """ Extract values of a map implemented as a set.
  501. Ex: tags = { 'tag_foo_value1', 'tag_bar_value2', 'tag_baz_value3' }
  502. key = 'bar'
  503. returns 'value2'
  504. """
  505. for tag in tags:
  506. if tag[:len(prefix) + len(key)] == prefix + key:
  507. return tag[len(prefix) + len(key) + 1:]
  508. raise KeyError(key)
  509. def _add_host(clusters,
  510. clusterid,
  511. host_type,
  512. sub_host_type,
  513. host):
  514. """ Add a new host in the clusters data structure """
  515. if clusterid not in clusters:
  516. clusters[clusterid] = {}
  517. if host_type not in clusters[clusterid]:
  518. clusters[clusterid][host_type] = {}
  519. if sub_host_type not in clusters[clusterid][host_type]:
  520. clusters[clusterid][host_type][sub_host_type] = []
  521. clusters[clusterid][host_type][sub_host_type].append(host)
  522. clusters = {}
  523. for host in data:
  524. try:
  525. _add_host(clusters=clusters,
  526. clusterid=_get_tag_value(host['group_names'], 'clusterid'),
  527. host_type=_get_tag_value(host['group_names'], 'host-type'),
  528. sub_host_type=_get_tag_value(host['group_names'], 'sub-host-type'),
  529. host={'name': host['inventory_hostname'],
  530. 'public IP': host['oo_public_ipv4'],
  531. 'private IP': host['oo_private_ipv4']})
  532. except KeyError:
  533. pass
  534. return clusters
  535. def oo_generate_secret(num_bytes):
  536. """ generate a session secret """
  537. if not isinstance(num_bytes, int):
  538. raise errors.AnsibleFilterError("|failed expects num_bytes is int")
  539. secret = os.urandom(num_bytes)
  540. return secret.encode('base-64').strip()
  541. def to_padded_yaml(data, level=0, indent=2, **kw):
  542. """ returns a yaml snippet padded to match the indent level you specify """
  543. if data in [None, ""]:
  544. return ""
  545. try:
  546. transformed = u(yaml.dump(data, indent=indent, allow_unicode=True,
  547. default_flow_style=False,
  548. Dumper=AnsibleDumper, **kw))
  549. padded = "\n".join([" " * level * indent + line for line in transformed.splitlines()])
  550. return "\n{0}".format(padded)
  551. except Exception as my_e:
  552. raise errors.AnsibleFilterError('Failed to convert: %s' % my_e)
  553. def oo_openshift_env(hostvars):
  554. ''' Return facts which begin with "openshift_" and translate
  555. legacy facts to their openshift_env counterparts.
  556. Ex: hostvars = {'openshift_fact': 42,
  557. 'theyre_taking_the_hobbits_to': 'isengard'}
  558. returns = {'openshift_fact': 42}
  559. '''
  560. if not issubclass(type(hostvars), dict):
  561. raise errors.AnsibleFilterError("|failed expects hostvars is a dict")
  562. facts = {}
  563. regex = re.compile('^openshift_.*')
  564. for key in hostvars:
  565. if regex.match(key):
  566. facts[key] = hostvars[key]
  567. migrations = {'openshift_router_selector': 'openshift_hosted_router_selector',
  568. 'openshift_registry_selector': 'openshift_hosted_registry_selector'}
  569. for old_fact, new_fact in migrations.items():
  570. if old_fact in facts and new_fact not in facts:
  571. facts[new_fact] = facts[old_fact]
  572. return facts
  573. # pylint: disable=too-many-branches, too-many-nested-blocks
  574. def oo_persistent_volumes(hostvars, groups, persistent_volumes=None):
  575. """ Generate list of persistent volumes based on oo_openshift_env
  576. storage options set in host variables.
  577. """
  578. if not issubclass(type(hostvars), dict):
  579. raise errors.AnsibleFilterError("|failed expects hostvars is a dict")
  580. if not issubclass(type(groups), dict):
  581. raise errors.AnsibleFilterError("|failed expects groups is a dict")
  582. if persistent_volumes is not None and not issubclass(type(persistent_volumes), list):
  583. raise errors.AnsibleFilterError("|failed expects persistent_volumes is a list")
  584. if persistent_volumes is None:
  585. persistent_volumes = []
  586. if 'hosted' in hostvars['openshift']:
  587. for component in hostvars['openshift']['hosted']:
  588. if 'storage' in hostvars['openshift']['hosted'][component]:
  589. params = hostvars['openshift']['hosted'][component]['storage']
  590. kind = params['kind']
  591. create_pv = params['create_pv']
  592. if kind is not None and create_pv:
  593. if kind == 'nfs':
  594. host = params['host']
  595. if host is None:
  596. if 'oo_nfs_to_config' in groups and len(groups['oo_nfs_to_config']) > 0:
  597. host = groups['oo_nfs_to_config'][0]
  598. else:
  599. raise errors.AnsibleFilterError("|failed no storage host detected")
  600. directory = params['nfs']['directory']
  601. volume = params['volume']['name']
  602. path = directory + '/' + volume
  603. size = params['volume']['size']
  604. access_modes = params['access']['modes']
  605. persistent_volume = dict(
  606. name="{0}-volume".format(volume),
  607. capacity=size,
  608. access_modes=access_modes,
  609. storage=dict(
  610. nfs=dict(
  611. server=host,
  612. path=path)))
  613. persistent_volumes.append(persistent_volume)
  614. elif kind == 'openstack':
  615. volume = params['volume']['name']
  616. size = params['volume']['size']
  617. access_modes = params['access']['modes']
  618. filesystem = params['openstack']['filesystem']
  619. volume_id = params['openstack']['volumeID']
  620. persistent_volume = dict(
  621. name="{0}-volume".format(volume),
  622. capacity=size,
  623. access_modes=access_modes,
  624. storage=dict(
  625. cinder=dict(
  626. fsType=filesystem,
  627. volumeID=volume_id)))
  628. persistent_volumes.append(persistent_volume)
  629. elif not (kind == 'object' or kind == 'dynamic'):
  630. msg = "|failed invalid storage kind '{0}' for component '{1}'".format(
  631. kind,
  632. component)
  633. raise errors.AnsibleFilterError(msg)
  634. return persistent_volumes
  635. def oo_persistent_volume_claims(hostvars, persistent_volume_claims=None):
  636. """ Generate list of persistent volume claims based on oo_openshift_env
  637. storage options set in host variables.
  638. """
  639. if not issubclass(type(hostvars), dict):
  640. raise errors.AnsibleFilterError("|failed expects hostvars is a dict")
  641. if persistent_volume_claims is not None and not issubclass(type(persistent_volume_claims), list):
  642. raise errors.AnsibleFilterError("|failed expects persistent_volume_claims is a list")
  643. if persistent_volume_claims is None:
  644. persistent_volume_claims = []
  645. if 'hosted' in hostvars['openshift']:
  646. for component in hostvars['openshift']['hosted']:
  647. if 'storage' in hostvars['openshift']['hosted'][component]:
  648. params = hostvars['openshift']['hosted'][component]['storage']
  649. kind = params['kind']
  650. create_pv = params['create_pv']
  651. create_pvc = params['create_pvc']
  652. if kind not in [None, 'object'] and create_pv and create_pvc:
  653. volume = params['volume']['name']
  654. size = params['volume']['size']
  655. access_modes = params['access']['modes']
  656. persistent_volume_claim = dict(
  657. name="{0}-claim".format(volume),
  658. capacity=size,
  659. access_modes=access_modes)
  660. persistent_volume_claims.append(persistent_volume_claim)
  661. return persistent_volume_claims
  662. def oo_31_rpm_rename_conversion(rpms, openshift_version=None):
  663. """ Filters a list of 3.0 rpms and return the corresponding 3.1 rpms
  664. names with proper version (if provided)
  665. If 3.1 rpms are passed in they will only be augmented with the
  666. correct version. This is important for hosts that are running both
  667. Masters and Nodes.
  668. """
  669. if not isinstance(rpms, list):
  670. raise errors.AnsibleFilterError("failed expects to filter on a list")
  671. if openshift_version is not None and not isinstance(openshift_version, string_types):
  672. raise errors.AnsibleFilterError("failed expects openshift_version to be a string")
  673. rpms_31 = []
  674. for rpm in rpms:
  675. if 'atomic' not in rpm:
  676. rpm = rpm.replace("openshift", "atomic-openshift")
  677. if openshift_version:
  678. rpm = rpm + openshift_version
  679. rpms_31.append(rpm)
  680. return rpms_31
  681. def oo_pods_match_component(pods, deployment_type, component):
  682. """ Filters a list of Pods and returns the ones matching the deployment_type and component
  683. """
  684. if not isinstance(pods, list):
  685. raise errors.AnsibleFilterError("failed expects to filter on a list")
  686. if not isinstance(deployment_type, string_types):
  687. raise errors.AnsibleFilterError("failed expects deployment_type to be a string")
  688. if not isinstance(component, string_types):
  689. raise errors.AnsibleFilterError("failed expects component to be a string")
  690. image_prefix = 'openshift/origin-'
  691. if deployment_type in ['enterprise', 'online', 'openshift-enterprise']:
  692. image_prefix = 'openshift3/ose-'
  693. elif deployment_type == 'atomic-enterprise':
  694. image_prefix = 'aep3_beta/aep-'
  695. matching_pods = []
  696. image_regex = image_prefix + component + r'.*'
  697. for pod in pods:
  698. for container in pod['spec']['containers']:
  699. if re.search(image_regex, container['image']):
  700. matching_pods.append(pod)
  701. break # stop here, don't add a pod more than once
  702. return matching_pods
  703. def oo_get_hosts_from_hostvars(hostvars, hosts):
  704. """ Return a list of hosts from hostvars """
  705. retval = []
  706. for host in hosts:
  707. try:
  708. retval.append(hostvars[host])
  709. except errors.AnsibleError:
  710. # host does not exist
  711. pass
  712. return retval
  713. def oo_image_tag_to_rpm_version(version, include_dash=False):
  714. """ Convert an image tag string to an RPM version if necessary
  715. Empty strings and strings that are already in rpm version format
  716. are ignored. Also remove non semantic version components.
  717. Ex. v3.2.0.10 -> -3.2.0.10
  718. v1.2.0-rc1 -> -1.2.0
  719. """
  720. if not isinstance(version, string_types):
  721. raise errors.AnsibleFilterError("|failed expects a string or unicode")
  722. if version.startswith("v"):
  723. version = version[1:]
  724. # Strip release from requested version, we no longer support this.
  725. version = version.split('-')[0]
  726. if include_dash and version and not version.startswith("-"):
  727. version = "-" + version
  728. return version
  729. def oo_hostname_from_url(url):
  730. """ Returns the hostname contained in a URL
  731. Ex: https://ose3-master.example.com/v1/api -> ose3-master.example.com
  732. """
  733. if not isinstance(url, string_types):
  734. raise errors.AnsibleFilterError("|failed expects a string or unicode")
  735. parse_result = urlparse(url)
  736. if parse_result.netloc != '':
  737. return parse_result.netloc
  738. else:
  739. # netloc wasn't parsed, assume url was missing scheme and path
  740. return parse_result.path
  741. # pylint: disable=invalid-name, unused-argument
  742. def oo_openshift_loadbalancer_frontends(
  743. api_port, servers_hostvars, use_nuage=False, nuage_rest_port=None):
  744. """TODO: Document me."""
  745. loadbalancer_frontends = [{'name': 'atomic-openshift-api',
  746. 'mode': 'tcp',
  747. 'options': ['tcplog'],
  748. 'binds': ["*:{0}".format(api_port)],
  749. 'default_backend': 'atomic-openshift-api'}]
  750. if bool(strtobool(str(use_nuage))) and nuage_rest_port is not None:
  751. loadbalancer_frontends.append({'name': 'nuage-monitor',
  752. 'mode': 'tcp',
  753. 'options': ['tcplog'],
  754. 'binds': ["*:{0}".format(nuage_rest_port)],
  755. 'default_backend': 'nuage-monitor'})
  756. return loadbalancer_frontends
  757. # pylint: disable=invalid-name
  758. def oo_openshift_loadbalancer_backends(
  759. api_port, servers_hostvars, use_nuage=False, nuage_rest_port=None):
  760. """TODO: Document me."""
  761. loadbalancer_backends = [{'name': 'atomic-openshift-api',
  762. 'mode': 'tcp',
  763. 'option': 'tcplog',
  764. 'balance': 'source',
  765. 'servers': oo_haproxy_backend_masters(servers_hostvars, api_port)}]
  766. if bool(strtobool(str(use_nuage))) and nuage_rest_port is not None:
  767. # pylint: disable=line-too-long
  768. loadbalancer_backends.append({'name': 'nuage-monitor',
  769. 'mode': 'tcp',
  770. 'option': 'tcplog',
  771. 'balance': 'source',
  772. 'servers': oo_haproxy_backend_masters(servers_hostvars, nuage_rest_port)})
  773. return loadbalancer_backends
  774. def oo_chomp_commit_offset(version):
  775. """Chomp any "+git.foo" commit offset string from the given `version`
  776. and return the modified version string.
  777. Ex:
  778. - chomp_commit_offset(None) => None
  779. - chomp_commit_offset(1337) => "1337"
  780. - chomp_commit_offset("v3.4.0.15+git.derp") => "v3.4.0.15"
  781. - chomp_commit_offset("v3.4.0.15") => "v3.4.0.15"
  782. - chomp_commit_offset("v1.3.0+52492b4") => "v1.3.0"
  783. """
  784. if version is None:
  785. return version
  786. else:
  787. # Stringify, just in case it's a Number type. Split by '+' and
  788. # return the first split. No concerns about strings without a
  789. # '+', .split() returns an array of the original string.
  790. return str(version).split('+')[0]
  791. def oo_random_word(length, source='abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789'):
  792. """Generates a random string of given length from a set of alphanumeric characters.
  793. The default source uses [a-z][A-Z][0-9]
  794. Ex:
  795. - oo_random_word(3) => aB9
  796. - oo_random_word(4, source='012') => 0123
  797. """
  798. return ''.join(random.choice(source) for i in range(length))
  799. class FilterModule(object):
  800. """ Custom ansible filter mapping """
  801. # pylint: disable=no-self-use, too-few-public-methods
  802. def filters(self):
  803. """ returns a mapping of filters to methods """
  804. return {
  805. "oo_select_keys": oo_select_keys,
  806. "oo_select_keys_from_list": oo_select_keys_from_list,
  807. "oo_chomp_commit_offset": oo_chomp_commit_offset,
  808. "oo_collect": oo_collect,
  809. "oo_flatten": oo_flatten,
  810. "oo_pdb": oo_pdb,
  811. "oo_prepend_strings_in_list": oo_prepend_strings_in_list,
  812. "oo_ami_selector": oo_ami_selector,
  813. "oo_ec2_volume_definition": oo_ec2_volume_definition,
  814. "oo_combine_key_value": oo_combine_key_value,
  815. "oo_combine_dict": oo_combine_dict,
  816. "oo_dict_to_list_of_dict": oo_dict_to_list_of_dict,
  817. "oo_split": oo_split,
  818. "oo_filter_list": oo_filter_list,
  819. "oo_parse_heat_stack_outputs": oo_parse_heat_stack_outputs,
  820. "oo_parse_named_certificates": oo_parse_named_certificates,
  821. "oo_haproxy_backend_masters": oo_haproxy_backend_masters,
  822. "oo_pretty_print_cluster": oo_pretty_print_cluster,
  823. "oo_generate_secret": oo_generate_secret,
  824. "oo_nodes_with_label": oo_nodes_with_label,
  825. "oo_openshift_env": oo_openshift_env,
  826. "oo_persistent_volumes": oo_persistent_volumes,
  827. "oo_persistent_volume_claims": oo_persistent_volume_claims,
  828. "oo_31_rpm_rename_conversion": oo_31_rpm_rename_conversion,
  829. "oo_pods_match_component": oo_pods_match_component,
  830. "oo_get_hosts_from_hostvars": oo_get_hosts_from_hostvars,
  831. "oo_image_tag_to_rpm_version": oo_image_tag_to_rpm_version,
  832. "oo_merge_dicts": oo_merge_dicts,
  833. "oo_hostname_from_url": oo_hostname_from_url,
  834. "oo_merge_hostvars": oo_merge_hostvars,
  835. "oo_openshift_loadbalancer_frontends": oo_openshift_loadbalancer_frontends,
  836. "oo_openshift_loadbalancer_backends": oo_openshift_loadbalancer_backends,
  837. "to_padded_yaml": to_padded_yaml,
  838. "oo_random_word": oo_random_word
  839. }