oc_label.py 57 KB

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