oadm_manage_node.py 53 KB

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