oc_adm_manage_node.py 56 KB

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