oc_label.py 59 KB

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