oc_edit.py 45 KB

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