oc_route.py 61 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857
  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): # pragma: no cover
  174. ''' Exception class for Yedit '''
  175. pass
  176. # pylint: disable=too-many-public-methods
  177. class Yedit(object): # pragma: no cover
  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, name=None, selector=None):
  782. '''call oc delete on a resource'''
  783. cmd = ['delete', resource]
  784. if selector is not None:
  785. cmd.append('--selector={}'.format(selector))
  786. elif name is not None:
  787. cmd.append(name)
  788. else:
  789. raise OpenShiftCLIError('Either name or selector is required when calling delete.')
  790. return self.openshift_cmd(cmd)
  791. def _process(self, template_name, create=False, params=None, template_data=None): # noqa: E501
  792. '''process a template
  793. template_name: the name of the template to process
  794. create: whether to send to oc create after processing
  795. params: the parameters for the template
  796. template_data: the incoming template's data; instead of a file
  797. '''
  798. cmd = ['process']
  799. if template_data:
  800. cmd.extend(['-f', '-'])
  801. else:
  802. cmd.append(template_name)
  803. if params:
  804. param_str = ["{}={}".format(key, value) for key, value in params.items()]
  805. cmd.append('-v')
  806. cmd.extend(param_str)
  807. results = self.openshift_cmd(cmd, output=True, input_data=template_data)
  808. if results['returncode'] != 0 or not create:
  809. return results
  810. fname = Utils.create_tmpfile(template_name + '-')
  811. yed = Yedit(fname, results['results'])
  812. yed.write()
  813. atexit.register(Utils.cleanup, [fname])
  814. return self.openshift_cmd(['create', '-f', fname])
  815. def _get(self, resource, name=None, selector=None):
  816. '''return a resource by name '''
  817. cmd = ['get', resource]
  818. if selector is not None:
  819. cmd.append('--selector={}'.format(selector))
  820. elif name is not None:
  821. cmd.append(name)
  822. cmd.extend(['-o', 'json'])
  823. rval = self.openshift_cmd(cmd, output=True)
  824. # Ensure results are retuned in an array
  825. if 'items' in rval:
  826. rval['results'] = rval['items']
  827. elif not isinstance(rval['results'], list):
  828. rval['results'] = [rval['results']]
  829. return rval
  830. def _schedulable(self, node=None, selector=None, schedulable=True):
  831. ''' perform oadm manage-node scheduable '''
  832. cmd = ['manage-node']
  833. if node:
  834. cmd.extend(node)
  835. else:
  836. cmd.append('--selector={}'.format(selector))
  837. cmd.append('--schedulable={}'.format(schedulable))
  838. return self.openshift_cmd(cmd, oadm=True, output=True, output_type='raw') # noqa: E501
  839. def _list_pods(self, node=None, selector=None, pod_selector=None):
  840. ''' perform oadm list pods
  841. node: the node in which to list pods
  842. selector: the label selector filter if provided
  843. pod_selector: the pod selector filter if provided
  844. '''
  845. cmd = ['manage-node']
  846. if node:
  847. cmd.extend(node)
  848. else:
  849. cmd.append('--selector={}'.format(selector))
  850. if pod_selector:
  851. cmd.append('--pod-selector={}'.format(pod_selector))
  852. cmd.extend(['--list-pods', '-o', 'json'])
  853. return self.openshift_cmd(cmd, oadm=True, output=True, output_type='raw')
  854. # pylint: disable=too-many-arguments
  855. def _evacuate(self, node=None, selector=None, pod_selector=None, dry_run=False, grace_period=None, force=False):
  856. ''' perform oadm manage-node evacuate '''
  857. cmd = ['manage-node']
  858. if node:
  859. cmd.extend(node)
  860. else:
  861. cmd.append('--selector={}'.format(selector))
  862. if dry_run:
  863. cmd.append('--dry-run')
  864. if pod_selector:
  865. cmd.append('--pod-selector={}'.format(pod_selector))
  866. if grace_period:
  867. cmd.append('--grace-period={}'.format(int(grace_period)))
  868. if force:
  869. cmd.append('--force')
  870. cmd.append('--evacuate')
  871. return self.openshift_cmd(cmd, oadm=True, output=True, output_type='raw')
  872. def _version(self):
  873. ''' return the openshift version'''
  874. return self.openshift_cmd(['version'], output=True, output_type='raw')
  875. def _import_image(self, url=None, name=None, tag=None):
  876. ''' perform image import '''
  877. cmd = ['import-image']
  878. image = '{0}'.format(name)
  879. if tag:
  880. image += ':{0}'.format(tag)
  881. cmd.append(image)
  882. if url:
  883. cmd.append('--from={0}/{1}'.format(url, image))
  884. cmd.append('-n{0}'.format(self.namespace))
  885. cmd.append('--confirm')
  886. return self.openshift_cmd(cmd)
  887. def _run(self, cmds, input_data):
  888. ''' Actually executes the command. This makes mocking easier. '''
  889. curr_env = os.environ.copy()
  890. curr_env.update({'KUBECONFIG': self.kubeconfig})
  891. proc = subprocess.Popen(cmds,
  892. stdin=subprocess.PIPE,
  893. stdout=subprocess.PIPE,
  894. stderr=subprocess.PIPE,
  895. env=curr_env)
  896. stdout, stderr = proc.communicate(input_data)
  897. return proc.returncode, stdout.decode(), stderr.decode()
  898. # pylint: disable=too-many-arguments,too-many-branches
  899. def openshift_cmd(self, cmd, oadm=False, output=False, output_type='json', input_data=None):
  900. '''Base command for oc '''
  901. cmds = [self.oc_binary]
  902. if oadm:
  903. cmds.append('adm')
  904. cmds.extend(cmd)
  905. if self.all_namespaces:
  906. cmds.extend(['--all-namespaces'])
  907. elif self.namespace is not None and self.namespace.lower() not in ['none', 'emtpy']: # E501
  908. cmds.extend(['-n', self.namespace])
  909. rval = {}
  910. results = ''
  911. err = None
  912. if self.verbose:
  913. print(' '.join(cmds))
  914. try:
  915. returncode, stdout, stderr = self._run(cmds, input_data)
  916. except OSError as ex:
  917. returncode, stdout, stderr = 1, '', 'Failed to execute {}: {}'.format(subprocess.list2cmdline(cmds), ex)
  918. rval = {"returncode": returncode,
  919. "results": results,
  920. "cmd": ' '.join(cmds)}
  921. if returncode == 0:
  922. if output:
  923. if output_type == 'json':
  924. try:
  925. rval['results'] = json.loads(stdout)
  926. except ValueError as verr:
  927. if "No JSON object could be decoded" in verr.args:
  928. err = verr.args
  929. elif output_type == 'raw':
  930. rval['results'] = stdout
  931. if self.verbose:
  932. print("STDOUT: {0}".format(stdout))
  933. print("STDERR: {0}".format(stderr))
  934. if err:
  935. rval.update({"err": err,
  936. "stderr": stderr,
  937. "stdout": stdout,
  938. "cmd": cmds})
  939. else:
  940. rval.update({"stderr": stderr,
  941. "stdout": stdout,
  942. "results": {}})
  943. return rval
  944. class Utils(object): # pragma: no cover
  945. ''' utilities for openshiftcli modules '''
  946. @staticmethod
  947. def _write(filename, contents):
  948. ''' Actually write the file contents to disk. This helps with mocking. '''
  949. with open(filename, 'w') as sfd:
  950. sfd.write(contents)
  951. @staticmethod
  952. def create_tmp_file_from_contents(rname, data, ftype='yaml'):
  953. ''' create a file in tmp with name and contents'''
  954. tmp = Utils.create_tmpfile(prefix=rname)
  955. if ftype == 'yaml':
  956. # AUDIT:no-member makes sense here due to ruamel.YAML/PyYAML usage
  957. # pylint: disable=no-member
  958. if hasattr(yaml, 'RoundTripDumper'):
  959. Utils._write(tmp, yaml.dump(data, Dumper=yaml.RoundTripDumper))
  960. else:
  961. Utils._write(tmp, yaml.safe_dump(data, default_flow_style=False))
  962. elif ftype == 'json':
  963. Utils._write(tmp, json.dumps(data))
  964. else:
  965. Utils._write(tmp, data)
  966. # Register cleanup when module is done
  967. atexit.register(Utils.cleanup, [tmp])
  968. return tmp
  969. @staticmethod
  970. def create_tmpfile_copy(inc_file):
  971. '''create a temporary copy of a file'''
  972. tmpfile = Utils.create_tmpfile('lib_openshift-')
  973. Utils._write(tmpfile, open(inc_file).read())
  974. # Cleanup the tmpfile
  975. atexit.register(Utils.cleanup, [tmpfile])
  976. return tmpfile
  977. @staticmethod
  978. def create_tmpfile(prefix='tmp'):
  979. ''' Generates and returns a temporary file name '''
  980. with tempfile.NamedTemporaryFile(prefix=prefix, delete=False) as tmp:
  981. return tmp.name
  982. @staticmethod
  983. def create_tmp_files_from_contents(content, content_type=None):
  984. '''Turn an array of dict: filename, content into a files array'''
  985. if not isinstance(content, list):
  986. content = [content]
  987. files = []
  988. for item in content:
  989. path = Utils.create_tmp_file_from_contents(item['path'] + '-',
  990. item['data'],
  991. ftype=content_type)
  992. files.append({'name': os.path.basename(item['path']),
  993. 'path': path})
  994. return files
  995. @staticmethod
  996. def cleanup(files):
  997. '''Clean up on exit '''
  998. for sfile in files:
  999. if os.path.exists(sfile):
  1000. if os.path.isdir(sfile):
  1001. shutil.rmtree(sfile)
  1002. elif os.path.isfile(sfile):
  1003. os.remove(sfile)
  1004. @staticmethod
  1005. def exists(results, _name):
  1006. ''' Check to see if the results include the name '''
  1007. if not results:
  1008. return False
  1009. if Utils.find_result(results, _name):
  1010. return True
  1011. return False
  1012. @staticmethod
  1013. def find_result(results, _name):
  1014. ''' Find the specified result by name'''
  1015. rval = None
  1016. for result in results:
  1017. if 'metadata' in result and result['metadata']['name'] == _name:
  1018. rval = result
  1019. break
  1020. return rval
  1021. @staticmethod
  1022. def get_resource_file(sfile, sfile_type='yaml'):
  1023. ''' return the service file '''
  1024. contents = None
  1025. with open(sfile) as sfd:
  1026. contents = sfd.read()
  1027. if sfile_type == 'yaml':
  1028. # AUDIT:no-member makes sense here due to ruamel.YAML/PyYAML usage
  1029. # pylint: disable=no-member
  1030. if hasattr(yaml, 'RoundTripLoader'):
  1031. contents = yaml.load(contents, yaml.RoundTripLoader)
  1032. else:
  1033. contents = yaml.safe_load(contents)
  1034. elif sfile_type == 'json':
  1035. contents = json.loads(contents)
  1036. return contents
  1037. @staticmethod
  1038. def filter_versions(stdout):
  1039. ''' filter the oc version output '''
  1040. version_dict = {}
  1041. version_search = ['oc', 'openshift', 'kubernetes']
  1042. for line in stdout.strip().split('\n'):
  1043. for term in version_search:
  1044. if not line:
  1045. continue
  1046. if line.startswith(term):
  1047. version_dict[term] = line.split()[-1]
  1048. # horrible hack to get openshift version in Openshift 3.2
  1049. # By default "oc version in 3.2 does not return an "openshift" version
  1050. if "openshift" not in version_dict:
  1051. version_dict["openshift"] = version_dict["oc"]
  1052. return version_dict
  1053. @staticmethod
  1054. def add_custom_versions(versions):
  1055. ''' create custom versions strings '''
  1056. versions_dict = {}
  1057. for tech, version in versions.items():
  1058. # clean up "-" from version
  1059. if "-" in version:
  1060. version = version.split("-")[0]
  1061. if version.startswith('v'):
  1062. versions_dict[tech + '_numeric'] = version[1:].split('+')[0]
  1063. # "v3.3.0.33" is what we have, we want "3.3"
  1064. versions_dict[tech + '_short'] = version[1:4]
  1065. return versions_dict
  1066. @staticmethod
  1067. def openshift_installed():
  1068. ''' check if openshift is installed '''
  1069. import yum
  1070. yum_base = yum.YumBase()
  1071. if yum_base.rpmdb.searchNevra(name='atomic-openshift'):
  1072. return True
  1073. return False
  1074. # Disabling too-many-branches. This is a yaml dictionary comparison function
  1075. # pylint: disable=too-many-branches,too-many-return-statements,too-many-statements
  1076. @staticmethod
  1077. def check_def_equal(user_def, result_def, skip_keys=None, debug=False):
  1078. ''' Given a user defined definition, compare it with the results given back by our query. '''
  1079. # Currently these values are autogenerated and we do not need to check them
  1080. skip = ['metadata', 'status']
  1081. if skip_keys:
  1082. skip.extend(skip_keys)
  1083. for key, value in result_def.items():
  1084. if key in skip:
  1085. continue
  1086. # Both are lists
  1087. if isinstance(value, list):
  1088. if key not in user_def:
  1089. if debug:
  1090. print('User data does not have key [%s]' % key)
  1091. print('User data: %s' % user_def)
  1092. return False
  1093. if not isinstance(user_def[key], list):
  1094. if debug:
  1095. print('user_def[key] is not a list key=[%s] user_def[key]=%s' % (key, user_def[key]))
  1096. return False
  1097. if len(user_def[key]) != len(value):
  1098. if debug:
  1099. print("List lengths are not equal.")
  1100. print("key=[%s]: user_def[%s] != value[%s]" % (key, len(user_def[key]), len(value)))
  1101. print("user_def: %s" % user_def[key])
  1102. print("value: %s" % value)
  1103. return False
  1104. for values in zip(user_def[key], value):
  1105. if isinstance(values[0], dict) and isinstance(values[1], dict):
  1106. if debug:
  1107. print('sending list - list')
  1108. print(type(values[0]))
  1109. print(type(values[1]))
  1110. result = Utils.check_def_equal(values[0], values[1], skip_keys=skip_keys, debug=debug)
  1111. if not result:
  1112. print('list compare returned false')
  1113. return False
  1114. elif value != user_def[key]:
  1115. if debug:
  1116. print('value should be identical')
  1117. print(user_def[key])
  1118. print(value)
  1119. return False
  1120. # recurse on a dictionary
  1121. elif isinstance(value, dict):
  1122. if key not in user_def:
  1123. if debug:
  1124. print("user_def does not have key [%s]" % key)
  1125. return False
  1126. if not isinstance(user_def[key], dict):
  1127. if debug:
  1128. print("dict returned false: not instance of dict")
  1129. return False
  1130. # before passing ensure keys match
  1131. api_values = set(value.keys()) - set(skip)
  1132. user_values = set(user_def[key].keys()) - set(skip)
  1133. if api_values != user_values:
  1134. if debug:
  1135. print("keys are not equal in dict")
  1136. print(user_values)
  1137. print(api_values)
  1138. return False
  1139. result = Utils.check_def_equal(user_def[key], value, skip_keys=skip_keys, debug=debug)
  1140. if not result:
  1141. if debug:
  1142. print("dict returned false")
  1143. print(result)
  1144. return False
  1145. # Verify each key, value pair is the same
  1146. else:
  1147. if key not in user_def or value != user_def[key]:
  1148. if debug:
  1149. print("value not equal; user_def does not have key")
  1150. print(key)
  1151. print(value)
  1152. if key in user_def:
  1153. print(user_def[key])
  1154. return False
  1155. if debug:
  1156. print('returning true')
  1157. return True
  1158. class OpenShiftCLIConfig(object):
  1159. '''Generic Config'''
  1160. def __init__(self, rname, namespace, kubeconfig, options):
  1161. self.kubeconfig = kubeconfig
  1162. self.name = rname
  1163. self.namespace = namespace
  1164. self._options = options
  1165. @property
  1166. def config_options(self):
  1167. ''' return config options '''
  1168. return self._options
  1169. def to_option_list(self):
  1170. '''return all options as a string'''
  1171. return self.stringify()
  1172. def stringify(self):
  1173. ''' return the options hash as cli params in a string '''
  1174. rval = []
  1175. for key in sorted(self.config_options.keys()):
  1176. data = self.config_options[key]
  1177. if data['include'] \
  1178. and (data['value'] or isinstance(data['value'], int)):
  1179. rval.append('--{}={}'.format(key.replace('_', '-'), data['value']))
  1180. return rval
  1181. # -*- -*- -*- End included fragment: lib/base.py -*- -*- -*-
  1182. # -*- -*- -*- Begin included fragment: lib/route.py -*- -*- -*-
  1183. # noqa: E302,E301
  1184. # pylint: disable=too-many-instance-attributes
  1185. class RouteConfig(object):
  1186. ''' Handle route options '''
  1187. # pylint: disable=too-many-arguments
  1188. def __init__(self,
  1189. sname,
  1190. namespace,
  1191. kubeconfig,
  1192. destcacert=None,
  1193. cacert=None,
  1194. cert=None,
  1195. key=None,
  1196. host=None,
  1197. tls_termination=None,
  1198. service_name=None,
  1199. wildcard_policy=None,
  1200. weight=None,
  1201. port=None):
  1202. ''' constructor for handling route options '''
  1203. self.kubeconfig = kubeconfig
  1204. self.name = sname
  1205. self.namespace = namespace
  1206. self.host = host
  1207. self.tls_termination = tls_termination
  1208. self.destcacert = destcacert
  1209. self.cacert = cacert
  1210. self.cert = cert
  1211. self.key = key
  1212. self.service_name = service_name
  1213. self.port = port
  1214. self.data = {}
  1215. self.wildcard_policy = wildcard_policy
  1216. if wildcard_policy is None:
  1217. self.wildcard_policy = 'None'
  1218. self.weight = weight
  1219. if weight is None:
  1220. self.weight = 100
  1221. self.create_dict()
  1222. def create_dict(self):
  1223. ''' return a service as a dict '''
  1224. self.data['apiVersion'] = 'v1'
  1225. self.data['kind'] = 'Route'
  1226. self.data['metadata'] = {}
  1227. self.data['metadata']['name'] = self.name
  1228. self.data['metadata']['namespace'] = self.namespace
  1229. self.data['spec'] = {}
  1230. self.data['spec']['host'] = self.host
  1231. if self.tls_termination:
  1232. self.data['spec']['tls'] = {}
  1233. self.data['spec']['tls']['termination'] = self.tls_termination
  1234. if self.tls_termination != 'passthrough':
  1235. self.data['spec']['tls']['key'] = self.key
  1236. self.data['spec']['tls']['caCertificate'] = self.cacert
  1237. self.data['spec']['tls']['certificate'] = self.cert
  1238. if self.tls_termination == 'reencrypt':
  1239. self.data['spec']['tls']['destinationCACertificate'] = self.destcacert
  1240. self.data['spec']['to'] = {'kind': 'Service',
  1241. 'name': self.service_name,
  1242. 'weight': self.weight}
  1243. self.data['spec']['wildcardPolicy'] = self.wildcard_policy
  1244. if self.port:
  1245. self.data['spec']['port'] = {}
  1246. self.data['spec']['port']['targetPort'] = self.port
  1247. # pylint: disable=too-many-instance-attributes,too-many-public-methods
  1248. class Route(Yedit):
  1249. ''' Class to wrap the oc command line tools '''
  1250. wildcard_policy = "spec.wildcardPolicy"
  1251. host_path = "spec.host"
  1252. port_path = "spec.port.targetPort"
  1253. service_path = "spec.to.name"
  1254. weight_path = "spec.to.weight"
  1255. cert_path = "spec.tls.certificate"
  1256. cacert_path = "spec.tls.caCertificate"
  1257. destcacert_path = "spec.tls.destinationCACertificate"
  1258. termination_path = "spec.tls.termination"
  1259. key_path = "spec.tls.key"
  1260. kind = 'route'
  1261. def __init__(self, content):
  1262. '''Route constructor'''
  1263. super(Route, self).__init__(content=content)
  1264. def get_destcacert(self):
  1265. ''' return cert '''
  1266. return self.get(Route.destcacert_path)
  1267. def get_cert(self):
  1268. ''' return cert '''
  1269. return self.get(Route.cert_path)
  1270. def get_key(self):
  1271. ''' return key '''
  1272. return self.get(Route.key_path)
  1273. def get_cacert(self):
  1274. ''' return cacert '''
  1275. return self.get(Route.cacert_path)
  1276. def get_service(self):
  1277. ''' return service name '''
  1278. return self.get(Route.service_path)
  1279. def get_weight(self):
  1280. ''' return service weight '''
  1281. return self.get(Route.weight_path)
  1282. def get_termination(self):
  1283. ''' return tls termination'''
  1284. return self.get(Route.termination_path)
  1285. def get_host(self):
  1286. ''' return host '''
  1287. return self.get(Route.host_path)
  1288. def get_port(self):
  1289. ''' return port '''
  1290. return self.get(Route.port_path)
  1291. def get_wildcard_policy(self):
  1292. ''' return wildcardPolicy '''
  1293. return self.get(Route.wildcard_policy)
  1294. # -*- -*- -*- End included fragment: lib/route.py -*- -*- -*-
  1295. # -*- -*- -*- Begin included fragment: class/oc_route.py -*- -*- -*-
  1296. # pylint: disable=too-many-instance-attributes
  1297. class OCRoute(OpenShiftCLI):
  1298. ''' Class to wrap the oc command line tools '''
  1299. kind = 'route'
  1300. def __init__(self,
  1301. config,
  1302. verbose=False):
  1303. ''' Constructor for OCVolume '''
  1304. super(OCRoute, self).__init__(config.namespace, kubeconfig=config.kubeconfig, verbose=verbose)
  1305. self.config = config
  1306. self._route = None
  1307. @property
  1308. def route(self):
  1309. ''' property function for route'''
  1310. if not self._route:
  1311. self.get()
  1312. return self._route
  1313. @route.setter
  1314. def route(self, data):
  1315. ''' setter function for route '''
  1316. self._route = data
  1317. def exists(self):
  1318. ''' return whether a route exists '''
  1319. if self.route:
  1320. return True
  1321. return False
  1322. def get(self):
  1323. '''return route information '''
  1324. result = self._get(self.kind, self.config.name)
  1325. if result['returncode'] == 0:
  1326. self.route = Route(content=result['results'][0])
  1327. elif 'routes \"%s\" not found' % self.config.name in result['stderr']:
  1328. result['returncode'] = 0
  1329. result['results'] = [{}]
  1330. return result
  1331. def delete(self):
  1332. '''delete the object'''
  1333. return self._delete(self.kind, self.config.name)
  1334. def create(self):
  1335. '''create the object'''
  1336. return self._create_from_content(self.config.name, self.config.data)
  1337. def update(self):
  1338. '''update the object'''
  1339. return self._replace_content(self.kind,
  1340. self.config.name,
  1341. self.config.data,
  1342. force=(self.config.host != self.route.get_host()))
  1343. def needs_update(self):
  1344. ''' verify an update is needed '''
  1345. skip = []
  1346. return not Utils.check_def_equal(self.config.data, self.route.yaml_dict, skip_keys=skip, debug=self.verbose)
  1347. @staticmethod
  1348. def get_cert_data(path, content):
  1349. '''get the data for a particular value'''
  1350. if not path and not content:
  1351. return None
  1352. rval = None
  1353. if path and os.path.exists(path) and os.access(path, os.R_OK):
  1354. rval = open(path).read()
  1355. elif content:
  1356. rval = content
  1357. return rval
  1358. # pylint: disable=too-many-return-statements,too-many-branches
  1359. @staticmethod
  1360. def run_ansible(params, check_mode=False):
  1361. ''' run the idempotent asnible code
  1362. params comes from the ansible portion for this module
  1363. files: a dictionary for the certificates
  1364. {'cert': {'path': '',
  1365. 'content': '',
  1366. 'value': ''
  1367. }
  1368. }
  1369. check_mode: does the module support check mode. (module.check_mode)
  1370. '''
  1371. files = {'destcacert': {'path': params['dest_cacert_path'],
  1372. 'content': params['dest_cacert_content'],
  1373. 'value': None, },
  1374. 'cacert': {'path': params['cacert_path'],
  1375. 'content': params['cacert_content'],
  1376. 'value': None, },
  1377. 'cert': {'path': params['cert_path'],
  1378. 'content': params['cert_content'],
  1379. 'value': None, },
  1380. 'key': {'path': params['key_path'],
  1381. 'content': params['key_content'],
  1382. 'value': None, }, }
  1383. if params['tls_termination'] and params['tls_termination'].lower() != 'passthrough': # E501
  1384. for key, option in files.items():
  1385. if key == 'destcacert' and params['tls_termination'] != 'reencrypt':
  1386. continue
  1387. option['value'] = OCRoute.get_cert_data(option['path'], option['content']) # E501
  1388. if not option['value']:
  1389. return {'failed': True,
  1390. 'msg': 'Verify that you pass a value for %s' % key}
  1391. rconfig = RouteConfig(params['name'],
  1392. params['namespace'],
  1393. params['kubeconfig'],
  1394. files['destcacert']['value'],
  1395. files['cacert']['value'],
  1396. files['cert']['value'],
  1397. files['key']['value'],
  1398. params['host'],
  1399. params['tls_termination'],
  1400. params['service_name'],
  1401. params['wildcard_policy'],
  1402. params['weight'],
  1403. params['port'])
  1404. oc_route = OCRoute(rconfig, verbose=params['debug'])
  1405. state = params['state']
  1406. api_rval = oc_route.get()
  1407. #####
  1408. # Get
  1409. #####
  1410. if state == 'list':
  1411. return {'changed': False,
  1412. 'results': api_rval['results'],
  1413. 'state': 'list'}
  1414. ########
  1415. # Delete
  1416. ########
  1417. if state == 'absent':
  1418. if oc_route.exists():
  1419. if check_mode:
  1420. return {'changed': False, 'msg': 'CHECK_MODE: Would have performed a delete.'} # noqa: E501
  1421. api_rval = oc_route.delete()
  1422. return {'changed': True, 'results': api_rval, 'state': "absent"} # noqa: E501
  1423. return {'changed': False, 'state': 'absent'}
  1424. if state == 'present':
  1425. ########
  1426. # Create
  1427. ########
  1428. if not oc_route.exists():
  1429. if check_mode:
  1430. return {'changed': True, 'msg': 'CHECK_MODE: Would have performed a create.'} # noqa: E501
  1431. # Create it here
  1432. api_rval = oc_route.create()
  1433. if api_rval['returncode'] != 0:
  1434. return {'failed': True, 'msg': api_rval, 'state': "present"} # noqa: E501
  1435. # return the created object
  1436. api_rval = oc_route.get()
  1437. if api_rval['returncode'] != 0:
  1438. return {'failed': True, 'msg': api_rval, 'state': "present"} # noqa: E501
  1439. return {'changed': True, 'results': api_rval, 'state': "present"} # noqa: E501
  1440. ########
  1441. # Update
  1442. ########
  1443. if oc_route.needs_update():
  1444. if check_mode:
  1445. return {'changed': True, 'msg': 'CHECK_MODE: Would have performed an update.'} # noqa: E501
  1446. api_rval = oc_route.update()
  1447. if api_rval['returncode'] != 0:
  1448. return {'failed': True, 'msg': api_rval, 'state': "present"} # noqa: E501
  1449. # return the created object
  1450. api_rval = oc_route.get()
  1451. if api_rval['returncode'] != 0:
  1452. return {'failed': True, 'msg': api_rval, 'state': "present"} # noqa: E501
  1453. return {'changed': True, 'results': api_rval, 'state': "present"} # noqa: E501
  1454. return {'changed': False, 'results': api_rval, 'state': "present"}
  1455. # catch all
  1456. return {'failed': True, 'msg': "Unknown State passed"}
  1457. # -*- -*- -*- End included fragment: class/oc_route.py -*- -*- -*-
  1458. # -*- -*- -*- Begin included fragment: ansible/oc_route.py -*- -*- -*-
  1459. # pylint: disable=too-many-branches
  1460. def main():
  1461. '''
  1462. ansible oc module for route
  1463. '''
  1464. module = AnsibleModule(
  1465. argument_spec=dict(
  1466. kubeconfig=dict(default='/etc/origin/master/admin.kubeconfig', type='str'),
  1467. state=dict(default='present', type='str',
  1468. choices=['present', 'absent', 'list']),
  1469. debug=dict(default=False, type='bool'),
  1470. name=dict(default=None, required=True, type='str'),
  1471. namespace=dict(default=None, required=True, type='str'),
  1472. tls_termination=dict(default=None, type='str'),
  1473. dest_cacert_path=dict(default=None, type='str'),
  1474. cacert_path=dict(default=None, type='str'),
  1475. cert_path=dict(default=None, type='str'),
  1476. key_path=dict(default=None, type='str'),
  1477. dest_cacert_content=dict(default=None, type='str'),
  1478. cacert_content=dict(default=None, type='str'),
  1479. cert_content=dict(default=None, type='str'),
  1480. key_content=dict(default=None, type='str'),
  1481. service_name=dict(default=None, type='str'),
  1482. host=dict(default=None, type='str'),
  1483. wildcard_policy=dict(default=None, type='str'),
  1484. weight=dict(default=None, type='int'),
  1485. port=dict(default=None, type='int'),
  1486. ),
  1487. mutually_exclusive=[('dest_cacert_path', 'dest_cacert_content'),
  1488. ('cacert_path', 'cacert_content'),
  1489. ('cert_path', 'cert_content'),
  1490. ('key_path', 'key_content'), ],
  1491. supports_check_mode=True,
  1492. )
  1493. results = OCRoute.run_ansible(module.params, module.check_mode)
  1494. if 'failed' in results:
  1495. module.fail_json(**results)
  1496. module.exit_json(**results)
  1497. if __name__ == '__main__':
  1498. main()
  1499. # -*- -*- -*- End included fragment: ansible/oc_route.py -*- -*- -*-