oadm_manage_node.py 53 KB

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