oadm_manage_node.py 55 KB

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