oo_filters.py 42 KB

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