oo_filters.py 42 KB

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