oc_route.py 55 KB

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