oc_edit.py 46 KB

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