oc_route.py 56 KB

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