oc_route.py 54 KB

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