oc_route.py 56 KB

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