oc_route.py 54 KB

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