oc_adm_manage_node.py 59 KB

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