oc_route.py 57 KB

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