oc_obj.py 56 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677
  1. #!/usr/bin/env python
  2. # pylint: disable=missing-docstring
  3. # flake8: noqa: T001
  4. # ___ ___ _ _ ___ ___ _ _____ ___ ___
  5. # / __| __| \| | __| _ \ /_\_ _| __| \
  6. # | (_ | _|| .` | _|| / / _ \| | | _|| |) |
  7. # \___|___|_|\_|___|_|_\/_/_\_\_|_|___|___/_ _____
  8. # | \ / _ \ | \| |/ _ \_ _| | __| \_ _|_ _|
  9. # | |) | (_) | | .` | (_) || | | _|| |) | | | |
  10. # |___/ \___/ |_|\_|\___/ |_| |___|___/___| |_|
  11. #
  12. # Copyright 2016 Red Hat, Inc. and/or its affiliates
  13. # and other contributors as indicated by the @author tags.
  14. #
  15. # Licensed under the Apache License, Version 2.0 (the "License");
  16. # you may not use this file except in compliance with the License.
  17. # You may obtain a copy of the License at
  18. #
  19. # http://www.apache.org/licenses/LICENSE-2.0
  20. #
  21. # Unless required by applicable law or agreed to in writing, software
  22. # distributed under the License is distributed on an "AS IS" BASIS,
  23. # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  24. # See the License for the specific language governing permissions and
  25. # limitations under the License.
  26. #
  27. # -*- -*- -*- Begin included fragment: lib/import.py -*- -*- -*-
  28. '''
  29. OpenShiftCLI class that wraps the oc commands in a subprocess
  30. '''
  31. # pylint: disable=too-many-lines
  32. from __future__ import print_function
  33. import atexit
  34. import 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. May be a comma-separated list, e.g. "dc,po,svc".
  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{}/_-]+)"
  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. # We are removing the 'resourceVersion' to handle
  737. # a race condition when modifying oc objects
  738. yed = Yedit(fname)
  739. results = yed.delete('metadata.resourceVersion')
  740. if results[0]:
  741. yed.write()
  742. cmd = ['replace', '-f', fname]
  743. if force:
  744. cmd.append('--force')
  745. return self.openshift_cmd(cmd)
  746. def _create_from_content(self, rname, content):
  747. '''create a temporary file and then call oc create on it'''
  748. fname = Utils.create_tmpfile(rname + '-')
  749. yed = Yedit(fname, content=content)
  750. yed.write()
  751. atexit.register(Utils.cleanup, [fname])
  752. return self._create(fname)
  753. def _create(self, fname):
  754. '''call oc create on a filename'''
  755. return self.openshift_cmd(['create', '-f', fname])
  756. def _delete(self, resource, name=None, selector=None):
  757. '''call oc delete on a resource'''
  758. cmd = ['delete', resource]
  759. if selector is not None:
  760. cmd.append('--selector={}'.format(selector))
  761. elif name is not None:
  762. cmd.append(name)
  763. else:
  764. raise OpenShiftCLIError('Either name or selector is required when calling delete.')
  765. return self.openshift_cmd(cmd)
  766. def _process(self, template_name, create=False, params=None, template_data=None): # noqa: E501
  767. '''process a template
  768. template_name: the name of the template to process
  769. create: whether to send to oc create after processing
  770. params: the parameters for the template
  771. template_data: the incoming template's data; instead of a file
  772. '''
  773. cmd = ['process']
  774. if template_data:
  775. cmd.extend(['-f', '-'])
  776. else:
  777. cmd.append(template_name)
  778. if params:
  779. param_str = ["{}={}".format(key, str(value).replace("'", r'"')) for key, value in params.items()]
  780. cmd.append('-v')
  781. cmd.extend(param_str)
  782. results = self.openshift_cmd(cmd, output=True, input_data=template_data)
  783. if results['returncode'] != 0 or not create:
  784. return results
  785. fname = Utils.create_tmpfile(template_name + '-')
  786. yed = Yedit(fname, results['results'])
  787. yed.write()
  788. atexit.register(Utils.cleanup, [fname])
  789. return self.openshift_cmd(['create', '-f', fname])
  790. def _get(self, resource, name=None, selector=None):
  791. '''return a resource by name '''
  792. cmd = ['get', resource]
  793. if selector is not None:
  794. cmd.append('--selector={}'.format(selector))
  795. elif name is not None:
  796. cmd.append(name)
  797. cmd.extend(['-o', 'json'])
  798. rval = self.openshift_cmd(cmd, output=True)
  799. # Ensure results are retuned in an array
  800. if 'items' in rval:
  801. rval['results'] = rval['items']
  802. elif not isinstance(rval['results'], list):
  803. rval['results'] = [rval['results']]
  804. return rval
  805. def _schedulable(self, node=None, selector=None, schedulable=True):
  806. ''' perform oadm manage-node scheduable '''
  807. cmd = ['manage-node']
  808. if node:
  809. cmd.extend(node)
  810. else:
  811. cmd.append('--selector={}'.format(selector))
  812. cmd.append('--schedulable={}'.format(schedulable))
  813. return self.openshift_cmd(cmd, oadm=True, output=True, output_type='raw') # noqa: E501
  814. def _list_pods(self, node=None, selector=None, pod_selector=None):
  815. ''' perform oadm list pods
  816. node: the node in which to list pods
  817. selector: the label selector filter if provided
  818. pod_selector: the pod selector filter if provided
  819. '''
  820. cmd = ['manage-node']
  821. if node:
  822. cmd.extend(node)
  823. else:
  824. cmd.append('--selector={}'.format(selector))
  825. if pod_selector:
  826. cmd.append('--pod-selector={}'.format(pod_selector))
  827. cmd.extend(['--list-pods', '-o', 'json'])
  828. return self.openshift_cmd(cmd, oadm=True, output=True, output_type='raw')
  829. # pylint: disable=too-many-arguments
  830. def _evacuate(self, node=None, selector=None, pod_selector=None, dry_run=False, grace_period=None, force=False):
  831. ''' perform oadm manage-node evacuate '''
  832. cmd = ['manage-node']
  833. if node:
  834. cmd.extend(node)
  835. else:
  836. cmd.append('--selector={}'.format(selector))
  837. if dry_run:
  838. cmd.append('--dry-run')
  839. if pod_selector:
  840. cmd.append('--pod-selector={}'.format(pod_selector))
  841. if grace_period:
  842. cmd.append('--grace-period={}'.format(int(grace_period)))
  843. if force:
  844. cmd.append('--force')
  845. cmd.append('--evacuate')
  846. return self.openshift_cmd(cmd, oadm=True, output=True, output_type='raw')
  847. def _version(self):
  848. ''' return the openshift version'''
  849. return self.openshift_cmd(['version'], output=True, output_type='raw')
  850. def _import_image(self, url=None, name=None, tag=None):
  851. ''' perform image import '''
  852. cmd = ['import-image']
  853. image = '{0}'.format(name)
  854. if tag:
  855. image += ':{0}'.format(tag)
  856. cmd.append(image)
  857. if url:
  858. cmd.append('--from={0}/{1}'.format(url, image))
  859. cmd.append('-n{0}'.format(self.namespace))
  860. cmd.append('--confirm')
  861. return self.openshift_cmd(cmd)
  862. def _run(self, cmds, input_data):
  863. ''' Actually executes the command. This makes mocking easier. '''
  864. curr_env = os.environ.copy()
  865. curr_env.update({'KUBECONFIG': self.kubeconfig})
  866. proc = subprocess.Popen(cmds,
  867. stdin=subprocess.PIPE,
  868. stdout=subprocess.PIPE,
  869. stderr=subprocess.PIPE,
  870. env=curr_env)
  871. stdout, stderr = proc.communicate(input_data)
  872. return proc.returncode, stdout.decode('utf-8'), stderr.decode('utf-8')
  873. # pylint: disable=too-many-arguments,too-many-branches
  874. def openshift_cmd(self, cmd, oadm=False, output=False, output_type='json', input_data=None):
  875. '''Base command for oc '''
  876. cmds = [self.oc_binary]
  877. if oadm:
  878. cmds.append('adm')
  879. cmds.extend(cmd)
  880. if self.all_namespaces:
  881. cmds.extend(['--all-namespaces'])
  882. elif self.namespace is not None and self.namespace.lower() not in ['none', 'emtpy']: # E501
  883. cmds.extend(['-n', self.namespace])
  884. rval = {}
  885. results = ''
  886. err = None
  887. if self.verbose:
  888. print(' '.join(cmds))
  889. try:
  890. returncode, stdout, stderr = self._run(cmds, input_data)
  891. except OSError as ex:
  892. returncode, stdout, stderr = 1, '', 'Failed to execute {}: {}'.format(subprocess.list2cmdline(cmds), ex)
  893. rval = {"returncode": returncode,
  894. "results": results,
  895. "cmd": ' '.join(cmds)}
  896. if returncode == 0:
  897. if output:
  898. if output_type == 'json':
  899. try:
  900. rval['results'] = json.loads(stdout)
  901. except ValueError as verr:
  902. if "No JSON object could be decoded" in verr.args:
  903. err = verr.args
  904. elif output_type == 'raw':
  905. rval['results'] = stdout
  906. if self.verbose:
  907. print("STDOUT: {0}".format(stdout))
  908. print("STDERR: {0}".format(stderr))
  909. if err:
  910. rval.update({"err": err,
  911. "stderr": stderr,
  912. "stdout": stdout,
  913. "cmd": cmds})
  914. else:
  915. rval.update({"stderr": stderr,
  916. "stdout": stdout,
  917. "results": {}})
  918. return rval
  919. class Utils(object): # pragma: no cover
  920. ''' utilities for openshiftcli modules '''
  921. @staticmethod
  922. def _write(filename, contents):
  923. ''' Actually write the file contents to disk. This helps with mocking. '''
  924. with open(filename, 'w') as sfd:
  925. sfd.write(contents)
  926. @staticmethod
  927. def create_tmp_file_from_contents(rname, data, ftype='yaml'):
  928. ''' create a file in tmp with name and contents'''
  929. tmp = Utils.create_tmpfile(prefix=rname)
  930. if ftype == 'yaml':
  931. # AUDIT:no-member makes sense here due to ruamel.YAML/PyYAML usage
  932. # pylint: disable=no-member
  933. if hasattr(yaml, 'RoundTripDumper'):
  934. Utils._write(tmp, yaml.dump(data, Dumper=yaml.RoundTripDumper))
  935. else:
  936. Utils._write(tmp, yaml.safe_dump(data, default_flow_style=False))
  937. elif ftype == 'json':
  938. Utils._write(tmp, json.dumps(data))
  939. else:
  940. Utils._write(tmp, data)
  941. # Register cleanup when module is done
  942. atexit.register(Utils.cleanup, [tmp])
  943. return tmp
  944. @staticmethod
  945. def create_tmpfile_copy(inc_file):
  946. '''create a temporary copy of a file'''
  947. tmpfile = Utils.create_tmpfile('lib_openshift-')
  948. Utils._write(tmpfile, open(inc_file).read())
  949. # Cleanup the tmpfile
  950. atexit.register(Utils.cleanup, [tmpfile])
  951. return tmpfile
  952. @staticmethod
  953. def create_tmpfile(prefix='tmp'):
  954. ''' Generates and returns a temporary file name '''
  955. with tempfile.NamedTemporaryFile(prefix=prefix, delete=False) as tmp:
  956. return tmp.name
  957. @staticmethod
  958. def create_tmp_files_from_contents(content, content_type=None):
  959. '''Turn an array of dict: filename, content into a files array'''
  960. if not isinstance(content, list):
  961. content = [content]
  962. files = []
  963. for item in content:
  964. path = Utils.create_tmp_file_from_contents(item['path'] + '-',
  965. item['data'],
  966. ftype=content_type)
  967. files.append({'name': os.path.basename(item['path']),
  968. 'path': path})
  969. return files
  970. @staticmethod
  971. def cleanup(files):
  972. '''Clean up on exit '''
  973. for sfile in files:
  974. if os.path.exists(sfile):
  975. if os.path.isdir(sfile):
  976. shutil.rmtree(sfile)
  977. elif os.path.isfile(sfile):
  978. os.remove(sfile)
  979. @staticmethod
  980. def exists(results, _name):
  981. ''' Check to see if the results include the name '''
  982. if not results:
  983. return False
  984. if Utils.find_result(results, _name):
  985. return True
  986. return False
  987. @staticmethod
  988. def find_result(results, _name):
  989. ''' Find the specified result by name'''
  990. rval = None
  991. for result in results:
  992. if 'metadata' in result and result['metadata']['name'] == _name:
  993. rval = result
  994. break
  995. return rval
  996. @staticmethod
  997. def get_resource_file(sfile, sfile_type='yaml'):
  998. ''' return the service file '''
  999. contents = None
  1000. with open(sfile) as sfd:
  1001. contents = sfd.read()
  1002. if sfile_type == 'yaml':
  1003. # AUDIT:no-member makes sense here due to ruamel.YAML/PyYAML usage
  1004. # pylint: disable=no-member
  1005. if hasattr(yaml, 'RoundTripLoader'):
  1006. contents = yaml.load(contents, yaml.RoundTripLoader)
  1007. else:
  1008. contents = yaml.safe_load(contents)
  1009. elif sfile_type == 'json':
  1010. contents = json.loads(contents)
  1011. return contents
  1012. @staticmethod
  1013. def filter_versions(stdout):
  1014. ''' filter the oc version output '''
  1015. version_dict = {}
  1016. version_search = ['oc', 'openshift', 'kubernetes']
  1017. for line in stdout.strip().split('\n'):
  1018. for term in version_search:
  1019. if not line:
  1020. continue
  1021. if line.startswith(term):
  1022. version_dict[term] = line.split()[-1]
  1023. # horrible hack to get openshift version in Openshift 3.2
  1024. # By default "oc version in 3.2 does not return an "openshift" version
  1025. if "openshift" not in version_dict:
  1026. version_dict["openshift"] = version_dict["oc"]
  1027. return version_dict
  1028. @staticmethod
  1029. def add_custom_versions(versions):
  1030. ''' create custom versions strings '''
  1031. versions_dict = {}
  1032. for tech, version in versions.items():
  1033. # clean up "-" from version
  1034. if "-" in version:
  1035. version = version.split("-")[0]
  1036. if version.startswith('v'):
  1037. versions_dict[tech + '_numeric'] = version[1:].split('+')[0]
  1038. # "v3.3.0.33" is what we have, we want "3.3"
  1039. versions_dict[tech + '_short'] = version[1:4]
  1040. return versions_dict
  1041. @staticmethod
  1042. def openshift_installed():
  1043. ''' check if openshift is installed '''
  1044. import yum
  1045. yum_base = yum.YumBase()
  1046. if yum_base.rpmdb.searchNevra(name='atomic-openshift'):
  1047. return True
  1048. return False
  1049. # Disabling too-many-branches. This is a yaml dictionary comparison function
  1050. # pylint: disable=too-many-branches,too-many-return-statements,too-many-statements
  1051. @staticmethod
  1052. def check_def_equal(user_def, result_def, skip_keys=None, debug=False):
  1053. ''' Given a user defined definition, compare it with the results given back by our query. '''
  1054. # Currently these values are autogenerated and we do not need to check them
  1055. skip = ['metadata', 'status']
  1056. if skip_keys:
  1057. skip.extend(skip_keys)
  1058. for key, value in result_def.items():
  1059. if key in skip:
  1060. continue
  1061. # Both are lists
  1062. if isinstance(value, list):
  1063. if key not in user_def:
  1064. if debug:
  1065. print('User data does not have key [%s]' % key)
  1066. print('User data: %s' % user_def)
  1067. return False
  1068. if not isinstance(user_def[key], list):
  1069. if debug:
  1070. print('user_def[key] is not a list key=[%s] user_def[key]=%s' % (key, user_def[key]))
  1071. return False
  1072. if len(user_def[key]) != len(value):
  1073. if debug:
  1074. print("List lengths are not equal.")
  1075. print("key=[%s]: user_def[%s] != value[%s]" % (key, len(user_def[key]), len(value)))
  1076. print("user_def: %s" % user_def[key])
  1077. print("value: %s" % value)
  1078. return False
  1079. for values in zip(user_def[key], value):
  1080. if isinstance(values[0], dict) and isinstance(values[1], dict):
  1081. if debug:
  1082. print('sending list - list')
  1083. print(type(values[0]))
  1084. print(type(values[1]))
  1085. result = Utils.check_def_equal(values[0], values[1], skip_keys=skip_keys, debug=debug)
  1086. if not result:
  1087. print('list compare returned false')
  1088. return False
  1089. elif value != user_def[key]:
  1090. if debug:
  1091. print('value should be identical')
  1092. print(user_def[key])
  1093. print(value)
  1094. return False
  1095. # recurse on a dictionary
  1096. elif isinstance(value, dict):
  1097. if key not in user_def:
  1098. if debug:
  1099. print("user_def does not have key [%s]" % key)
  1100. return False
  1101. if not isinstance(user_def[key], dict):
  1102. if debug:
  1103. print("dict returned false: not instance of dict")
  1104. return False
  1105. # before passing ensure keys match
  1106. api_values = set(value.keys()) - set(skip)
  1107. user_values = set(user_def[key].keys()) - set(skip)
  1108. if api_values != user_values:
  1109. if debug:
  1110. print("keys are not equal in dict")
  1111. print(user_values)
  1112. print(api_values)
  1113. return False
  1114. result = Utils.check_def_equal(user_def[key], value, skip_keys=skip_keys, debug=debug)
  1115. if not result:
  1116. if debug:
  1117. print("dict returned false")
  1118. print(result)
  1119. return False
  1120. # Verify each key, value pair is the same
  1121. else:
  1122. if key not in user_def or value != user_def[key]:
  1123. if debug:
  1124. print("value not equal; user_def does not have key")
  1125. print(key)
  1126. print(value)
  1127. if key in user_def:
  1128. print(user_def[key])
  1129. return False
  1130. if debug:
  1131. print('returning true')
  1132. return True
  1133. class OpenShiftCLIConfig(object):
  1134. '''Generic Config'''
  1135. def __init__(self, rname, namespace, kubeconfig, options):
  1136. self.kubeconfig = kubeconfig
  1137. self.name = rname
  1138. self.namespace = namespace
  1139. self._options = options
  1140. @property
  1141. def config_options(self):
  1142. ''' return config options '''
  1143. return self._options
  1144. def to_option_list(self, ascommalist=''):
  1145. '''return all options as a string
  1146. if ascommalist is set to the name of a key, and
  1147. the value of that key is a dict, format the dict
  1148. as a list of comma delimited key=value pairs'''
  1149. return self.stringify(ascommalist)
  1150. def stringify(self, ascommalist=''):
  1151. ''' return the options hash as cli params in a string
  1152. if ascommalist is set to the name of a key, and
  1153. the value of that key is a dict, format the dict
  1154. as a list of comma delimited key=value pairs '''
  1155. rval = []
  1156. for key in sorted(self.config_options.keys()):
  1157. data = self.config_options[key]
  1158. if data['include'] \
  1159. and (data['value'] or isinstance(data['value'], int)):
  1160. if key == ascommalist:
  1161. val = ','.join(['{}={}'.format(kk, vv) for kk, vv in sorted(data['value'].items())])
  1162. else:
  1163. val = data['value']
  1164. rval.append('--{}={}'.format(key.replace('_', '-'), val))
  1165. return rval
  1166. # -*- -*- -*- End included fragment: lib/base.py -*- -*- -*-
  1167. # -*- -*- -*- Begin included fragment: class/oc_obj.py -*- -*- -*-
  1168. # pylint: disable=too-many-instance-attributes
  1169. class OCObject(OpenShiftCLI):
  1170. ''' Class to wrap the oc command line tools '''
  1171. # pylint allows 5. we need 6
  1172. # pylint: disable=too-many-arguments
  1173. def __init__(self,
  1174. kind,
  1175. namespace,
  1176. name=None,
  1177. selector=None,
  1178. kubeconfig='/etc/origin/master/admin.kubeconfig',
  1179. verbose=False,
  1180. all_namespaces=False):
  1181. ''' Constructor for OpenshiftOC '''
  1182. super(OCObject, self).__init__(namespace, kubeconfig=kubeconfig, verbose=verbose,
  1183. all_namespaces=all_namespaces)
  1184. self.kind = kind
  1185. self.name = name
  1186. self.selector = selector
  1187. def get(self):
  1188. '''return a kind by name '''
  1189. results = self._get(self.kind, name=self.name, selector=self.selector)
  1190. if (results['returncode'] != 0 and 'stderr' in results and
  1191. '\"{}\" not found'.format(self.name) in results['stderr']):
  1192. results['returncode'] = 0
  1193. return results
  1194. def delete(self):
  1195. '''delete the object'''
  1196. return self._delete(self.kind, name=self.name, selector=self.selector)
  1197. def create(self, files=None, content=None):
  1198. '''
  1199. Create a config
  1200. NOTE: This creates the first file OR the first conent.
  1201. TODO: Handle all files and content passed in
  1202. '''
  1203. if files:
  1204. return self._create(files[0])
  1205. content['data'] = yaml.dump(content['data'])
  1206. content_file = Utils.create_tmp_files_from_contents(content)[0]
  1207. return self._create(content_file['path'])
  1208. # pylint: disable=too-many-function-args
  1209. def update(self, files=None, content=None, force=False):
  1210. '''update a current openshift object
  1211. This receives a list of file names or content
  1212. and takes the first and calls replace.
  1213. TODO: take an entire list
  1214. '''
  1215. if files:
  1216. return self._replace(files[0], force)
  1217. if content and 'data' in content:
  1218. content = content['data']
  1219. return self.update_content(content, force)
  1220. def update_content(self, content, force=False):
  1221. '''update an object through using the content param'''
  1222. return self._replace_content(self.kind, self.name, content, force=force)
  1223. def needs_update(self, files=None, content=None, content_type='yaml'):
  1224. ''' check to see if we need to update '''
  1225. objects = self.get()
  1226. if objects['returncode'] != 0:
  1227. return objects
  1228. data = None
  1229. if files:
  1230. data = Utils.get_resource_file(files[0], content_type)
  1231. elif content and 'data' in content:
  1232. data = content['data']
  1233. else:
  1234. data = content
  1235. # if equal then no need. So not equal is True
  1236. return not Utils.check_def_equal(data, objects['results'][0], skip_keys=None, debug=False)
  1237. # pylint: disable=too-many-return-statements,too-many-branches
  1238. @staticmethod
  1239. def run_ansible(params, check_mode=False):
  1240. '''perform the ansible idempotent code'''
  1241. ocobj = OCObject(params['kind'],
  1242. params['namespace'],
  1243. params['name'],
  1244. params['selector'],
  1245. kubeconfig=params['kubeconfig'],
  1246. verbose=params['debug'],
  1247. all_namespaces=params['all_namespaces'])
  1248. state = params['state']
  1249. api_rval = ocobj.get()
  1250. #####
  1251. # Get
  1252. #####
  1253. if state == 'list':
  1254. return {'changed': False, 'results': api_rval, 'state': state}
  1255. ########
  1256. # Delete
  1257. ########
  1258. if state == 'absent':
  1259. # verify its not in our results
  1260. if (params['name'] is not None or params['selector'] is not None) and \
  1261. (len(api_rval['results']) == 0 or \
  1262. ('items' in api_rval['results'][0] and len(api_rval['results'][0]['items']) == 0)):
  1263. return {'changed': False, 'state': state}
  1264. if check_mode:
  1265. return {'changed': True, 'msg': 'CHECK_MODE: Would have performed a delete'}
  1266. api_rval = ocobj.delete()
  1267. if api_rval['returncode'] != 0:
  1268. return {'failed': True, 'msg': api_rval}
  1269. return {'changed': True, 'results': api_rval, 'state': state}
  1270. # create/update: Must define a name beyond this point
  1271. if not params['name']:
  1272. return {'failed': True, 'msg': 'Please specify a name when state is present.'}
  1273. if state == 'present':
  1274. ########
  1275. # Create
  1276. ########
  1277. if not Utils.exists(api_rval['results'], params['name']):
  1278. if check_mode:
  1279. return {'changed': True, 'msg': 'CHECK_MODE: Would have performed a create'}
  1280. # Create it here
  1281. api_rval = ocobj.create(params['files'], params['content'])
  1282. if api_rval['returncode'] != 0:
  1283. return {'failed': True, 'msg': api_rval}
  1284. # return the created object
  1285. api_rval = ocobj.get()
  1286. if api_rval['returncode'] != 0:
  1287. return {'failed': True, 'msg': api_rval}
  1288. # Remove files
  1289. if params['files'] and params['delete_after']:
  1290. Utils.cleanup(params['files'])
  1291. return {'changed': True, 'results': api_rval, 'state': state}
  1292. ########
  1293. # Update
  1294. ########
  1295. # if a file path is passed, use it.
  1296. update = ocobj.needs_update(params['files'], params['content'])
  1297. if not isinstance(update, bool):
  1298. return {'failed': True, 'msg': update}
  1299. # No changes
  1300. if not update:
  1301. if params['files'] and params['delete_after']:
  1302. Utils.cleanup(params['files'])
  1303. return {'changed': False, 'results': api_rval['results'][0], 'state': state}
  1304. if check_mode:
  1305. return {'changed': True, 'msg': 'CHECK_MODE: Would have performed an update.'}
  1306. api_rval = ocobj.update(params['files'],
  1307. params['content'],
  1308. params['force'])
  1309. if api_rval['returncode'] != 0:
  1310. return {'failed': True, 'msg': api_rval}
  1311. # return the created object
  1312. api_rval = ocobj.get()
  1313. if api_rval['returncode'] != 0:
  1314. return {'failed': True, 'msg': api_rval}
  1315. return {'changed': True, 'results': api_rval, 'state': state}
  1316. # -*- -*- -*- End included fragment: class/oc_obj.py -*- -*- -*-
  1317. # -*- -*- -*- Begin included fragment: ansible/oc_obj.py -*- -*- -*-
  1318. # pylint: disable=too-many-branches
  1319. def main():
  1320. '''
  1321. ansible oc module for services
  1322. '''
  1323. module = AnsibleModule(
  1324. argument_spec=dict(
  1325. kubeconfig=dict(default='/etc/origin/master/admin.kubeconfig', type='str'),
  1326. state=dict(default='present', type='str',
  1327. choices=['present', 'absent', 'list']),
  1328. debug=dict(default=False, type='bool'),
  1329. namespace=dict(default='default', type='str'),
  1330. all_namespaces=dict(defaul=False, type='bool'),
  1331. name=dict(default=None, type='str'),
  1332. files=dict(default=None, type='list'),
  1333. kind=dict(required=True, type='str'),
  1334. delete_after=dict(default=False, type='bool'),
  1335. content=dict(default=None, type='dict'),
  1336. force=dict(default=False, type='bool'),
  1337. selector=dict(default=None, type='str'),
  1338. ),
  1339. mutually_exclusive=[["content", "files"], ["selector", "name"]],
  1340. supports_check_mode=True,
  1341. )
  1342. rval = OCObject.run_ansible(module.params, module.check_mode)
  1343. if 'failed' in rval:
  1344. module.fail_json(**rval)
  1345. module.exit_json(**rval)
  1346. if __name__ == '__main__':
  1347. main()
  1348. # -*- -*- -*- End included fragment: ansible/oc_obj.py -*- -*- -*-