oo_filters.py 39 KB

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