oadm_manage_node.py 50 KB

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