oo_filters.py 42 KB

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