oadm_manage_node.py 53 KB

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