oadm_manage_node.py 51 KB

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