oc_route.py 58 KB

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