oc_edit.py 46 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436
  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 = 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(prefix=None):
  853. ''' Generates and returns a temporary file name '''
  854. with tempfile.NamedTemporaryFile(prefix=prefix, delete=False) as tmp:
  855. return tmp.name
  856. @staticmethod
  857. def create_tmp_files_from_contents(content, content_type=None):
  858. '''Turn an array of dict: filename, content into a files array'''
  859. if not isinstance(content, list):
  860. content = [content]
  861. files = []
  862. for item in content:
  863. path = Utils.create_tmp_file_from_contents(item['path'] + '-',
  864. item['data'],
  865. ftype=content_type)
  866. files.append({'name': os.path.basename(item['path']),
  867. 'path': path})
  868. return files
  869. @staticmethod
  870. def cleanup(files):
  871. '''Clean up on exit '''
  872. for sfile in files:
  873. if os.path.exists(sfile):
  874. if os.path.isdir(sfile):
  875. shutil.rmtree(sfile)
  876. elif os.path.isfile(sfile):
  877. os.remove(sfile)
  878. @staticmethod
  879. def exists(results, _name):
  880. ''' Check to see if the results include the name '''
  881. if not results:
  882. return False
  883. if Utils.find_result(results, _name):
  884. return True
  885. return False
  886. @staticmethod
  887. def find_result(results, _name):
  888. ''' Find the specified result by name'''
  889. rval = None
  890. for result in results:
  891. if 'metadata' in result and result['metadata']['name'] == _name:
  892. rval = result
  893. break
  894. return rval
  895. @staticmethod
  896. def get_resource_file(sfile, sfile_type='yaml'):
  897. ''' return the service file '''
  898. contents = None
  899. with open(sfile) as sfd:
  900. contents = sfd.read()
  901. if sfile_type == 'yaml':
  902. contents = yaml.load(contents, yaml.RoundTripLoader)
  903. elif sfile_type == 'json':
  904. contents = json.loads(contents)
  905. return contents
  906. @staticmethod
  907. def filter_versions(stdout):
  908. ''' filter the oc version output '''
  909. version_dict = {}
  910. version_search = ['oc', 'openshift', 'kubernetes']
  911. for line in stdout.strip().split('\n'):
  912. for term in version_search:
  913. if not line:
  914. continue
  915. if line.startswith(term):
  916. version_dict[term] = line.split()[-1]
  917. # horrible hack to get openshift version in Openshift 3.2
  918. # By default "oc version in 3.2 does not return an "openshift" version
  919. if "openshift" not in version_dict:
  920. version_dict["openshift"] = version_dict["oc"]
  921. return version_dict
  922. @staticmethod
  923. def add_custom_versions(versions):
  924. ''' create custom versions strings '''
  925. versions_dict = {}
  926. for tech, version in versions.items():
  927. # clean up "-" from version
  928. if "-" in version:
  929. version = version.split("-")[0]
  930. if version.startswith('v'):
  931. versions_dict[tech + '_numeric'] = version[1:].split('+')[0]
  932. # "v3.3.0.33" is what we have, we want "3.3"
  933. versions_dict[tech + '_short'] = version[1:4]
  934. return versions_dict
  935. @staticmethod
  936. def openshift_installed():
  937. ''' check if openshift is installed '''
  938. import yum
  939. yum_base = yum.YumBase()
  940. if yum_base.rpmdb.searchNevra(name='atomic-openshift'):
  941. return True
  942. return False
  943. # Disabling too-many-branches. This is a yaml dictionary comparison function
  944. # pylint: disable=too-many-branches,too-many-return-statements,too-many-statements
  945. @staticmethod
  946. def check_def_equal(user_def, result_def, skip_keys=None, debug=False):
  947. ''' Given a user defined definition, compare it with the results given back by our query. '''
  948. # Currently these values are autogenerated and we do not need to check them
  949. skip = ['metadata', 'status']
  950. if skip_keys:
  951. skip.extend(skip_keys)
  952. for key, value in result_def.items():
  953. if key in skip:
  954. continue
  955. # Both are lists
  956. if isinstance(value, list):
  957. if key not in user_def:
  958. if debug:
  959. print('User data does not have key [%s]' % key)
  960. print('User data: %s' % user_def)
  961. return False
  962. if not isinstance(user_def[key], list):
  963. if debug:
  964. print('user_def[key] is not a list key=[%s] user_def[key]=%s' % (key, user_def[key]))
  965. return False
  966. if len(user_def[key]) != len(value):
  967. if debug:
  968. print("List lengths are not equal.")
  969. print("key=[%s]: user_def[%s] != value[%s]" % (key, len(user_def[key]), len(value)))
  970. print("user_def: %s" % user_def[key])
  971. print("value: %s" % value)
  972. return False
  973. for values in zip(user_def[key], value):
  974. if isinstance(values[0], dict) and isinstance(values[1], dict):
  975. if debug:
  976. print('sending list - list')
  977. print(type(values[0]))
  978. print(type(values[1]))
  979. result = Utils.check_def_equal(values[0], values[1], skip_keys=skip_keys, debug=debug)
  980. if not result:
  981. print('list compare returned false')
  982. return False
  983. elif value != user_def[key]:
  984. if debug:
  985. print('value should be identical')
  986. print(value)
  987. print(user_def[key])
  988. return False
  989. # recurse on a dictionary
  990. elif isinstance(value, dict):
  991. if key not in user_def:
  992. if debug:
  993. print("user_def does not have key [%s]" % key)
  994. return False
  995. if not isinstance(user_def[key], dict):
  996. if debug:
  997. print("dict returned false: not instance of dict")
  998. return False
  999. # before passing ensure keys match
  1000. api_values = set(value.keys()) - set(skip)
  1001. user_values = set(user_def[key].keys()) - set(skip)
  1002. if api_values != user_values:
  1003. if debug:
  1004. print("keys are not equal in dict")
  1005. print(api_values)
  1006. print(user_values)
  1007. return False
  1008. result = Utils.check_def_equal(user_def[key], value, skip_keys=skip_keys, debug=debug)
  1009. if not result:
  1010. if debug:
  1011. print("dict returned false")
  1012. print(result)
  1013. return False
  1014. # Verify each key, value pair is the same
  1015. else:
  1016. if key not in user_def or value != user_def[key]:
  1017. if debug:
  1018. print("value not equal; user_def does not have key")
  1019. print(key)
  1020. print(value)
  1021. if key in user_def:
  1022. print(user_def[key])
  1023. return False
  1024. if debug:
  1025. print('returning true')
  1026. return True
  1027. class OpenShiftCLIConfig(object):
  1028. '''Generic Config'''
  1029. def __init__(self, rname, namespace, kubeconfig, options):
  1030. self.kubeconfig = kubeconfig
  1031. self.name = rname
  1032. self.namespace = namespace
  1033. self._options = options
  1034. @property
  1035. def config_options(self):
  1036. ''' return config options '''
  1037. return self._options
  1038. def to_option_list(self):
  1039. '''return all options as a string'''
  1040. return self.stringify()
  1041. def stringify(self):
  1042. ''' return the options hash as cli params in a string '''
  1043. rval = []
  1044. for key, data in self.config_options.items():
  1045. if data['include'] \
  1046. and (data['value'] or isinstance(data['value'], int)):
  1047. rval.append('--%s=%s' % (key.replace('_', '-'), data['value']))
  1048. return rval
  1049. # -*- -*- -*- End included fragment: lib/base.py -*- -*- -*-
  1050. # -*- -*- -*- Begin included fragment: class/oc_edit.py -*- -*- -*-
  1051. class Edit(OpenShiftCLI):
  1052. ''' Class to wrap the oc command line tools
  1053. '''
  1054. # pylint: disable=too-many-arguments
  1055. def __init__(self,
  1056. kind,
  1057. namespace,
  1058. resource_name=None,
  1059. kubeconfig='/etc/origin/master/admin.kubeconfig',
  1060. separator='.',
  1061. verbose=False):
  1062. ''' Constructor for OpenshiftOC '''
  1063. super(Edit, self).__init__(namespace, kubeconfig)
  1064. self.namespace = namespace
  1065. self.kind = kind
  1066. self.name = resource_name
  1067. self.kubeconfig = kubeconfig
  1068. self.separator = separator
  1069. self.verbose = verbose
  1070. def get(self):
  1071. '''return a secret by name '''
  1072. return self._get(self.kind, self.name)
  1073. def update(self, file_name, content, force=False, content_type='yaml'):
  1074. '''run update '''
  1075. if file_name:
  1076. if content_type == 'yaml':
  1077. data = yaml.load(open(file_name))
  1078. elif content_type == 'json':
  1079. data = json.loads(open(file_name).read())
  1080. changes = []
  1081. yed = Yedit(filename=file_name, content=data, separator=self.separator)
  1082. for key, value in content.items():
  1083. changes.append(yed.put(key, value))
  1084. if any([not change[0] for change in changes]):
  1085. return {'returncode': 0, 'updated': False}
  1086. yed.write()
  1087. atexit.register(Utils.cleanup, [file_name])
  1088. return self._replace(file_name, force=force)
  1089. return self._replace_content(self.kind, self.name, content, force=force, sep=self.separator)
  1090. @staticmethod
  1091. def run_ansible(params, check_mode):
  1092. '''run the ansible idempotent code'''
  1093. ocedit = Edit(params['kind'],
  1094. params['namespace'],
  1095. params['name'],
  1096. kubeconfig=params['kubeconfig'],
  1097. separator=params['separator'],
  1098. verbose=params['debug'])
  1099. api_rval = ocedit.get()
  1100. ########
  1101. # Create
  1102. ########
  1103. if not Utils.exists(api_rval['results'], params['name']):
  1104. return {"failed": True, 'msg': api_rval}
  1105. ########
  1106. # Update
  1107. ########
  1108. if check_mode:
  1109. return {'changed': True, 'msg': 'CHECK_MODE: Would have performed edit'}
  1110. api_rval = ocedit.update(params['file_name'],
  1111. params['content'],
  1112. params['force'],
  1113. params['file_format'])
  1114. if api_rval['returncode'] != 0:
  1115. return {"failed": True, 'msg': api_rval}
  1116. if 'updated' in api_rval and not api_rval['updated']:
  1117. return {"changed": False, 'results': api_rval, 'state': 'present'}
  1118. # return the created object
  1119. api_rval = ocedit.get()
  1120. if api_rval['returncode'] != 0:
  1121. return {"failed": True, 'msg': api_rval}
  1122. return {"changed": True, 'results': api_rval, 'state': 'present'}
  1123. # -*- -*- -*- End included fragment: class/oc_edit.py -*- -*- -*-
  1124. # -*- -*- -*- Begin included fragment: ansible/oc_edit.py -*- -*- -*-
  1125. def main():
  1126. '''
  1127. ansible oc module for editing objects
  1128. '''
  1129. module = AnsibleModule(
  1130. argument_spec=dict(
  1131. kubeconfig=dict(default='/etc/origin/master/admin.kubeconfig', type='str'),
  1132. state=dict(default='present', type='str',
  1133. choices=['present']),
  1134. debug=dict(default=False, type='bool'),
  1135. namespace=dict(default='default', type='str'),
  1136. name=dict(default=None, required=True, type='str'),
  1137. kind=dict(required=True,
  1138. type='str',
  1139. choices=['dc', 'deploymentconfig',
  1140. 'rc', 'replicationcontroller',
  1141. 'svc', 'service',
  1142. 'scc', 'securitycontextconstraints',
  1143. 'ns', 'namespace', 'project', 'projects',
  1144. 'is', 'imagestream',
  1145. 'istag', 'imagestreamtag',
  1146. 'bc', 'buildconfig',
  1147. 'routes',
  1148. 'node',
  1149. 'secret',
  1150. 'pv', 'persistentvolume']),
  1151. file_name=dict(default=None, type='str'),
  1152. file_format=dict(default='yaml', type='str'),
  1153. content=dict(default=None, required=True, type='dict'),
  1154. force=dict(default=False, type='bool'),
  1155. separator=dict(default='.', type='str'),
  1156. ),
  1157. supports_check_mode=True,
  1158. )
  1159. rval = Edit.run_ansible(module.params, module.check_mode)
  1160. if 'failed' in rval:
  1161. module.fail_json(**rval)
  1162. module.exit_json(**rval)
  1163. if __name__ == '__main__':
  1164. main()
  1165. # -*- -*- -*- End included fragment: ansible/oc_edit.py -*- -*- -*-