oc_label.py 55 KB

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