oc_route.py 61 KB

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