oc_route.py 61 KB

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