oc_label.py 54 KB

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