oc_route.py 54 KB

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