oc_label.py 60 KB

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