oc_volume.py 67 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067
  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/volume -*- -*- -*-
  49. DOCUMENTATION = '''
  50. ---
  51. module: oc_volume
  52. short_description: Create, modify, and idempotently manage openshift volumes.
  53. description:
  54. - Modify openshift volumes programmatically.
  55. options:
  56. state:
  57. description:
  58. - State controls the action that will be taken with resource
  59. - 'present' will create or update and object to the desired state
  60. - 'absent' will ensure volumes are removed
  61. - 'list' will read the volumes
  62. default: present
  63. choices: ["present", "absent", "list"]
  64. aliases: []
  65. kubeconfig:
  66. description:
  67. - The path for the kubeconfig file to use for authentication
  68. required: false
  69. default: /etc/origin/master/admin.kubeconfig
  70. aliases: []
  71. debug:
  72. description:
  73. - Turn on debug output.
  74. required: false
  75. default: False
  76. aliases: []
  77. namespace:
  78. description:
  79. - The name of the namespace where the object lives
  80. required: false
  81. default: default
  82. aliases: []
  83. kind:
  84. description:
  85. - The kind of object that can be managed.
  86. default: dc
  87. choices:
  88. - dc
  89. - rc
  90. - pods
  91. aliases: []
  92. mount_type:
  93. description:
  94. - The type of volume to be used
  95. required: false
  96. default: None
  97. choices:
  98. - emptydir
  99. - hostpath
  100. - secret
  101. - pvc
  102. - configmap
  103. aliases: []
  104. mount_path:
  105. description:
  106. - The path to where the mount will be attached
  107. required: false
  108. default: None
  109. aliases: []
  110. secret_name:
  111. description:
  112. - The name of the secret. Used when mount_type is secret.
  113. required: false
  114. default: None
  115. aliases: []
  116. claim_size:
  117. description:
  118. - The size in GB of the pv claim. e.g. 100G
  119. required: false
  120. default: None
  121. aliases: []
  122. claim_name:
  123. description:
  124. - The name of the pv claim
  125. required: false
  126. default: None
  127. aliases: []
  128. configmap_name:
  129. description:
  130. - The name of the configmap
  131. required: false
  132. default: None
  133. aliases: []
  134. author:
  135. - "Kenny Woodson <kwoodson@redhat.com>"
  136. extends_documentation_fragment: []
  137. '''
  138. EXAMPLES = '''
  139. - name: attach storage volumes to deploymentconfig
  140. oc_volume:
  141. namespace: logging
  142. kind: dc
  143. name: name_of_the_dc
  144. mount_type: pvc
  145. claim_name: loggingclaim
  146. claim_size: 100G
  147. vol_name: logging-storage
  148. run_once: true
  149. '''
  150. # -*- -*- -*- End included fragment: doc/volume -*- -*- -*-
  151. # -*- -*- -*- Begin included fragment: ../../lib_utils/src/class/yedit.py -*- -*- -*-
  152. class YeditException(Exception):
  153. ''' Exception class for Yedit '''
  154. pass
  155. # pylint: disable=too-many-public-methods
  156. class Yedit(object):
  157. ''' Class to modify yaml files '''
  158. re_valid_key = r"(((\[-?\d+\])|([0-9a-zA-Z%s/_-]+)).?)+$"
  159. re_key = r"(?:\[(-?\d+)\])|([0-9a-zA-Z%s/_-]+)"
  160. com_sep = set(['.', '#', '|', ':'])
  161. # pylint: disable=too-many-arguments
  162. def __init__(self,
  163. filename=None,
  164. content=None,
  165. content_type='yaml',
  166. separator='.',
  167. backup=False):
  168. self.content = content
  169. self._separator = separator
  170. self.filename = filename
  171. self.__yaml_dict = content
  172. self.content_type = content_type
  173. self.backup = backup
  174. self.load(content_type=self.content_type)
  175. if self.__yaml_dict is None:
  176. self.__yaml_dict = {}
  177. @property
  178. def separator(self):
  179. ''' getter method for separator '''
  180. return self._separator
  181. @separator.setter
  182. def separator(self, inc_sep):
  183. ''' setter method for separator '''
  184. self._separator = inc_sep
  185. @property
  186. def yaml_dict(self):
  187. ''' getter method for yaml_dict '''
  188. return self.__yaml_dict
  189. @yaml_dict.setter
  190. def yaml_dict(self, value):
  191. ''' setter method for yaml_dict '''
  192. self.__yaml_dict = value
  193. @staticmethod
  194. def parse_key(key, sep='.'):
  195. '''parse the key allowing the appropriate separator'''
  196. common_separators = list(Yedit.com_sep - set([sep]))
  197. return re.findall(Yedit.re_key.format(''.join(common_separators)), key)
  198. @staticmethod
  199. def valid_key(key, sep='.'):
  200. '''validate the incoming key'''
  201. common_separators = list(Yedit.com_sep - set([sep]))
  202. if not re.match(Yedit.re_valid_key.format(''.join(common_separators)), key):
  203. return False
  204. return True
  205. @staticmethod
  206. def remove_entry(data, key, sep='.'):
  207. ''' remove data at location key '''
  208. if key == '' and isinstance(data, dict):
  209. data.clear()
  210. return True
  211. elif key == '' and isinstance(data, list):
  212. del data[:]
  213. return True
  214. if not (key and Yedit.valid_key(key, sep)) and \
  215. isinstance(data, (list, dict)):
  216. return None
  217. key_indexes = Yedit.parse_key(key, sep)
  218. for arr_ind, dict_key in key_indexes[:-1]:
  219. if dict_key and isinstance(data, dict):
  220. data = data.get(dict_key)
  221. elif (arr_ind and isinstance(data, list) and
  222. int(arr_ind) <= len(data) - 1):
  223. data = data[int(arr_ind)]
  224. else:
  225. return None
  226. # process last index for remove
  227. # expected list entry
  228. if key_indexes[-1][0]:
  229. if isinstance(data, list) and int(key_indexes[-1][0]) <= len(data) - 1: # noqa: E501
  230. del data[int(key_indexes[-1][0])]
  231. return True
  232. # expected dict entry
  233. elif key_indexes[-1][1]:
  234. if isinstance(data, dict):
  235. del data[key_indexes[-1][1]]
  236. return True
  237. @staticmethod
  238. def add_entry(data, key, item=None, sep='.'):
  239. ''' Get an item from a dictionary with key notation a.b.c
  240. d = {'a': {'b': 'c'}}}
  241. key = a#b
  242. return c
  243. '''
  244. if key == '':
  245. pass
  246. elif (not (key and Yedit.valid_key(key, sep)) and
  247. isinstance(data, (list, dict))):
  248. return None
  249. key_indexes = Yedit.parse_key(key, sep)
  250. for arr_ind, dict_key in key_indexes[:-1]:
  251. if dict_key:
  252. if isinstance(data, dict) and dict_key in data and data[dict_key]: # noqa: E501
  253. data = data[dict_key]
  254. continue
  255. elif data and not isinstance(data, dict):
  256. raise YeditException("Unexpected item type found while going through key " +
  257. "path: {} (at key: {})".format(key, dict_key))
  258. data[dict_key] = {}
  259. data = data[dict_key]
  260. elif (arr_ind and isinstance(data, list) and
  261. int(arr_ind) <= len(data) - 1):
  262. data = data[int(arr_ind)]
  263. else:
  264. raise YeditException("Unexpected item type found while going through key path: {}".format(key))
  265. if key == '':
  266. data = item
  267. # process last index for add
  268. # expected list entry
  269. elif key_indexes[-1][0] and isinstance(data, list) and int(key_indexes[-1][0]) <= len(data) - 1: # noqa: E501
  270. data[int(key_indexes[-1][0])] = item
  271. # expected dict entry
  272. elif key_indexes[-1][1] and isinstance(data, dict):
  273. data[key_indexes[-1][1]] = item
  274. # didn't add/update to an existing list, nor add/update key to a dict
  275. # so we must have been provided some syntax like a.b.c[<int>] = "data" for a
  276. # non-existent array
  277. else:
  278. raise YeditException("Error adding to object at path: {}".format(key))
  279. return data
  280. @staticmethod
  281. def get_entry(data, key, sep='.'):
  282. ''' Get an item from a dictionary with key notation a.b.c
  283. d = {'a': {'b': 'c'}}}
  284. key = a.b
  285. return c
  286. '''
  287. if key == '':
  288. pass
  289. elif (not (key and Yedit.valid_key(key, sep)) and
  290. isinstance(data, (list, dict))):
  291. return None
  292. key_indexes = Yedit.parse_key(key, sep)
  293. for arr_ind, dict_key in key_indexes:
  294. if dict_key and isinstance(data, dict):
  295. data = data.get(dict_key)
  296. elif (arr_ind and isinstance(data, list) and
  297. int(arr_ind) <= len(data) - 1):
  298. data = data[int(arr_ind)]
  299. else:
  300. return None
  301. return data
  302. @staticmethod
  303. def _write(filename, contents):
  304. ''' Actually write the file contents to disk. This helps with mocking. '''
  305. tmp_filename = filename + '.yedit'
  306. with open(tmp_filename, 'w') as yfd:
  307. yfd.write(contents)
  308. os.rename(tmp_filename, filename)
  309. def write(self):
  310. ''' write to file '''
  311. if not self.filename:
  312. raise YeditException('Please specify a filename.')
  313. if self.backup and self.file_exists():
  314. shutil.copy(self.filename, self.filename + '.orig')
  315. # Try to set format attributes if supported
  316. try:
  317. self.yaml_dict.fa.set_block_style()
  318. except AttributeError:
  319. pass
  320. # Try to use RoundTripDumper if supported.
  321. try:
  322. Yedit._write(self.filename, yaml.dump(self.yaml_dict, Dumper=yaml.RoundTripDumper))
  323. except AttributeError:
  324. Yedit._write(self.filename, yaml.safe_dump(self.yaml_dict, default_flow_style=False))
  325. return (True, self.yaml_dict)
  326. def read(self):
  327. ''' read from file '''
  328. # check if it exists
  329. if self.filename is None or not self.file_exists():
  330. return None
  331. contents = None
  332. with open(self.filename) as yfd:
  333. contents = yfd.read()
  334. return contents
  335. def file_exists(self):
  336. ''' return whether file exists '''
  337. if os.path.exists(self.filename):
  338. return True
  339. return False
  340. def load(self, content_type='yaml'):
  341. ''' return yaml file '''
  342. contents = self.read()
  343. if not contents and not self.content:
  344. return None
  345. if self.content:
  346. if isinstance(self.content, dict):
  347. self.yaml_dict = self.content
  348. return self.yaml_dict
  349. elif isinstance(self.content, str):
  350. contents = self.content
  351. # check if it is yaml
  352. try:
  353. if content_type == 'yaml' and contents:
  354. # Try to set format attributes if supported
  355. try:
  356. self.yaml_dict.fa.set_block_style()
  357. except AttributeError:
  358. pass
  359. # Try to use RoundTripLoader if supported.
  360. try:
  361. self.yaml_dict = yaml.safe_load(contents, yaml.RoundTripLoader)
  362. except AttributeError:
  363. self.yaml_dict = yaml.safe_load(contents)
  364. # Try to set format attributes if supported
  365. try:
  366. self.yaml_dict.fa.set_block_style()
  367. except AttributeError:
  368. pass
  369. elif content_type == 'json' and contents:
  370. self.yaml_dict = json.loads(contents)
  371. except yaml.YAMLError as err:
  372. # Error loading yaml or json
  373. raise YeditException('Problem with loading yaml file. {}'.format(err))
  374. return self.yaml_dict
  375. def get(self, key):
  376. ''' get a specified key'''
  377. try:
  378. entry = Yedit.get_entry(self.yaml_dict, key, self.separator)
  379. except KeyError:
  380. entry = None
  381. return entry
  382. def pop(self, path, key_or_item):
  383. ''' remove a key, value pair from a dict or an item for a list'''
  384. try:
  385. entry = Yedit.get_entry(self.yaml_dict, path, self.separator)
  386. except KeyError:
  387. entry = None
  388. if entry is None:
  389. return (False, self.yaml_dict)
  390. if isinstance(entry, dict):
  391. # AUDIT:maybe-no-member makes sense due to fuzzy types
  392. # pylint: disable=maybe-no-member
  393. if key_or_item in entry:
  394. entry.pop(key_or_item)
  395. return (True, self.yaml_dict)
  396. return (False, self.yaml_dict)
  397. elif isinstance(entry, list):
  398. # AUDIT:maybe-no-member makes sense due to fuzzy types
  399. # pylint: disable=maybe-no-member
  400. ind = None
  401. try:
  402. ind = entry.index(key_or_item)
  403. except ValueError:
  404. return (False, self.yaml_dict)
  405. entry.pop(ind)
  406. return (True, self.yaml_dict)
  407. return (False, self.yaml_dict)
  408. def delete(self, path):
  409. ''' remove path from a dict'''
  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. return (False, self.yaml_dict)
  416. result = Yedit.remove_entry(self.yaml_dict, path, self.separator)
  417. if not result:
  418. return (False, self.yaml_dict)
  419. return (True, self.yaml_dict)
  420. def exists(self, path, value):
  421. ''' check if value exists at path'''
  422. try:
  423. entry = Yedit.get_entry(self.yaml_dict, path, self.separator)
  424. except KeyError:
  425. entry = None
  426. if isinstance(entry, list):
  427. if value in entry:
  428. return True
  429. return False
  430. elif isinstance(entry, dict):
  431. if isinstance(value, dict):
  432. rval = False
  433. for key, val in value.items():
  434. if entry[key] != val:
  435. rval = False
  436. break
  437. else:
  438. rval = True
  439. return rval
  440. return value in entry
  441. return entry == value
  442. def append(self, path, value):
  443. '''append value to a list'''
  444. try:
  445. entry = Yedit.get_entry(self.yaml_dict, path, self.separator)
  446. except KeyError:
  447. entry = None
  448. if entry is None:
  449. self.put(path, [])
  450. entry = Yedit.get_entry(self.yaml_dict, path, self.separator)
  451. if not isinstance(entry, list):
  452. return (False, self.yaml_dict)
  453. # AUDIT:maybe-no-member makes sense due to loading data from
  454. # a serialized format.
  455. # pylint: disable=maybe-no-member
  456. entry.append(value)
  457. return (True, self.yaml_dict)
  458. # pylint: disable=too-many-arguments
  459. def update(self, path, value, index=None, curr_value=None):
  460. ''' put path, value into a dict '''
  461. try:
  462. entry = Yedit.get_entry(self.yaml_dict, path, self.separator)
  463. except KeyError:
  464. entry = None
  465. if isinstance(entry, dict):
  466. # AUDIT:maybe-no-member makes sense due to fuzzy types
  467. # pylint: disable=maybe-no-member
  468. if not isinstance(value, dict):
  469. raise YeditException('Cannot replace key, value entry in dict with non-dict type. ' +
  470. 'value=[{}] type=[{}]'.format(value, type(value)))
  471. entry.update(value)
  472. return (True, self.yaml_dict)
  473. elif isinstance(entry, list):
  474. # AUDIT:maybe-no-member makes sense due to fuzzy types
  475. # pylint: disable=maybe-no-member
  476. ind = None
  477. if curr_value:
  478. try:
  479. ind = entry.index(curr_value)
  480. except ValueError:
  481. return (False, self.yaml_dict)
  482. elif index is not None:
  483. ind = index
  484. if ind is not None and entry[ind] != value:
  485. entry[ind] = value
  486. return (True, self.yaml_dict)
  487. # see if it exists in the list
  488. try:
  489. ind = entry.index(value)
  490. except ValueError:
  491. # doesn't exist, append it
  492. entry.append(value)
  493. return (True, self.yaml_dict)
  494. # already exists, return
  495. if ind is not None:
  496. return (False, self.yaml_dict)
  497. return (False, self.yaml_dict)
  498. def put(self, path, value):
  499. ''' put path, value into a dict '''
  500. try:
  501. entry = Yedit.get_entry(self.yaml_dict, path, self.separator)
  502. except KeyError:
  503. entry = None
  504. if entry == value:
  505. return (False, self.yaml_dict)
  506. # deepcopy didn't work
  507. # Try to use ruamel.yaml and fallback to pyyaml
  508. try:
  509. tmp_copy = yaml.load(yaml.round_trip_dump(self.yaml_dict,
  510. default_flow_style=False),
  511. yaml.RoundTripLoader)
  512. except AttributeError:
  513. tmp_copy = copy.deepcopy(self.yaml_dict)
  514. # set the format attributes if available
  515. try:
  516. tmp_copy.fa.set_block_style()
  517. except AttributeError:
  518. pass
  519. result = Yedit.add_entry(tmp_copy, path, value, self.separator)
  520. if result is None:
  521. return (False, self.yaml_dict)
  522. # When path equals "" it is a special case.
  523. # "" refers to the root of the document
  524. # Only update the root path (entire document) when its a list or dict
  525. if path == '':
  526. if isinstance(result, list) or isinstance(result, dict):
  527. self.yaml_dict = result
  528. return (True, self.yaml_dict)
  529. return (False, self.yaml_dict)
  530. self.yaml_dict = tmp_copy
  531. return (True, self.yaml_dict)
  532. def create(self, path, value):
  533. ''' create a yaml file '''
  534. if not self.file_exists():
  535. # deepcopy didn't work
  536. # Try to use ruamel.yaml and fallback to pyyaml
  537. try:
  538. tmp_copy = yaml.load(yaml.round_trip_dump(self.yaml_dict,
  539. default_flow_style=False),
  540. yaml.RoundTripLoader)
  541. except AttributeError:
  542. tmp_copy = copy.deepcopy(self.yaml_dict)
  543. # set the format attributes if available
  544. try:
  545. tmp_copy.fa.set_block_style()
  546. except AttributeError:
  547. pass
  548. result = Yedit.add_entry(tmp_copy, path, value, self.separator)
  549. if result is not None:
  550. self.yaml_dict = tmp_copy
  551. return (True, self.yaml_dict)
  552. return (False, self.yaml_dict)
  553. @staticmethod
  554. def get_curr_value(invalue, val_type):
  555. '''return the current value'''
  556. if invalue is None:
  557. return None
  558. curr_value = invalue
  559. if val_type == 'yaml':
  560. curr_value = yaml.load(invalue)
  561. elif val_type == 'json':
  562. curr_value = json.loads(invalue)
  563. return curr_value
  564. @staticmethod
  565. def parse_value(inc_value, vtype=''):
  566. '''determine value type passed'''
  567. true_bools = ['y', 'Y', 'yes', 'Yes', 'YES', 'true', 'True', 'TRUE',
  568. 'on', 'On', 'ON', ]
  569. false_bools = ['n', 'N', 'no', 'No', 'NO', 'false', 'False', 'FALSE',
  570. 'off', 'Off', 'OFF']
  571. # It came in as a string but you didn't specify value_type as string
  572. # we will convert to bool if it matches any of the above cases
  573. if isinstance(inc_value, str) and 'bool' in vtype:
  574. if inc_value not in true_bools and inc_value not in false_bools:
  575. raise YeditException('Not a boolean type. str=[{}] vtype=[{}]'.format(inc_value, vtype))
  576. elif isinstance(inc_value, bool) and 'str' in vtype:
  577. inc_value = str(inc_value)
  578. # There is a special case where '' will turn into None after yaml loading it so skip
  579. if isinstance(inc_value, str) and inc_value == '':
  580. pass
  581. # If vtype is not str then go ahead and attempt to yaml load it.
  582. elif isinstance(inc_value, str) and 'str' not in vtype:
  583. try:
  584. inc_value = yaml.safe_load(inc_value)
  585. except Exception:
  586. raise YeditException('Could not determine type of incoming value. ' +
  587. 'value=[{}] vtype=[{}]'.format(type(inc_value), vtype))
  588. return inc_value
  589. @staticmethod
  590. def process_edits(edits, yamlfile):
  591. '''run through a list of edits and process them one-by-one'''
  592. results = []
  593. for edit in edits:
  594. value = Yedit.parse_value(edit['value'], edit.get('value_type', ''))
  595. if edit.get('action') == 'update':
  596. # pylint: disable=line-too-long
  597. curr_value = Yedit.get_curr_value(
  598. Yedit.parse_value(edit.get('curr_value')),
  599. edit.get('curr_value_format'))
  600. rval = yamlfile.update(edit['key'],
  601. value,
  602. edit.get('index'),
  603. curr_value)
  604. elif edit.get('action') == 'append':
  605. rval = yamlfile.append(edit['key'], value)
  606. else:
  607. rval = yamlfile.put(edit['key'], value)
  608. if rval[0]:
  609. results.append({'key': edit['key'], 'edit': rval[1]})
  610. return {'changed': len(results) > 0, 'results': results}
  611. # pylint: disable=too-many-return-statements,too-many-branches
  612. @staticmethod
  613. def run_ansible(params):
  614. '''perform the idempotent crud operations'''
  615. yamlfile = Yedit(filename=params['src'],
  616. backup=params['backup'],
  617. separator=params['separator'])
  618. state = params['state']
  619. if params['src']:
  620. rval = yamlfile.load()
  621. if yamlfile.yaml_dict is None and state != 'present':
  622. return {'failed': True,
  623. 'msg': 'Error opening file [{}]. Verify that the '.format(params['src']) +
  624. 'file exists, that it is has correct permissions, and is valid yaml.'}
  625. if state == 'list':
  626. if params['content']:
  627. content = Yedit.parse_value(params['content'], params['content_type'])
  628. yamlfile.yaml_dict = content
  629. if params['key']:
  630. rval = yamlfile.get(params['key']) or {}
  631. return {'changed': False, 'result': rval, 'state': state}
  632. elif state == 'absent':
  633. if params['content']:
  634. content = Yedit.parse_value(params['content'], params['content_type'])
  635. yamlfile.yaml_dict = content
  636. if params['update']:
  637. rval = yamlfile.pop(params['key'], params['value'])
  638. else:
  639. rval = yamlfile.delete(params['key'])
  640. if rval[0] and params['src']:
  641. yamlfile.write()
  642. return {'changed': rval[0], 'result': rval[1], 'state': state}
  643. elif state == 'present':
  644. # check if content is different than what is in the file
  645. if params['content']:
  646. content = Yedit.parse_value(params['content'], params['content_type'])
  647. # We had no edits to make and the contents are the same
  648. if yamlfile.yaml_dict == content and \
  649. params['value'] is None:
  650. return {'changed': False, 'result': yamlfile.yaml_dict, 'state': state}
  651. yamlfile.yaml_dict = content
  652. # If we were passed a key, value then
  653. # we enapsulate it in a list and process it
  654. # Key, Value passed to the module : Converted to Edits list #
  655. edits = []
  656. _edit = {}
  657. if params['value'] is not None:
  658. _edit['value'] = params['value']
  659. _edit['value_type'] = params['value_type']
  660. _edit['key'] = params['key']
  661. if params['update']:
  662. _edit['action'] = 'update'
  663. _edit['curr_value'] = params['curr_value']
  664. _edit['curr_value_format'] = params['curr_value_format']
  665. _edit['index'] = params['index']
  666. elif params['append']:
  667. _edit['action'] = 'append'
  668. edits.append(_edit)
  669. elif params['edits'] is not None:
  670. edits = params['edits']
  671. if edits:
  672. results = Yedit.process_edits(edits, yamlfile)
  673. # if there were changes and a src provided to us we need to write
  674. if results['changed'] and params['src']:
  675. yamlfile.write()
  676. return {'changed': results['changed'], 'result': results['results'], 'state': state}
  677. # no edits to make
  678. if params['src']:
  679. # pylint: disable=redefined-variable-type
  680. rval = yamlfile.write()
  681. return {'changed': rval[0],
  682. 'result': rval[1],
  683. 'state': state}
  684. # We were passed content but no src, key or value, or edits. Return contents in memory
  685. return {'changed': False, 'result': yamlfile.yaml_dict, 'state': state}
  686. return {'failed': True, 'msg': 'Unkown state passed'}
  687. # -*- -*- -*- End included fragment: ../../lib_utils/src/class/yedit.py -*- -*- -*-
  688. # -*- -*- -*- Begin included fragment: lib/base.py -*- -*- -*-
  689. # pylint: disable=too-many-lines
  690. # noqa: E301,E302,E303,T001
  691. class OpenShiftCLIError(Exception):
  692. '''Exception class for openshiftcli'''
  693. pass
  694. ADDITIONAL_PATH_LOOKUPS = ['/usr/local/bin', os.path.expanduser('~/bin')]
  695. def locate_oc_binary():
  696. ''' Find and return oc binary file '''
  697. # https://github.com/openshift/openshift-ansible/issues/3410
  698. # oc can be in /usr/local/bin in some cases, but that may not
  699. # be in $PATH due to ansible/sudo
  700. paths = os.environ.get("PATH", os.defpath).split(os.pathsep) + ADDITIONAL_PATH_LOOKUPS
  701. oc_binary = 'oc'
  702. # Use shutil.which if it is available, otherwise fallback to a naive path search
  703. try:
  704. which_result = shutil.which(oc_binary, path=os.pathsep.join(paths))
  705. if which_result is not None:
  706. oc_binary = which_result
  707. except AttributeError:
  708. for path in paths:
  709. if os.path.exists(os.path.join(path, oc_binary)):
  710. oc_binary = os.path.join(path, oc_binary)
  711. break
  712. return oc_binary
  713. # pylint: disable=too-few-public-methods
  714. class OpenShiftCLI(object):
  715. ''' Class to wrap the command line tools '''
  716. def __init__(self,
  717. namespace,
  718. kubeconfig='/etc/origin/master/admin.kubeconfig',
  719. verbose=False,
  720. all_namespaces=False):
  721. ''' Constructor for OpenshiftCLI '''
  722. self.namespace = namespace
  723. self.verbose = verbose
  724. self.kubeconfig = Utils.create_tmpfile_copy(kubeconfig)
  725. self.all_namespaces = all_namespaces
  726. self.oc_binary = locate_oc_binary()
  727. # Pylint allows only 5 arguments to be passed.
  728. # pylint: disable=too-many-arguments
  729. def _replace_content(self, resource, rname, content, force=False, sep='.'):
  730. ''' replace the current object with the content '''
  731. res = self._get(resource, rname)
  732. if not res['results']:
  733. return res
  734. fname = Utils.create_tmpfile(rname + '-')
  735. yed = Yedit(fname, res['results'][0], separator=sep)
  736. changes = []
  737. for key, value in content.items():
  738. changes.append(yed.put(key, value))
  739. if any([change[0] for change in changes]):
  740. yed.write()
  741. atexit.register(Utils.cleanup, [fname])
  742. return self._replace(fname, force)
  743. return {'returncode': 0, 'updated': False}
  744. def _replace(self, fname, force=False):
  745. '''replace the current object with oc replace'''
  746. cmd = ['replace', '-f', fname]
  747. if force:
  748. cmd.append('--force')
  749. return self.openshift_cmd(cmd)
  750. def _create_from_content(self, rname, content):
  751. '''create a temporary file and then call oc create on it'''
  752. fname = Utils.create_tmpfile(rname + '-')
  753. yed = Yedit(fname, content=content)
  754. yed.write()
  755. atexit.register(Utils.cleanup, [fname])
  756. return self._create(fname)
  757. def _create(self, fname):
  758. '''call oc create on a filename'''
  759. return self.openshift_cmd(['create', '-f', fname])
  760. def _delete(self, resource, rname, selector=None):
  761. '''call oc delete on a resource'''
  762. cmd = ['delete', resource, rname]
  763. if selector:
  764. cmd.append('--selector=%s' % selector)
  765. return self.openshift_cmd(cmd)
  766. def _process(self, template_name, create=False, params=None, template_data=None): # noqa: E501
  767. '''process a template
  768. template_name: the name of the template to process
  769. create: whether to send to oc create after processing
  770. params: the parameters for the template
  771. template_data: the incoming template's data; instead of a file
  772. '''
  773. cmd = ['process']
  774. if template_data:
  775. cmd.extend(['-f', '-'])
  776. else:
  777. cmd.append(template_name)
  778. if params:
  779. param_str = ["%s=%s" % (key, value) for key, value in params.items()]
  780. cmd.append('-v')
  781. cmd.extend(param_str)
  782. results = self.openshift_cmd(cmd, output=True, input_data=template_data)
  783. if results['returncode'] != 0 or not create:
  784. return results
  785. fname = Utils.create_tmpfile(template_name + '-')
  786. yed = Yedit(fname, results['results'])
  787. yed.write()
  788. atexit.register(Utils.cleanup, [fname])
  789. return self.openshift_cmd(['create', '-f', fname])
  790. def _get(self, resource, rname=None, selector=None):
  791. '''return a resource by name '''
  792. cmd = ['get', resource]
  793. if selector:
  794. cmd.append('--selector=%s' % selector)
  795. elif rname:
  796. cmd.append(rname)
  797. cmd.extend(['-o', 'json'])
  798. rval = self.openshift_cmd(cmd, output=True)
  799. # Ensure results are retuned in an array
  800. if 'items' in rval:
  801. rval['results'] = rval['items']
  802. elif not isinstance(rval['results'], list):
  803. rval['results'] = [rval['results']]
  804. return rval
  805. def _schedulable(self, node=None, selector=None, schedulable=True):
  806. ''' perform oadm manage-node scheduable '''
  807. cmd = ['manage-node']
  808. if node:
  809. cmd.extend(node)
  810. else:
  811. cmd.append('--selector=%s' % selector)
  812. cmd.append('--schedulable=%s' % schedulable)
  813. return self.openshift_cmd(cmd, oadm=True, output=True, output_type='raw') # noqa: E501
  814. def _list_pods(self, node=None, selector=None, pod_selector=None):
  815. ''' perform oadm list pods
  816. node: the node in which to list pods
  817. selector: the label selector filter if provided
  818. pod_selector: the pod selector filter if provided
  819. '''
  820. cmd = ['manage-node']
  821. if node:
  822. cmd.extend(node)
  823. else:
  824. cmd.append('--selector=%s' % selector)
  825. if pod_selector:
  826. cmd.append('--pod-selector=%s' % pod_selector)
  827. cmd.extend(['--list-pods', '-o', 'json'])
  828. return self.openshift_cmd(cmd, oadm=True, output=True, output_type='raw')
  829. # pylint: disable=too-many-arguments
  830. def _evacuate(self, node=None, selector=None, pod_selector=None, dry_run=False, grace_period=None, force=False):
  831. ''' perform oadm manage-node evacuate '''
  832. cmd = ['manage-node']
  833. if node:
  834. cmd.extend(node)
  835. else:
  836. cmd.append('--selector=%s' % selector)
  837. if dry_run:
  838. cmd.append('--dry-run')
  839. if pod_selector:
  840. cmd.append('--pod-selector=%s' % pod_selector)
  841. if grace_period:
  842. cmd.append('--grace-period=%s' % int(grace_period))
  843. if force:
  844. cmd.append('--force')
  845. cmd.append('--evacuate')
  846. return self.openshift_cmd(cmd, oadm=True, output=True, output_type='raw')
  847. def _version(self):
  848. ''' return the openshift version'''
  849. return self.openshift_cmd(['version'], output=True, output_type='raw')
  850. def _import_image(self, url=None, name=None, tag=None):
  851. ''' perform image import '''
  852. cmd = ['import-image']
  853. image = '{0}'.format(name)
  854. if tag:
  855. image += ':{0}'.format(tag)
  856. cmd.append(image)
  857. if url:
  858. cmd.append('--from={0}/{1}'.format(url, image))
  859. cmd.append('-n{0}'.format(self.namespace))
  860. cmd.append('--confirm')
  861. return self.openshift_cmd(cmd)
  862. def _run(self, cmds, input_data):
  863. ''' Actually executes the command. This makes mocking easier. '''
  864. curr_env = os.environ.copy()
  865. curr_env.update({'KUBECONFIG': self.kubeconfig})
  866. proc = subprocess.Popen(cmds,
  867. stdin=subprocess.PIPE,
  868. stdout=subprocess.PIPE,
  869. stderr=subprocess.PIPE,
  870. env=curr_env)
  871. stdout, stderr = proc.communicate(input_data)
  872. return proc.returncode, stdout.decode(), stderr.decode()
  873. # pylint: disable=too-many-arguments,too-many-branches
  874. def openshift_cmd(self, cmd, oadm=False, output=False, output_type='json', input_data=None):
  875. '''Base command for oc '''
  876. cmds = [self.oc_binary]
  877. if oadm:
  878. cmds.append('adm')
  879. cmds.extend(cmd)
  880. if self.all_namespaces:
  881. cmds.extend(['--all-namespaces'])
  882. elif self.namespace is not None and self.namespace.lower() not in ['none', 'emtpy']: # E501
  883. cmds.extend(['-n', self.namespace])
  884. rval = {}
  885. results = ''
  886. err = None
  887. if self.verbose:
  888. print(' '.join(cmds))
  889. try:
  890. returncode, stdout, stderr = self._run(cmds, input_data)
  891. except OSError as ex:
  892. returncode, stdout, stderr = 1, '', 'Failed to execute {}: {}'.format(subprocess.list2cmdline(cmds), ex)
  893. rval = {"returncode": returncode,
  894. "results": results,
  895. "cmd": ' '.join(cmds)}
  896. if returncode == 0:
  897. if output:
  898. if output_type == 'json':
  899. try:
  900. rval['results'] = json.loads(stdout)
  901. except ValueError as verr:
  902. if "No JSON object could be decoded" in verr.args:
  903. err = verr.args
  904. elif output_type == 'raw':
  905. rval['results'] = stdout
  906. if self.verbose:
  907. print("STDOUT: {0}".format(stdout))
  908. print("STDERR: {0}".format(stderr))
  909. if err:
  910. rval.update({"err": err,
  911. "stderr": stderr,
  912. "stdout": stdout,
  913. "cmd": cmds})
  914. else:
  915. rval.update({"stderr": stderr,
  916. "stdout": stdout,
  917. "results": {}})
  918. return rval
  919. class Utils(object):
  920. ''' utilities for openshiftcli modules '''
  921. @staticmethod
  922. def _write(filename, contents):
  923. ''' Actually write the file contents to disk. This helps with mocking. '''
  924. with open(filename, 'w') as sfd:
  925. sfd.write(contents)
  926. @staticmethod
  927. def create_tmp_file_from_contents(rname, data, ftype='yaml'):
  928. ''' create a file in tmp with name and contents'''
  929. tmp = Utils.create_tmpfile(prefix=rname)
  930. if ftype == 'yaml':
  931. # AUDIT:no-member makes sense here due to ruamel.YAML/PyYAML usage
  932. # pylint: disable=no-member
  933. if hasattr(yaml, 'RoundTripDumper'):
  934. Utils._write(tmp, yaml.dump(data, Dumper=yaml.RoundTripDumper))
  935. else:
  936. Utils._write(tmp, yaml.safe_dump(data, default_flow_style=False))
  937. elif ftype == 'json':
  938. Utils._write(tmp, json.dumps(data))
  939. else:
  940. Utils._write(tmp, data)
  941. # Register cleanup when module is done
  942. atexit.register(Utils.cleanup, [tmp])
  943. return tmp
  944. @staticmethod
  945. def create_tmpfile_copy(inc_file):
  946. '''create a temporary copy of a file'''
  947. tmpfile = Utils.create_tmpfile('lib_openshift-')
  948. Utils._write(tmpfile, open(inc_file).read())
  949. # Cleanup the tmpfile
  950. atexit.register(Utils.cleanup, [tmpfile])
  951. return tmpfile
  952. @staticmethod
  953. def create_tmpfile(prefix='tmp'):
  954. ''' Generates and returns a temporary file name '''
  955. with tempfile.NamedTemporaryFile(prefix=prefix, delete=False) as tmp:
  956. return tmp.name
  957. @staticmethod
  958. def create_tmp_files_from_contents(content, content_type=None):
  959. '''Turn an array of dict: filename, content into a files array'''
  960. if not isinstance(content, list):
  961. content = [content]
  962. files = []
  963. for item in content:
  964. path = Utils.create_tmp_file_from_contents(item['path'] + '-',
  965. item['data'],
  966. ftype=content_type)
  967. files.append({'name': os.path.basename(item['path']),
  968. 'path': path})
  969. return files
  970. @staticmethod
  971. def cleanup(files):
  972. '''Clean up on exit '''
  973. for sfile in files:
  974. if os.path.exists(sfile):
  975. if os.path.isdir(sfile):
  976. shutil.rmtree(sfile)
  977. elif os.path.isfile(sfile):
  978. os.remove(sfile)
  979. @staticmethod
  980. def exists(results, _name):
  981. ''' Check to see if the results include the name '''
  982. if not results:
  983. return False
  984. if Utils.find_result(results, _name):
  985. return True
  986. return False
  987. @staticmethod
  988. def find_result(results, _name):
  989. ''' Find the specified result by name'''
  990. rval = None
  991. for result in results:
  992. if 'metadata' in result and result['metadata']['name'] == _name:
  993. rval = result
  994. break
  995. return rval
  996. @staticmethod
  997. def get_resource_file(sfile, sfile_type='yaml'):
  998. ''' return the service file '''
  999. contents = None
  1000. with open(sfile) as sfd:
  1001. contents = sfd.read()
  1002. if sfile_type == 'yaml':
  1003. # AUDIT:no-member makes sense here due to ruamel.YAML/PyYAML usage
  1004. # pylint: disable=no-member
  1005. if hasattr(yaml, 'RoundTripLoader'):
  1006. contents = yaml.load(contents, yaml.RoundTripLoader)
  1007. else:
  1008. contents = yaml.safe_load(contents)
  1009. elif sfile_type == 'json':
  1010. contents = json.loads(contents)
  1011. return contents
  1012. @staticmethod
  1013. def filter_versions(stdout):
  1014. ''' filter the oc version output '''
  1015. version_dict = {}
  1016. version_search = ['oc', 'openshift', 'kubernetes']
  1017. for line in stdout.strip().split('\n'):
  1018. for term in version_search:
  1019. if not line:
  1020. continue
  1021. if line.startswith(term):
  1022. version_dict[term] = line.split()[-1]
  1023. # horrible hack to get openshift version in Openshift 3.2
  1024. # By default "oc version in 3.2 does not return an "openshift" version
  1025. if "openshift" not in version_dict:
  1026. version_dict["openshift"] = version_dict["oc"]
  1027. return version_dict
  1028. @staticmethod
  1029. def add_custom_versions(versions):
  1030. ''' create custom versions strings '''
  1031. versions_dict = {}
  1032. for tech, version in versions.items():
  1033. # clean up "-" from version
  1034. if "-" in version:
  1035. version = version.split("-")[0]
  1036. if version.startswith('v'):
  1037. versions_dict[tech + '_numeric'] = version[1:].split('+')[0]
  1038. # "v3.3.0.33" is what we have, we want "3.3"
  1039. versions_dict[tech + '_short'] = version[1:4]
  1040. return versions_dict
  1041. @staticmethod
  1042. def openshift_installed():
  1043. ''' check if openshift is installed '''
  1044. import yum
  1045. yum_base = yum.YumBase()
  1046. if yum_base.rpmdb.searchNevra(name='atomic-openshift'):
  1047. return True
  1048. return False
  1049. # Disabling too-many-branches. This is a yaml dictionary comparison function
  1050. # pylint: disable=too-many-branches,too-many-return-statements,too-many-statements
  1051. @staticmethod
  1052. def check_def_equal(user_def, result_def, skip_keys=None, debug=False):
  1053. ''' Given a user defined definition, compare it with the results given back by our query. '''
  1054. # Currently these values are autogenerated and we do not need to check them
  1055. skip = ['metadata', 'status']
  1056. if skip_keys:
  1057. skip.extend(skip_keys)
  1058. for key, value in result_def.items():
  1059. if key in skip:
  1060. continue
  1061. # Both are lists
  1062. if isinstance(value, list):
  1063. if key not in user_def:
  1064. if debug:
  1065. print('User data does not have key [%s]' % key)
  1066. print('User data: %s' % user_def)
  1067. return False
  1068. if not isinstance(user_def[key], list):
  1069. if debug:
  1070. print('user_def[key] is not a list key=[%s] user_def[key]=%s' % (key, user_def[key]))
  1071. return False
  1072. if len(user_def[key]) != len(value):
  1073. if debug:
  1074. print("List lengths are not equal.")
  1075. print("key=[%s]: user_def[%s] != value[%s]" % (key, len(user_def[key]), len(value)))
  1076. print("user_def: %s" % user_def[key])
  1077. print("value: %s" % value)
  1078. return False
  1079. for values in zip(user_def[key], value):
  1080. if isinstance(values[0], dict) and isinstance(values[1], dict):
  1081. if debug:
  1082. print('sending list - list')
  1083. print(type(values[0]))
  1084. print(type(values[1]))
  1085. result = Utils.check_def_equal(values[0], values[1], skip_keys=skip_keys, debug=debug)
  1086. if not result:
  1087. print('list compare returned false')
  1088. return False
  1089. elif value != user_def[key]:
  1090. if debug:
  1091. print('value should be identical')
  1092. print(user_def[key])
  1093. print(value)
  1094. return False
  1095. # recurse on a dictionary
  1096. elif isinstance(value, dict):
  1097. if key not in user_def:
  1098. if debug:
  1099. print("user_def does not have key [%s]" % key)
  1100. return False
  1101. if not isinstance(user_def[key], dict):
  1102. if debug:
  1103. print("dict returned false: not instance of dict")
  1104. return False
  1105. # before passing ensure keys match
  1106. api_values = set(value.keys()) - set(skip)
  1107. user_values = set(user_def[key].keys()) - set(skip)
  1108. if api_values != user_values:
  1109. if debug:
  1110. print("keys are not equal in dict")
  1111. print(user_values)
  1112. print(api_values)
  1113. return False
  1114. result = Utils.check_def_equal(user_def[key], value, skip_keys=skip_keys, debug=debug)
  1115. if not result:
  1116. if debug:
  1117. print("dict returned false")
  1118. print(result)
  1119. return False
  1120. # Verify each key, value pair is the same
  1121. else:
  1122. if key not in user_def or value != user_def[key]:
  1123. if debug:
  1124. print("value not equal; user_def does not have key")
  1125. print(key)
  1126. print(value)
  1127. if key in user_def:
  1128. print(user_def[key])
  1129. return False
  1130. if debug:
  1131. print('returning true')
  1132. return True
  1133. class OpenShiftCLIConfig(object):
  1134. '''Generic Config'''
  1135. def __init__(self, rname, namespace, kubeconfig, options):
  1136. self.kubeconfig = kubeconfig
  1137. self.name = rname
  1138. self.namespace = namespace
  1139. self._options = options
  1140. @property
  1141. def config_options(self):
  1142. ''' return config options '''
  1143. return self._options
  1144. def to_option_list(self):
  1145. '''return all options as a string'''
  1146. return self.stringify()
  1147. def stringify(self):
  1148. ''' return the options hash as cli params in a string '''
  1149. rval = []
  1150. for key in sorted(self.config_options.keys()):
  1151. data = self.config_options[key]
  1152. if data['include'] \
  1153. and (data['value'] or isinstance(data['value'], int)):
  1154. rval.append('--{}={}'.format(key.replace('_', '-'), data['value']))
  1155. return rval
  1156. # -*- -*- -*- End included fragment: lib/base.py -*- -*- -*-
  1157. # -*- -*- -*- Begin included fragment: lib/deploymentconfig.py -*- -*- -*-
  1158. # pylint: disable=too-many-public-methods
  1159. class DeploymentConfig(Yedit):
  1160. ''' Class to model an openshift DeploymentConfig'''
  1161. default_deployment_config = '''
  1162. apiVersion: v1
  1163. kind: DeploymentConfig
  1164. metadata:
  1165. name: default_dc
  1166. namespace: default
  1167. spec:
  1168. replicas: 0
  1169. selector:
  1170. default_dc: default_dc
  1171. strategy:
  1172. resources: {}
  1173. rollingParams:
  1174. intervalSeconds: 1
  1175. maxSurge: 0
  1176. maxUnavailable: 25%
  1177. timeoutSeconds: 600
  1178. updatePercent: -25
  1179. updatePeriodSeconds: 1
  1180. type: Rolling
  1181. template:
  1182. metadata:
  1183. spec:
  1184. containers:
  1185. - env:
  1186. - name: default
  1187. value: default
  1188. image: default
  1189. imagePullPolicy: IfNotPresent
  1190. name: default_dc
  1191. ports:
  1192. - containerPort: 8000
  1193. hostPort: 8000
  1194. protocol: TCP
  1195. name: default_port
  1196. resources: {}
  1197. terminationMessagePath: /dev/termination-log
  1198. dnsPolicy: ClusterFirst
  1199. hostNetwork: true
  1200. nodeSelector:
  1201. type: compute
  1202. restartPolicy: Always
  1203. securityContext: {}
  1204. serviceAccount: default
  1205. serviceAccountName: default
  1206. terminationGracePeriodSeconds: 30
  1207. triggers:
  1208. - type: ConfigChange
  1209. '''
  1210. replicas_path = "spec.replicas"
  1211. env_path = "spec.template.spec.containers[0].env"
  1212. volumes_path = "spec.template.spec.volumes"
  1213. container_path = "spec.template.spec.containers"
  1214. volume_mounts_path = "spec.template.spec.containers[0].volumeMounts"
  1215. def __init__(self, content=None):
  1216. ''' Constructor for deploymentconfig '''
  1217. if not content:
  1218. content = DeploymentConfig.default_deployment_config
  1219. super(DeploymentConfig, self).__init__(content=content)
  1220. def add_env_value(self, key, value):
  1221. ''' add key, value pair to env array '''
  1222. rval = False
  1223. env = self.get_env_vars()
  1224. if env:
  1225. env.append({'name': key, 'value': value})
  1226. rval = True
  1227. else:
  1228. result = self.put(DeploymentConfig.env_path, {'name': key, 'value': value})
  1229. rval = result[0]
  1230. return rval
  1231. def exists_env_value(self, key, value):
  1232. ''' return whether a key, value pair exists '''
  1233. results = self.get_env_vars()
  1234. if not results:
  1235. return False
  1236. for result in results:
  1237. if result['name'] == key and result['value'] == value:
  1238. return True
  1239. return False
  1240. def exists_env_key(self, key):
  1241. ''' return whether a key, value pair exists '''
  1242. results = self.get_env_vars()
  1243. if not results:
  1244. return False
  1245. for result in results:
  1246. if result['name'] == key:
  1247. return True
  1248. return False
  1249. def get_env_var(self, key):
  1250. '''return a environment variables '''
  1251. results = self.get(DeploymentConfig.env_path) or []
  1252. if not results:
  1253. return None
  1254. for env_var in results:
  1255. if env_var['name'] == key:
  1256. return env_var
  1257. return None
  1258. def get_env_vars(self):
  1259. '''return a environment variables '''
  1260. return self.get(DeploymentConfig.env_path) or []
  1261. def delete_env_var(self, keys):
  1262. '''delete a list of keys '''
  1263. if not isinstance(keys, list):
  1264. keys = [keys]
  1265. env_vars_array = self.get_env_vars()
  1266. modified = False
  1267. idx = None
  1268. for key in keys:
  1269. for env_idx, env_var in enumerate(env_vars_array):
  1270. if env_var['name'] == key:
  1271. idx = env_idx
  1272. break
  1273. if idx:
  1274. modified = True
  1275. del env_vars_array[idx]
  1276. if modified:
  1277. return True
  1278. return False
  1279. def update_env_var(self, key, value):
  1280. '''place an env in the env var list'''
  1281. env_vars_array = self.get_env_vars()
  1282. idx = None
  1283. for env_idx, env_var in enumerate(env_vars_array):
  1284. if env_var['name'] == key:
  1285. idx = env_idx
  1286. break
  1287. if idx:
  1288. env_vars_array[idx]['value'] = value
  1289. else:
  1290. self.add_env_value(key, value)
  1291. return True
  1292. def exists_volume_mount(self, volume_mount):
  1293. ''' return whether a volume mount exists '''
  1294. exist_volume_mounts = self.get_volume_mounts()
  1295. if not exist_volume_mounts:
  1296. return False
  1297. volume_mount_found = False
  1298. for exist_volume_mount in exist_volume_mounts:
  1299. if exist_volume_mount['name'] == volume_mount['name']:
  1300. volume_mount_found = True
  1301. break
  1302. return volume_mount_found
  1303. def exists_volume(self, volume):
  1304. ''' return whether a volume exists '''
  1305. exist_volumes = self.get_volumes()
  1306. volume_found = False
  1307. for exist_volume in exist_volumes:
  1308. if exist_volume['name'] == volume['name']:
  1309. volume_found = True
  1310. break
  1311. return volume_found
  1312. def find_volume_by_name(self, volume, mounts=False):
  1313. ''' return the index of a volume '''
  1314. volumes = []
  1315. if mounts:
  1316. volumes = self.get_volume_mounts()
  1317. else:
  1318. volumes = self.get_volumes()
  1319. for exist_volume in volumes:
  1320. if exist_volume['name'] == volume['name']:
  1321. return exist_volume
  1322. return None
  1323. def get_replicas(self):
  1324. ''' return replicas setting '''
  1325. return self.get(DeploymentConfig.replicas_path)
  1326. def get_volume_mounts(self):
  1327. '''return volume mount information '''
  1328. return self.get_volumes(mounts=True)
  1329. def get_volumes(self, mounts=False):
  1330. '''return volume mount information '''
  1331. if mounts:
  1332. return self.get(DeploymentConfig.volume_mounts_path) or []
  1333. return self.get(DeploymentConfig.volumes_path) or []
  1334. def delete_volume_by_name(self, volume):
  1335. '''delete a volume '''
  1336. modified = False
  1337. exist_volume_mounts = self.get_volume_mounts()
  1338. exist_volumes = self.get_volumes()
  1339. del_idx = None
  1340. for idx, exist_volume in enumerate(exist_volumes):
  1341. if 'name' in exist_volume and exist_volume['name'] == volume['name']:
  1342. del_idx = idx
  1343. break
  1344. if del_idx != None:
  1345. del exist_volumes[del_idx]
  1346. modified = True
  1347. del_idx = None
  1348. for idx, exist_volume_mount in enumerate(exist_volume_mounts):
  1349. if 'name' in exist_volume_mount and exist_volume_mount['name'] == volume['name']:
  1350. del_idx = idx
  1351. break
  1352. if del_idx != None:
  1353. del exist_volume_mounts[idx]
  1354. modified = True
  1355. return modified
  1356. def add_volume_mount(self, volume_mount):
  1357. ''' add a volume or volume mount to the proper location '''
  1358. exist_volume_mounts = self.get_volume_mounts()
  1359. if not exist_volume_mounts and volume_mount:
  1360. self.put(DeploymentConfig.volume_mounts_path, [volume_mount])
  1361. else:
  1362. exist_volume_mounts.append(volume_mount)
  1363. def add_volume(self, volume):
  1364. ''' add a volume or volume mount to the proper location '''
  1365. exist_volumes = self.get_volumes()
  1366. if not volume:
  1367. return
  1368. if not exist_volumes:
  1369. self.put(DeploymentConfig.volumes_path, [volume])
  1370. else:
  1371. exist_volumes.append(volume)
  1372. def update_replicas(self, replicas):
  1373. ''' update replicas value '''
  1374. self.put(DeploymentConfig.replicas_path, replicas)
  1375. def update_volume(self, volume):
  1376. '''place an env in the env var list'''
  1377. exist_volumes = self.get_volumes()
  1378. if not volume:
  1379. return False
  1380. # update the volume
  1381. update_idx = None
  1382. for idx, exist_vol in enumerate(exist_volumes):
  1383. if exist_vol['name'] == volume['name']:
  1384. update_idx = idx
  1385. break
  1386. if update_idx != None:
  1387. exist_volumes[update_idx] = volume
  1388. else:
  1389. self.add_volume(volume)
  1390. return True
  1391. def update_volume_mount(self, volume_mount):
  1392. '''place an env in the env var list'''
  1393. modified = False
  1394. exist_volume_mounts = self.get_volume_mounts()
  1395. if not volume_mount:
  1396. return False
  1397. # update the volume mount
  1398. for exist_vol_mount in exist_volume_mounts:
  1399. if exist_vol_mount['name'] == volume_mount['name']:
  1400. if 'mountPath' in exist_vol_mount and \
  1401. str(exist_vol_mount['mountPath']) != str(volume_mount['mountPath']):
  1402. exist_vol_mount['mountPath'] = volume_mount['mountPath']
  1403. modified = True
  1404. break
  1405. if not modified:
  1406. self.add_volume_mount(volume_mount)
  1407. modified = True
  1408. return modified
  1409. def needs_update_volume(self, volume, volume_mount):
  1410. ''' verify a volume update is needed '''
  1411. exist_volume = self.find_volume_by_name(volume)
  1412. exist_volume_mount = self.find_volume_by_name(volume, mounts=True)
  1413. results = []
  1414. results.append(exist_volume['name'] == volume['name'])
  1415. if 'secret' in volume:
  1416. results.append('secret' in exist_volume)
  1417. results.append(exist_volume['secret']['secretName'] == volume['secret']['secretName'])
  1418. results.append(exist_volume_mount['name'] == volume_mount['name'])
  1419. results.append(exist_volume_mount['mountPath'] == volume_mount['mountPath'])
  1420. elif 'emptyDir' in volume:
  1421. results.append(exist_volume_mount['name'] == volume['name'])
  1422. results.append(exist_volume_mount['mountPath'] == volume_mount['mountPath'])
  1423. elif 'persistentVolumeClaim' in volume:
  1424. pvc = 'persistentVolumeClaim'
  1425. results.append(pvc in exist_volume)
  1426. if results[-1]:
  1427. results.append(exist_volume[pvc]['claimName'] == volume[pvc]['claimName'])
  1428. if 'claimSize' in volume[pvc]:
  1429. results.append(exist_volume[pvc]['claimSize'] == volume[pvc]['claimSize'])
  1430. elif 'hostpath' in volume:
  1431. results.append('hostPath' in exist_volume)
  1432. results.append(exist_volume['hostPath']['path'] == volume_mount['mountPath'])
  1433. return not all(results)
  1434. def needs_update_replicas(self, replicas):
  1435. ''' verify whether a replica update is needed '''
  1436. current_reps = self.get(DeploymentConfig.replicas_path)
  1437. return not current_reps == replicas
  1438. # -*- -*- -*- End included fragment: lib/deploymentconfig.py -*- -*- -*-
  1439. # -*- -*- -*- Begin included fragment: lib/volume.py -*- -*- -*-
  1440. class Volume(object):
  1441. ''' Class to represent an openshift volume object'''
  1442. volume_mounts_path = {"pod": "spec.containers[0].volumeMounts",
  1443. "dc": "spec.template.spec.containers[0].volumeMounts",
  1444. "rc": "spec.template.spec.containers[0].volumeMounts",
  1445. }
  1446. volumes_path = {"pod": "spec.volumes",
  1447. "dc": "spec.template.spec.volumes",
  1448. "rc": "spec.template.spec.volumes",
  1449. }
  1450. @staticmethod
  1451. def create_volume_structure(volume_info):
  1452. ''' return a properly structured volume '''
  1453. volume_mount = None
  1454. volume = {'name': volume_info['name']}
  1455. volume_type = volume_info['type'].lower()
  1456. if volume_type == 'secret':
  1457. volume['secret'] = {}
  1458. volume[volume_info['type']] = {'secretName': volume_info['secret_name']}
  1459. volume_mount = {'mountPath': volume_info['path'],
  1460. 'name': volume_info['name']}
  1461. elif volume_type == 'emptydir':
  1462. volume['emptyDir'] = {}
  1463. volume_mount = {'mountPath': volume_info['path'],
  1464. 'name': volume_info['name']}
  1465. elif volume_type == 'pvc' or volume_type == 'persistentvolumeclaim':
  1466. volume['persistentVolumeClaim'] = {}
  1467. volume['persistentVolumeClaim']['claimName'] = volume_info['claimName']
  1468. volume['persistentVolumeClaim']['claimSize'] = volume_info['claimSize']
  1469. elif volume_type == 'hostpath':
  1470. volume['hostPath'] = {}
  1471. volume['hostPath']['path'] = volume_info['path']
  1472. elif volume_type == 'configmap':
  1473. volume['configMap'] = {}
  1474. volume['configMap']['name'] = volume_info['configmap_name']
  1475. volume_mount = {'mountPath': volume_info['path'],
  1476. 'name': volume_info['name']}
  1477. return (volume, volume_mount)
  1478. # -*- -*- -*- End included fragment: lib/volume.py -*- -*- -*-
  1479. # -*- -*- -*- Begin included fragment: class/oc_volume.py -*- -*- -*-
  1480. # pylint: disable=too-many-instance-attributes
  1481. class OCVolume(OpenShiftCLI):
  1482. ''' Class to wrap the oc command line tools '''
  1483. volume_mounts_path = {"pod": "spec.containers[0].volumeMounts",
  1484. "dc": "spec.template.spec.containers[0].volumeMounts",
  1485. "rc": "spec.template.spec.containers[0].volumeMounts",
  1486. }
  1487. volumes_path = {"pod": "spec.volumes",
  1488. "dc": "spec.template.spec.volumes",
  1489. "rc": "spec.template.spec.volumes",
  1490. }
  1491. # pylint allows 5
  1492. # pylint: disable=too-many-arguments
  1493. def __init__(self,
  1494. kind,
  1495. resource_name,
  1496. namespace,
  1497. vol_name,
  1498. mount_path,
  1499. mount_type,
  1500. secret_name,
  1501. claim_size,
  1502. claim_name,
  1503. configmap_name,
  1504. kubeconfig='/etc/origin/master/admin.kubeconfig',
  1505. verbose=False):
  1506. ''' Constructor for OCVolume '''
  1507. super(OCVolume, self).__init__(namespace, kubeconfig)
  1508. self.kind = kind
  1509. self.volume_info = {'name': vol_name,
  1510. 'secret_name': secret_name,
  1511. 'path': mount_path,
  1512. 'type': mount_type,
  1513. 'claimSize': claim_size,
  1514. 'claimName': claim_name,
  1515. 'configmap_name': configmap_name}
  1516. self.volume, self.volume_mount = Volume.create_volume_structure(self.volume_info)
  1517. self.name = resource_name
  1518. self.namespace = namespace
  1519. self.kubeconfig = kubeconfig
  1520. self.verbose = verbose
  1521. self._resource = None
  1522. @property
  1523. def resource(self):
  1524. ''' property function for resource var '''
  1525. if not self._resource:
  1526. self.get()
  1527. return self._resource
  1528. @resource.setter
  1529. def resource(self, data):
  1530. ''' setter function for resource var '''
  1531. self._resource = data
  1532. def exists(self):
  1533. ''' return whether a volume exists '''
  1534. volume_mount_found = False
  1535. volume_found = self.resource.exists_volume(self.volume)
  1536. if not self.volume_mount and volume_found:
  1537. return True
  1538. if self.volume_mount:
  1539. volume_mount_found = self.resource.exists_volume_mount(self.volume_mount)
  1540. if volume_found and self.volume_mount and volume_mount_found:
  1541. return True
  1542. return False
  1543. def get(self):
  1544. '''return volume information '''
  1545. vol = self._get(self.kind, self.name)
  1546. if vol['returncode'] == 0:
  1547. if self.kind == 'dc':
  1548. self.resource = DeploymentConfig(content=vol['results'][0])
  1549. vol['results'] = self.resource.get_volumes()
  1550. return vol
  1551. def delete(self):
  1552. '''remove a volume'''
  1553. self.resource.delete_volume_by_name(self.volume)
  1554. return self._replace_content(self.kind, self.name, self.resource.yaml_dict)
  1555. def put(self):
  1556. '''place volume into dc '''
  1557. self.resource.update_volume(self.volume)
  1558. self.resource.get_volumes()
  1559. self.resource.update_volume_mount(self.volume_mount)
  1560. return self._replace_content(self.kind, self.name, self.resource.yaml_dict)
  1561. def needs_update(self):
  1562. ''' verify an update is needed '''
  1563. return self.resource.needs_update_volume(self.volume, self.volume_mount)
  1564. # pylint: disable=too-many-branches,too-many-return-statements
  1565. @staticmethod
  1566. def run_ansible(params, check_mode=False):
  1567. '''run the idempotent ansible code'''
  1568. oc_volume = OCVolume(params['kind'],
  1569. params['name'],
  1570. params['namespace'],
  1571. params['vol_name'],
  1572. params['mount_path'],
  1573. params['mount_type'],
  1574. # secrets
  1575. params['secret_name'],
  1576. # pvc
  1577. params['claim_size'],
  1578. params['claim_name'],
  1579. # configmap
  1580. params['configmap_name'],
  1581. kubeconfig=params['kubeconfig'],
  1582. verbose=params['debug'])
  1583. state = params['state']
  1584. api_rval = oc_volume.get()
  1585. if api_rval['returncode'] != 0:
  1586. return {'failed': True, 'msg': api_rval}
  1587. #####
  1588. # Get
  1589. #####
  1590. if state == 'list':
  1591. return {'changed': False, 'results': api_rval['results'], 'state': state}
  1592. ########
  1593. # Delete
  1594. ########
  1595. if state == 'absent':
  1596. if oc_volume.exists():
  1597. if check_mode:
  1598. return {'changed': False, 'msg': 'CHECK_MODE: Would have performed a delete.'}
  1599. api_rval = oc_volume.delete()
  1600. if api_rval['returncode'] != 0:
  1601. return {'failed': True, 'msg': api_rval}
  1602. return {'changed': True, 'results': api_rval, 'state': state}
  1603. return {'changed': False, 'state': state}
  1604. if state == 'present':
  1605. ########
  1606. # Create
  1607. ########
  1608. if not oc_volume.exists():
  1609. if check_mode:
  1610. return {'changed': True, 'msg': 'CHECK_MODE: Would have performed a create.'}
  1611. # Create it here
  1612. api_rval = oc_volume.put()
  1613. if api_rval['returncode'] != 0:
  1614. return {'failed': True, 'msg': api_rval}
  1615. # return the created object
  1616. api_rval = oc_volume.get()
  1617. if api_rval['returncode'] != 0:
  1618. return {'failed': True, 'msg': api_rval}
  1619. return {'changed': True, 'results': api_rval, 'state': state}
  1620. ########
  1621. # Update
  1622. ########
  1623. if oc_volume.needs_update():
  1624. api_rval = oc_volume.put()
  1625. if api_rval['returncode'] != 0:
  1626. return {'failed': True, 'msg': api_rval}
  1627. # return the created object
  1628. api_rval = oc_volume.get()
  1629. if api_rval['returncode'] != 0:
  1630. return {'failed': True, 'msg': api_rval}
  1631. return {'changed': True, 'results': api_rval, state: state}
  1632. return {'changed': False, 'results': api_rval, state: state}
  1633. return {'failed': True, 'msg': 'Unknown state passed. {}'.format(state)}
  1634. # -*- -*- -*- End included fragment: class/oc_volume.py -*- -*- -*-
  1635. # -*- -*- -*- Begin included fragment: ansible/oc_volume.py -*- -*- -*-
  1636. def main():
  1637. '''
  1638. ansible oc module for volumes
  1639. '''
  1640. module = AnsibleModule(
  1641. argument_spec=dict(
  1642. kubeconfig=dict(default='/etc/origin/master/admin.kubeconfig', type='str'),
  1643. state=dict(default='present', type='str',
  1644. choices=['present', 'absent', 'list']),
  1645. debug=dict(default=False, type='bool'),
  1646. kind=dict(default='dc', choices=['dc', 'rc', 'pods'], type='str'),
  1647. namespace=dict(default='default', type='str'),
  1648. vol_name=dict(default=None, type='str'),
  1649. name=dict(default=None, type='str'),
  1650. mount_type=dict(default=None,
  1651. choices=['emptydir', 'hostpath', 'secret', 'pvc', 'configmap'],
  1652. type='str'),
  1653. mount_path=dict(default=None, type='str'),
  1654. # secrets require a name
  1655. secret_name=dict(default=None, type='str'),
  1656. # pvc requires a size
  1657. claim_size=dict(default=None, type='str'),
  1658. claim_name=dict(default=None, type='str'),
  1659. # configmap requires a name
  1660. configmap_name=dict(default=None, type='str'),
  1661. ),
  1662. supports_check_mode=True,
  1663. )
  1664. rval = OCVolume.run_ansible(module.params, module.check_mode)
  1665. if 'failed' in rval:
  1666. module.fail_json(**rval)
  1667. module.exit_json(**rval)
  1668. if __name__ == '__main__':
  1669. main()
  1670. # -*- -*- -*- End included fragment: ansible/oc_volume.py -*- -*- -*-