oc_route.py 56 KB

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