oadm_manage_node.py 54 KB

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