oadm_manage_node.py 51 KB

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