oc_label.py 52 KB

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