oadm_manage_node.py 55 KB

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