oc_label.py 53 KB

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