oo_filters.py 43 KB

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