oc_edit.py 52 KB

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