oadm_manage_node.py 50 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484
  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. def _run(self, cmds, input_data):
  742. ''' Actually executes the command. This makes mocking easier. '''
  743. proc = subprocess.Popen(cmds,
  744. stdin=subprocess.PIPE,
  745. stdout=subprocess.PIPE,
  746. stderr=subprocess.PIPE,
  747. env={'KUBECONFIG': self.kubeconfig})
  748. stdout, stderr = proc.communicate(input_data)
  749. return proc.returncode, stdout, stderr
  750. # pylint: disable=too-many-arguments,too-many-branches
  751. def openshift_cmd(self, cmd, oadm=False, output=False, output_type='json', input_data=None):
  752. '''Base command for oc '''
  753. cmds = []
  754. if oadm:
  755. cmds = ['/usr/bin/oadm']
  756. else:
  757. cmds = ['/usr/bin/oc']
  758. if self.all_namespaces:
  759. cmds.extend(['--all-namespaces'])
  760. elif self.namespace is not None and self.namespace.lower() not in ['none', 'emtpy']: # E501
  761. cmds.extend(['-n', self.namespace])
  762. cmds.extend(cmd)
  763. rval = {}
  764. results = ''
  765. err = None
  766. if self.verbose:
  767. print(' '.join(cmds))
  768. returncode, stdout, stderr = self._run(cmds, input_data)
  769. rval = {"returncode": returncode,
  770. "results": results,
  771. "cmd": ' '.join(cmds)}
  772. if returncode == 0:
  773. if output:
  774. if output_type == 'json':
  775. try:
  776. rval['results'] = json.loads(stdout)
  777. except ValueError as err:
  778. if "No JSON object could be decoded" in err.args:
  779. err = err.args
  780. elif output_type == 'raw':
  781. rval['results'] = stdout
  782. if self.verbose:
  783. print("STDOUT: {0}".format(stdout))
  784. print("STDERR: {0}".format(stderr))
  785. if err:
  786. rval.update({"err": err,
  787. "stderr": stderr,
  788. "stdout": stdout,
  789. "cmd": cmds})
  790. else:
  791. rval.update({"stderr": stderr,
  792. "stdout": stdout,
  793. "results": {}})
  794. return rval
  795. class Utils(object):
  796. ''' utilities for openshiftcli modules '''
  797. @staticmethod
  798. def create_file(rname, data, ftype='yaml'):
  799. ''' create a file in tmp with name and contents'''
  800. path = os.path.join('/tmp', rname)
  801. with open(path, 'w') as fds:
  802. if ftype == 'yaml':
  803. fds.write(yaml.dump(data, Dumper=yaml.RoundTripDumper))
  804. elif ftype == 'json':
  805. fds.write(json.dumps(data))
  806. else:
  807. fds.write(data)
  808. # Register cleanup when module is done
  809. atexit.register(Utils.cleanup, [path])
  810. return path
  811. @staticmethod
  812. def create_files_from_contents(content, content_type=None):
  813. '''Turn an array of dict: filename, content into a files array'''
  814. if not isinstance(content, list):
  815. content = [content]
  816. files = []
  817. for item in content:
  818. path = Utils.create_file(item['path'], item['data'], ftype=content_type)
  819. files.append({'name': os.path.basename(path), 'path': path})
  820. return files
  821. @staticmethod
  822. def cleanup(files):
  823. '''Clean up on exit '''
  824. for sfile in files:
  825. if os.path.exists(sfile):
  826. if os.path.isdir(sfile):
  827. shutil.rmtree(sfile)
  828. elif os.path.isfile(sfile):
  829. os.remove(sfile)
  830. @staticmethod
  831. def exists(results, _name):
  832. ''' Check to see if the results include the name '''
  833. if not results:
  834. return False
  835. if Utils.find_result(results, _name):
  836. return True
  837. return False
  838. @staticmethod
  839. def find_result(results, _name):
  840. ''' Find the specified result by name'''
  841. rval = None
  842. for result in results:
  843. if 'metadata' in result and result['metadata']['name'] == _name:
  844. rval = result
  845. break
  846. return rval
  847. @staticmethod
  848. def get_resource_file(sfile, sfile_type='yaml'):
  849. ''' return the service file '''
  850. contents = None
  851. with open(sfile) as sfd:
  852. contents = sfd.read()
  853. if sfile_type == 'yaml':
  854. contents = yaml.load(contents, yaml.RoundTripLoader)
  855. elif sfile_type == 'json':
  856. contents = json.loads(contents)
  857. return contents
  858. @staticmethod
  859. def filter_versions(stdout):
  860. ''' filter the oc version output '''
  861. version_dict = {}
  862. version_search = ['oc', 'openshift', 'kubernetes']
  863. for line in stdout.strip().split('\n'):
  864. for term in version_search:
  865. if not line:
  866. continue
  867. if line.startswith(term):
  868. version_dict[term] = line.split()[-1]
  869. # horrible hack to get openshift version in Openshift 3.2
  870. # By default "oc version in 3.2 does not return an "openshift" version
  871. if "openshift" not in version_dict:
  872. version_dict["openshift"] = version_dict["oc"]
  873. return version_dict
  874. @staticmethod
  875. def add_custom_versions(versions):
  876. ''' create custom versions strings '''
  877. versions_dict = {}
  878. for tech, version in versions.items():
  879. # clean up "-" from version
  880. if "-" in version:
  881. version = version.split("-")[0]
  882. if version.startswith('v'):
  883. versions_dict[tech + '_numeric'] = version[1:].split('+')[0]
  884. # "v3.3.0.33" is what we have, we want "3.3"
  885. versions_dict[tech + '_short'] = version[1:4]
  886. return versions_dict
  887. @staticmethod
  888. def openshift_installed():
  889. ''' check if openshift is installed '''
  890. import yum
  891. yum_base = yum.YumBase()
  892. if yum_base.rpmdb.searchNevra(name='atomic-openshift'):
  893. return True
  894. return False
  895. # Disabling too-many-branches. This is a yaml dictionary comparison function
  896. # pylint: disable=too-many-branches,too-many-return-statements,too-many-statements
  897. @staticmethod
  898. def check_def_equal(user_def, result_def, skip_keys=None, debug=False):
  899. ''' Given a user defined definition, compare it with the results given back by our query. '''
  900. # Currently these values are autogenerated and we do not need to check them
  901. skip = ['metadata', 'status']
  902. if skip_keys:
  903. skip.extend(skip_keys)
  904. for key, value in result_def.items():
  905. if key in skip:
  906. continue
  907. # Both are lists
  908. if isinstance(value, list):
  909. if key not in user_def:
  910. if debug:
  911. print('User data does not have key [%s]' % key)
  912. print('User data: %s' % user_def)
  913. return False
  914. if not isinstance(user_def[key], list):
  915. if debug:
  916. print('user_def[key] is not a list key=[%s] user_def[key]=%s' % (key, user_def[key]))
  917. return False
  918. if len(user_def[key]) != len(value):
  919. if debug:
  920. print("List lengths are not equal.")
  921. print("key=[%s]: user_def[%s] != value[%s]" % (key, len(user_def[key]), len(value)))
  922. print("user_def: %s" % user_def[key])
  923. print("value: %s" % value)
  924. return False
  925. for values in zip(user_def[key], value):
  926. if isinstance(values[0], dict) and isinstance(values[1], dict):
  927. if debug:
  928. print('sending list - list')
  929. print(type(values[0]))
  930. print(type(values[1]))
  931. result = Utils.check_def_equal(values[0], values[1], skip_keys=skip_keys, debug=debug)
  932. if not result:
  933. print('list compare returned false')
  934. return False
  935. elif value != user_def[key]:
  936. if debug:
  937. print('value should be identical')
  938. print(value)
  939. print(user_def[key])
  940. return False
  941. # recurse on a dictionary
  942. elif isinstance(value, dict):
  943. if key not in user_def:
  944. if debug:
  945. print("user_def does not have key [%s]" % key)
  946. return False
  947. if not isinstance(user_def[key], dict):
  948. if debug:
  949. print("dict returned false: not instance of dict")
  950. return False
  951. # before passing ensure keys match
  952. api_values = set(value.keys()) - set(skip)
  953. user_values = set(user_def[key].keys()) - set(skip)
  954. if api_values != user_values:
  955. if debug:
  956. print("keys are not equal in dict")
  957. print(api_values)
  958. print(user_values)
  959. return False
  960. result = Utils.check_def_equal(user_def[key], value, skip_keys=skip_keys, debug=debug)
  961. if not result:
  962. if debug:
  963. print("dict returned false")
  964. print(result)
  965. return False
  966. # Verify each key, value pair is the same
  967. else:
  968. if key not in user_def or value != user_def[key]:
  969. if debug:
  970. print("value not equal; user_def does not have key")
  971. print(key)
  972. print(value)
  973. if key in user_def:
  974. print(user_def[key])
  975. return False
  976. if debug:
  977. print('returning true')
  978. return True
  979. class OpenShiftCLIConfig(object):
  980. '''Generic Config'''
  981. def __init__(self, rname, namespace, kubeconfig, options):
  982. self.kubeconfig = kubeconfig
  983. self.name = rname
  984. self.namespace = namespace
  985. self._options = options
  986. @property
  987. def config_options(self):
  988. ''' return config options '''
  989. return self._options
  990. def to_option_list(self):
  991. '''return all options as a string'''
  992. return self.stringify()
  993. def stringify(self):
  994. ''' return the options hash as cli params in a string '''
  995. rval = []
  996. for key, data in self.config_options.items():
  997. if data['include'] \
  998. and (data['value'] or isinstance(data['value'], int)):
  999. rval.append('--%s=%s' % (key.replace('_', '-'), data['value']))
  1000. return rval
  1001. # -*- -*- -*- End included fragment: lib/base.py -*- -*- -*-
  1002. # -*- -*- -*- Begin included fragment: class/oadm_manage_node.py -*- -*- -*-
  1003. class ManageNodeException(Exception):
  1004. ''' manage-node exception class '''
  1005. pass
  1006. class ManageNodeConfig(OpenShiftCLIConfig):
  1007. ''' ManageNodeConfig is a DTO for the manage-node command.'''
  1008. def __init__(self, kubeconfig, node_options):
  1009. super(ManageNodeConfig, self).__init__(None, None, kubeconfig, node_options)
  1010. # pylint: disable=too-many-instance-attributes
  1011. class ManageNode(OpenShiftCLI):
  1012. ''' Class to wrap the oc command line tools '''
  1013. # pylint allows 5
  1014. # pylint: disable=too-many-arguments
  1015. def __init__(self,
  1016. config,
  1017. verbose=False):
  1018. ''' Constructor for ManageNode '''
  1019. super(ManageNode, self).__init__(None, config.kubeconfig)
  1020. self.config = config
  1021. def evacuate(self):
  1022. ''' formulate the params and run oadm manage-node '''
  1023. return self._evacuate(node=self.config.config_options['node']['value'],
  1024. selector=self.config.config_options['selector']['value'],
  1025. pod_selector=self.config.config_options['pod_selector']['value'],
  1026. dry_run=self.config.config_options['dry_run']['value'],
  1027. grace_period=self.config.config_options['grace_period']['value'],
  1028. force=self.config.config_options['force']['value'],
  1029. )
  1030. def get_nodes(self, node=None, selector=''):
  1031. '''perform oc get node'''
  1032. _node = None
  1033. _sel = None
  1034. if node:
  1035. _node = node
  1036. if selector:
  1037. _sel = selector
  1038. results = self._get('node', rname=_node, selector=_sel)
  1039. if results['returncode'] != 0:
  1040. return results
  1041. nodes = []
  1042. items = None
  1043. if results['results'][0]['kind'] == 'List':
  1044. items = results['results'][0]['items']
  1045. else:
  1046. items = results['results']
  1047. for node in items:
  1048. _node = {}
  1049. _node['name'] = node['metadata']['name']
  1050. _node['schedulable'] = True
  1051. if 'unschedulable' in node['spec']:
  1052. _node['schedulable'] = False
  1053. nodes.append(_node)
  1054. return nodes
  1055. def get_pods_from_node(self, node, pod_selector=None):
  1056. '''return pods for a node'''
  1057. results = self._list_pods(node=[node], pod_selector=pod_selector)
  1058. if results['returncode'] != 0:
  1059. return results
  1060. # When a selector or node is matched it is returned along with the json.
  1061. # We are going to split the results based on the regexp and then
  1062. # load the json for each matching node.
  1063. # Before we return we are going to loop over the results and pull out the node names.
  1064. # {'node': [pod, pod], 'node': [pod, pod]}
  1065. # 3.2 includes the following lines in stdout: "Listing matched pods on node:"
  1066. all_pods = []
  1067. if "Listing matched" in results['results']:
  1068. listing_match = re.compile('\n^Listing matched.*$\n', flags=re.MULTILINE)
  1069. pods = listing_match.split(results['results'])
  1070. for pod in pods:
  1071. if pod:
  1072. all_pods.extend(json.loads(pod)['items'])
  1073. # 3.3 specific
  1074. else:
  1075. # this is gross but I filed a bug...
  1076. # https://bugzilla.redhat.com/show_bug.cgi?id=1381621
  1077. # build our own json from the output.
  1078. all_pods = json.loads(results['results'])['items']
  1079. return all_pods
  1080. def list_pods(self):
  1081. ''' run oadm manage-node --list-pods'''
  1082. _nodes = self.config.config_options['node']['value']
  1083. _selector = self.config.config_options['selector']['value']
  1084. _pod_selector = self.config.config_options['pod_selector']['value']
  1085. if not _nodes:
  1086. _nodes = self.get_nodes(selector=_selector)
  1087. else:
  1088. _nodes = [{'name': name} for name in _nodes]
  1089. all_pods = {}
  1090. for node in _nodes:
  1091. results = self.get_pods_from_node(node['name'], pod_selector=_pod_selector)
  1092. if isinstance(results, dict):
  1093. return results
  1094. all_pods[node['name']] = results
  1095. results = {}
  1096. results['nodes'] = all_pods
  1097. results['returncode'] = 0
  1098. return results
  1099. def schedulable(self):
  1100. '''oadm manage-node call for making nodes unschedulable'''
  1101. nodes = self.config.config_options['node']['value']
  1102. selector = self.config.config_options['selector']['value']
  1103. if not nodes:
  1104. nodes = self.get_nodes(selector=selector)
  1105. else:
  1106. tmp_nodes = []
  1107. for name in nodes:
  1108. tmp_result = self.get_nodes(name)
  1109. if isinstance(tmp_result, dict):
  1110. tmp_nodes.append(tmp_result)
  1111. continue
  1112. tmp_nodes.extend(tmp_result)
  1113. nodes = tmp_nodes
  1114. # This is a short circuit based on the way we fetch nodes.
  1115. # If node is a dict/list then we've already fetched them.
  1116. for node in nodes:
  1117. if isinstance(node, dict) and 'returncode' in node:
  1118. return {'results': nodes, 'returncode': node['returncode']}
  1119. if isinstance(node, list) and 'returncode' in node[0]:
  1120. return {'results': nodes, 'returncode': node[0]['returncode']}
  1121. # check all the nodes that were returned and verify they are:
  1122. # node['schedulable'] == self.config.config_options['schedulable']['value']
  1123. if any([node['schedulable'] != self.config.config_options['schedulable']['value'] for node in nodes]):
  1124. results = self._schedulable(node=self.config.config_options['node']['value'],
  1125. selector=self.config.config_options['selector']['value'],
  1126. schedulable=self.config.config_options['schedulable']['value'])
  1127. # 'NAME STATUS AGE\\nip-172-31-49-140.ec2.internal Ready 4h\\n' # E501
  1128. # normalize formatting with previous return objects
  1129. if results['results'].startswith('NAME'):
  1130. nodes = []
  1131. # removing header line and trailing new line character of node lines
  1132. for node_results in results['results'].split('\n')[1:-1]:
  1133. parts = node_results.split()
  1134. nodes.append({'name': parts[0], 'schedulable': parts[1] == 'Ready'})
  1135. results['nodes'] = nodes
  1136. return results
  1137. results = {}
  1138. results['returncode'] = 0
  1139. results['changed'] = False
  1140. results['nodes'] = nodes
  1141. return results
  1142. @staticmethod
  1143. def run_ansible(params, check_mode):
  1144. '''run the idempotent ansible code'''
  1145. nconfig = ManageNodeConfig(params['kubeconfig'],
  1146. {'node': {'value': params['node'], 'include': True},
  1147. 'selector': {'value': params['selector'], 'include': True},
  1148. 'pod_selector': {'value': params['pod_selector'], 'include': True},
  1149. 'schedulable': {'value': params['schedulable'], 'include': True},
  1150. 'list_pods': {'value': params['list_pods'], 'include': True},
  1151. 'evacuate': {'value': params['evacuate'], 'include': True},
  1152. 'dry_run': {'value': params['dry_run'], 'include': True},
  1153. 'force': {'value': params['force'], 'include': True},
  1154. 'grace_period': {'value': params['grace_period'], 'include': True},
  1155. })
  1156. oadm_mn = ManageNode(nconfig)
  1157. # Run the oadm manage-node commands
  1158. results = None
  1159. changed = False
  1160. if params['schedulable'] != None:
  1161. if check_mode:
  1162. # schedulable returns results after the fact.
  1163. # We need to redo how this works to support check_mode completely.
  1164. return {'changed': True, 'msg': 'CHECK_MODE: would have called schedulable.'}
  1165. results = oadm_mn.schedulable()
  1166. if 'changed' not in results:
  1167. changed = True
  1168. if params['evacuate']:
  1169. results = oadm_mn.evacuate()
  1170. changed = True
  1171. elif params['list_pods']:
  1172. results = oadm_mn.list_pods()
  1173. if not results or results['returncode'] != 0:
  1174. return {'failed': True, 'msg': results}
  1175. return {'changed': changed, 'results': results, 'state': "present"}
  1176. # -*- -*- -*- End included fragment: class/oadm_manage_node.py -*- -*- -*-
  1177. # -*- -*- -*- Begin included fragment: ansible/oadm_manage_node.py -*- -*- -*-
  1178. def main():
  1179. '''
  1180. ansible oadm module for manage-node
  1181. '''
  1182. module = AnsibleModule(
  1183. argument_spec=dict(
  1184. debug=dict(default=False, type='bool'),
  1185. kubeconfig=dict(default='/etc/origin/master/admin.kubeconfig', type='str'),
  1186. node=dict(default=None, type='list'),
  1187. selector=dict(default=None, type='str'),
  1188. pod_selector=dict(default=None, type='str'),
  1189. schedulable=dict(default=None, type='bool'),
  1190. list_pods=dict(default=False, type='bool'),
  1191. evacuate=dict(default=False, type='bool'),
  1192. dry_run=dict(default=False, type='bool'),
  1193. force=dict(default=False, type='bool'),
  1194. grace_period=dict(default=None, type='int'),
  1195. ),
  1196. mutually_exclusive=[["selector", "node"], ['evacuate', 'list_pods'], ['list_pods', 'schedulable']],
  1197. required_one_of=[["node", "selector"]],
  1198. supports_check_mode=True,
  1199. )
  1200. results = ManageNode.run_ansible(module.params, module.check_mode)
  1201. if 'failed' in results:
  1202. module.fail_json(**results)
  1203. module.exit_json(**results)
  1204. if __name__ == "__main__":
  1205. main()
  1206. # -*- -*- -*- End included fragment: ansible/oadm_manage_node.py -*- -*- -*-