oc_obj.py 55 KB

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