oc_route.py 57 KB

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