oc_label.py 52 KB

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