oc_route.py 59 KB

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