oc_route.py 59 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810
  1. #!/usr/bin/env python
  2. # pylint: disable=missing-docstring
  3. # flake8: noqa: T001
  4. # ___ ___ _ _ ___ ___ _ _____ ___ ___
  5. # / __| __| \| | __| _ \ /_\_ _| __| \
  6. # | (_ | _|| .` | _|| / / _ \| | | _|| |) |
  7. # \___|___|_|\_|___|_|_\/_/_\_\_|_|___|___/_ _____
  8. # | \ / _ \ | \| |/ _ \_ _| | __| \_ _|_ _|
  9. # | |) | (_) | | .` | (_) || | | _|| |) | | | |
  10. # |___/ \___/ |_|\_|\___/ |_| |___|___/___| |_|
  11. #
  12. # Copyright 2016 Red Hat, Inc. and/or its affiliates
  13. # and other contributors as indicated by the @author tags.
  14. #
  15. # Licensed under the Apache License, Version 2.0 (the "License");
  16. # you may not use this file except in compliance with the License.
  17. # You may obtain a copy of the License at
  18. #
  19. # http://www.apache.org/licenses/LICENSE-2.0
  20. #
  21. # Unless required by applicable law or agreed to in writing, software
  22. # distributed under the License is distributed on an "AS IS" BASIS,
  23. # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  24. # See the License for the specific language governing permissions and
  25. # limitations under the License.
  26. #
  27. # -*- -*- -*- Begin included fragment: lib/import.py -*- -*- -*-
  28. '''
  29. OpenShiftCLI class that wraps the oc commands in a subprocess
  30. '''
  31. # pylint: disable=too-many-lines
  32. from __future__ import print_function
  33. import atexit
  34. import copy
  35. import json
  36. import os
  37. import re
  38. import shutil
  39. import subprocess
  40. import tempfile
  41. # pylint: disable=import-error
  42. try:
  43. import ruamel.yaml as yaml
  44. except ImportError:
  45. import yaml
  46. from ansible.module_utils.basic import AnsibleModule
  47. # -*- -*- -*- End included fragment: lib/import.py -*- -*- -*-
  48. # -*- -*- -*- Begin included fragment: doc/route -*- -*- -*-
  49. DOCUMENTATION = '''
  50. ---
  51. module: oc_route
  52. short_description: Create, modify, and idempotently manage openshift routes.
  53. description:
  54. - Manage openshift route objects programmatically.
  55. options:
  56. state:
  57. description:
  58. - State represents whether to create, modify, delete, or list
  59. required: true
  60. default: present
  61. choices: ["present", "absent", "list"]
  62. aliases: []
  63. kubeconfig:
  64. description:
  65. - The path for the kubeconfig file to use for authentication
  66. required: false
  67. default: /etc/origin/master/admin.kubeconfig
  68. aliases: []
  69. debug:
  70. description:
  71. - Turn on debug output.
  72. required: false
  73. default: False
  74. aliases: []
  75. name:
  76. description:
  77. - Name of the object that is being queried.
  78. required: false
  79. default: None
  80. aliases: []
  81. namespace:
  82. description:
  83. - The namespace where the object lives.
  84. required: false
  85. default: str
  86. aliases: []
  87. tls_termination:
  88. description:
  89. - The options for termination. e.g. reencrypt
  90. required: false
  91. default: None
  92. aliases: []
  93. dest_cacert_path:
  94. description:
  95. - The path to the dest_cacert
  96. required: false
  97. default: None
  98. aliases: []
  99. cacert_path:
  100. description:
  101. - The path to the cacert
  102. required: false
  103. default: None
  104. aliases: []
  105. cert_path:
  106. description:
  107. - The path to the cert
  108. required: false
  109. default: None
  110. aliases: []
  111. key_path:
  112. description:
  113. - The path to the key
  114. required: false
  115. default: None
  116. aliases: []
  117. dest_cacert_content:
  118. description:
  119. - The dest_cacert content
  120. required: false
  121. default: None
  122. aliases: []
  123. cacert_content:
  124. description:
  125. - The cacert content
  126. required: false
  127. default: None
  128. aliases: []
  129. cert_content:
  130. description:
  131. - The cert content
  132. required: false
  133. default: None
  134. aliases: []
  135. service_name:
  136. description:
  137. - The name of the service that this route points to.
  138. required: false
  139. default: None
  140. aliases: []
  141. host:
  142. description:
  143. - The host that the route will use. e.g. myapp.x.y.z
  144. required: false
  145. default: None
  146. aliases: []
  147. port:
  148. description:
  149. - The Name of the service port or number of the container port the route will route traffic to
  150. required: false
  151. default: None
  152. aliases: []
  153. author:
  154. - "Kenny Woodson <kwoodson@redhat.com>"
  155. extends_documentation_fragment: []
  156. '''
  157. EXAMPLES = '''
  158. - name: Configure certificates for reencrypt route
  159. oc_route:
  160. name: myapproute
  161. namespace: awesomeapp
  162. cert_path: "/etc/origin/master/named_certificates/myapp_cert
  163. key_path: "/etc/origin/master/named_certificates/myapp_key
  164. cacert_path: "/etc/origin/master/named_certificates/myapp_cacert
  165. dest_cacert_content: "{{ dest_cacert_content }}"
  166. service_name: myapp_php
  167. host: myapp.awesomeapp.openshift.com
  168. tls_termination: reencrypt
  169. run_once: true
  170. '''
  171. # -*- -*- -*- End included fragment: doc/route -*- -*- -*-
  172. # -*- -*- -*- Begin included fragment: ../../lib_utils/src/class/yedit.py -*- -*- -*-
  173. # pylint: disable=undefined-variable,missing-docstring
  174. # noqa: E301,E302
  175. class YeditException(Exception):
  176. ''' Exception class for Yedit '''
  177. pass
  178. # pylint: disable=too-many-public-methods
  179. class Yedit(object):
  180. ''' Class to modify yaml files '''
  181. re_valid_key = r"(((\[-?\d+\])|([0-9a-zA-Z%s/_-]+)).?)+$"
  182. re_key = r"(?:\[(-?\d+)\])|([0-9a-zA-Z%s/_-]+)"
  183. com_sep = set(['.', '#', '|', ':'])
  184. # pylint: disable=too-many-arguments
  185. def __init__(self,
  186. filename=None,
  187. content=None,
  188. content_type='yaml',
  189. separator='.',
  190. backup=False):
  191. self.content = content
  192. self._separator = separator
  193. self.filename = filename
  194. self.__yaml_dict = content
  195. self.content_type = content_type
  196. self.backup = backup
  197. self.load(content_type=self.content_type)
  198. if self.__yaml_dict is None:
  199. self.__yaml_dict = {}
  200. @property
  201. def separator(self):
  202. ''' getter method for yaml_dict '''
  203. return self._separator
  204. @separator.setter
  205. def separator(self):
  206. ''' getter method for yaml_dict '''
  207. return self._separator
  208. @property
  209. def yaml_dict(self):
  210. ''' getter method for yaml_dict '''
  211. return self.__yaml_dict
  212. @yaml_dict.setter
  213. def yaml_dict(self, value):
  214. ''' setter method for yaml_dict '''
  215. self.__yaml_dict = value
  216. @staticmethod
  217. def parse_key(key, sep='.'):
  218. '''parse the key allowing the appropriate separator'''
  219. common_separators = list(Yedit.com_sep - set([sep]))
  220. return re.findall(Yedit.re_key % ''.join(common_separators), key)
  221. @staticmethod
  222. def valid_key(key, sep='.'):
  223. '''validate the incoming key'''
  224. common_separators = list(Yedit.com_sep - set([sep]))
  225. if not re.match(Yedit.re_valid_key % ''.join(common_separators), key):
  226. return False
  227. return True
  228. @staticmethod
  229. def remove_entry(data, key, sep='.'):
  230. ''' remove data at location key '''
  231. if key == '' and isinstance(data, dict):
  232. data.clear()
  233. return True
  234. elif key == '' and isinstance(data, list):
  235. del data[:]
  236. return True
  237. if not (key and Yedit.valid_key(key, sep)) and \
  238. isinstance(data, (list, dict)):
  239. return None
  240. key_indexes = Yedit.parse_key(key, sep)
  241. for arr_ind, dict_key in key_indexes[:-1]:
  242. if dict_key and isinstance(data, dict):
  243. data = data.get(dict_key, None)
  244. elif (arr_ind and isinstance(data, list) and
  245. int(arr_ind) <= len(data) - 1):
  246. data = data[int(arr_ind)]
  247. else:
  248. return None
  249. # process last index for remove
  250. # expected list entry
  251. if key_indexes[-1][0]:
  252. if isinstance(data, list) and int(key_indexes[-1][0]) <= len(data) - 1: # noqa: E501
  253. del data[int(key_indexes[-1][0])]
  254. return True
  255. # expected dict entry
  256. elif key_indexes[-1][1]:
  257. if isinstance(data, dict):
  258. del data[key_indexes[-1][1]]
  259. return True
  260. @staticmethod
  261. def add_entry(data, key, item=None, sep='.'):
  262. ''' Get an item from a dictionary with key notation a.b.c
  263. d = {'a': {'b': 'c'}}}
  264. key = a#b
  265. return c
  266. '''
  267. if key == '':
  268. pass
  269. elif (not (key and Yedit.valid_key(key, sep)) and
  270. isinstance(data, (list, dict))):
  271. return None
  272. key_indexes = Yedit.parse_key(key, sep)
  273. for arr_ind, dict_key in key_indexes[:-1]:
  274. if dict_key:
  275. if isinstance(data, dict) and dict_key in data and data[dict_key]: # noqa: E501
  276. data = data[dict_key]
  277. continue
  278. elif data and not isinstance(data, dict):
  279. raise YeditException("Unexpected item type found while going through key " +
  280. "path: {} (at key: {})".format(key, dict_key))
  281. data[dict_key] = {}
  282. data = data[dict_key]
  283. elif (arr_ind and isinstance(data, list) and
  284. int(arr_ind) <= len(data) - 1):
  285. data = data[int(arr_ind)]
  286. else:
  287. raise YeditException("Unexpected item type found while going through key path: {}".format(key))
  288. if key == '':
  289. data = item
  290. # process last index for add
  291. # expected list entry
  292. elif key_indexes[-1][0] and isinstance(data, list) and int(key_indexes[-1][0]) <= len(data) - 1: # noqa: E501
  293. data[int(key_indexes[-1][0])] = item
  294. # expected dict entry
  295. elif key_indexes[-1][1] and isinstance(data, dict):
  296. data[key_indexes[-1][1]] = item
  297. # didn't add/update to an existing list, nor add/update key to a dict
  298. # so we must have been provided some syntax like a.b.c[<int>] = "data" for a
  299. # non-existent array
  300. else:
  301. raise YeditException("Error adding to object at path: {}".format(key))
  302. return data
  303. @staticmethod
  304. def get_entry(data, key, sep='.'):
  305. ''' Get an item from a dictionary with key notation a.b.c
  306. d = {'a': {'b': 'c'}}}
  307. key = a.b
  308. return c
  309. '''
  310. if key == '':
  311. pass
  312. elif (not (key and Yedit.valid_key(key, sep)) and
  313. isinstance(data, (list, dict))):
  314. return None
  315. key_indexes = Yedit.parse_key(key, sep)
  316. for arr_ind, dict_key in key_indexes:
  317. if dict_key and isinstance(data, dict):
  318. data = data.get(dict_key, None)
  319. elif (arr_ind and isinstance(data, list) and
  320. int(arr_ind) <= len(data) - 1):
  321. data = data[int(arr_ind)]
  322. else:
  323. return None
  324. return data
  325. @staticmethod
  326. def _write(filename, contents):
  327. ''' Actually write the file contents to disk. This helps with mocking. '''
  328. tmp_filename = filename + '.yedit'
  329. with open(tmp_filename, 'w') as yfd:
  330. yfd.write(contents)
  331. os.rename(tmp_filename, filename)
  332. def write(self):
  333. ''' write to file '''
  334. if not self.filename:
  335. raise YeditException('Please specify a filename.')
  336. if self.backup and self.file_exists():
  337. shutil.copy(self.filename, self.filename + '.orig')
  338. # Try to set format attributes if supported
  339. try:
  340. self.yaml_dict.fa.set_block_style()
  341. except AttributeError:
  342. pass
  343. # Try to use RoundTripDumper if supported.
  344. try:
  345. Yedit._write(self.filename, yaml.dump(self.yaml_dict, Dumper=yaml.RoundTripDumper))
  346. except AttributeError:
  347. Yedit._write(self.filename, yaml.safe_dump(self.yaml_dict, default_flow_style=False))
  348. return (True, self.yaml_dict)
  349. def read(self):
  350. ''' read from file '''
  351. # check if it exists
  352. if self.filename is None or not self.file_exists():
  353. return None
  354. contents = None
  355. with open(self.filename) as yfd:
  356. contents = yfd.read()
  357. return contents
  358. def file_exists(self):
  359. ''' return whether file exists '''
  360. if os.path.exists(self.filename):
  361. return True
  362. return False
  363. def load(self, content_type='yaml'):
  364. ''' return yaml file '''
  365. contents = self.read()
  366. if not contents and not self.content:
  367. return None
  368. if self.content:
  369. if isinstance(self.content, dict):
  370. self.yaml_dict = self.content
  371. return self.yaml_dict
  372. elif isinstance(self.content, str):
  373. contents = self.content
  374. # check if it is yaml
  375. try:
  376. if content_type == 'yaml' and contents:
  377. # Try to set format attributes if supported
  378. try:
  379. self.yaml_dict.fa.set_block_style()
  380. except AttributeError:
  381. pass
  382. # Try to use RoundTripLoader if supported.
  383. try:
  384. self.yaml_dict = yaml.safe_load(contents, yaml.RoundTripLoader)
  385. except AttributeError:
  386. self.yaml_dict = yaml.safe_load(contents)
  387. # Try to set format attributes if supported
  388. try:
  389. self.yaml_dict.fa.set_block_style()
  390. except AttributeError:
  391. pass
  392. elif content_type == 'json' and contents:
  393. self.yaml_dict = json.loads(contents)
  394. except yaml.YAMLError as err:
  395. # Error loading yaml or json
  396. raise YeditException('Problem with loading yaml file. %s' % err)
  397. return self.yaml_dict
  398. def get(self, key):
  399. ''' get a specified key'''
  400. try:
  401. entry = Yedit.get_entry(self.yaml_dict, key, self.separator)
  402. except KeyError:
  403. entry = None
  404. return entry
  405. def pop(self, path, key_or_item):
  406. ''' remove a key, value pair from a dict or an item for a list'''
  407. try:
  408. entry = Yedit.get_entry(self.yaml_dict, path, self.separator)
  409. except KeyError:
  410. entry = None
  411. if entry is None:
  412. return (False, self.yaml_dict)
  413. if isinstance(entry, dict):
  414. # AUDIT:maybe-no-member makes sense due to fuzzy types
  415. # pylint: disable=maybe-no-member
  416. if key_or_item in entry:
  417. entry.pop(key_or_item)
  418. return (True, self.yaml_dict)
  419. return (False, self.yaml_dict)
  420. elif isinstance(entry, list):
  421. # AUDIT:maybe-no-member makes sense due to fuzzy types
  422. # pylint: disable=maybe-no-member
  423. ind = None
  424. try:
  425. ind = entry.index(key_or_item)
  426. except ValueError:
  427. return (False, self.yaml_dict)
  428. entry.pop(ind)
  429. return (True, self.yaml_dict)
  430. return (False, self.yaml_dict)
  431. def delete(self, path):
  432. ''' remove path from a dict'''
  433. try:
  434. entry = Yedit.get_entry(self.yaml_dict, path, self.separator)
  435. except KeyError:
  436. entry = None
  437. if entry is None:
  438. return (False, self.yaml_dict)
  439. result = Yedit.remove_entry(self.yaml_dict, path, self.separator)
  440. if not result:
  441. return (False, self.yaml_dict)
  442. return (True, self.yaml_dict)
  443. def exists(self, path, value):
  444. ''' check if value exists at path'''
  445. try:
  446. entry = Yedit.get_entry(self.yaml_dict, path, self.separator)
  447. except KeyError:
  448. entry = None
  449. if isinstance(entry, list):
  450. if value in entry:
  451. return True
  452. return False
  453. elif isinstance(entry, dict):
  454. if isinstance(value, dict):
  455. rval = False
  456. for key, val in value.items():
  457. if entry[key] != val:
  458. rval = False
  459. break
  460. else:
  461. rval = True
  462. return rval
  463. return value in entry
  464. return entry == value
  465. def append(self, path, value):
  466. '''append value to a list'''
  467. try:
  468. entry = Yedit.get_entry(self.yaml_dict, path, self.separator)
  469. except KeyError:
  470. entry = None
  471. if entry is None:
  472. self.put(path, [])
  473. entry = Yedit.get_entry(self.yaml_dict, path, self.separator)
  474. if not isinstance(entry, list):
  475. return (False, self.yaml_dict)
  476. # AUDIT:maybe-no-member makes sense due to loading data from
  477. # a serialized format.
  478. # pylint: disable=maybe-no-member
  479. entry.append(value)
  480. return (True, self.yaml_dict)
  481. # pylint: disable=too-many-arguments
  482. def update(self, path, value, index=None, curr_value=None):
  483. ''' put path, value into a dict '''
  484. try:
  485. entry = Yedit.get_entry(self.yaml_dict, path, self.separator)
  486. except KeyError:
  487. entry = None
  488. if isinstance(entry, dict):
  489. # AUDIT:maybe-no-member makes sense due to fuzzy types
  490. # pylint: disable=maybe-no-member
  491. if not isinstance(value, dict):
  492. raise YeditException('Cannot replace key, value entry in ' +
  493. 'dict with non-dict type. value=[%s] [%s]' % (value, type(value))) # noqa: E501
  494. entry.update(value)
  495. return (True, self.yaml_dict)
  496. elif isinstance(entry, list):
  497. # AUDIT:maybe-no-member makes sense due to fuzzy types
  498. # pylint: disable=maybe-no-member
  499. ind = None
  500. if curr_value:
  501. try:
  502. ind = entry.index(curr_value)
  503. except ValueError:
  504. return (False, self.yaml_dict)
  505. elif index is not None:
  506. ind = index
  507. if ind is not None and entry[ind] != value:
  508. entry[ind] = value
  509. return (True, self.yaml_dict)
  510. # see if it exists in the list
  511. try:
  512. ind = entry.index(value)
  513. except ValueError:
  514. # doesn't exist, append it
  515. entry.append(value)
  516. return (True, self.yaml_dict)
  517. # already exists, return
  518. if ind is not None:
  519. return (False, self.yaml_dict)
  520. return (False, self.yaml_dict)
  521. def put(self, path, value):
  522. ''' put path, value into a dict '''
  523. try:
  524. entry = Yedit.get_entry(self.yaml_dict, path, self.separator)
  525. except KeyError:
  526. entry = None
  527. if entry == value:
  528. return (False, self.yaml_dict)
  529. # deepcopy didn't work
  530. # Try to use ruamel.yaml and fallback to pyyaml
  531. try:
  532. tmp_copy = yaml.load(yaml.round_trip_dump(self.yaml_dict,
  533. default_flow_style=False),
  534. yaml.RoundTripLoader)
  535. except AttributeError:
  536. tmp_copy = copy.deepcopy(self.yaml_dict)
  537. # set the format attributes if available
  538. try:
  539. tmp_copy.fa.set_block_style()
  540. except AttributeError:
  541. pass
  542. result = Yedit.add_entry(tmp_copy, path, value, self.separator)
  543. if not result:
  544. return (False, self.yaml_dict)
  545. self.yaml_dict = tmp_copy
  546. return (True, self.yaml_dict)
  547. def create(self, path, value):
  548. ''' create a yaml file '''
  549. if not self.file_exists():
  550. # deepcopy didn't work
  551. # Try to use ruamel.yaml and fallback to pyyaml
  552. try:
  553. tmp_copy = yaml.load(yaml.round_trip_dump(self.yaml_dict,
  554. default_flow_style=False),
  555. yaml.RoundTripLoader)
  556. except AttributeError:
  557. tmp_copy = copy.deepcopy(self.yaml_dict)
  558. # set the format attributes if available
  559. try:
  560. tmp_copy.fa.set_block_style()
  561. except AttributeError:
  562. pass
  563. result = Yedit.add_entry(tmp_copy, path, value, self.separator)
  564. if result:
  565. self.yaml_dict = tmp_copy
  566. return (True, self.yaml_dict)
  567. return (False, self.yaml_dict)
  568. @staticmethod
  569. def get_curr_value(invalue, val_type):
  570. '''return the current value'''
  571. if invalue is None:
  572. return None
  573. curr_value = invalue
  574. if val_type == 'yaml':
  575. curr_value = yaml.load(invalue)
  576. elif val_type == 'json':
  577. curr_value = json.loads(invalue)
  578. return curr_value
  579. @staticmethod
  580. def parse_value(inc_value, vtype=''):
  581. '''determine value type passed'''
  582. true_bools = ['y', 'Y', 'yes', 'Yes', 'YES', 'true', 'True', 'TRUE',
  583. 'on', 'On', 'ON', ]
  584. false_bools = ['n', 'N', 'no', 'No', 'NO', 'false', 'False', 'FALSE',
  585. 'off', 'Off', 'OFF']
  586. # It came in as a string but you didn't specify value_type as string
  587. # we will convert to bool if it matches any of the above cases
  588. if isinstance(inc_value, str) and 'bool' in vtype:
  589. if inc_value not in true_bools and inc_value not in false_bools:
  590. raise YeditException('Not a boolean type. str=[%s] vtype=[%s]'
  591. % (inc_value, vtype))
  592. elif isinstance(inc_value, bool) and 'str' in vtype:
  593. inc_value = str(inc_value)
  594. # If vtype is not str then go ahead and attempt to yaml load it.
  595. if isinstance(inc_value, str) and 'str' not in vtype:
  596. try:
  597. inc_value = yaml.load(inc_value)
  598. except Exception:
  599. raise YeditException('Could not determine type of incoming ' +
  600. 'value. value=[%s] vtype=[%s]'
  601. % (type(inc_value), vtype))
  602. return inc_value
  603. # pylint: disable=too-many-return-statements,too-many-branches
  604. @staticmethod
  605. def run_ansible(module):
  606. '''perform the idempotent crud operations'''
  607. yamlfile = Yedit(filename=module.params['src'],
  608. backup=module.params['backup'],
  609. separator=module.params['separator'])
  610. if module.params['src']:
  611. rval = yamlfile.load()
  612. if yamlfile.yaml_dict is None and \
  613. module.params['state'] != 'present':
  614. return {'failed': True,
  615. 'msg': 'Error opening file [%s]. Verify that the ' +
  616. 'file exists, that it is has correct' +
  617. ' permissions, and is valid yaml.'}
  618. if module.params['state'] == 'list':
  619. if module.params['content']:
  620. content = Yedit.parse_value(module.params['content'],
  621. module.params['content_type'])
  622. yamlfile.yaml_dict = content
  623. if module.params['key']:
  624. rval = yamlfile.get(module.params['key']) or {}
  625. return {'changed': False, 'result': rval, 'state': "list"}
  626. elif module.params['state'] == 'absent':
  627. if module.params['content']:
  628. content = Yedit.parse_value(module.params['content'],
  629. module.params['content_type'])
  630. yamlfile.yaml_dict = content
  631. if module.params['update']:
  632. rval = yamlfile.pop(module.params['key'],
  633. module.params['value'])
  634. else:
  635. rval = yamlfile.delete(module.params['key'])
  636. if rval[0] and module.params['src']:
  637. yamlfile.write()
  638. return {'changed': rval[0], 'result': rval[1], 'state': "absent"}
  639. elif module.params['state'] == 'present':
  640. # check if content is different than what is in the file
  641. if module.params['content']:
  642. content = Yedit.parse_value(module.params['content'],
  643. module.params['content_type'])
  644. # We had no edits to make and the contents are the same
  645. if yamlfile.yaml_dict == content and \
  646. module.params['value'] is None:
  647. return {'changed': False,
  648. 'result': yamlfile.yaml_dict,
  649. 'state': "present"}
  650. yamlfile.yaml_dict = content
  651. # we were passed a value; parse it
  652. if module.params['value']:
  653. value = Yedit.parse_value(module.params['value'],
  654. module.params['value_type'])
  655. key = module.params['key']
  656. if module.params['update']:
  657. # pylint: disable=line-too-long
  658. curr_value = Yedit.get_curr_value(Yedit.parse_value(module.params['curr_value']), # noqa: E501
  659. module.params['curr_value_format']) # noqa: E501
  660. rval = yamlfile.update(key, value, module.params['index'], curr_value) # noqa: E501
  661. elif module.params['append']:
  662. rval = yamlfile.append(key, value)
  663. else:
  664. rval = yamlfile.put(key, value)
  665. if rval[0] and module.params['src']:
  666. yamlfile.write()
  667. return {'changed': rval[0],
  668. 'result': rval[1], 'state': "present"}
  669. # no edits to make
  670. if module.params['src']:
  671. # pylint: disable=redefined-variable-type
  672. rval = yamlfile.write()
  673. return {'changed': rval[0],
  674. 'result': rval[1],
  675. 'state': "present"}
  676. return {'failed': True, 'msg': 'Unkown state passed'}
  677. # -*- -*- -*- End included fragment: ../../lib_utils/src/class/yedit.py -*- -*- -*-
  678. # -*- -*- -*- Begin included fragment: lib/base.py -*- -*- -*-
  679. # pylint: disable=too-many-lines
  680. # noqa: E301,E302,E303,T001
  681. class OpenShiftCLIError(Exception):
  682. '''Exception class for openshiftcli'''
  683. pass
  684. ADDITIONAL_PATH_LOOKUPS = ['/usr/local/bin', os.path.expanduser('~/bin')]
  685. def locate_oc_binary():
  686. ''' Find and return oc binary file '''
  687. # https://github.com/openshift/openshift-ansible/issues/3410
  688. # oc can be in /usr/local/bin in some cases, but that may not
  689. # be in $PATH due to ansible/sudo
  690. paths = os.environ.get("PATH", os.defpath).split(os.pathsep) + ADDITIONAL_PATH_LOOKUPS
  691. oc_binary = 'oc'
  692. # Use shutil.which if it is available, otherwise fallback to a naive path search
  693. try:
  694. which_result = shutil.which(oc_binary, path=os.pathsep.join(paths))
  695. if which_result is not None:
  696. oc_binary = which_result
  697. except AttributeError:
  698. for path in paths:
  699. if os.path.exists(os.path.join(path, oc_binary)):
  700. oc_binary = os.path.join(path, oc_binary)
  701. break
  702. return oc_binary
  703. # pylint: disable=too-few-public-methods
  704. class OpenShiftCLI(object):
  705. ''' Class to wrap the command line tools '''
  706. def __init__(self,
  707. namespace,
  708. kubeconfig='/etc/origin/master/admin.kubeconfig',
  709. verbose=False,
  710. all_namespaces=False):
  711. ''' Constructor for OpenshiftCLI '''
  712. self.namespace = namespace
  713. self.verbose = verbose
  714. self.kubeconfig = Utils.create_tmpfile_copy(kubeconfig)
  715. self.all_namespaces = all_namespaces
  716. self.oc_binary = locate_oc_binary()
  717. # Pylint allows only 5 arguments to be passed.
  718. # pylint: disable=too-many-arguments
  719. def _replace_content(self, resource, rname, content, force=False, sep='.'):
  720. ''' replace the current object with the content '''
  721. res = self._get(resource, rname)
  722. if not res['results']:
  723. return res
  724. fname = Utils.create_tmpfile(rname + '-')
  725. yed = Yedit(fname, res['results'][0], separator=sep)
  726. changes = []
  727. for key, value in content.items():
  728. changes.append(yed.put(key, value))
  729. if any([change[0] for change in changes]):
  730. yed.write()
  731. atexit.register(Utils.cleanup, [fname])
  732. return self._replace(fname, force)
  733. return {'returncode': 0, 'updated': False}
  734. def _replace(self, fname, force=False):
  735. '''replace the current object with oc replace'''
  736. cmd = ['replace', '-f', fname]
  737. if force:
  738. cmd.append('--force')
  739. return self.openshift_cmd(cmd)
  740. def _create_from_content(self, rname, content):
  741. '''create a temporary file and then call oc create on it'''
  742. fname = Utils.create_tmpfile(rname + '-')
  743. yed = Yedit(fname, content=content)
  744. yed.write()
  745. atexit.register(Utils.cleanup, [fname])
  746. return self._create(fname)
  747. def _create(self, fname):
  748. '''call oc create on a filename'''
  749. return self.openshift_cmd(['create', '-f', fname])
  750. def _delete(self, resource, rname, selector=None):
  751. '''call oc delete on a resource'''
  752. cmd = ['delete', resource, rname]
  753. if selector:
  754. cmd.append('--selector=%s' % selector)
  755. return self.openshift_cmd(cmd)
  756. def _process(self, template_name, create=False, params=None, template_data=None): # noqa: E501
  757. '''process a template
  758. template_name: the name of the template to process
  759. create: whether to send to oc create after processing
  760. params: the parameters for the template
  761. template_data: the incoming template's data; instead of a file
  762. '''
  763. cmd = ['process']
  764. if template_data:
  765. cmd.extend(['-f', '-'])
  766. else:
  767. cmd.append(template_name)
  768. if params:
  769. param_str = ["%s=%s" % (key, value) for key, value in params.items()]
  770. cmd.append('-v')
  771. cmd.extend(param_str)
  772. results = self.openshift_cmd(cmd, output=True, input_data=template_data)
  773. if results['returncode'] != 0 or not create:
  774. return results
  775. fname = Utils.create_tmpfile(template_name + '-')
  776. yed = Yedit(fname, results['results'])
  777. yed.write()
  778. atexit.register(Utils.cleanup, [fname])
  779. return self.openshift_cmd(['create', '-f', fname])
  780. def _get(self, resource, rname=None, selector=None):
  781. '''return a resource by name '''
  782. cmd = ['get', resource]
  783. if selector:
  784. cmd.append('--selector=%s' % selector)
  785. elif rname:
  786. cmd.append(rname)
  787. cmd.extend(['-o', 'json'])
  788. rval = self.openshift_cmd(cmd, output=True)
  789. # Ensure results are retuned in an array
  790. if 'items' in rval:
  791. rval['results'] = rval['items']
  792. elif not isinstance(rval['results'], list):
  793. rval['results'] = [rval['results']]
  794. return rval
  795. def _schedulable(self, node=None, selector=None, schedulable=True):
  796. ''' perform oadm manage-node scheduable '''
  797. cmd = ['manage-node']
  798. if node:
  799. cmd.extend(node)
  800. else:
  801. cmd.append('--selector=%s' % selector)
  802. cmd.append('--schedulable=%s' % schedulable)
  803. return self.openshift_cmd(cmd, oadm=True, output=True, output_type='raw') # noqa: E501
  804. def _list_pods(self, node=None, selector=None, pod_selector=None):
  805. ''' perform oadm list pods
  806. node: the node in which to list pods
  807. selector: the label selector filter if provided
  808. pod_selector: the pod selector filter if provided
  809. '''
  810. cmd = ['manage-node']
  811. if node:
  812. cmd.extend(node)
  813. else:
  814. cmd.append('--selector=%s' % selector)
  815. if pod_selector:
  816. cmd.append('--pod-selector=%s' % pod_selector)
  817. cmd.extend(['--list-pods', '-o', 'json'])
  818. return self.openshift_cmd(cmd, oadm=True, output=True, output_type='raw')
  819. # pylint: disable=too-many-arguments
  820. def _evacuate(self, node=None, selector=None, pod_selector=None, dry_run=False, grace_period=None, force=False):
  821. ''' perform oadm manage-node evacuate '''
  822. cmd = ['manage-node']
  823. if node:
  824. cmd.extend(node)
  825. else:
  826. cmd.append('--selector=%s' % selector)
  827. if dry_run:
  828. cmd.append('--dry-run')
  829. if pod_selector:
  830. cmd.append('--pod-selector=%s' % pod_selector)
  831. if grace_period:
  832. cmd.append('--grace-period=%s' % int(grace_period))
  833. if force:
  834. cmd.append('--force')
  835. cmd.append('--evacuate')
  836. return self.openshift_cmd(cmd, oadm=True, output=True, output_type='raw')
  837. def _version(self):
  838. ''' return the openshift version'''
  839. return self.openshift_cmd(['version'], output=True, output_type='raw')
  840. def _import_image(self, url=None, name=None, tag=None):
  841. ''' perform image import '''
  842. cmd = ['import-image']
  843. image = '{0}'.format(name)
  844. if tag:
  845. image += ':{0}'.format(tag)
  846. cmd.append(image)
  847. if url:
  848. cmd.append('--from={0}/{1}'.format(url, image))
  849. cmd.append('-n{0}'.format(self.namespace))
  850. cmd.append('--confirm')
  851. return self.openshift_cmd(cmd)
  852. def _run(self, cmds, input_data):
  853. ''' Actually executes the command. This makes mocking easier. '''
  854. curr_env = os.environ.copy()
  855. curr_env.update({'KUBECONFIG': self.kubeconfig})
  856. proc = subprocess.Popen(cmds,
  857. stdin=subprocess.PIPE,
  858. stdout=subprocess.PIPE,
  859. stderr=subprocess.PIPE,
  860. env=curr_env)
  861. stdout, stderr = proc.communicate(input_data)
  862. return proc.returncode, stdout.decode(), stderr.decode()
  863. # pylint: disable=too-many-arguments,too-many-branches
  864. def openshift_cmd(self, cmd, oadm=False, output=False, output_type='json', input_data=None):
  865. '''Base command for oc '''
  866. cmds = [self.oc_binary]
  867. if oadm:
  868. cmds.append('adm')
  869. cmds.extend(cmd)
  870. if self.all_namespaces:
  871. cmds.extend(['--all-namespaces'])
  872. elif self.namespace is not None and self.namespace.lower() not in ['none', 'emtpy']: # E501
  873. cmds.extend(['-n', self.namespace])
  874. rval = {}
  875. results = ''
  876. err = None
  877. if self.verbose:
  878. print(' '.join(cmds))
  879. try:
  880. returncode, stdout, stderr = self._run(cmds, input_data)
  881. except OSError as ex:
  882. returncode, stdout, stderr = 1, '', 'Failed to execute {}: {}'.format(subprocess.list2cmdline(cmds), ex)
  883. rval = {"returncode": returncode,
  884. "results": results,
  885. "cmd": ' '.join(cmds)}
  886. if returncode == 0:
  887. if output:
  888. if output_type == 'json':
  889. try:
  890. rval['results'] = json.loads(stdout)
  891. except ValueError as err:
  892. if "No JSON object could be decoded" in err.args:
  893. err = err.args
  894. elif output_type == 'raw':
  895. rval['results'] = stdout
  896. if self.verbose:
  897. print("STDOUT: {0}".format(stdout))
  898. print("STDERR: {0}".format(stderr))
  899. if err:
  900. rval.update({"err": err,
  901. "stderr": stderr,
  902. "stdout": stdout,
  903. "cmd": cmds})
  904. else:
  905. rval.update({"stderr": stderr,
  906. "stdout": stdout,
  907. "results": {}})
  908. return rval
  909. class Utils(object):
  910. ''' utilities for openshiftcli modules '''
  911. @staticmethod
  912. def _write(filename, contents):
  913. ''' Actually write the file contents to disk. This helps with mocking. '''
  914. with open(filename, 'w') as sfd:
  915. sfd.write(contents)
  916. @staticmethod
  917. def create_tmp_file_from_contents(rname, data, ftype='yaml'):
  918. ''' create a file in tmp with name and contents'''
  919. tmp = Utils.create_tmpfile(prefix=rname)
  920. if ftype == 'yaml':
  921. # AUDIT:no-member makes sense here due to ruamel.YAML/PyYAML usage
  922. # pylint: disable=no-member
  923. if hasattr(yaml, 'RoundTripDumper'):
  924. Utils._write(tmp, yaml.dump(data, Dumper=yaml.RoundTripDumper))
  925. else:
  926. Utils._write(tmp, yaml.safe_dump(data, default_flow_style=False))
  927. elif ftype == 'json':
  928. Utils._write(tmp, json.dumps(data))
  929. else:
  930. Utils._write(tmp, data)
  931. # Register cleanup when module is done
  932. atexit.register(Utils.cleanup, [tmp])
  933. return tmp
  934. @staticmethod
  935. def create_tmpfile_copy(inc_file):
  936. '''create a temporary copy of a file'''
  937. tmpfile = Utils.create_tmpfile('lib_openshift-')
  938. Utils._write(tmpfile, open(inc_file).read())
  939. # Cleanup the tmpfile
  940. atexit.register(Utils.cleanup, [tmpfile])
  941. return tmpfile
  942. @staticmethod
  943. def create_tmpfile(prefix='tmp'):
  944. ''' Generates and returns a temporary file name '''
  945. with tempfile.NamedTemporaryFile(prefix=prefix, delete=False) as tmp:
  946. return tmp.name
  947. @staticmethod
  948. def create_tmp_files_from_contents(content, content_type=None):
  949. '''Turn an array of dict: filename, content into a files array'''
  950. if not isinstance(content, list):
  951. content = [content]
  952. files = []
  953. for item in content:
  954. path = Utils.create_tmp_file_from_contents(item['path'] + '-',
  955. item['data'],
  956. ftype=content_type)
  957. files.append({'name': os.path.basename(item['path']),
  958. 'path': path})
  959. return files
  960. @staticmethod
  961. def cleanup(files):
  962. '''Clean up on exit '''
  963. for sfile in files:
  964. if os.path.exists(sfile):
  965. if os.path.isdir(sfile):
  966. shutil.rmtree(sfile)
  967. elif os.path.isfile(sfile):
  968. os.remove(sfile)
  969. @staticmethod
  970. def exists(results, _name):
  971. ''' Check to see if the results include the name '''
  972. if not results:
  973. return False
  974. if Utils.find_result(results, _name):
  975. return True
  976. return False
  977. @staticmethod
  978. def find_result(results, _name):
  979. ''' Find the specified result by name'''
  980. rval = None
  981. for result in results:
  982. if 'metadata' in result and result['metadata']['name'] == _name:
  983. rval = result
  984. break
  985. return rval
  986. @staticmethod
  987. def get_resource_file(sfile, sfile_type='yaml'):
  988. ''' return the service file '''
  989. contents = None
  990. with open(sfile) as sfd:
  991. contents = sfd.read()
  992. if sfile_type == 'yaml':
  993. # AUDIT:no-member makes sense here due to ruamel.YAML/PyYAML usage
  994. # pylint: disable=no-member
  995. if hasattr(yaml, 'RoundTripLoader'):
  996. contents = yaml.load(contents, yaml.RoundTripLoader)
  997. else:
  998. contents = yaml.safe_load(contents)
  999. elif sfile_type == 'json':
  1000. contents = json.loads(contents)
  1001. return contents
  1002. @staticmethod
  1003. def filter_versions(stdout):
  1004. ''' filter the oc version output '''
  1005. version_dict = {}
  1006. version_search = ['oc', 'openshift', 'kubernetes']
  1007. for line in stdout.strip().split('\n'):
  1008. for term in version_search:
  1009. if not line:
  1010. continue
  1011. if line.startswith(term):
  1012. version_dict[term] = line.split()[-1]
  1013. # horrible hack to get openshift version in Openshift 3.2
  1014. # By default "oc version in 3.2 does not return an "openshift" version
  1015. if "openshift" not in version_dict:
  1016. version_dict["openshift"] = version_dict["oc"]
  1017. return version_dict
  1018. @staticmethod
  1019. def add_custom_versions(versions):
  1020. ''' create custom versions strings '''
  1021. versions_dict = {}
  1022. for tech, version in versions.items():
  1023. # clean up "-" from version
  1024. if "-" in version:
  1025. version = version.split("-")[0]
  1026. if version.startswith('v'):
  1027. versions_dict[tech + '_numeric'] = version[1:].split('+')[0]
  1028. # "v3.3.0.33" is what we have, we want "3.3"
  1029. versions_dict[tech + '_short'] = version[1:4]
  1030. return versions_dict
  1031. @staticmethod
  1032. def openshift_installed():
  1033. ''' check if openshift is installed '''
  1034. import yum
  1035. yum_base = yum.YumBase()
  1036. if yum_base.rpmdb.searchNevra(name='atomic-openshift'):
  1037. return True
  1038. return False
  1039. # Disabling too-many-branches. This is a yaml dictionary comparison function
  1040. # pylint: disable=too-many-branches,too-many-return-statements,too-many-statements
  1041. @staticmethod
  1042. def check_def_equal(user_def, result_def, skip_keys=None, debug=False):
  1043. ''' Given a user defined definition, compare it with the results given back by our query. '''
  1044. # Currently these values are autogenerated and we do not need to check them
  1045. skip = ['metadata', 'status']
  1046. if skip_keys:
  1047. skip.extend(skip_keys)
  1048. for key, value in result_def.items():
  1049. if key in skip:
  1050. continue
  1051. # Both are lists
  1052. if isinstance(value, list):
  1053. if key not in user_def:
  1054. if debug:
  1055. print('User data does not have key [%s]' % key)
  1056. print('User data: %s' % user_def)
  1057. return False
  1058. if not isinstance(user_def[key], list):
  1059. if debug:
  1060. print('user_def[key] is not a list key=[%s] user_def[key]=%s' % (key, user_def[key]))
  1061. return False
  1062. if len(user_def[key]) != len(value):
  1063. if debug:
  1064. print("List lengths are not equal.")
  1065. print("key=[%s]: user_def[%s] != value[%s]" % (key, len(user_def[key]), len(value)))
  1066. print("user_def: %s" % user_def[key])
  1067. print("value: %s" % value)
  1068. return False
  1069. for values in zip(user_def[key], value):
  1070. if isinstance(values[0], dict) and isinstance(values[1], dict):
  1071. if debug:
  1072. print('sending list - list')
  1073. print(type(values[0]))
  1074. print(type(values[1]))
  1075. result = Utils.check_def_equal(values[0], values[1], skip_keys=skip_keys, debug=debug)
  1076. if not result:
  1077. print('list compare returned false')
  1078. return False
  1079. elif value != user_def[key]:
  1080. if debug:
  1081. print('value should be identical')
  1082. print(user_def[key])
  1083. print(value)
  1084. return False
  1085. # recurse on a dictionary
  1086. elif isinstance(value, dict):
  1087. if key not in user_def:
  1088. if debug:
  1089. print("user_def does not have key [%s]" % key)
  1090. return False
  1091. if not isinstance(user_def[key], dict):
  1092. if debug:
  1093. print("dict returned false: not instance of dict")
  1094. return False
  1095. # before passing ensure keys match
  1096. api_values = set(value.keys()) - set(skip)
  1097. user_values = set(user_def[key].keys()) - set(skip)
  1098. if api_values != user_values:
  1099. if debug:
  1100. print("keys are not equal in dict")
  1101. print(user_values)
  1102. print(api_values)
  1103. return False
  1104. result = Utils.check_def_equal(user_def[key], value, skip_keys=skip_keys, debug=debug)
  1105. if not result:
  1106. if debug:
  1107. print("dict returned false")
  1108. print(result)
  1109. return False
  1110. # Verify each key, value pair is the same
  1111. else:
  1112. if key not in user_def or value != user_def[key]:
  1113. if debug:
  1114. print("value not equal; user_def does not have key")
  1115. print(key)
  1116. print(value)
  1117. if key in user_def:
  1118. print(user_def[key])
  1119. return False
  1120. if debug:
  1121. print('returning true')
  1122. return True
  1123. class OpenShiftCLIConfig(object):
  1124. '''Generic Config'''
  1125. def __init__(self, rname, namespace, kubeconfig, options):
  1126. self.kubeconfig = kubeconfig
  1127. self.name = rname
  1128. self.namespace = namespace
  1129. self._options = options
  1130. @property
  1131. def config_options(self):
  1132. ''' return config options '''
  1133. return self._options
  1134. def to_option_list(self):
  1135. '''return all options as a string'''
  1136. return self.stringify()
  1137. def stringify(self):
  1138. ''' return the options hash as cli params in a string '''
  1139. rval = []
  1140. for key in sorted(self.config_options.keys()):
  1141. data = self.config_options[key]
  1142. if data['include'] \
  1143. and (data['value'] or isinstance(data['value'], int)):
  1144. rval.append('--{}={}'.format(key.replace('_', '-'), data['value']))
  1145. return rval
  1146. # -*- -*- -*- End included fragment: lib/base.py -*- -*- -*-
  1147. # -*- -*- -*- Begin included fragment: lib/route.py -*- -*- -*-
  1148. # noqa: E302,E301
  1149. # pylint: disable=too-many-instance-attributes
  1150. class RouteConfig(object):
  1151. ''' Handle route options '''
  1152. # pylint: disable=too-many-arguments
  1153. def __init__(self,
  1154. sname,
  1155. namespace,
  1156. kubeconfig,
  1157. destcacert=None,
  1158. cacert=None,
  1159. cert=None,
  1160. key=None,
  1161. host=None,
  1162. tls_termination=None,
  1163. service_name=None,
  1164. wildcard_policy=None,
  1165. weight=None,
  1166. port=None):
  1167. ''' constructor for handling route options '''
  1168. self.kubeconfig = kubeconfig
  1169. self.name = sname
  1170. self.namespace = namespace
  1171. self.host = host
  1172. self.tls_termination = tls_termination
  1173. self.destcacert = destcacert
  1174. self.cacert = cacert
  1175. self.cert = cert
  1176. self.key = key
  1177. self.service_name = service_name
  1178. self.port = port
  1179. self.data = {}
  1180. self.wildcard_policy = wildcard_policy
  1181. if wildcard_policy is None:
  1182. self.wildcard_policy = 'None'
  1183. self.weight = weight
  1184. if weight is None:
  1185. self.weight = 100
  1186. self.create_dict()
  1187. def create_dict(self):
  1188. ''' return a service as a dict '''
  1189. self.data['apiVersion'] = 'v1'
  1190. self.data['kind'] = 'Route'
  1191. self.data['metadata'] = {}
  1192. self.data['metadata']['name'] = self.name
  1193. self.data['metadata']['namespace'] = self.namespace
  1194. self.data['spec'] = {}
  1195. self.data['spec']['host'] = self.host
  1196. if self.tls_termination:
  1197. self.data['spec']['tls'] = {}
  1198. self.data['spec']['tls']['termination'] = self.tls_termination
  1199. if self.tls_termination != 'passthrough':
  1200. self.data['spec']['tls']['key'] = self.key
  1201. self.data['spec']['tls']['caCertificate'] = self.cacert
  1202. self.data['spec']['tls']['certificate'] = self.cert
  1203. if self.tls_termination == 'reencrypt':
  1204. self.data['spec']['tls']['destinationCACertificate'] = self.destcacert
  1205. self.data['spec']['to'] = {'kind': 'Service',
  1206. 'name': self.service_name,
  1207. 'weight': self.weight}
  1208. self.data['spec']['wildcardPolicy'] = self.wildcard_policy
  1209. if self.port:
  1210. self.data['spec']['port'] = {}
  1211. self.data['spec']['port']['targetPort'] = self.port
  1212. # pylint: disable=too-many-instance-attributes,too-many-public-methods
  1213. class Route(Yedit):
  1214. ''' Class to wrap the oc command line tools '''
  1215. wildcard_policy = "spec.wildcardPolicy"
  1216. host_path = "spec.host"
  1217. port_path = "spec.port.targetPort"
  1218. service_path = "spec.to.name"
  1219. weight_path = "spec.to.weight"
  1220. cert_path = "spec.tls.certificate"
  1221. cacert_path = "spec.tls.caCertificate"
  1222. destcacert_path = "spec.tls.destinationCACertificate"
  1223. termination_path = "spec.tls.termination"
  1224. key_path = "spec.tls.key"
  1225. kind = 'route'
  1226. def __init__(self, content):
  1227. '''Route constructor'''
  1228. super(Route, self).__init__(content=content)
  1229. def get_destcacert(self):
  1230. ''' return cert '''
  1231. return self.get(Route.destcacert_path)
  1232. def get_cert(self):
  1233. ''' return cert '''
  1234. return self.get(Route.cert_path)
  1235. def get_key(self):
  1236. ''' return key '''
  1237. return self.get(Route.key_path)
  1238. def get_cacert(self):
  1239. ''' return cacert '''
  1240. return self.get(Route.cacert_path)
  1241. def get_service(self):
  1242. ''' return service name '''
  1243. return self.get(Route.service_path)
  1244. def get_weight(self):
  1245. ''' return service weight '''
  1246. return self.get(Route.weight_path)
  1247. def get_termination(self):
  1248. ''' return tls termination'''
  1249. return self.get(Route.termination_path)
  1250. def get_host(self):
  1251. ''' return host '''
  1252. return self.get(Route.host_path)
  1253. def get_port(self):
  1254. ''' return port '''
  1255. return self.get(Route.port_path)
  1256. def get_wildcard_policy(self):
  1257. ''' return wildcardPolicy '''
  1258. return self.get(Route.wildcard_policy)
  1259. # -*- -*- -*- End included fragment: lib/route.py -*- -*- -*-
  1260. # -*- -*- -*- Begin included fragment: class/oc_route.py -*- -*- -*-
  1261. # pylint: disable=too-many-instance-attributes
  1262. class OCRoute(OpenShiftCLI):
  1263. ''' Class to wrap the oc command line tools '''
  1264. kind = 'route'
  1265. def __init__(self,
  1266. config,
  1267. verbose=False):
  1268. ''' Constructor for OCVolume '''
  1269. super(OCRoute, self).__init__(config.namespace, kubeconfig=config.kubeconfig, verbose=verbose)
  1270. self.config = config
  1271. self._route = None
  1272. @property
  1273. def route(self):
  1274. ''' property function for route'''
  1275. if not self._route:
  1276. self.get()
  1277. return self._route
  1278. @route.setter
  1279. def route(self, data):
  1280. ''' setter function for route '''
  1281. self._route = data
  1282. def exists(self):
  1283. ''' return whether a route exists '''
  1284. if self.route:
  1285. return True
  1286. return False
  1287. def get(self):
  1288. '''return route information '''
  1289. result = self._get(self.kind, self.config.name)
  1290. if result['returncode'] == 0:
  1291. self.route = Route(content=result['results'][0])
  1292. elif 'routes \"%s\" not found' % self.config.name in result['stderr']:
  1293. result['returncode'] = 0
  1294. result['results'] = [{}]
  1295. return result
  1296. def delete(self):
  1297. '''delete the object'''
  1298. return self._delete(self.kind, self.config.name)
  1299. def create(self):
  1300. '''create the object'''
  1301. return self._create_from_content(self.config.name, self.config.data)
  1302. def update(self):
  1303. '''update the object'''
  1304. return self._replace_content(self.kind,
  1305. self.config.name,
  1306. self.config.data,
  1307. force=(self.config.host != self.route.get_host()))
  1308. def needs_update(self):
  1309. ''' verify an update is needed '''
  1310. skip = []
  1311. return not Utils.check_def_equal(self.config.data, self.route.yaml_dict, skip_keys=skip, debug=self.verbose)
  1312. @staticmethod
  1313. def get_cert_data(path, content):
  1314. '''get the data for a particular value'''
  1315. if not path and not content:
  1316. return None
  1317. rval = None
  1318. if path and os.path.exists(path) and os.access(path, os.R_OK):
  1319. rval = open(path).read()
  1320. elif content:
  1321. rval = content
  1322. return rval
  1323. # pylint: disable=too-many-return-statements,too-many-branches
  1324. @staticmethod
  1325. def run_ansible(params, check_mode=False):
  1326. ''' run the idempotent asnible code
  1327. params comes from the ansible portion for this module
  1328. files: a dictionary for the certificates
  1329. {'cert': {'path': '',
  1330. 'content': '',
  1331. 'value': ''
  1332. }
  1333. }
  1334. check_mode: does the module support check mode. (module.check_mode)
  1335. '''
  1336. files = {'destcacert': {'path': params['dest_cacert_path'],
  1337. 'content': params['dest_cacert_content'],
  1338. 'value': None, },
  1339. 'cacert': {'path': params['cacert_path'],
  1340. 'content': params['cacert_content'],
  1341. 'value': None, },
  1342. 'cert': {'path': params['cert_path'],
  1343. 'content': params['cert_content'],
  1344. 'value': None, },
  1345. 'key': {'path': params['key_path'],
  1346. 'content': params['key_content'],
  1347. 'value': None, }, }
  1348. if params['tls_termination'] and params['tls_termination'].lower() != 'passthrough': # E501
  1349. for key, option in files.items():
  1350. if key == 'destcacert' and params['tls_termination'] != 'reencrypt':
  1351. continue
  1352. option['value'] = OCRoute.get_cert_data(option['path'], option['content']) # E501
  1353. if not option['value']:
  1354. return {'failed': True,
  1355. 'msg': 'Verify that you pass a value for %s' % key}
  1356. rconfig = RouteConfig(params['name'],
  1357. params['namespace'],
  1358. params['kubeconfig'],
  1359. files['destcacert']['value'],
  1360. files['cacert']['value'],
  1361. files['cert']['value'],
  1362. files['key']['value'],
  1363. params['host'],
  1364. params['tls_termination'],
  1365. params['service_name'],
  1366. params['wildcard_policy'],
  1367. params['weight'],
  1368. params['port'])
  1369. oc_route = OCRoute(rconfig, verbose=params['debug'])
  1370. state = params['state']
  1371. api_rval = oc_route.get()
  1372. #####
  1373. # Get
  1374. #####
  1375. if state == 'list':
  1376. return {'changed': False,
  1377. 'results': api_rval['results'],
  1378. 'state': 'list'}
  1379. ########
  1380. # Delete
  1381. ########
  1382. if state == 'absent':
  1383. if oc_route.exists():
  1384. if check_mode:
  1385. return {'changed': False, 'msg': 'CHECK_MODE: Would have performed a delete.'} # noqa: E501
  1386. api_rval = oc_route.delete()
  1387. return {'changed': True, 'results': api_rval, 'state': "absent"} # noqa: E501
  1388. return {'changed': False, 'state': 'absent'}
  1389. if state == 'present':
  1390. ########
  1391. # Create
  1392. ########
  1393. if not oc_route.exists():
  1394. if check_mode:
  1395. return {'changed': True, 'msg': 'CHECK_MODE: Would have performed a create.'} # noqa: E501
  1396. # Create it here
  1397. api_rval = oc_route.create()
  1398. if api_rval['returncode'] != 0:
  1399. return {'failed': True, 'msg': api_rval, 'state': "present"} # noqa: E501
  1400. # return the created object
  1401. api_rval = oc_route.get()
  1402. if api_rval['returncode'] != 0:
  1403. return {'failed': True, 'msg': api_rval, 'state': "present"} # noqa: E501
  1404. return {'changed': True, 'results': api_rval, 'state': "present"} # noqa: E501
  1405. ########
  1406. # Update
  1407. ########
  1408. if oc_route.needs_update():
  1409. if check_mode:
  1410. return {'changed': True, 'msg': 'CHECK_MODE: Would have performed an update.'} # noqa: E501
  1411. api_rval = oc_route.update()
  1412. if api_rval['returncode'] != 0:
  1413. return {'failed': True, 'msg': api_rval, 'state': "present"} # noqa: E501
  1414. # return the created object
  1415. api_rval = oc_route.get()
  1416. if api_rval['returncode'] != 0:
  1417. return {'failed': True, 'msg': api_rval, 'state': "present"} # noqa: E501
  1418. return {'changed': True, 'results': api_rval, 'state': "present"} # noqa: E501
  1419. return {'changed': False, 'results': api_rval, 'state': "present"}
  1420. # catch all
  1421. return {'failed': True, 'msg': "Unknown State passed"}
  1422. # -*- -*- -*- End included fragment: class/oc_route.py -*- -*- -*-
  1423. # -*- -*- -*- Begin included fragment: ansible/oc_route.py -*- -*- -*-
  1424. # pylint: disable=too-many-branches
  1425. def main():
  1426. '''
  1427. ansible oc module for route
  1428. '''
  1429. module = AnsibleModule(
  1430. argument_spec=dict(
  1431. kubeconfig=dict(default='/etc/origin/master/admin.kubeconfig', type='str'),
  1432. state=dict(default='present', type='str',
  1433. choices=['present', 'absent', 'list']),
  1434. debug=dict(default=False, type='bool'),
  1435. name=dict(default=None, required=True, type='str'),
  1436. namespace=dict(default=None, required=True, type='str'),
  1437. tls_termination=dict(default=None, type='str'),
  1438. dest_cacert_path=dict(default=None, type='str'),
  1439. cacert_path=dict(default=None, type='str'),
  1440. cert_path=dict(default=None, type='str'),
  1441. key_path=dict(default=None, type='str'),
  1442. dest_cacert_content=dict(default=None, type='str'),
  1443. cacert_content=dict(default=None, type='str'),
  1444. cert_content=dict(default=None, type='str'),
  1445. key_content=dict(default=None, type='str'),
  1446. service_name=dict(default=None, type='str'),
  1447. host=dict(default=None, type='str'),
  1448. wildcard_policy=dict(default=None, type='str'),
  1449. weight=dict(default=None, type='int'),
  1450. port=dict(default=None, type='int'),
  1451. ),
  1452. mutually_exclusive=[('dest_cacert_path', 'dest_cacert_content'),
  1453. ('cacert_path', 'cacert_content'),
  1454. ('cert_path', 'cert_content'),
  1455. ('key_path', 'key_content'), ],
  1456. supports_check_mode=True,
  1457. )
  1458. results = OCRoute.run_ansible(module.params, module.check_mode)
  1459. if 'failed' in results:
  1460. module.fail_json(**results)
  1461. module.exit_json(**results)
  1462. if __name__ == '__main__':
  1463. main()
  1464. # -*- -*- -*- End included fragment: ansible/oc_route.py -*- -*- -*-