oc_route.py 59 KB

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