oadm_manage_node.py 52 KB

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