oo_filters.py 43 KB

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