oc_route.py 58 KB

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