oc_route.py 64 KB

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