oc_label.py 54 KB

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