oadm_manage_node.py 52 KB

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