oc_label.py 60 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805
  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('-p')
  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, field_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. if field_selector is not None:
  831. cmd.append('--field-selector={}'.format(field_selector))
  832. # Name cannot be used with selector or field_selector.
  833. if selector is None and field_selector is None and name is not None:
  834. cmd.append(name)
  835. cmd.extend(['-o', 'json'])
  836. rval = self.openshift_cmd(cmd, output=True)
  837. # Ensure results are retuned in an array
  838. if 'items' in rval:
  839. rval['results'] = rval['items']
  840. elif not isinstance(rval['results'], list):
  841. rval['results'] = [rval['results']]
  842. return rval
  843. def _schedulable(self, node=None, selector=None, schedulable=True):
  844. ''' perform oadm manage-node scheduable '''
  845. cmd = ['manage-node']
  846. if node:
  847. cmd.extend(node)
  848. else:
  849. cmd.append('--selector={}'.format(selector))
  850. cmd.append('--schedulable={}'.format(schedulable))
  851. return self.openshift_cmd(cmd, oadm=True, output=True, output_type='raw') # noqa: E501
  852. def _list_pods(self, node=None, selector=None, pod_selector=None):
  853. ''' perform oadm list pods
  854. node: the node in which to list pods
  855. selector: the label selector filter if provided
  856. pod_selector: the pod selector filter if provided
  857. '''
  858. cmd = ['manage-node']
  859. if node:
  860. cmd.extend(node)
  861. else:
  862. cmd.append('--selector={}'.format(selector))
  863. if pod_selector:
  864. cmd.append('--pod-selector={}'.format(pod_selector))
  865. cmd.extend(['--list-pods', '-o', 'json'])
  866. return self.openshift_cmd(cmd, oadm=True, output=True, output_type='raw')
  867. # pylint: disable=too-many-arguments
  868. def _evacuate(self, node=None, selector=None, pod_selector=None, dry_run=False, grace_period=None, force=False):
  869. ''' perform oadm manage-node evacuate '''
  870. cmd = ['manage-node']
  871. if node:
  872. cmd.extend(node)
  873. else:
  874. cmd.append('--selector={}'.format(selector))
  875. if dry_run:
  876. cmd.append('--dry-run')
  877. if pod_selector:
  878. cmd.append('--pod-selector={}'.format(pod_selector))
  879. if grace_period:
  880. cmd.append('--grace-period={}'.format(int(grace_period)))
  881. if force:
  882. cmd.append('--force')
  883. cmd.append('--evacuate')
  884. return self.openshift_cmd(cmd, oadm=True, output=True, output_type='raw')
  885. def _version(self):
  886. ''' return the openshift version'''
  887. return self.openshift_cmd(['version'], output=True, output_type='raw')
  888. def _import_image(self, url=None, name=None, tag=None):
  889. ''' perform image import '''
  890. cmd = ['import-image']
  891. image = '{0}'.format(name)
  892. if tag:
  893. image += ':{0}'.format(tag)
  894. cmd.append(image)
  895. if url:
  896. cmd.append('--from={0}/{1}'.format(url, image))
  897. cmd.append('-n{0}'.format(self.namespace))
  898. cmd.append('--confirm')
  899. return self.openshift_cmd(cmd)
  900. def _run(self, cmds, input_data):
  901. ''' Actually executes the command. This makes mocking easier. '''
  902. curr_env = os.environ.copy()
  903. curr_env.update({'KUBECONFIG': self.kubeconfig})
  904. proc = subprocess.Popen(cmds,
  905. stdin=subprocess.PIPE,
  906. stdout=subprocess.PIPE,
  907. stderr=subprocess.PIPE,
  908. env=curr_env)
  909. stdout, stderr = proc.communicate(input_data)
  910. return proc.returncode, stdout.decode('utf-8'), stderr.decode('utf-8')
  911. # pylint: disable=too-many-arguments,too-many-branches
  912. def openshift_cmd(self, cmd, oadm=False, output=False, output_type='json', input_data=None):
  913. '''Base command for oc '''
  914. cmds = [self.oc_binary]
  915. if oadm:
  916. cmds.append('adm')
  917. cmds.extend(cmd)
  918. if self.all_namespaces:
  919. cmds.extend(['--all-namespaces'])
  920. elif self.namespace is not None and self.namespace.lower() not in ['none', 'emtpy']: # E501
  921. cmds.extend(['-n', self.namespace])
  922. if self.verbose:
  923. print(' '.join(cmds))
  924. try:
  925. returncode, stdout, stderr = self._run(cmds, input_data)
  926. except OSError as ex:
  927. returncode, stdout, stderr = 1, '', 'Failed to execute {}: {}'.format(subprocess.list2cmdline(cmds), ex)
  928. rval = {"returncode": returncode,
  929. "cmd": ' '.join(cmds)}
  930. if output_type == 'json':
  931. rval['results'] = {}
  932. if output and stdout:
  933. try:
  934. rval['results'] = json.loads(stdout)
  935. except ValueError as verr:
  936. if "No JSON object could be decoded" in verr.args:
  937. rval['err'] = verr.args
  938. elif output_type == 'raw':
  939. rval['results'] = stdout if output else ''
  940. if self.verbose:
  941. print("STDOUT: {0}".format(stdout))
  942. print("STDERR: {0}".format(stderr))
  943. if 'err' in rval or returncode != 0:
  944. rval.update({"stderr": stderr,
  945. "stdout": stdout})
  946. return rval
  947. class Utils(object): # pragma: no cover
  948. ''' utilities for openshiftcli modules '''
  949. @staticmethod
  950. def _write(filename, contents):
  951. ''' Actually write the file contents to disk. This helps with mocking. '''
  952. with open(filename, 'w') as sfd:
  953. sfd.write(str(contents))
  954. @staticmethod
  955. def create_tmp_file_from_contents(rname, data, ftype='yaml'):
  956. ''' create a file in tmp with name and contents'''
  957. tmp = Utils.create_tmpfile(prefix=rname)
  958. if ftype == 'yaml':
  959. # AUDIT:no-member makes sense here due to ruamel.YAML/PyYAML usage
  960. # pylint: disable=no-member
  961. if hasattr(yaml, 'RoundTripDumper'):
  962. Utils._write(tmp, yaml.dump(data, Dumper=yaml.RoundTripDumper))
  963. else:
  964. Utils._write(tmp, yaml.safe_dump(data, default_flow_style=False))
  965. elif ftype == 'json':
  966. Utils._write(tmp, json.dumps(data))
  967. else:
  968. Utils._write(tmp, data)
  969. # Register cleanup when module is done
  970. atexit.register(Utils.cleanup, [tmp])
  971. return tmp
  972. @staticmethod
  973. def create_tmpfile_copy(inc_file):
  974. '''create a temporary copy of a file'''
  975. tmpfile = Utils.create_tmpfile('lib_openshift-')
  976. Utils._write(tmpfile, open(inc_file).read())
  977. # Cleanup the tmpfile
  978. atexit.register(Utils.cleanup, [tmpfile])
  979. return tmpfile
  980. @staticmethod
  981. def create_tmpfile(prefix='tmp'):
  982. ''' Generates and returns a temporary file name '''
  983. with tempfile.NamedTemporaryFile(prefix=prefix, delete=False) as tmp:
  984. return tmp.name
  985. @staticmethod
  986. def create_tmp_files_from_contents(content, content_type=None):
  987. '''Turn an array of dict: filename, content into a files array'''
  988. if not isinstance(content, list):
  989. content = [content]
  990. files = []
  991. for item in content:
  992. path = Utils.create_tmp_file_from_contents(item['path'] + '-',
  993. item['data'],
  994. ftype=content_type)
  995. files.append({'name': os.path.basename(item['path']),
  996. 'path': path})
  997. return files
  998. @staticmethod
  999. def cleanup(files):
  1000. '''Clean up on exit '''
  1001. for sfile in files:
  1002. if os.path.exists(sfile):
  1003. if os.path.isdir(sfile):
  1004. shutil.rmtree(sfile)
  1005. elif os.path.isfile(sfile):
  1006. os.remove(sfile)
  1007. @staticmethod
  1008. def exists(results, _name):
  1009. ''' Check to see if the results include the name '''
  1010. if not results:
  1011. return False
  1012. if Utils.find_result(results, _name):
  1013. return True
  1014. return False
  1015. @staticmethod
  1016. def find_result(results, _name):
  1017. ''' Find the specified result by name'''
  1018. rval = None
  1019. for result in results:
  1020. if 'metadata' in result and result['metadata']['name'] == _name:
  1021. rval = result
  1022. break
  1023. return rval
  1024. @staticmethod
  1025. def get_resource_file(sfile, sfile_type='yaml'):
  1026. ''' return the service file '''
  1027. contents = None
  1028. with open(sfile) as sfd:
  1029. contents = sfd.read()
  1030. if sfile_type == 'yaml':
  1031. # AUDIT:no-member makes sense here due to ruamel.YAML/PyYAML usage
  1032. # pylint: disable=no-member
  1033. if hasattr(yaml, 'RoundTripLoader'):
  1034. contents = yaml.load(contents, yaml.RoundTripLoader)
  1035. else:
  1036. contents = yaml.safe_load(contents)
  1037. elif sfile_type == 'json':
  1038. contents = json.loads(contents)
  1039. return contents
  1040. @staticmethod
  1041. def filter_versions(stdout):
  1042. ''' filter the oc version output '''
  1043. version_dict = {}
  1044. version_search = ['oc', 'openshift', 'kubernetes']
  1045. for line in stdout.strip().split('\n'):
  1046. for term in version_search:
  1047. if not line:
  1048. continue
  1049. if line.startswith(term):
  1050. version_dict[term] = line.split()[-1]
  1051. # horrible hack to get openshift version in Openshift 3.2
  1052. # By default "oc version in 3.2 does not return an "openshift" version
  1053. if "openshift" not in version_dict:
  1054. version_dict["openshift"] = version_dict["oc"]
  1055. return version_dict
  1056. @staticmethod
  1057. def add_custom_versions(versions):
  1058. ''' create custom versions strings '''
  1059. versions_dict = {}
  1060. for tech, version in versions.items():
  1061. # clean up "-" from version
  1062. if "-" in version:
  1063. version = version.split("-")[0]
  1064. if version.startswith('v'):
  1065. versions_dict[tech + '_numeric'] = version[1:].split('+')[0]
  1066. # "v3.3.0.33" is what we have, we want "3.3"
  1067. versions_dict[tech + '_short'] = version[1:4]
  1068. return versions_dict
  1069. @staticmethod
  1070. def openshift_installed():
  1071. ''' check if openshift is installed '''
  1072. import rpm
  1073. transaction_set = rpm.TransactionSet()
  1074. rpmquery = transaction_set.dbMatch("name", "atomic-openshift")
  1075. return rpmquery.count() > 0
  1076. # Disabling too-many-branches. This is a yaml dictionary comparison function
  1077. # pylint: disable=too-many-branches,too-many-return-statements,too-many-statements
  1078. @staticmethod
  1079. def check_def_equal(user_def, result_def, skip_keys=None, debug=False):
  1080. ''' Given a user defined definition, compare it with the results given back by our query. '''
  1081. # Currently these values are autogenerated and we do not need to check them
  1082. skip = ['metadata', 'status']
  1083. if skip_keys:
  1084. skip.extend(skip_keys)
  1085. for key, value in result_def.items():
  1086. if key in skip:
  1087. continue
  1088. # Both are lists
  1089. if isinstance(value, list):
  1090. if key not in user_def:
  1091. if debug:
  1092. print('User data does not have key [%s]' % key)
  1093. print('User data: %s' % user_def)
  1094. return False
  1095. if not isinstance(user_def[key], list):
  1096. if debug:
  1097. print('user_def[key] is not a list key=[%s] user_def[key]=%s' % (key, user_def[key]))
  1098. return False
  1099. if len(user_def[key]) != len(value):
  1100. if debug:
  1101. print("List lengths are not equal.")
  1102. print("key=[%s]: user_def[%s] != value[%s]" % (key, len(user_def[key]), len(value)))
  1103. print("user_def: %s" % user_def[key])
  1104. print("value: %s" % value)
  1105. return False
  1106. for values in zip(user_def[key], value):
  1107. if isinstance(values[0], dict) and isinstance(values[1], dict):
  1108. if debug:
  1109. print('sending list - list')
  1110. print(type(values[0]))
  1111. print(type(values[1]))
  1112. result = Utils.check_def_equal(values[0], values[1], skip_keys=skip_keys, debug=debug)
  1113. if not result:
  1114. print('list compare returned false')
  1115. return False
  1116. elif value != user_def[key]:
  1117. if debug:
  1118. print('value should be identical')
  1119. print(user_def[key])
  1120. print(value)
  1121. return False
  1122. # recurse on a dictionary
  1123. elif isinstance(value, dict):
  1124. if key not in user_def:
  1125. if debug:
  1126. print("user_def does not have key [%s]" % key)
  1127. return False
  1128. if not isinstance(user_def[key], dict):
  1129. if debug:
  1130. print("dict returned false: not instance of dict")
  1131. return False
  1132. # before passing ensure keys match
  1133. api_values = set(value.keys()) - set(skip)
  1134. user_values = set(user_def[key].keys()) - set(skip)
  1135. if api_values != user_values:
  1136. if debug:
  1137. print("keys are not equal in dict")
  1138. print(user_values)
  1139. print(api_values)
  1140. return False
  1141. result = Utils.check_def_equal(user_def[key], value, skip_keys=skip_keys, debug=debug)
  1142. if not result:
  1143. if debug:
  1144. print("dict returned false")
  1145. print(result)
  1146. return False
  1147. # Verify each key, value pair is the same
  1148. else:
  1149. if key not in user_def or value != user_def[key]:
  1150. if debug:
  1151. print("value not equal; user_def does not have key")
  1152. print(key)
  1153. print(value)
  1154. if key in user_def:
  1155. print(user_def[key])
  1156. return False
  1157. if debug:
  1158. print('returning true')
  1159. return True
  1160. class OpenShiftCLIConfig(object):
  1161. '''Generic Config'''
  1162. def __init__(self, rname, namespace, kubeconfig, options):
  1163. self.kubeconfig = kubeconfig
  1164. self.name = rname
  1165. self.namespace = namespace
  1166. self._options = options
  1167. @property
  1168. def config_options(self):
  1169. ''' return config options '''
  1170. return self._options
  1171. def to_option_list(self, ascommalist=''):
  1172. '''return all options as a string
  1173. if ascommalist is set to the name of a key, and
  1174. the value of that key is a dict, format the dict
  1175. as a list of comma delimited key=value pairs'''
  1176. return self.stringify(ascommalist)
  1177. def stringify(self, ascommalist=''):
  1178. ''' return the options hash as cli params in a string
  1179. if ascommalist is set to the name of a key, and
  1180. the value of that key is a dict, format the dict
  1181. as a list of comma delimited key=value pairs '''
  1182. rval = []
  1183. for key in sorted(self.config_options.keys()):
  1184. data = self.config_options[key]
  1185. if data['include'] \
  1186. and (data['value'] is not None or isinstance(data['value'], int)):
  1187. if key == ascommalist:
  1188. val = ','.join(['{}={}'.format(kk, vv) for kk, vv in sorted(data['value'].items())])
  1189. else:
  1190. val = data['value']
  1191. rval.append('--{}={}'.format(key.replace('_', '-'), val))
  1192. return rval
  1193. # -*- -*- -*- End included fragment: lib/base.py -*- -*- -*-
  1194. # -*- -*- -*- Begin included fragment: class/oc_label.py -*- -*- -*-
  1195. # pylint: disable=too-many-instance-attributes
  1196. class OCLabel(OpenShiftCLI):
  1197. ''' Class to wrap the oc command line tools '''
  1198. # pylint allows 5
  1199. # pylint: disable=too-many-arguments
  1200. def __init__(self,
  1201. name,
  1202. namespace,
  1203. kind,
  1204. kubeconfig,
  1205. labels=None,
  1206. selector=None,
  1207. verbose=False):
  1208. ''' Constructor for OCLabel '''
  1209. super(OCLabel, self).__init__(namespace, kubeconfig=kubeconfig, verbose=verbose)
  1210. self.name = name
  1211. self.kind = kind
  1212. self.labels = labels
  1213. self._curr_labels = None
  1214. self.selector = selector
  1215. @property
  1216. def current_labels(self):
  1217. '''property for the current labels'''
  1218. if self._curr_labels is None:
  1219. results = self.get()
  1220. self._curr_labels = results['labels']
  1221. return self._curr_labels
  1222. @current_labels.setter
  1223. def current_labels(self, data):
  1224. '''property setter for current labels'''
  1225. self._curr_labels = data
  1226. def compare_labels(self, host_labels):
  1227. ''' compare incoming labels against current labels'''
  1228. for label in self.labels:
  1229. if label['key'] not in host_labels or \
  1230. label['value'] != host_labels[label['key']]:
  1231. return False
  1232. return True
  1233. def all_user_labels_exist(self):
  1234. ''' return whether all the labels already exist '''
  1235. for current_host_labels in self.current_labels:
  1236. rbool = self.compare_labels(current_host_labels)
  1237. if not rbool:
  1238. return False
  1239. return True
  1240. def any_label_exists(self):
  1241. ''' return whether any single label already exists '''
  1242. for current_host_labels in self.current_labels:
  1243. for label in self.labels:
  1244. if label['key'] in current_host_labels:
  1245. return True
  1246. return False
  1247. def get_user_keys(self):
  1248. ''' go through list of user key:values and return all keys '''
  1249. user_keys = []
  1250. for label in self.labels:
  1251. user_keys.append(label['key'])
  1252. return user_keys
  1253. def get_current_label_keys(self):
  1254. ''' collect all the current label keys '''
  1255. current_label_keys = []
  1256. for current_host_labels in self.current_labels:
  1257. for key in current_host_labels.keys():
  1258. current_label_keys.append(key)
  1259. return list(set(current_label_keys))
  1260. def get_extra_current_labels(self):
  1261. ''' return list of labels that are currently stored, but aren't
  1262. in user-provided list '''
  1263. extra_labels = []
  1264. user_label_keys = self.get_user_keys()
  1265. current_label_keys = self.get_current_label_keys()
  1266. for current_key in current_label_keys:
  1267. if current_key not in user_label_keys:
  1268. extra_labels.append(current_key)
  1269. return extra_labels
  1270. def extra_current_labels(self):
  1271. ''' return whether there are labels currently stored that user
  1272. hasn't directly provided '''
  1273. extra_labels = self.get_extra_current_labels()
  1274. if len(extra_labels) > 0:
  1275. return True
  1276. return False
  1277. def replace(self):
  1278. ''' replace currently stored labels with user provided labels '''
  1279. cmd = self.cmd_template()
  1280. # First delete any extra labels
  1281. extra_labels = self.get_extra_current_labels()
  1282. if len(extra_labels) > 0:
  1283. for label in extra_labels:
  1284. cmd.append("{}-".format(label))
  1285. # Now add/modify the user-provided label list
  1286. if len(self.labels) > 0:
  1287. for label in self.labels:
  1288. cmd.append("{}={}".format(label['key'], label['value']))
  1289. # --overwrite for the case where we are updating existing labels
  1290. cmd.append("--overwrite")
  1291. return self.openshift_cmd(cmd)
  1292. def get(self):
  1293. '''return label information '''
  1294. result_dict = {}
  1295. label_list = []
  1296. if self.name:
  1297. result = self._get(resource=self.kind, name=self.name, selector=self.selector)
  1298. if result['results'][0] and 'labels' in result['results'][0]['metadata']:
  1299. label_list.append(result['results'][0]['metadata']['labels'])
  1300. else:
  1301. label_list.append({})
  1302. else:
  1303. result = self._get(resource=self.kind, selector=self.selector)
  1304. for item in result['results'][0]['items']:
  1305. if 'labels' in item['metadata']:
  1306. label_list.append(item['metadata']['labels'])
  1307. else:
  1308. label_list.append({})
  1309. self.current_labels = label_list
  1310. result_dict['labels'] = self.current_labels
  1311. result_dict['item_count'] = len(self.current_labels)
  1312. result['results'] = result_dict
  1313. return result
  1314. def cmd_template(self):
  1315. ''' boilerplate oc command for modifying lables on this object '''
  1316. # let's build the cmd with what we have passed in
  1317. cmd = ["label", self.kind]
  1318. if self.selector:
  1319. cmd.extend(["--selector", self.selector])
  1320. elif self.name:
  1321. cmd.extend([self.name])
  1322. return cmd
  1323. def add(self):
  1324. ''' add labels '''
  1325. cmd = self.cmd_template()
  1326. for label in self.labels:
  1327. cmd.append("{}={}".format(label['key'], label['value']))
  1328. cmd.append("--overwrite")
  1329. return self.openshift_cmd(cmd)
  1330. def delete(self):
  1331. '''delete the labels'''
  1332. cmd = self.cmd_template()
  1333. for label in self.labels:
  1334. cmd.append("{}-".format(label['key']))
  1335. return self.openshift_cmd(cmd)
  1336. # pylint: disable=too-many-branches,too-many-return-statements
  1337. @staticmethod
  1338. def run_ansible(params, check_mode=False):
  1339. ''' run the idempotent ansible code
  1340. prams comes from the ansible portion of this module
  1341. check_mode: does the module support check mode. (module.check_mode)
  1342. '''
  1343. oc_label = OCLabel(params['name'],
  1344. params['namespace'],
  1345. params['kind'],
  1346. params['kubeconfig'],
  1347. params['labels'],
  1348. params['selector'],
  1349. verbose=params['debug'])
  1350. state = params['state']
  1351. name = params['name']
  1352. selector = params['selector']
  1353. api_rval = oc_label.get()
  1354. #####
  1355. # Get
  1356. #####
  1357. if state == 'list':
  1358. return {'changed': False, 'results': api_rval['results'], 'state': "list"}
  1359. #######
  1360. # Add
  1361. #######
  1362. if state == 'add':
  1363. if not (name or selector):
  1364. return {'failed': True,
  1365. 'msg': "Param 'name' or 'selector' is required if state == 'add'"}
  1366. if not oc_label.all_user_labels_exist():
  1367. if check_mode:
  1368. return {'changed': False, 'msg': 'Would have performed an addition.'}
  1369. api_rval = oc_label.add()
  1370. if api_rval['returncode'] != 0:
  1371. return {'failed': True, 'msg': api_rval}
  1372. return {'changed': True, 'results': api_rval, 'state': "add"}
  1373. return {'changed': False, 'state': "add"}
  1374. ########
  1375. # Delete
  1376. ########
  1377. if state == 'absent':
  1378. if not (name or selector):
  1379. return {'failed': True,
  1380. 'msg': "Param 'name' or 'selector' is required if state == 'absent'"}
  1381. if oc_label.any_label_exists():
  1382. if check_mode:
  1383. return {'changed': False, 'msg': 'Would have performed a delete.'}
  1384. api_rval = oc_label.delete()
  1385. if api_rval['returncode'] != 0:
  1386. return {'failed': True, 'msg': api_rval}
  1387. return {'changed': True, 'results': api_rval, 'state': "absent"}
  1388. return {'changed': False, 'state': "absent"}
  1389. if state == 'present':
  1390. ########
  1391. # Update
  1392. ########
  1393. if not (name or selector):
  1394. return {'failed': True,
  1395. 'msg': "Param 'name' or 'selector' is required if state == 'present'"}
  1396. # if all the labels passed in don't already exist
  1397. # or if there are currently stored labels that haven't
  1398. # been passed in
  1399. if not oc_label.all_user_labels_exist() or \
  1400. oc_label.extra_current_labels():
  1401. if check_mode:
  1402. return {'changed': False, 'msg': 'Would have made changes.'}
  1403. api_rval = oc_label.replace()
  1404. if api_rval['returncode'] != 0:
  1405. return {'failed': True, 'msg': api_rval}
  1406. # return the created object
  1407. api_rval = oc_label.get()
  1408. if api_rval['returncode'] != 0:
  1409. return {'failed': True, 'msg': api_rval}
  1410. return {'changed': True, 'results': api_rval, 'state': "present"}
  1411. return {'changed': False, 'results': api_rval, 'state': "present"}
  1412. return {'failed': True,
  1413. 'changed': False,
  1414. 'results': 'Unknown state passed. %s' % state,
  1415. 'state': "unknown"}
  1416. # -*- -*- -*- End included fragment: class/oc_label.py -*- -*- -*-
  1417. # -*- -*- -*- Begin included fragment: ansible/oc_label.py -*- -*- -*-
  1418. def main():
  1419. ''' ansible oc module for labels '''
  1420. module = AnsibleModule(
  1421. argument_spec=dict(
  1422. kubeconfig=dict(default='/etc/origin/master/admin.kubeconfig', type='str'),
  1423. state=dict(default='present', type='str',
  1424. choices=['present', 'absent', 'list', 'add']),
  1425. debug=dict(default=False, type='bool'),
  1426. kind=dict(default='node', type='str',
  1427. choices=['node', 'pod', 'namespace']),
  1428. name=dict(default=None, type='str'),
  1429. namespace=dict(default=None, type='str'),
  1430. labels=dict(default=None, type='list'),
  1431. selector=dict(default=None, type='str'),
  1432. ),
  1433. supports_check_mode=True,
  1434. mutually_exclusive=(['name', 'selector']),
  1435. )
  1436. results = OCLabel.run_ansible(module.params, module.check_mode)
  1437. if 'failed' in results:
  1438. module.fail_json(**results)
  1439. module.exit_json(**results)
  1440. if __name__ == '__main__':
  1441. main()
  1442. # -*- -*- -*- End included fragment: ansible/oc_label.py -*- -*- -*-