oo_filters.py 36 KB

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