oc_label.py 54 KB

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