oadm_manage_node.py 52 KB

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