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 collections
  35. import copy
  36. import json
  37. import os
  38. import re
  39. import shutil
  40. import subprocess
  41. import tempfile
  42. # pylint: disable=import-error
  43. try:
  44. import ruamel.yaml as yaml
  45. except ImportError:
  46. import yaml
  47. from ansible.module_utils.basic import AnsibleModule
  48. # -*- -*- -*- End included fragment: lib/import.py -*- -*- -*-
  49. # -*- -*- -*- Begin included fragment: doc/route -*- -*- -*-
  50. DOCUMENTATION = '''
  51. ---
  52. module: oc_route
  53. short_description: Create, modify, and idempotently manage openshift routes.
  54. description:
  55. - Manage openshift route objects programmatically.
  56. options:
  57. state:
  58. description:
  59. - State represents whether to create, modify, delete, or list
  60. required: true
  61. default: present
  62. choices: ["present", "absent", "list"]
  63. aliases: []
  64. kubeconfig:
  65. description:
  66. - The path for the kubeconfig file to use for authentication
  67. required: false
  68. default: /etc/origin/master/admin.kubeconfig
  69. aliases: []
  70. debug:
  71. description:
  72. - Turn on debug output.
  73. required: false
  74. default: False
  75. aliases: []
  76. name:
  77. description:
  78. - Name of the object that is being queried.
  79. required: false
  80. default: None
  81. aliases: []
  82. namespace:
  83. description:
  84. - The namespace where the object lives.
  85. required: false
  86. default: str
  87. aliases: []
  88. tls_termination:
  89. description:
  90. - The options for termination. e.g. reencrypt
  91. required: false
  92. default: None
  93. aliases: []
  94. dest_cacert_path:
  95. description:
  96. - The path to the dest_cacert
  97. required: false
  98. default: None
  99. aliases: []
  100. cacert_path:
  101. description:
  102. - The path to the cacert
  103. required: false
  104. default: None
  105. aliases: []
  106. cert_path:
  107. description:
  108. - The path to the cert
  109. required: false
  110. default: None
  111. aliases: []
  112. key_path:
  113. description:
  114. - The path to the key
  115. required: false
  116. default: None
  117. aliases: []
  118. dest_cacert_content:
  119. description:
  120. - The dest_cacert content
  121. required: false
  122. default: None
  123. aliases: []
  124. cacert_content:
  125. description:
  126. - The cacert content
  127. required: false
  128. default: None
  129. aliases: []
  130. cert_content:
  131. description:
  132. - The cert content
  133. required: false
  134. default: None
  135. aliases: []
  136. service_name:
  137. description:
  138. - The name of the service that this route points to.
  139. required: false
  140. default: None
  141. aliases: []
  142. host:
  143. description:
  144. - The host that the route will use. e.g. myapp.x.y.z
  145. required: false
  146. default: None
  147. aliases: []
  148. port:
  149. description:
  150. - The Name of the service port or number of the container port the route will route traffic to
  151. required: false
  152. default: None
  153. aliases: []
  154. author:
  155. - "Kenny Woodson <kwoodson@redhat.com>"
  156. extends_documentation_fragment: []
  157. '''
  158. EXAMPLES = '''
  159. - name: Configure certificates for reencrypt route
  160. oc_route:
  161. name: myapproute
  162. namespace: awesomeapp
  163. cert_path: "/etc/origin/master/named_certificates/myapp_cert
  164. key_path: "/etc/origin/master/named_certificates/myapp_key
  165. cacert_path: "/etc/origin/master/named_certificates/myapp_cacert
  166. dest_cacert_content: "{{ dest_cacert_content }}"
  167. service_name: myapp_php
  168. host: myapp.awesomeapp.openshift.com
  169. tls_termination: reencrypt
  170. run_once: true
  171. '''
  172. # -*- -*- -*- End included fragment: doc/route -*- -*- -*-
  173. # -*- -*- -*- Begin included fragment: ../../lib_utils/src/class/yedit.py -*- -*- -*-
  174. # pylint: disable=undefined-variable,missing-docstring
  175. # noqa: E301,E302
  176. class YeditException(Exception):
  177. ''' Exception class for Yedit '''
  178. pass
  179. # pylint: disable=too-many-public-methods
  180. class Yedit(object):
  181. ''' Class to modify yaml files '''
  182. re_valid_key = r"(((\[-?\d+\])|([0-9a-zA-Z%s/_-]+)).?)+$"
  183. re_key = r"(?:\[(-?\d+)\])|([0-9a-zA-Z%s/_-]+)"
  184. com_sep = set(['.', '#', '|', ':'])
  185. # pylint: disable=too-many-arguments
  186. def __init__(self,
  187. filename=None,
  188. content=None,
  189. content_type='yaml',
  190. separator='.',
  191. backup=False):
  192. self.content = content
  193. self._separator = separator
  194. self.filename = filename
  195. self.__yaml_dict = content
  196. self.content_type = content_type
  197. self.backup = backup
  198. self.load(content_type=self.content_type)
  199. if self.__yaml_dict is None:
  200. self.__yaml_dict = {}
  201. @property
  202. def separator(self):
  203. ''' getter method for yaml_dict '''
  204. return self._separator
  205. @separator.setter
  206. def separator(self):
  207. ''' getter method for yaml_dict '''
  208. return self._separator
  209. @property
  210. def yaml_dict(self):
  211. ''' getter method for yaml_dict '''
  212. return self.__yaml_dict
  213. @yaml_dict.setter
  214. def yaml_dict(self, value):
  215. ''' setter method for yaml_dict '''
  216. self.__yaml_dict = value
  217. @staticmethod
  218. def parse_key(key, sep='.'):
  219. '''parse the key allowing the appropriate separator'''
  220. common_separators = list(Yedit.com_sep - set([sep]))
  221. return re.findall(Yedit.re_key % ''.join(common_separators), key)
  222. @staticmethod
  223. def valid_key(key, sep='.'):
  224. '''validate the incoming key'''
  225. common_separators = list(Yedit.com_sep - set([sep]))
  226. if not re.match(Yedit.re_valid_key % ''.join(common_separators), key):
  227. return False
  228. return True
  229. @staticmethod
  230. def remove_entry(data, key, sep='.'):
  231. ''' remove data at location key '''
  232. if key == '' and isinstance(data, dict):
  233. data.clear()
  234. return True
  235. elif key == '' and isinstance(data, list):
  236. del data[:]
  237. return True
  238. if not (key and Yedit.valid_key(key, sep)) and \
  239. isinstance(data, (list, dict)):
  240. return None
  241. key_indexes = Yedit.parse_key(key, sep)
  242. for arr_ind, dict_key in key_indexes[:-1]:
  243. if dict_key and isinstance(data, dict):
  244. data = data.get(dict_key, None)
  245. elif (arr_ind and isinstance(data, list) and
  246. int(arr_ind) <= len(data) - 1):
  247. data = data[int(arr_ind)]
  248. else:
  249. return None
  250. # process last index for remove
  251. # expected list entry
  252. if key_indexes[-1][0]:
  253. if isinstance(data, list) and int(key_indexes[-1][0]) <= len(data) - 1: # noqa: E501
  254. del data[int(key_indexes[-1][0])]
  255. return True
  256. # expected dict entry
  257. elif key_indexes[-1][1]:
  258. if isinstance(data, dict):
  259. del data[key_indexes[-1][1]]
  260. return True
  261. @staticmethod
  262. def add_entry(data, key, item=None, sep='.'):
  263. ''' Get an item from a dictionary with key notation a.b.c
  264. d = {'a': {'b': 'c'}}}
  265. key = a#b
  266. return c
  267. '''
  268. if key == '':
  269. pass
  270. elif (not (key and Yedit.valid_key(key, sep)) and
  271. isinstance(data, (list, dict))):
  272. return None
  273. key_indexes = Yedit.parse_key(key, sep)
  274. for arr_ind, dict_key in key_indexes[:-1]:
  275. if dict_key:
  276. if isinstance(data, dict) and dict_key in data and data[dict_key]: # noqa: E501
  277. data = data[dict_key]
  278. continue
  279. elif data and not isinstance(data, dict):
  280. raise YeditException("Unexpected item type found while going through key " +
  281. "path: {} (at key: {})".format(key, dict_key))
  282. data[dict_key] = {}
  283. data = data[dict_key]
  284. elif (arr_ind and isinstance(data, list) and
  285. int(arr_ind) <= len(data) - 1):
  286. data = data[int(arr_ind)]
  287. else:
  288. raise YeditException("Unexpected item type found while going through key path: {}".format(key))
  289. if key == '':
  290. data = item
  291. # process last index for add
  292. # expected list entry
  293. elif key_indexes[-1][0] and isinstance(data, list) and int(key_indexes[-1][0]) <= len(data) - 1: # noqa: E501
  294. data[int(key_indexes[-1][0])] = item
  295. # expected dict entry
  296. elif key_indexes[-1][1] and isinstance(data, dict):
  297. data[key_indexes[-1][1]] = item
  298. # didn't add/update to an existing list, nor add/update key to a dict
  299. # so we must have been provided some syntax like a.b.c[<int>] = "data" for a
  300. # non-existent array
  301. else:
  302. raise YeditException("Error adding to object at path: {}".format(key))
  303. return data
  304. @staticmethod
  305. def get_entry(data, key, sep='.'):
  306. ''' Get an item from a dictionary with key notation a.b.c
  307. d = {'a': {'b': 'c'}}}
  308. key = a.b
  309. return c
  310. '''
  311. if key == '':
  312. pass
  313. elif (not (key and Yedit.valid_key(key, sep)) and
  314. isinstance(data, (list, dict))):
  315. return None
  316. key_indexes = Yedit.parse_key(key, sep)
  317. for arr_ind, dict_key in key_indexes:
  318. if dict_key and isinstance(data, dict):
  319. data = data.get(dict_key, None)
  320. elif (arr_ind and isinstance(data, list) and
  321. int(arr_ind) <= len(data) - 1):
  322. data = data[int(arr_ind)]
  323. else:
  324. return None
  325. return data
  326. @staticmethod
  327. def _write(filename, contents):
  328. ''' Actually write the file contents to disk. This helps with mocking. '''
  329. tmp_filename = filename + '.yedit'
  330. with open(tmp_filename, 'w') as yfd:
  331. yfd.write(contents)
  332. os.rename(tmp_filename, filename)
  333. def write(self):
  334. ''' write to file '''
  335. if not self.filename:
  336. raise YeditException('Please specify a filename.')
  337. if self.backup and self.file_exists():
  338. shutil.copy(self.filename, self.filename + '.orig')
  339. # Try to set format attributes if supported
  340. try:
  341. self.yaml_dict.fa.set_block_style()
  342. except AttributeError:
  343. pass
  344. # Try to use RoundTripDumper if supported.
  345. try:
  346. Yedit._write(self.filename, yaml.dump(self.yaml_dict, Dumper=yaml.RoundTripDumper))
  347. except AttributeError:
  348. Yedit._write(self.filename, yaml.safe_dump(self.yaml_dict, default_flow_style=False))
  349. return (True, self.yaml_dict)
  350. def read(self):
  351. ''' read from file '''
  352. # check if it exists
  353. if self.filename is None or not self.file_exists():
  354. return None
  355. contents = None
  356. with open(self.filename) as yfd:
  357. contents = yfd.read()
  358. return contents
  359. def file_exists(self):
  360. ''' return whether file exists '''
  361. if os.path.exists(self.filename):
  362. return True
  363. return False
  364. def load(self, content_type='yaml'):
  365. ''' return yaml file '''
  366. contents = self.read()
  367. if not contents and not self.content:
  368. return None
  369. if self.content:
  370. if isinstance(self.content, dict):
  371. self.yaml_dict = self.content
  372. return self.yaml_dict
  373. elif isinstance(self.content, str):
  374. contents = self.content
  375. # check if it is yaml
  376. try:
  377. if content_type == 'yaml' and contents:
  378. # Try to set format attributes if supported
  379. try:
  380. self.yaml_dict.fa.set_block_style()
  381. except AttributeError:
  382. pass
  383. # Try to use RoundTripLoader if supported.
  384. try:
  385. self.yaml_dict = yaml.safe_load(contents, yaml.RoundTripLoader)
  386. except AttributeError:
  387. self.yaml_dict = yaml.safe_load(contents)
  388. # Try to set format attributes if supported
  389. try:
  390. self.yaml_dict.fa.set_block_style()
  391. except AttributeError:
  392. pass
  393. elif content_type == 'json' and contents:
  394. self.yaml_dict = json.loads(contents)
  395. except yaml.YAMLError as err:
  396. # Error loading yaml or json
  397. raise YeditException('Problem with loading yaml file. %s' % err)
  398. return self.yaml_dict
  399. def get(self, key):
  400. ''' get a specified key'''
  401. try:
  402. entry = Yedit.get_entry(self.yaml_dict, key, self.separator)
  403. except KeyError:
  404. entry = None
  405. return entry
  406. def pop(self, path, key_or_item):
  407. ''' remove a key, value pair from a dict or an item for a list'''
  408. try:
  409. entry = Yedit.get_entry(self.yaml_dict, path, self.separator)
  410. except KeyError:
  411. entry = None
  412. if entry is None:
  413. return (False, self.yaml_dict)
  414. if isinstance(entry, dict):
  415. # AUDIT:maybe-no-member makes sense due to fuzzy types
  416. # pylint: disable=maybe-no-member
  417. if key_or_item in entry:
  418. entry.pop(key_or_item)
  419. return (True, self.yaml_dict)
  420. return (False, self.yaml_dict)
  421. elif isinstance(entry, list):
  422. # AUDIT:maybe-no-member makes sense due to fuzzy types
  423. # pylint: disable=maybe-no-member
  424. ind = None
  425. try:
  426. ind = entry.index(key_or_item)
  427. except ValueError:
  428. return (False, self.yaml_dict)
  429. entry.pop(ind)
  430. return (True, self.yaml_dict)
  431. return (False, self.yaml_dict)
  432. def delete(self, path):
  433. ''' remove path from a dict'''
  434. try:
  435. entry = Yedit.get_entry(self.yaml_dict, path, self.separator)
  436. except KeyError:
  437. entry = None
  438. if entry is None:
  439. return (False, self.yaml_dict)
  440. result = Yedit.remove_entry(self.yaml_dict, path, self.separator)
  441. if not result:
  442. return (False, self.yaml_dict)
  443. return (True, self.yaml_dict)
  444. def exists(self, path, value):
  445. ''' check if value exists at path'''
  446. try:
  447. entry = Yedit.get_entry(self.yaml_dict, path, self.separator)
  448. except KeyError:
  449. entry = None
  450. if isinstance(entry, list):
  451. if value in entry:
  452. return True
  453. return False
  454. elif isinstance(entry, dict):
  455. if isinstance(value, dict):
  456. rval = False
  457. for key, val in value.items():
  458. if entry[key] != val:
  459. rval = False
  460. break
  461. else:
  462. rval = True
  463. return rval
  464. return value in entry
  465. return entry == value
  466. def append(self, path, value):
  467. '''append value to a list'''
  468. try:
  469. entry = Yedit.get_entry(self.yaml_dict, path, self.separator)
  470. except KeyError:
  471. entry = None
  472. if entry is None:
  473. self.put(path, [])
  474. entry = Yedit.get_entry(self.yaml_dict, path, self.separator)
  475. if not isinstance(entry, list):
  476. return (False, self.yaml_dict)
  477. # AUDIT:maybe-no-member makes sense due to loading data from
  478. # a serialized format.
  479. # pylint: disable=maybe-no-member
  480. entry.append(value)
  481. return (True, self.yaml_dict)
  482. # pylint: disable=too-many-arguments
  483. def update(self, path, value, index=None, curr_value=None):
  484. ''' put path, value into a dict '''
  485. try:
  486. entry = Yedit.get_entry(self.yaml_dict, path, self.separator)
  487. except KeyError:
  488. entry = None
  489. if isinstance(entry, dict):
  490. # AUDIT:maybe-no-member makes sense due to fuzzy types
  491. # pylint: disable=maybe-no-member
  492. if not isinstance(value, dict):
  493. raise YeditException('Cannot replace key, value entry in ' +
  494. 'dict with non-dict type. value=[%s] [%s]' % (value, type(value))) # noqa: E501
  495. entry.update(value)
  496. return (True, self.yaml_dict)
  497. elif isinstance(entry, list):
  498. # AUDIT:maybe-no-member makes sense due to fuzzy types
  499. # pylint: disable=maybe-no-member
  500. ind = None
  501. if curr_value:
  502. try:
  503. ind = entry.index(curr_value)
  504. except ValueError:
  505. return (False, self.yaml_dict)
  506. elif index is not None:
  507. ind = index
  508. if ind is not None and entry[ind] != value:
  509. entry[ind] = value
  510. return (True, self.yaml_dict)
  511. # see if it exists in the list
  512. try:
  513. ind = entry.index(value)
  514. except ValueError:
  515. # doesn't exist, append it
  516. entry.append(value)
  517. return (True, self.yaml_dict)
  518. # already exists, return
  519. if ind is not None:
  520. return (False, self.yaml_dict)
  521. return (False, self.yaml_dict)
  522. def put(self, path, value):
  523. ''' put path, value into a dict '''
  524. try:
  525. entry = Yedit.get_entry(self.yaml_dict, path, self.separator)
  526. except KeyError:
  527. entry = None
  528. if entry == value:
  529. return (False, self.yaml_dict)
  530. # deepcopy didn't work
  531. # Try to use ruamel.yaml and fallback to pyyaml
  532. try:
  533. tmp_copy = yaml.load(yaml.round_trip_dump(self.yaml_dict,
  534. default_flow_style=False),
  535. yaml.RoundTripLoader)
  536. except AttributeError:
  537. tmp_copy = copy.deepcopy(self.yaml_dict)
  538. # set the format attributes if available
  539. try:
  540. tmp_copy.fa.set_block_style()
  541. except AttributeError:
  542. pass
  543. result = Yedit.add_entry(tmp_copy, path, value, self.separator)
  544. if not result:
  545. return (False, self.yaml_dict)
  546. self.yaml_dict = tmp_copy
  547. return (True, self.yaml_dict)
  548. def create(self, path, value):
  549. ''' create a yaml file '''
  550. if not self.file_exists():
  551. # deepcopy didn't work
  552. # Try to use ruamel.yaml and fallback to pyyaml
  553. try:
  554. tmp_copy = yaml.load(yaml.round_trip_dump(self.yaml_dict,
  555. default_flow_style=False),
  556. yaml.RoundTripLoader)
  557. except AttributeError:
  558. tmp_copy = copy.deepcopy(self.yaml_dict)
  559. # set the format attributes if available
  560. try:
  561. tmp_copy.fa.set_block_style()
  562. except AttributeError:
  563. pass
  564. result = Yedit.add_entry(tmp_copy, path, value, self.separator)
  565. if result:
  566. self.yaml_dict = tmp_copy
  567. return (True, self.yaml_dict)
  568. return (False, self.yaml_dict)
  569. @staticmethod
  570. def get_curr_value(invalue, val_type):
  571. '''return the current value'''
  572. if invalue is None:
  573. return None
  574. curr_value = invalue
  575. if val_type == 'yaml':
  576. curr_value = yaml.load(invalue)
  577. elif val_type == 'json':
  578. curr_value = json.loads(invalue)
  579. return curr_value
  580. @staticmethod
  581. def parse_value(inc_value, vtype=''):
  582. '''determine value type passed'''
  583. true_bools = ['y', 'Y', 'yes', 'Yes', 'YES', 'true', 'True', 'TRUE',
  584. 'on', 'On', 'ON', ]
  585. false_bools = ['n', 'N', 'no', 'No', 'NO', 'false', 'False', 'FALSE',
  586. 'off', 'Off', 'OFF']
  587. # It came in as a string but you didn't specify value_type as string
  588. # we will convert to bool if it matches any of the above cases
  589. if isinstance(inc_value, str) and 'bool' in vtype:
  590. if inc_value not in true_bools and inc_value not in false_bools:
  591. raise YeditException('Not a boolean type. str=[%s] vtype=[%s]'
  592. % (inc_value, vtype))
  593. elif isinstance(inc_value, bool) and 'str' in vtype:
  594. inc_value = str(inc_value)
  595. # If vtype is not str then go ahead and attempt to yaml load it.
  596. if isinstance(inc_value, str) and 'str' not in vtype:
  597. try:
  598. inc_value = yaml.load(inc_value)
  599. except Exception:
  600. raise YeditException('Could not determine type of incoming ' +
  601. 'value. value=[%s] vtype=[%s]'
  602. % (type(inc_value), vtype))
  603. return inc_value
  604. # pylint: disable=too-many-return-statements,too-many-branches
  605. @staticmethod
  606. def run_ansible(module):
  607. '''perform the idempotent crud operations'''
  608. yamlfile = Yedit(filename=module.params['src'],
  609. backup=module.params['backup'],
  610. separator=module.params['separator'])
  611. if module.params['src']:
  612. rval = yamlfile.load()
  613. if yamlfile.yaml_dict is None and \
  614. module.params['state'] != 'present':
  615. return {'failed': True,
  616. 'msg': 'Error opening file [%s]. Verify that the ' +
  617. 'file exists, that it is has correct' +
  618. ' permissions, and is valid yaml.'}
  619. if module.params['state'] == 'list':
  620. if module.params['content']:
  621. content = Yedit.parse_value(module.params['content'],
  622. module.params['content_type'])
  623. yamlfile.yaml_dict = content
  624. if module.params['key']:
  625. rval = yamlfile.get(module.params['key']) or {}
  626. return {'changed': False, 'result': rval, 'state': "list"}
  627. elif module.params['state'] == 'absent':
  628. if module.params['content']:
  629. content = Yedit.parse_value(module.params['content'],
  630. module.params['content_type'])
  631. yamlfile.yaml_dict = content
  632. if module.params['update']:
  633. rval = yamlfile.pop(module.params['key'],
  634. module.params['value'])
  635. else:
  636. rval = yamlfile.delete(module.params['key'])
  637. if rval[0] and module.params['src']:
  638. yamlfile.write()
  639. return {'changed': rval[0], 'result': rval[1], 'state': "absent"}
  640. elif module.params['state'] == 'present':
  641. # check if content is different than what is in the file
  642. if module.params['content']:
  643. content = Yedit.parse_value(module.params['content'],
  644. module.params['content_type'])
  645. # We had no edits to make and the contents are the same
  646. if yamlfile.yaml_dict == content and \
  647. module.params['value'] is None:
  648. return {'changed': False,
  649. 'result': yamlfile.yaml_dict,
  650. 'state': "present"}
  651. yamlfile.yaml_dict = content
  652. # we were passed a value; parse it
  653. if module.params['value']:
  654. value = Yedit.parse_value(module.params['value'],
  655. module.params['value_type'])
  656. key = module.params['key']
  657. if module.params['update']:
  658. # pylint: disable=line-too-long
  659. curr_value = Yedit.get_curr_value(Yedit.parse_value(module.params['curr_value']), # noqa: E501
  660. module.params['curr_value_format']) # noqa: E501
  661. rval = yamlfile.update(key, value, module.params['index'], curr_value) # noqa: E501
  662. elif module.params['append']:
  663. rval = yamlfile.append(key, value)
  664. else:
  665. rval = yamlfile.put(key, value)
  666. if rval[0] and module.params['src']:
  667. yamlfile.write()
  668. return {'changed': rval[0],
  669. 'result': rval[1], 'state': "present"}
  670. # no edits to make
  671. if module.params['src']:
  672. # pylint: disable=redefined-variable-type
  673. rval = yamlfile.write()
  674. return {'changed': rval[0],
  675. 'result': rval[1],
  676. 'state': "present"}
  677. return {'failed': True, 'msg': 'Unkown state passed'}
  678. # -*- -*- -*- End included fragment: ../../lib_utils/src/class/yedit.py -*- -*- -*-
  679. # -*- -*- -*- Begin included fragment: lib/base.py -*- -*- -*-
  680. # pylint: disable=too-many-lines
  681. # noqa: E301,E302,E303,T001
  682. class OpenShiftCLIError(Exception):
  683. '''Exception class for openshiftcli'''
  684. pass
  685. ADDITIONAL_PATH_LOOKUPS = ['/usr/local/bin', os.path.expanduser('~/bin')]
  686. def locate_oc_binary():
  687. ''' Find and return oc binary file '''
  688. # https://github.com/openshift/openshift-ansible/issues/3410
  689. # oc can be in /usr/local/bin in some cases, but that may not
  690. # be in $PATH due to ansible/sudo
  691. paths = os.environ.get("PATH", os.defpath).split(os.pathsep) + ADDITIONAL_PATH_LOOKUPS
  692. oc_binary = 'oc'
  693. # Use shutil.which if it is available, otherwise fallback to a naive path search
  694. try:
  695. which_result = shutil.which(oc_binary, path=os.pathsep.join(paths))
  696. if which_result is not None:
  697. oc_binary = which_result
  698. except AttributeError:
  699. for path in paths:
  700. if os.path.exists(os.path.join(path, oc_binary)):
  701. oc_binary = os.path.join(path, oc_binary)
  702. break
  703. return oc_binary
  704. # pylint: disable=too-few-public-methods
  705. class OpenShiftCLI(object):
  706. ''' Class to wrap the command line tools '''
  707. def __init__(self,
  708. namespace,
  709. kubeconfig='/etc/origin/master/admin.kubeconfig',
  710. verbose=False,
  711. all_namespaces=False):
  712. ''' Constructor for OpenshiftCLI '''
  713. self.namespace = namespace
  714. self.verbose = verbose
  715. self.kubeconfig = Utils.create_tmpfile_copy(kubeconfig)
  716. self.all_namespaces = all_namespaces
  717. self.oc_binary = locate_oc_binary()
  718. # Pylint allows only 5 arguments to be passed.
  719. # pylint: disable=too-many-arguments
  720. def _replace_content(self, resource, rname, content, force=False, sep='.'):
  721. ''' replace the current object with the content '''
  722. res = self._get(resource, rname)
  723. if not res['results']:
  724. return res
  725. fname = Utils.create_tmpfile(rname + '-')
  726. yed = Yedit(fname, res['results'][0], separator=sep)
  727. changes = []
  728. for key, value in content.items():
  729. changes.append(yed.put(key, value))
  730. if any([change[0] for change in changes]):
  731. yed.write()
  732. atexit.register(Utils.cleanup, [fname])
  733. return self._replace(fname, force)
  734. return {'returncode': 0, 'updated': False}
  735. def _replace(self, fname, force=False):
  736. '''replace the current object with oc replace'''
  737. cmd = ['replace', '-f', fname]
  738. if force:
  739. cmd.append('--force')
  740. return self.openshift_cmd(cmd)
  741. def _create_from_content(self, rname, content):
  742. '''create a temporary file and then call oc create on it'''
  743. fname = Utils.create_tmpfile(rname + '-')
  744. yed = Yedit(fname, content=content)
  745. yed.write()
  746. atexit.register(Utils.cleanup, [fname])
  747. return self._create(fname)
  748. def _create(self, fname):
  749. '''call oc create on a filename'''
  750. return self.openshift_cmd(['create', '-f', fname])
  751. def _delete(self, resource, rname, selector=None):
  752. '''call oc delete on a resource'''
  753. cmd = ['delete', resource, rname]
  754. if selector:
  755. cmd.append('--selector=%s' % selector)
  756. return self.openshift_cmd(cmd)
  757. def _process(self, template_name, create=False, params=None, template_data=None): # noqa: E501
  758. '''process a template
  759. template_name: the name of the template to process
  760. create: whether to send to oc create after processing
  761. params: the parameters for the template
  762. template_data: the incoming template's data; instead of a file
  763. '''
  764. cmd = ['process']
  765. if template_data:
  766. cmd.extend(['-f', '-'])
  767. else:
  768. cmd.append(template_name)
  769. if params:
  770. param_str = ["%s=%s" % (key, value) for key, value in params.items()]
  771. cmd.append('-v')
  772. cmd.extend(param_str)
  773. results = self.openshift_cmd(cmd, output=True, input_data=template_data)
  774. if results['returncode'] != 0 or not create:
  775. return results
  776. fname = Utils.create_tmpfile(template_name + '-')
  777. yed = Yedit(fname, results['results'])
  778. yed.write()
  779. atexit.register(Utils.cleanup, [fname])
  780. return self.openshift_cmd(['create', '-f', fname])
  781. def _get(self, resource, rname=None, selector=None):
  782. '''return a resource by name '''
  783. cmd = ['get', resource]
  784. if selector:
  785. cmd.append('--selector=%s' % selector)
  786. elif rname:
  787. cmd.append(rname)
  788. cmd.extend(['-o', 'json'])
  789. rval = self.openshift_cmd(cmd, output=True)
  790. # Ensure results are retuned in an array
  791. if 'items' in rval:
  792. rval['results'] = rval['items']
  793. elif not isinstance(rval['results'], list):
  794. rval['results'] = [rval['results']]
  795. return rval
  796. def _schedulable(self, node=None, selector=None, schedulable=True):
  797. ''' perform oadm manage-node scheduable '''
  798. cmd = ['manage-node']
  799. if node:
  800. cmd.extend(node)
  801. else:
  802. cmd.append('--selector=%s' % selector)
  803. cmd.append('--schedulable=%s' % schedulable)
  804. return self.openshift_cmd(cmd, oadm=True, output=True, output_type='raw') # noqa: E501
  805. def _list_pods(self, node=None, selector=None, pod_selector=None):
  806. ''' perform oadm list pods
  807. node: the node in which to list pods
  808. selector: the label selector filter if provided
  809. pod_selector: the pod selector filter if provided
  810. '''
  811. cmd = ['manage-node']
  812. if node:
  813. cmd.extend(node)
  814. else:
  815. cmd.append('--selector=%s' % selector)
  816. if pod_selector:
  817. cmd.append('--pod-selector=%s' % pod_selector)
  818. cmd.extend(['--list-pods', '-o', 'json'])
  819. return self.openshift_cmd(cmd, oadm=True, output=True, output_type='raw')
  820. # pylint: disable=too-many-arguments
  821. def _evacuate(self, node=None, selector=None, pod_selector=None, dry_run=False, grace_period=None, force=False):
  822. ''' perform oadm manage-node evacuate '''
  823. cmd = ['manage-node']
  824. if node:
  825. cmd.extend(node)
  826. else:
  827. cmd.append('--selector=%s' % selector)
  828. if dry_run:
  829. cmd.append('--dry-run')
  830. if pod_selector:
  831. cmd.append('--pod-selector=%s' % pod_selector)
  832. if grace_period:
  833. cmd.append('--grace-period=%s' % int(grace_period))
  834. if force:
  835. cmd.append('--force')
  836. cmd.append('--evacuate')
  837. return self.openshift_cmd(cmd, oadm=True, output=True, output_type='raw')
  838. def _version(self):
  839. ''' return the openshift version'''
  840. return self.openshift_cmd(['version'], output=True, output_type='raw')
  841. def _import_image(self, url=None, name=None, tag=None):
  842. ''' perform image import '''
  843. cmd = ['import-image']
  844. image = '{0}'.format(name)
  845. if tag:
  846. image += ':{0}'.format(tag)
  847. cmd.append(image)
  848. if url:
  849. cmd.append('--from={0}/{1}'.format(url, image))
  850. cmd.append('-n{0}'.format(self.namespace))
  851. cmd.append('--confirm')
  852. return self.openshift_cmd(cmd)
  853. def _run(self, cmds, input_data):
  854. ''' Actually executes the command. This makes mocking easier. '''
  855. curr_env = os.environ.copy()
  856. curr_env.update({'KUBECONFIG': self.kubeconfig})
  857. proc = subprocess.Popen(cmds,
  858. stdin=subprocess.PIPE,
  859. stdout=subprocess.PIPE,
  860. stderr=subprocess.PIPE,
  861. env=curr_env)
  862. stdout, stderr = proc.communicate(input_data)
  863. return proc.returncode, stdout.decode(), stderr.decode()
  864. # pylint: disable=too-many-arguments,too-many-branches
  865. def openshift_cmd(self, cmd, oadm=False, output=False, output_type='json', input_data=None):
  866. '''Base command for oc '''
  867. cmds = [self.oc_binary]
  868. if oadm:
  869. cmds.append('adm')
  870. cmds.extend(cmd)
  871. if self.all_namespaces:
  872. cmds.extend(['--all-namespaces'])
  873. elif self.namespace is not None and self.namespace.lower() not in ['none', 'emtpy']: # E501
  874. cmds.extend(['-n', self.namespace])
  875. rval = {}
  876. results = ''
  877. err = None
  878. if self.verbose:
  879. print(' '.join(cmds))
  880. try:
  881. returncode, stdout, stderr = self._run(cmds, input_data)
  882. except OSError as ex:
  883. returncode, stdout, stderr = 1, '', 'Failed to execute {}: {}'.format(subprocess.list2cmdline(cmds), ex)
  884. rval = {"returncode": returncode,
  885. "results": results,
  886. "cmd": ' '.join(cmds)}
  887. if returncode == 0:
  888. if output:
  889. if output_type == 'json':
  890. try:
  891. rval['results'] = json.loads(stdout)
  892. except ValueError as err:
  893. if "No JSON object could be decoded" in err.args:
  894. err = err.args
  895. elif output_type == 'raw':
  896. rval['results'] = stdout
  897. if self.verbose:
  898. print("STDOUT: {0}".format(stdout))
  899. print("STDERR: {0}".format(stderr))
  900. if err:
  901. rval.update({"err": err,
  902. "stderr": stderr,
  903. "stdout": stdout,
  904. "cmd": cmds})
  905. else:
  906. rval.update({"stderr": stderr,
  907. "stdout": stdout,
  908. "results": {}})
  909. return rval
  910. class Utils(object):
  911. ''' utilities for openshiftcli modules '''
  912. @staticmethod
  913. def _write(filename, contents):
  914. ''' Actually write the file contents to disk. This helps with mocking. '''
  915. with open(filename, 'w') as sfd:
  916. sfd.write(contents)
  917. @staticmethod
  918. def create_tmp_file_from_contents(rname, data, ftype='yaml'):
  919. ''' create a file in tmp with name and contents'''
  920. tmp = Utils.create_tmpfile(prefix=rname)
  921. if ftype == 'yaml':
  922. # AUDIT:no-member makes sense here due to ruamel.YAML/PyYAML usage
  923. # pylint: disable=no-member
  924. if hasattr(yaml, 'RoundTripDumper'):
  925. Utils._write(tmp, yaml.dump(data, Dumper=yaml.RoundTripDumper))
  926. else:
  927. Utils._write(tmp, yaml.safe_dump(data, default_flow_style=False))
  928. elif ftype == 'json':
  929. Utils._write(tmp, json.dumps(data))
  930. else:
  931. Utils._write(tmp, data)
  932. # Register cleanup when module is done
  933. atexit.register(Utils.cleanup, [tmp])
  934. return tmp
  935. @staticmethod
  936. def create_tmpfile_copy(inc_file):
  937. '''create a temporary copy of a file'''
  938. tmpfile = Utils.create_tmpfile('lib_openshift-')
  939. Utils._write(tmpfile, open(inc_file).read())
  940. # Cleanup the tmpfile
  941. atexit.register(Utils.cleanup, [tmpfile])
  942. return tmpfile
  943. @staticmethod
  944. def create_tmpfile(prefix='tmp'):
  945. ''' Generates and returns a temporary file name '''
  946. with tempfile.NamedTemporaryFile(prefix=prefix, delete=False) as tmp:
  947. return tmp.name
  948. @staticmethod
  949. def create_tmp_files_from_contents(content, content_type=None):
  950. '''Turn an array of dict: filename, content into a files array'''
  951. if not isinstance(content, list):
  952. content = [content]
  953. files = []
  954. for item in content:
  955. path = Utils.create_tmp_file_from_contents(item['path'] + '-',
  956. item['data'],
  957. ftype=content_type)
  958. files.append({'name': os.path.basename(item['path']),
  959. 'path': path})
  960. return files
  961. @staticmethod
  962. def cleanup(files):
  963. '''Clean up on exit '''
  964. for sfile in files:
  965. if os.path.exists(sfile):
  966. if os.path.isdir(sfile):
  967. shutil.rmtree(sfile)
  968. elif os.path.isfile(sfile):
  969. os.remove(sfile)
  970. @staticmethod
  971. def exists(results, _name):
  972. ''' Check to see if the results include the name '''
  973. if not results:
  974. return False
  975. if Utils.find_result(results, _name):
  976. return True
  977. return False
  978. @staticmethod
  979. def find_result(results, _name):
  980. ''' Find the specified result by name'''
  981. rval = None
  982. for result in results:
  983. if 'metadata' in result and result['metadata']['name'] == _name:
  984. rval = result
  985. break
  986. return rval
  987. @staticmethod
  988. def get_resource_file(sfile, sfile_type='yaml'):
  989. ''' return the service file '''
  990. contents = None
  991. with open(sfile) as sfd:
  992. contents = sfd.read()
  993. if sfile_type == 'yaml':
  994. # AUDIT:no-member makes sense here due to ruamel.YAML/PyYAML usage
  995. # pylint: disable=no-member
  996. if hasattr(yaml, 'RoundTripLoader'):
  997. contents = yaml.load(contents, yaml.RoundTripLoader)
  998. else:
  999. contents = yaml.safe_load(contents)
  1000. elif sfile_type == 'json':
  1001. contents = json.loads(contents)
  1002. return contents
  1003. @staticmethod
  1004. def filter_versions(stdout):
  1005. ''' filter the oc version output '''
  1006. version_dict = {}
  1007. version_search = ['oc', 'openshift', 'kubernetes']
  1008. for line in stdout.strip().split('\n'):
  1009. for term in version_search:
  1010. if not line:
  1011. continue
  1012. if line.startswith(term):
  1013. version_dict[term] = line.split()[-1]
  1014. # horrible hack to get openshift version in Openshift 3.2
  1015. # By default "oc version in 3.2 does not return an "openshift" version
  1016. if "openshift" not in version_dict:
  1017. version_dict["openshift"] = version_dict["oc"]
  1018. return version_dict
  1019. @staticmethod
  1020. def add_custom_versions(versions):
  1021. ''' create custom versions strings '''
  1022. versions_dict = {}
  1023. for tech, version in versions.items():
  1024. # clean up "-" from version
  1025. if "-" in version:
  1026. version = version.split("-")[0]
  1027. if version.startswith('v'):
  1028. versions_dict[tech + '_numeric'] = version[1:].split('+')[0]
  1029. # "v3.3.0.33" is what we have, we want "3.3"
  1030. versions_dict[tech + '_short'] = version[1:4]
  1031. return versions_dict
  1032. @staticmethod
  1033. def openshift_installed():
  1034. ''' check if openshift is installed '''
  1035. import yum
  1036. yum_base = yum.YumBase()
  1037. if yum_base.rpmdb.searchNevra(name='atomic-openshift'):
  1038. return True
  1039. return False
  1040. # Disabling too-many-branches. This is a yaml dictionary comparison function
  1041. # pylint: disable=too-many-branches,too-many-return-statements,too-many-statements
  1042. @staticmethod
  1043. def check_def_equal(user_def, result_def, skip_keys=None, debug=False):
  1044. ''' Given a user defined definition, compare it with the results given back by our query. '''
  1045. # Currently these values are autogenerated and we do not need to check them
  1046. skip = ['metadata', 'status']
  1047. if skip_keys:
  1048. skip.extend(skip_keys)
  1049. for key, value in result_def.items():
  1050. if key in skip:
  1051. continue
  1052. # Both are lists
  1053. if isinstance(value, list):
  1054. if key not in user_def:
  1055. if debug:
  1056. print('User data does not have key [%s]' % key)
  1057. print('User data: %s' % user_def)
  1058. return False
  1059. if not isinstance(user_def[key], list):
  1060. if debug:
  1061. print('user_def[key] is not a list key=[%s] user_def[key]=%s' % (key, user_def[key]))
  1062. return False
  1063. if len(user_def[key]) != len(value):
  1064. if debug:
  1065. print("List lengths are not equal.")
  1066. print("key=[%s]: user_def[%s] != value[%s]" % (key, len(user_def[key]), len(value)))
  1067. print("user_def: %s" % user_def[key])
  1068. print("value: %s" % value)
  1069. return False
  1070. for values in zip(user_def[key], value):
  1071. if isinstance(values[0], dict) and isinstance(values[1], dict):
  1072. if debug:
  1073. print('sending list - list')
  1074. print(type(values[0]))
  1075. print(type(values[1]))
  1076. result = Utils.check_def_equal(values[0], values[1], skip_keys=skip_keys, debug=debug)
  1077. if not result:
  1078. print('list compare returned false')
  1079. return False
  1080. elif value != user_def[key]:
  1081. if debug:
  1082. print('value should be identical')
  1083. print(user_def[key])
  1084. print(value)
  1085. return False
  1086. # recurse on a dictionary
  1087. elif isinstance(value, dict):
  1088. if key not in user_def:
  1089. if debug:
  1090. print("user_def does not have key [%s]" % key)
  1091. return False
  1092. if not isinstance(user_def[key], dict):
  1093. if debug:
  1094. print("dict returned false: not instance of dict")
  1095. return False
  1096. # before passing ensure keys match
  1097. api_values = set(value.keys()) - set(skip)
  1098. user_values = set(user_def[key].keys()) - set(skip)
  1099. if api_values != user_values:
  1100. if debug:
  1101. print("keys are not equal in dict")
  1102. print(user_values)
  1103. print(api_values)
  1104. return False
  1105. result = Utils.check_def_equal(user_def[key], value, skip_keys=skip_keys, debug=debug)
  1106. if not result:
  1107. if debug:
  1108. print("dict returned false")
  1109. print(result)
  1110. return False
  1111. # Verify each key, value pair is the same
  1112. else:
  1113. if key not in user_def or value != user_def[key]:
  1114. if debug:
  1115. print("value not equal; user_def does not have key")
  1116. print(key)
  1117. print(value)
  1118. if key in user_def:
  1119. print(user_def[key])
  1120. return False
  1121. if debug:
  1122. print('returning true')
  1123. return True
  1124. class OpenShiftCLIConfig(object):
  1125. '''Generic Config'''
  1126. def __init__(self, rname, namespace, kubeconfig, options):
  1127. self.kubeconfig = kubeconfig
  1128. self.name = rname
  1129. self.namespace = namespace
  1130. self._options = collections.OrderedDict(options)
  1131. @property
  1132. def config_options(self):
  1133. ''' return config options '''
  1134. return self._options
  1135. def to_option_list(self):
  1136. '''return all options as a string'''
  1137. return self.stringify()
  1138. def stringify(self):
  1139. ''' return the options hash as cli params in a string '''
  1140. rval = []
  1141. for key, data in self.config_options.items():
  1142. if data['include'] \
  1143. and (data['value'] or isinstance(data['value'], int)):
  1144. rval.append('--%s=%s' % (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 -*- -*- -*-