oadm_manage_node.py 50 KB

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