oc_adm_registry.py 87 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305230623072308230923102311231223132314231523162317231823192320232123222323232423252326232723282329233023312332233323342335233623372338233923402341234223432344234523462347234823492350235123522353235423552356235723582359236023612362236323642365236623672368236923702371237223732374237523762377237823792380238123822383238423852386238723882389239023912392239323942395239623972398239924002401240224032404240524062407240824092410241124122413241424152416241724182419242024212422242324242425242624272428242924302431243224332434243524362437243824392440244124422443244424452446244724482449245024512452245324542455245624572458245924602461246224632464246524662467246824692470247124722473247424752476247724782479248024812482248324842485248624872488248924902491249224932494249524962497249824992500250125022503250425052506250725082509251025112512251325142515251625172518251925202521252225232524252525262527252825292530253125322533253425352536253725382539254025412542254325442545254625472548254925502551255225532554255525562557255825592560256125622563256425652566256725682569257025712572257325742575257625772578257925802581258225832584258525862587258825892590259125922593259425952596259725982599260026012602260326042605260626072608260926102611261226132614261526162617261826192620
  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/registry -*- -*- -*-
  49. DOCUMENTATION = '''
  50. ---
  51. module: oc_adm_registry
  52. short_description: Module to manage openshift registry
  53. description:
  54. - Manage openshift registry programmatically.
  55. options:
  56. state:
  57. description:
  58. - The desired action when managing openshift registry
  59. - present - update or create the registry
  60. - absent - tear down the registry service and deploymentconfig
  61. - list - returns the current representiation of a registry
  62. required: false
  63. default: False
  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. name:
  78. description:
  79. - The name of the registry
  80. required: false
  81. default: None
  82. aliases: []
  83. namespace:
  84. description:
  85. - The selector when filtering on node labels
  86. required: false
  87. default: None
  88. aliases: []
  89. images:
  90. description:
  91. - The image to base this registry on - ${component} will be replaced with --type
  92. required: 'openshift3/ose-${component}:${version}'
  93. default: None
  94. aliases: []
  95. latest_images:
  96. description:
  97. - If true, attempt to use the latest image for the registry instead of the latest release.
  98. required: false
  99. default: False
  100. aliases: []
  101. labels:
  102. description:
  103. - A set of labels to uniquely identify the registry and its components.
  104. required: false
  105. default: None
  106. aliases: []
  107. enforce_quota:
  108. description:
  109. - If set, the registry will refuse to write blobs if they exceed quota limits
  110. required: False
  111. default: False
  112. aliases: []
  113. mount_host:
  114. description:
  115. - If set, the registry volume will be created as a host-mount at this path.
  116. required: False
  117. default: False
  118. aliases: []
  119. ports:
  120. description:
  121. - A comma delimited list of ports or port pairs to expose on the registry pod. The default is set for 5000.
  122. required: False
  123. default: [5000]
  124. aliases: []
  125. replicas:
  126. description:
  127. - The replication factor of the registry; commonly 2 when high availability is desired.
  128. required: False
  129. default: 1
  130. aliases: []
  131. selector:
  132. description:
  133. - Selector used to filter nodes on deployment. Used to run registries on a specific set of nodes.
  134. required: False
  135. default: None
  136. aliases: []
  137. service_account:
  138. description:
  139. - Name of the service account to use to run the registry pod.
  140. required: False
  141. default: 'registry'
  142. aliases: []
  143. tls_certificate:
  144. description:
  145. - An optional path to a PEM encoded certificate (which may contain the private key) for serving over TLS
  146. required: false
  147. default: None
  148. aliases: []
  149. tls_key:
  150. description:
  151. - An optional path to a PEM encoded private key for serving over TLS
  152. required: false
  153. default: None
  154. aliases: []
  155. volume_mounts:
  156. description:
  157. - The volume mounts for the registry.
  158. required: false
  159. default: None
  160. aliases: []
  161. daemonset:
  162. description:
  163. - Use a daemonset instead of a deployment config.
  164. required: false
  165. default: False
  166. aliases: []
  167. edits:
  168. description:
  169. - A list of modifications to make on the deploymentconfig
  170. required: false
  171. default: None
  172. aliases: []
  173. env_vars:
  174. description:
  175. - A dictionary of modifications to make on the deploymentconfig. e.g. FOO: BAR
  176. required: false
  177. default: None
  178. aliases: []
  179. force:
  180. description:
  181. - Force a registry update.
  182. required: false
  183. default: False
  184. aliases: []
  185. author:
  186. - "Kenny Woodson <kwoodson@redhat.com>"
  187. extends_documentation_fragment: []
  188. '''
  189. EXAMPLES = '''
  190. - name: create a secure registry
  191. oc_adm_registry:
  192. name: docker-registry
  193. service_account: registry
  194. replicas: 2
  195. namespace: default
  196. selector: type=infra
  197. images: "registry.ops.openshift.com/openshift3/ose-${component}:${version}"
  198. env_vars:
  199. REGISTRY_CONFIGURATION_PATH: /etc/registryconfig/config.yml
  200. REGISTRY_HTTP_TLS_CERTIFICATE: /etc/secrets/registry.crt
  201. REGISTRY_HTTP_TLS_KEY: /etc/secrets/registry.key
  202. REGISTRY_HTTP_SECRET: supersecret
  203. volume_mounts:
  204. - path: /etc/secrets
  205. name: dockercerts
  206. type: secret
  207. secret_name: registry-secret
  208. - path: /etc/registryconfig
  209. name: dockersecrets
  210. type: secret
  211. secret_name: docker-registry-config
  212. edits:
  213. - key: spec.template.spec.containers[0].livenessProbe.httpGet.scheme
  214. value: HTTPS
  215. action: put
  216. - key: spec.template.spec.containers[0].readinessProbe.httpGet.scheme
  217. value: HTTPS
  218. action: put
  219. - key: spec.strategy.rollingParams
  220. value:
  221. intervalSeconds: 1
  222. maxSurge: 50%
  223. maxUnavailable: 50%
  224. timeoutSeconds: 600
  225. updatePeriodSeconds: 1
  226. action: put
  227. - key: spec.template.spec.containers[0].resources.limits.memory
  228. value: 2G
  229. action: update
  230. - key: spec.template.spec.containers[0].resources.requests.memory
  231. value: 1G
  232. action: update
  233. register: registryout
  234. '''
  235. # -*- -*- -*- End included fragment: doc/registry -*- -*- -*-
  236. # -*- -*- -*- Begin included fragment: ../../lib_utils/src/class/yedit.py -*- -*- -*-
  237. # pylint: disable=undefined-variable,missing-docstring
  238. # noqa: E301,E302
  239. class YeditException(Exception):
  240. ''' Exception class for Yedit '''
  241. pass
  242. # pylint: disable=too-many-public-methods
  243. class Yedit(object):
  244. ''' Class to modify yaml files '''
  245. re_valid_key = r"(((\[-?\d+\])|([0-9a-zA-Z%s/_-]+)).?)+$"
  246. re_key = r"(?:\[(-?\d+)\])|([0-9a-zA-Z%s/_-]+)"
  247. com_sep = set(['.', '#', '|', ':'])
  248. # pylint: disable=too-many-arguments
  249. def __init__(self,
  250. filename=None,
  251. content=None,
  252. content_type='yaml',
  253. separator='.',
  254. backup=False):
  255. self.content = content
  256. self._separator = separator
  257. self.filename = filename
  258. self.__yaml_dict = content
  259. self.content_type = content_type
  260. self.backup = backup
  261. self.load(content_type=self.content_type)
  262. if self.__yaml_dict is None:
  263. self.__yaml_dict = {}
  264. @property
  265. def separator(self):
  266. ''' getter method for yaml_dict '''
  267. return self._separator
  268. @separator.setter
  269. def separator(self):
  270. ''' getter method for yaml_dict '''
  271. return self._separator
  272. @property
  273. def yaml_dict(self):
  274. ''' getter method for yaml_dict '''
  275. return self.__yaml_dict
  276. @yaml_dict.setter
  277. def yaml_dict(self, value):
  278. ''' setter method for yaml_dict '''
  279. self.__yaml_dict = value
  280. @staticmethod
  281. def parse_key(key, sep='.'):
  282. '''parse the key allowing the appropriate separator'''
  283. common_separators = list(Yedit.com_sep - set([sep]))
  284. return re.findall(Yedit.re_key % ''.join(common_separators), key)
  285. @staticmethod
  286. def valid_key(key, sep='.'):
  287. '''validate the incoming key'''
  288. common_separators = list(Yedit.com_sep - set([sep]))
  289. if not re.match(Yedit.re_valid_key % ''.join(common_separators), key):
  290. return False
  291. return True
  292. @staticmethod
  293. def remove_entry(data, key, sep='.'):
  294. ''' remove data at location key '''
  295. if key == '' and isinstance(data, dict):
  296. data.clear()
  297. return True
  298. elif key == '' and isinstance(data, list):
  299. del data[:]
  300. return True
  301. if not (key and Yedit.valid_key(key, sep)) and \
  302. isinstance(data, (list, dict)):
  303. return None
  304. key_indexes = Yedit.parse_key(key, sep)
  305. for arr_ind, dict_key in key_indexes[:-1]:
  306. if dict_key and isinstance(data, dict):
  307. data = data.get(dict_key, None)
  308. elif (arr_ind and isinstance(data, list) and
  309. int(arr_ind) <= len(data) - 1):
  310. data = data[int(arr_ind)]
  311. else:
  312. return None
  313. # process last index for remove
  314. # expected list entry
  315. if key_indexes[-1][0]:
  316. if isinstance(data, list) and int(key_indexes[-1][0]) <= len(data) - 1: # noqa: E501
  317. del data[int(key_indexes[-1][0])]
  318. return True
  319. # expected dict entry
  320. elif key_indexes[-1][1]:
  321. if isinstance(data, dict):
  322. del data[key_indexes[-1][1]]
  323. return True
  324. @staticmethod
  325. def add_entry(data, key, item=None, sep='.'):
  326. ''' Get an item from a dictionary with key notation a.b.c
  327. d = {'a': {'b': 'c'}}}
  328. key = a#b
  329. return c
  330. '''
  331. if key == '':
  332. pass
  333. elif (not (key and Yedit.valid_key(key, sep)) and
  334. isinstance(data, (list, dict))):
  335. return None
  336. key_indexes = Yedit.parse_key(key, sep)
  337. for arr_ind, dict_key in key_indexes[:-1]:
  338. if dict_key:
  339. if isinstance(data, dict) and dict_key in data and data[dict_key]: # noqa: E501
  340. data = data[dict_key]
  341. continue
  342. elif data and not isinstance(data, dict):
  343. raise YeditException("Unexpected item type found while going through key " +
  344. "path: {} (at key: {})".format(key, dict_key))
  345. data[dict_key] = {}
  346. data = data[dict_key]
  347. elif (arr_ind and isinstance(data, list) and
  348. int(arr_ind) <= len(data) - 1):
  349. data = data[int(arr_ind)]
  350. else:
  351. raise YeditException("Unexpected item type found while going through key path: {}".format(key))
  352. if key == '':
  353. data = item
  354. # process last index for add
  355. # expected list entry
  356. elif key_indexes[-1][0] and isinstance(data, list) and int(key_indexes[-1][0]) <= len(data) - 1: # noqa: E501
  357. data[int(key_indexes[-1][0])] = item
  358. # expected dict entry
  359. elif key_indexes[-1][1] and isinstance(data, dict):
  360. data[key_indexes[-1][1]] = item
  361. # didn't add/update to an existing list, nor add/update key to a dict
  362. # so we must have been provided some syntax like a.b.c[<int>] = "data" for a
  363. # non-existent array
  364. else:
  365. raise YeditException("Error adding to object at path: {}".format(key))
  366. return data
  367. @staticmethod
  368. def get_entry(data, key, sep='.'):
  369. ''' Get an item from a dictionary with key notation a.b.c
  370. d = {'a': {'b': 'c'}}}
  371. key = a.b
  372. return c
  373. '''
  374. if key == '':
  375. pass
  376. elif (not (key and Yedit.valid_key(key, sep)) and
  377. isinstance(data, (list, dict))):
  378. return None
  379. key_indexes = Yedit.parse_key(key, sep)
  380. for arr_ind, dict_key in key_indexes:
  381. if dict_key and isinstance(data, dict):
  382. data = data.get(dict_key, None)
  383. elif (arr_ind and isinstance(data, list) and
  384. int(arr_ind) <= len(data) - 1):
  385. data = data[int(arr_ind)]
  386. else:
  387. return None
  388. return data
  389. @staticmethod
  390. def _write(filename, contents):
  391. ''' Actually write the file contents to disk. This helps with mocking. '''
  392. tmp_filename = filename + '.yedit'
  393. with open(tmp_filename, 'w') as yfd:
  394. yfd.write(contents)
  395. os.rename(tmp_filename, filename)
  396. def write(self):
  397. ''' write to file '''
  398. if not self.filename:
  399. raise YeditException('Please specify a filename.')
  400. if self.backup and self.file_exists():
  401. shutil.copy(self.filename, self.filename + '.orig')
  402. # Try to set format attributes if supported
  403. try:
  404. self.yaml_dict.fa.set_block_style()
  405. except AttributeError:
  406. pass
  407. # Try to use RoundTripDumper if supported.
  408. try:
  409. Yedit._write(self.filename, yaml.dump(self.yaml_dict, Dumper=yaml.RoundTripDumper))
  410. except AttributeError:
  411. Yedit._write(self.filename, yaml.safe_dump(self.yaml_dict, default_flow_style=False))
  412. return (True, self.yaml_dict)
  413. def read(self):
  414. ''' read from file '''
  415. # check if it exists
  416. if self.filename is None or not self.file_exists():
  417. return None
  418. contents = None
  419. with open(self.filename) as yfd:
  420. contents = yfd.read()
  421. return contents
  422. def file_exists(self):
  423. ''' return whether file exists '''
  424. if os.path.exists(self.filename):
  425. return True
  426. return False
  427. def load(self, content_type='yaml'):
  428. ''' return yaml file '''
  429. contents = self.read()
  430. if not contents and not self.content:
  431. return None
  432. if self.content:
  433. if isinstance(self.content, dict):
  434. self.yaml_dict = self.content
  435. return self.yaml_dict
  436. elif isinstance(self.content, str):
  437. contents = self.content
  438. # check if it is yaml
  439. try:
  440. if content_type == 'yaml' and contents:
  441. # Try to set format attributes if supported
  442. try:
  443. self.yaml_dict.fa.set_block_style()
  444. except AttributeError:
  445. pass
  446. # Try to use RoundTripLoader if supported.
  447. try:
  448. self.yaml_dict = yaml.safe_load(contents, yaml.RoundTripLoader)
  449. except AttributeError:
  450. self.yaml_dict = yaml.safe_load(contents)
  451. # Try to set format attributes if supported
  452. try:
  453. self.yaml_dict.fa.set_block_style()
  454. except AttributeError:
  455. pass
  456. elif content_type == 'json' and contents:
  457. self.yaml_dict = json.loads(contents)
  458. except yaml.YAMLError as err:
  459. # Error loading yaml or json
  460. raise YeditException('Problem with loading yaml file. %s' % err)
  461. return self.yaml_dict
  462. def get(self, key):
  463. ''' get a specified key'''
  464. try:
  465. entry = Yedit.get_entry(self.yaml_dict, key, self.separator)
  466. except KeyError:
  467. entry = None
  468. return entry
  469. def pop(self, path, key_or_item):
  470. ''' remove a key, value pair from a dict or an item for a list'''
  471. try:
  472. entry = Yedit.get_entry(self.yaml_dict, path, self.separator)
  473. except KeyError:
  474. entry = None
  475. if entry is None:
  476. return (False, self.yaml_dict)
  477. if isinstance(entry, dict):
  478. # AUDIT:maybe-no-member makes sense due to fuzzy types
  479. # pylint: disable=maybe-no-member
  480. if key_or_item in entry:
  481. entry.pop(key_or_item)
  482. return (True, self.yaml_dict)
  483. return (False, self.yaml_dict)
  484. elif isinstance(entry, list):
  485. # AUDIT:maybe-no-member makes sense due to fuzzy types
  486. # pylint: disable=maybe-no-member
  487. ind = None
  488. try:
  489. ind = entry.index(key_or_item)
  490. except ValueError:
  491. return (False, self.yaml_dict)
  492. entry.pop(ind)
  493. return (True, self.yaml_dict)
  494. return (False, self.yaml_dict)
  495. def delete(self, path):
  496. ''' remove path from a dict'''
  497. try:
  498. entry = Yedit.get_entry(self.yaml_dict, path, self.separator)
  499. except KeyError:
  500. entry = None
  501. if entry is None:
  502. return (False, self.yaml_dict)
  503. result = Yedit.remove_entry(self.yaml_dict, path, self.separator)
  504. if not result:
  505. return (False, self.yaml_dict)
  506. return (True, self.yaml_dict)
  507. def exists(self, path, value):
  508. ''' check if value exists at path'''
  509. try:
  510. entry = Yedit.get_entry(self.yaml_dict, path, self.separator)
  511. except KeyError:
  512. entry = None
  513. if isinstance(entry, list):
  514. if value in entry:
  515. return True
  516. return False
  517. elif isinstance(entry, dict):
  518. if isinstance(value, dict):
  519. rval = False
  520. for key, val in value.items():
  521. if entry[key] != val:
  522. rval = False
  523. break
  524. else:
  525. rval = True
  526. return rval
  527. return value in entry
  528. return entry == value
  529. def append(self, path, value):
  530. '''append value to a list'''
  531. try:
  532. entry = Yedit.get_entry(self.yaml_dict, path, self.separator)
  533. except KeyError:
  534. entry = None
  535. if entry is None:
  536. self.put(path, [])
  537. entry = Yedit.get_entry(self.yaml_dict, path, self.separator)
  538. if not isinstance(entry, list):
  539. return (False, self.yaml_dict)
  540. # AUDIT:maybe-no-member makes sense due to loading data from
  541. # a serialized format.
  542. # pylint: disable=maybe-no-member
  543. entry.append(value)
  544. return (True, self.yaml_dict)
  545. # pylint: disable=too-many-arguments
  546. def update(self, path, value, index=None, curr_value=None):
  547. ''' put path, value into a dict '''
  548. try:
  549. entry = Yedit.get_entry(self.yaml_dict, path, self.separator)
  550. except KeyError:
  551. entry = None
  552. if isinstance(entry, dict):
  553. # AUDIT:maybe-no-member makes sense due to fuzzy types
  554. # pylint: disable=maybe-no-member
  555. if not isinstance(value, dict):
  556. raise YeditException('Cannot replace key, value entry in ' +
  557. 'dict with non-dict type. value=[%s] [%s]' % (value, type(value))) # noqa: E501
  558. entry.update(value)
  559. return (True, self.yaml_dict)
  560. elif isinstance(entry, list):
  561. # AUDIT:maybe-no-member makes sense due to fuzzy types
  562. # pylint: disable=maybe-no-member
  563. ind = None
  564. if curr_value:
  565. try:
  566. ind = entry.index(curr_value)
  567. except ValueError:
  568. return (False, self.yaml_dict)
  569. elif index is not None:
  570. ind = index
  571. if ind is not None and entry[ind] != value:
  572. entry[ind] = value
  573. return (True, self.yaml_dict)
  574. # see if it exists in the list
  575. try:
  576. ind = entry.index(value)
  577. except ValueError:
  578. # doesn't exist, append it
  579. entry.append(value)
  580. return (True, self.yaml_dict)
  581. # already exists, return
  582. if ind is not None:
  583. return (False, self.yaml_dict)
  584. return (False, self.yaml_dict)
  585. def put(self, path, value):
  586. ''' put path, value into a dict '''
  587. try:
  588. entry = Yedit.get_entry(self.yaml_dict, path, self.separator)
  589. except KeyError:
  590. entry = None
  591. if entry == value:
  592. return (False, self.yaml_dict)
  593. # deepcopy didn't work
  594. # Try to use ruamel.yaml and fallback to pyyaml
  595. try:
  596. tmp_copy = yaml.load(yaml.round_trip_dump(self.yaml_dict,
  597. default_flow_style=False),
  598. yaml.RoundTripLoader)
  599. except AttributeError:
  600. tmp_copy = copy.deepcopy(self.yaml_dict)
  601. # set the format attributes if available
  602. try:
  603. tmp_copy.fa.set_block_style()
  604. except AttributeError:
  605. pass
  606. result = Yedit.add_entry(tmp_copy, path, value, self.separator)
  607. if not result:
  608. return (False, self.yaml_dict)
  609. self.yaml_dict = tmp_copy
  610. return (True, self.yaml_dict)
  611. def create(self, path, value):
  612. ''' create a yaml file '''
  613. if not self.file_exists():
  614. # deepcopy didn't work
  615. # Try to use ruamel.yaml and fallback to pyyaml
  616. try:
  617. tmp_copy = yaml.load(yaml.round_trip_dump(self.yaml_dict,
  618. default_flow_style=False),
  619. yaml.RoundTripLoader)
  620. except AttributeError:
  621. tmp_copy = copy.deepcopy(self.yaml_dict)
  622. # set the format attributes if available
  623. try:
  624. tmp_copy.fa.set_block_style()
  625. except AttributeError:
  626. pass
  627. result = Yedit.add_entry(tmp_copy, path, value, self.separator)
  628. if result:
  629. self.yaml_dict = tmp_copy
  630. return (True, self.yaml_dict)
  631. return (False, self.yaml_dict)
  632. @staticmethod
  633. def get_curr_value(invalue, val_type):
  634. '''return the current value'''
  635. if invalue is None:
  636. return None
  637. curr_value = invalue
  638. if val_type == 'yaml':
  639. curr_value = yaml.load(invalue)
  640. elif val_type == 'json':
  641. curr_value = json.loads(invalue)
  642. return curr_value
  643. @staticmethod
  644. def parse_value(inc_value, vtype=''):
  645. '''determine value type passed'''
  646. true_bools = ['y', 'Y', 'yes', 'Yes', 'YES', 'true', 'True', 'TRUE',
  647. 'on', 'On', 'ON', ]
  648. false_bools = ['n', 'N', 'no', 'No', 'NO', 'false', 'False', 'FALSE',
  649. 'off', 'Off', 'OFF']
  650. # It came in as a string but you didn't specify value_type as string
  651. # we will convert to bool if it matches any of the above cases
  652. if isinstance(inc_value, str) and 'bool' in vtype:
  653. if inc_value not in true_bools and inc_value not in false_bools:
  654. raise YeditException('Not a boolean type. str=[%s] vtype=[%s]'
  655. % (inc_value, vtype))
  656. elif isinstance(inc_value, bool) and 'str' in vtype:
  657. inc_value = str(inc_value)
  658. # If vtype is not str then go ahead and attempt to yaml load it.
  659. if isinstance(inc_value, str) and 'str' not in vtype:
  660. try:
  661. inc_value = yaml.load(inc_value)
  662. except Exception:
  663. raise YeditException('Could not determine type of incoming ' +
  664. 'value. value=[%s] vtype=[%s]'
  665. % (type(inc_value), vtype))
  666. return inc_value
  667. # pylint: disable=too-many-return-statements,too-many-branches
  668. @staticmethod
  669. def run_ansible(module):
  670. '''perform the idempotent crud operations'''
  671. yamlfile = Yedit(filename=module.params['src'],
  672. backup=module.params['backup'],
  673. separator=module.params['separator'])
  674. if module.params['src']:
  675. rval = yamlfile.load()
  676. if yamlfile.yaml_dict is None and \
  677. module.params['state'] != 'present':
  678. return {'failed': True,
  679. 'msg': 'Error opening file [%s]. Verify that the ' +
  680. 'file exists, that it is has correct' +
  681. ' permissions, and is valid yaml.'}
  682. if module.params['state'] == 'list':
  683. if module.params['content']:
  684. content = Yedit.parse_value(module.params['content'],
  685. module.params['content_type'])
  686. yamlfile.yaml_dict = content
  687. if module.params['key']:
  688. rval = yamlfile.get(module.params['key']) or {}
  689. return {'changed': False, 'result': rval, 'state': "list"}
  690. elif module.params['state'] == 'absent':
  691. if module.params['content']:
  692. content = Yedit.parse_value(module.params['content'],
  693. module.params['content_type'])
  694. yamlfile.yaml_dict = content
  695. if module.params['update']:
  696. rval = yamlfile.pop(module.params['key'],
  697. module.params['value'])
  698. else:
  699. rval = yamlfile.delete(module.params['key'])
  700. if rval[0] and module.params['src']:
  701. yamlfile.write()
  702. return {'changed': rval[0], 'result': rval[1], 'state': "absent"}
  703. elif module.params['state'] == 'present':
  704. # check if content is different than what is in the file
  705. if module.params['content']:
  706. content = Yedit.parse_value(module.params['content'],
  707. module.params['content_type'])
  708. # We had no edits to make and the contents are the same
  709. if yamlfile.yaml_dict == content and \
  710. module.params['value'] is None:
  711. return {'changed': False,
  712. 'result': yamlfile.yaml_dict,
  713. 'state': "present"}
  714. yamlfile.yaml_dict = content
  715. # we were passed a value; parse it
  716. if module.params['value']:
  717. value = Yedit.parse_value(module.params['value'],
  718. module.params['value_type'])
  719. key = module.params['key']
  720. if module.params['update']:
  721. # pylint: disable=line-too-long
  722. curr_value = Yedit.get_curr_value(Yedit.parse_value(module.params['curr_value']), # noqa: E501
  723. module.params['curr_value_format']) # noqa: E501
  724. rval = yamlfile.update(key, value, module.params['index'], curr_value) # noqa: E501
  725. elif module.params['append']:
  726. rval = yamlfile.append(key, value)
  727. else:
  728. rval = yamlfile.put(key, value)
  729. if rval[0] and module.params['src']:
  730. yamlfile.write()
  731. return {'changed': rval[0],
  732. 'result': rval[1], 'state': "present"}
  733. # no edits to make
  734. if module.params['src']:
  735. # pylint: disable=redefined-variable-type
  736. rval = yamlfile.write()
  737. return {'changed': rval[0],
  738. 'result': rval[1],
  739. 'state': "present"}
  740. return {'failed': True, 'msg': 'Unkown state passed'}
  741. # -*- -*- -*- End included fragment: ../../lib_utils/src/class/yedit.py -*- -*- -*-
  742. # -*- -*- -*- Begin included fragment: lib/base.py -*- -*- -*-
  743. # pylint: disable=too-many-lines
  744. # noqa: E301,E302,E303,T001
  745. class OpenShiftCLIError(Exception):
  746. '''Exception class for openshiftcli'''
  747. pass
  748. ADDITIONAL_PATH_LOOKUPS = ['/usr/local/bin', os.path.expanduser('~/bin')]
  749. def locate_oc_binary():
  750. ''' Find and return oc binary file '''
  751. # https://github.com/openshift/openshift-ansible/issues/3410
  752. # oc can be in /usr/local/bin in some cases, but that may not
  753. # be in $PATH due to ansible/sudo
  754. paths = os.environ.get("PATH", os.defpath).split(os.pathsep) + ADDITIONAL_PATH_LOOKUPS
  755. oc_binary = 'oc'
  756. # Use shutil.which if it is available, otherwise fallback to a naive path search
  757. try:
  758. which_result = shutil.which(oc_binary, path=os.pathsep.join(paths))
  759. if which_result is not None:
  760. oc_binary = which_result
  761. except AttributeError:
  762. for path in paths:
  763. if os.path.exists(os.path.join(path, oc_binary)):
  764. oc_binary = os.path.join(path, oc_binary)
  765. break
  766. return oc_binary
  767. # pylint: disable=too-few-public-methods
  768. class OpenShiftCLI(object):
  769. ''' Class to wrap the command line tools '''
  770. def __init__(self,
  771. namespace,
  772. kubeconfig='/etc/origin/master/admin.kubeconfig',
  773. verbose=False,
  774. all_namespaces=False):
  775. ''' Constructor for OpenshiftCLI '''
  776. self.namespace = namespace
  777. self.verbose = verbose
  778. self.kubeconfig = Utils.create_tmpfile_copy(kubeconfig)
  779. self.all_namespaces = all_namespaces
  780. self.oc_binary = locate_oc_binary()
  781. # Pylint allows only 5 arguments to be passed.
  782. # pylint: disable=too-many-arguments
  783. def _replace_content(self, resource, rname, content, force=False, sep='.'):
  784. ''' replace the current object with the content '''
  785. res = self._get(resource, rname)
  786. if not res['results']:
  787. return res
  788. fname = Utils.create_tmpfile(rname + '-')
  789. yed = Yedit(fname, res['results'][0], separator=sep)
  790. changes = []
  791. for key, value in content.items():
  792. changes.append(yed.put(key, value))
  793. if any([change[0] for change in changes]):
  794. yed.write()
  795. atexit.register(Utils.cleanup, [fname])
  796. return self._replace(fname, force)
  797. return {'returncode': 0, 'updated': False}
  798. def _replace(self, fname, force=False):
  799. '''replace the current object with oc replace'''
  800. cmd = ['replace', '-f', fname]
  801. if force:
  802. cmd.append('--force')
  803. return self.openshift_cmd(cmd)
  804. def _create_from_content(self, rname, content):
  805. '''create a temporary file and then call oc create on it'''
  806. fname = Utils.create_tmpfile(rname + '-')
  807. yed = Yedit(fname, content=content)
  808. yed.write()
  809. atexit.register(Utils.cleanup, [fname])
  810. return self._create(fname)
  811. def _create(self, fname):
  812. '''call oc create on a filename'''
  813. return self.openshift_cmd(['create', '-f', fname])
  814. def _delete(self, resource, rname, selector=None):
  815. '''call oc delete on a resource'''
  816. cmd = ['delete', resource, rname]
  817. if selector:
  818. cmd.append('--selector=%s' % selector)
  819. return self.openshift_cmd(cmd)
  820. def _process(self, template_name, create=False, params=None, template_data=None): # noqa: E501
  821. '''process a template
  822. template_name: the name of the template to process
  823. create: whether to send to oc create after processing
  824. params: the parameters for the template
  825. template_data: the incoming template's data; instead of a file
  826. '''
  827. cmd = ['process']
  828. if template_data:
  829. cmd.extend(['-f', '-'])
  830. else:
  831. cmd.append(template_name)
  832. if params:
  833. param_str = ["%s=%s" % (key, value) for key, value in params.items()]
  834. cmd.append('-v')
  835. cmd.extend(param_str)
  836. results = self.openshift_cmd(cmd, output=True, input_data=template_data)
  837. if results['returncode'] != 0 or not create:
  838. return results
  839. fname = Utils.create_tmpfile(template_name + '-')
  840. yed = Yedit(fname, results['results'])
  841. yed.write()
  842. atexit.register(Utils.cleanup, [fname])
  843. return self.openshift_cmd(['create', '-f', fname])
  844. def _get(self, resource, rname=None, selector=None):
  845. '''return a resource by name '''
  846. cmd = ['get', resource]
  847. if selector:
  848. cmd.append('--selector=%s' % selector)
  849. elif rname:
  850. cmd.append(rname)
  851. cmd.extend(['-o', 'json'])
  852. rval = self.openshift_cmd(cmd, output=True)
  853. # Ensure results are retuned in an array
  854. if 'items' in rval:
  855. rval['results'] = rval['items']
  856. elif not isinstance(rval['results'], list):
  857. rval['results'] = [rval['results']]
  858. return rval
  859. def _schedulable(self, node=None, selector=None, schedulable=True):
  860. ''' perform oadm manage-node scheduable '''
  861. cmd = ['manage-node']
  862. if node:
  863. cmd.extend(node)
  864. else:
  865. cmd.append('--selector=%s' % selector)
  866. cmd.append('--schedulable=%s' % schedulable)
  867. return self.openshift_cmd(cmd, oadm=True, output=True, output_type='raw') # noqa: E501
  868. def _list_pods(self, node=None, selector=None, pod_selector=None):
  869. ''' perform oadm list pods
  870. node: the node in which to list pods
  871. selector: the label selector filter if provided
  872. pod_selector: the pod selector filter if provided
  873. '''
  874. cmd = ['manage-node']
  875. if node:
  876. cmd.extend(node)
  877. else:
  878. cmd.append('--selector=%s' % selector)
  879. if pod_selector:
  880. cmd.append('--pod-selector=%s' % pod_selector)
  881. cmd.extend(['--list-pods', '-o', 'json'])
  882. return self.openshift_cmd(cmd, oadm=True, output=True, output_type='raw')
  883. # pylint: disable=too-many-arguments
  884. def _evacuate(self, node=None, selector=None, pod_selector=None, dry_run=False, grace_period=None, force=False):
  885. ''' perform oadm manage-node evacuate '''
  886. cmd = ['manage-node']
  887. if node:
  888. cmd.extend(node)
  889. else:
  890. cmd.append('--selector=%s' % selector)
  891. if dry_run:
  892. cmd.append('--dry-run')
  893. if pod_selector:
  894. cmd.append('--pod-selector=%s' % pod_selector)
  895. if grace_period:
  896. cmd.append('--grace-period=%s' % int(grace_period))
  897. if force:
  898. cmd.append('--force')
  899. cmd.append('--evacuate')
  900. return self.openshift_cmd(cmd, oadm=True, output=True, output_type='raw')
  901. def _version(self):
  902. ''' return the openshift version'''
  903. return self.openshift_cmd(['version'], output=True, output_type='raw')
  904. def _import_image(self, url=None, name=None, tag=None):
  905. ''' perform image import '''
  906. cmd = ['import-image']
  907. image = '{0}'.format(name)
  908. if tag:
  909. image += ':{0}'.format(tag)
  910. cmd.append(image)
  911. if url:
  912. cmd.append('--from={0}/{1}'.format(url, image))
  913. cmd.append('-n{0}'.format(self.namespace))
  914. cmd.append('--confirm')
  915. return self.openshift_cmd(cmd)
  916. def _run(self, cmds, input_data):
  917. ''' Actually executes the command. This makes mocking easier. '''
  918. curr_env = os.environ.copy()
  919. curr_env.update({'KUBECONFIG': self.kubeconfig})
  920. proc = subprocess.Popen(cmds,
  921. stdin=subprocess.PIPE,
  922. stdout=subprocess.PIPE,
  923. stderr=subprocess.PIPE,
  924. env=curr_env)
  925. stdout, stderr = proc.communicate(input_data)
  926. return proc.returncode, stdout.decode(), stderr.decode()
  927. # pylint: disable=too-many-arguments,too-many-branches
  928. def openshift_cmd(self, cmd, oadm=False, output=False, output_type='json', input_data=None):
  929. '''Base command for oc '''
  930. cmds = [self.oc_binary]
  931. if oadm:
  932. cmds.append('adm')
  933. cmds.extend(cmd)
  934. if self.all_namespaces:
  935. cmds.extend(['--all-namespaces'])
  936. elif self.namespace is not None and self.namespace.lower() not in ['none', 'emtpy']: # E501
  937. cmds.extend(['-n', self.namespace])
  938. rval = {}
  939. results = ''
  940. err = None
  941. if self.verbose:
  942. print(' '.join(cmds))
  943. try:
  944. returncode, stdout, stderr = self._run(cmds, input_data)
  945. except OSError as ex:
  946. returncode, stdout, stderr = 1, '', 'Failed to execute {}: {}'.format(subprocess.list2cmdline(cmds), ex)
  947. rval = {"returncode": returncode,
  948. "results": results,
  949. "cmd": ' '.join(cmds)}
  950. if returncode == 0:
  951. if output:
  952. if output_type == 'json':
  953. try:
  954. rval['results'] = json.loads(stdout)
  955. except ValueError as err:
  956. if "No JSON object could be decoded" in err.args:
  957. err = err.args
  958. elif output_type == 'raw':
  959. rval['results'] = stdout
  960. if self.verbose:
  961. print("STDOUT: {0}".format(stdout))
  962. print("STDERR: {0}".format(stderr))
  963. if err:
  964. rval.update({"err": err,
  965. "stderr": stderr,
  966. "stdout": stdout,
  967. "cmd": cmds})
  968. else:
  969. rval.update({"stderr": stderr,
  970. "stdout": stdout,
  971. "results": {}})
  972. return rval
  973. class Utils(object):
  974. ''' utilities for openshiftcli modules '''
  975. @staticmethod
  976. def _write(filename, contents):
  977. ''' Actually write the file contents to disk. This helps with mocking. '''
  978. with open(filename, 'w') as sfd:
  979. sfd.write(contents)
  980. @staticmethod
  981. def create_tmp_file_from_contents(rname, data, ftype='yaml'):
  982. ''' create a file in tmp with name and contents'''
  983. tmp = Utils.create_tmpfile(prefix=rname)
  984. if ftype == 'yaml':
  985. # AUDIT:no-member makes sense here due to ruamel.YAML/PyYAML usage
  986. # pylint: disable=no-member
  987. if hasattr(yaml, 'RoundTripDumper'):
  988. Utils._write(tmp, yaml.dump(data, Dumper=yaml.RoundTripDumper))
  989. else:
  990. Utils._write(tmp, yaml.safe_dump(data, default_flow_style=False))
  991. elif ftype == 'json':
  992. Utils._write(tmp, json.dumps(data))
  993. else:
  994. Utils._write(tmp, data)
  995. # Register cleanup when module is done
  996. atexit.register(Utils.cleanup, [tmp])
  997. return tmp
  998. @staticmethod
  999. def create_tmpfile_copy(inc_file):
  1000. '''create a temporary copy of a file'''
  1001. tmpfile = Utils.create_tmpfile('lib_openshift-')
  1002. Utils._write(tmpfile, open(inc_file).read())
  1003. # Cleanup the tmpfile
  1004. atexit.register(Utils.cleanup, [tmpfile])
  1005. return tmpfile
  1006. @staticmethod
  1007. def create_tmpfile(prefix='tmp'):
  1008. ''' Generates and returns a temporary file name '''
  1009. with tempfile.NamedTemporaryFile(prefix=prefix, delete=False) as tmp:
  1010. return tmp.name
  1011. @staticmethod
  1012. def create_tmp_files_from_contents(content, content_type=None):
  1013. '''Turn an array of dict: filename, content into a files array'''
  1014. if not isinstance(content, list):
  1015. content = [content]
  1016. files = []
  1017. for item in content:
  1018. path = Utils.create_tmp_file_from_contents(item['path'] + '-',
  1019. item['data'],
  1020. ftype=content_type)
  1021. files.append({'name': os.path.basename(item['path']),
  1022. 'path': path})
  1023. return files
  1024. @staticmethod
  1025. def cleanup(files):
  1026. '''Clean up on exit '''
  1027. for sfile in files:
  1028. if os.path.exists(sfile):
  1029. if os.path.isdir(sfile):
  1030. shutil.rmtree(sfile)
  1031. elif os.path.isfile(sfile):
  1032. os.remove(sfile)
  1033. @staticmethod
  1034. def exists(results, _name):
  1035. ''' Check to see if the results include the name '''
  1036. if not results:
  1037. return False
  1038. if Utils.find_result(results, _name):
  1039. return True
  1040. return False
  1041. @staticmethod
  1042. def find_result(results, _name):
  1043. ''' Find the specified result by name'''
  1044. rval = None
  1045. for result in results:
  1046. if 'metadata' in result and result['metadata']['name'] == _name:
  1047. rval = result
  1048. break
  1049. return rval
  1050. @staticmethod
  1051. def get_resource_file(sfile, sfile_type='yaml'):
  1052. ''' return the service file '''
  1053. contents = None
  1054. with open(sfile) as sfd:
  1055. contents = sfd.read()
  1056. if sfile_type == 'yaml':
  1057. # AUDIT:no-member makes sense here due to ruamel.YAML/PyYAML usage
  1058. # pylint: disable=no-member
  1059. if hasattr(yaml, 'RoundTripLoader'):
  1060. contents = yaml.load(contents, yaml.RoundTripLoader)
  1061. else:
  1062. contents = yaml.safe_load(contents)
  1063. elif sfile_type == 'json':
  1064. contents = json.loads(contents)
  1065. return contents
  1066. @staticmethod
  1067. def filter_versions(stdout):
  1068. ''' filter the oc version output '''
  1069. version_dict = {}
  1070. version_search = ['oc', 'openshift', 'kubernetes']
  1071. for line in stdout.strip().split('\n'):
  1072. for term in version_search:
  1073. if not line:
  1074. continue
  1075. if line.startswith(term):
  1076. version_dict[term] = line.split()[-1]
  1077. # horrible hack to get openshift version in Openshift 3.2
  1078. # By default "oc version in 3.2 does not return an "openshift" version
  1079. if "openshift" not in version_dict:
  1080. version_dict["openshift"] = version_dict["oc"]
  1081. return version_dict
  1082. @staticmethod
  1083. def add_custom_versions(versions):
  1084. ''' create custom versions strings '''
  1085. versions_dict = {}
  1086. for tech, version in versions.items():
  1087. # clean up "-" from version
  1088. if "-" in version:
  1089. version = version.split("-")[0]
  1090. if version.startswith('v'):
  1091. versions_dict[tech + '_numeric'] = version[1:].split('+')[0]
  1092. # "v3.3.0.33" is what we have, we want "3.3"
  1093. versions_dict[tech + '_short'] = version[1:4]
  1094. return versions_dict
  1095. @staticmethod
  1096. def openshift_installed():
  1097. ''' check if openshift is installed '''
  1098. import yum
  1099. yum_base = yum.YumBase()
  1100. if yum_base.rpmdb.searchNevra(name='atomic-openshift'):
  1101. return True
  1102. return False
  1103. # Disabling too-many-branches. This is a yaml dictionary comparison function
  1104. # pylint: disable=too-many-branches,too-many-return-statements,too-many-statements
  1105. @staticmethod
  1106. def check_def_equal(user_def, result_def, skip_keys=None, debug=False):
  1107. ''' Given a user defined definition, compare it with the results given back by our query. '''
  1108. # Currently these values are autogenerated and we do not need to check them
  1109. skip = ['metadata', 'status']
  1110. if skip_keys:
  1111. skip.extend(skip_keys)
  1112. for key, value in result_def.items():
  1113. if key in skip:
  1114. continue
  1115. # Both are lists
  1116. if isinstance(value, list):
  1117. if key not in user_def:
  1118. if debug:
  1119. print('User data does not have key [%s]' % key)
  1120. print('User data: %s' % user_def)
  1121. return False
  1122. if not isinstance(user_def[key], list):
  1123. if debug:
  1124. print('user_def[key] is not a list key=[%s] user_def[key]=%s' % (key, user_def[key]))
  1125. return False
  1126. if len(user_def[key]) != len(value):
  1127. if debug:
  1128. print("List lengths are not equal.")
  1129. print("key=[%s]: user_def[%s] != value[%s]" % (key, len(user_def[key]), len(value)))
  1130. print("user_def: %s" % user_def[key])
  1131. print("value: %s" % value)
  1132. return False
  1133. for values in zip(user_def[key], value):
  1134. if isinstance(values[0], dict) and isinstance(values[1], dict):
  1135. if debug:
  1136. print('sending list - list')
  1137. print(type(values[0]))
  1138. print(type(values[1]))
  1139. result = Utils.check_def_equal(values[0], values[1], skip_keys=skip_keys, debug=debug)
  1140. if not result:
  1141. print('list compare returned false')
  1142. return False
  1143. elif value != user_def[key]:
  1144. if debug:
  1145. print('value should be identical')
  1146. print(user_def[key])
  1147. print(value)
  1148. return False
  1149. # recurse on a dictionary
  1150. elif isinstance(value, dict):
  1151. if key not in user_def:
  1152. if debug:
  1153. print("user_def does not have key [%s]" % key)
  1154. return False
  1155. if not isinstance(user_def[key], dict):
  1156. if debug:
  1157. print("dict returned false: not instance of dict")
  1158. return False
  1159. # before passing ensure keys match
  1160. api_values = set(value.keys()) - set(skip)
  1161. user_values = set(user_def[key].keys()) - set(skip)
  1162. if api_values != user_values:
  1163. if debug:
  1164. print("keys are not equal in dict")
  1165. print(user_values)
  1166. print(api_values)
  1167. return False
  1168. result = Utils.check_def_equal(user_def[key], value, skip_keys=skip_keys, debug=debug)
  1169. if not result:
  1170. if debug:
  1171. print("dict returned false")
  1172. print(result)
  1173. return False
  1174. # Verify each key, value pair is the same
  1175. else:
  1176. if key not in user_def or value != user_def[key]:
  1177. if debug:
  1178. print("value not equal; user_def does not have key")
  1179. print(key)
  1180. print(value)
  1181. if key in user_def:
  1182. print(user_def[key])
  1183. return False
  1184. if debug:
  1185. print('returning true')
  1186. return True
  1187. class OpenShiftCLIConfig(object):
  1188. '''Generic Config'''
  1189. def __init__(self, rname, namespace, kubeconfig, options):
  1190. self.kubeconfig = kubeconfig
  1191. self.name = rname
  1192. self.namespace = namespace
  1193. self._options = options
  1194. @property
  1195. def config_options(self):
  1196. ''' return config options '''
  1197. return self._options
  1198. def to_option_list(self):
  1199. '''return all options as a string'''
  1200. return self.stringify()
  1201. def stringify(self):
  1202. ''' return the options hash as cli params in a string '''
  1203. rval = []
  1204. for key in sorted(self.config_options.keys()):
  1205. data = self.config_options[key]
  1206. if data['include'] \
  1207. and (data['value'] or isinstance(data['value'], int)):
  1208. rval.append('--{}={}'.format(key.replace('_', '-'), data['value']))
  1209. return rval
  1210. # -*- -*- -*- End included fragment: lib/base.py -*- -*- -*-
  1211. # -*- -*- -*- Begin included fragment: lib/deploymentconfig.py -*- -*- -*-
  1212. # pylint: disable=too-many-public-methods
  1213. class DeploymentConfig(Yedit):
  1214. ''' Class to model an openshift DeploymentConfig'''
  1215. default_deployment_config = '''
  1216. apiVersion: v1
  1217. kind: DeploymentConfig
  1218. metadata:
  1219. name: default_dc
  1220. namespace: default
  1221. spec:
  1222. replicas: 0
  1223. selector:
  1224. default_dc: default_dc
  1225. strategy:
  1226. resources: {}
  1227. rollingParams:
  1228. intervalSeconds: 1
  1229. maxSurge: 0
  1230. maxUnavailable: 25%
  1231. timeoutSeconds: 600
  1232. updatePercent: -25
  1233. updatePeriodSeconds: 1
  1234. type: Rolling
  1235. template:
  1236. metadata:
  1237. spec:
  1238. containers:
  1239. - env:
  1240. - name: default
  1241. value: default
  1242. image: default
  1243. imagePullPolicy: IfNotPresent
  1244. name: default_dc
  1245. ports:
  1246. - containerPort: 8000
  1247. hostPort: 8000
  1248. protocol: TCP
  1249. name: default_port
  1250. resources: {}
  1251. terminationMessagePath: /dev/termination-log
  1252. dnsPolicy: ClusterFirst
  1253. hostNetwork: true
  1254. nodeSelector:
  1255. type: compute
  1256. restartPolicy: Always
  1257. securityContext: {}
  1258. serviceAccount: default
  1259. serviceAccountName: default
  1260. terminationGracePeriodSeconds: 30
  1261. triggers:
  1262. - type: ConfigChange
  1263. '''
  1264. replicas_path = "spec.replicas"
  1265. env_path = "spec.template.spec.containers[0].env"
  1266. volumes_path = "spec.template.spec.volumes"
  1267. container_path = "spec.template.spec.containers"
  1268. volume_mounts_path = "spec.template.spec.containers[0].volumeMounts"
  1269. def __init__(self, content=None):
  1270. ''' Constructor for deploymentconfig '''
  1271. if not content:
  1272. content = DeploymentConfig.default_deployment_config
  1273. super(DeploymentConfig, self).__init__(content=content)
  1274. def add_env_value(self, key, value):
  1275. ''' add key, value pair to env array '''
  1276. rval = False
  1277. env = self.get_env_vars()
  1278. if env:
  1279. env.append({'name': key, 'value': value})
  1280. rval = True
  1281. else:
  1282. result = self.put(DeploymentConfig.env_path, {'name': key, 'value': value})
  1283. rval = result[0]
  1284. return rval
  1285. def exists_env_value(self, key, value):
  1286. ''' return whether a key, value pair exists '''
  1287. results = self.get_env_vars()
  1288. if not results:
  1289. return False
  1290. for result in results:
  1291. if result['name'] == key and result['value'] == value:
  1292. return True
  1293. return False
  1294. def exists_env_key(self, key):
  1295. ''' return whether a key, value pair exists '''
  1296. results = self.get_env_vars()
  1297. if not results:
  1298. return False
  1299. for result in results:
  1300. if result['name'] == key:
  1301. return True
  1302. return False
  1303. def get_env_var(self, key):
  1304. '''return a environment variables '''
  1305. results = self.get(DeploymentConfig.env_path) or []
  1306. if not results:
  1307. return None
  1308. for env_var in results:
  1309. if env_var['name'] == key:
  1310. return env_var
  1311. return None
  1312. def get_env_vars(self):
  1313. '''return a environment variables '''
  1314. return self.get(DeploymentConfig.env_path) or []
  1315. def delete_env_var(self, keys):
  1316. '''delete a list of keys '''
  1317. if not isinstance(keys, list):
  1318. keys = [keys]
  1319. env_vars_array = self.get_env_vars()
  1320. modified = False
  1321. idx = None
  1322. for key in keys:
  1323. for env_idx, env_var in enumerate(env_vars_array):
  1324. if env_var['name'] == key:
  1325. idx = env_idx
  1326. break
  1327. if idx:
  1328. modified = True
  1329. del env_vars_array[idx]
  1330. if modified:
  1331. return True
  1332. return False
  1333. def update_env_var(self, key, value):
  1334. '''place an env in the env var list'''
  1335. env_vars_array = self.get_env_vars()
  1336. idx = None
  1337. for env_idx, env_var in enumerate(env_vars_array):
  1338. if env_var['name'] == key:
  1339. idx = env_idx
  1340. break
  1341. if idx:
  1342. env_vars_array[idx]['value'] = value
  1343. else:
  1344. self.add_env_value(key, value)
  1345. return True
  1346. def exists_volume_mount(self, volume_mount):
  1347. ''' return whether a volume mount exists '''
  1348. exist_volume_mounts = self.get_volume_mounts()
  1349. if not exist_volume_mounts:
  1350. return False
  1351. volume_mount_found = False
  1352. for exist_volume_mount in exist_volume_mounts:
  1353. if exist_volume_mount['name'] == volume_mount['name']:
  1354. volume_mount_found = True
  1355. break
  1356. return volume_mount_found
  1357. def exists_volume(self, volume):
  1358. ''' return whether a volume exists '''
  1359. exist_volumes = self.get_volumes()
  1360. volume_found = False
  1361. for exist_volume in exist_volumes:
  1362. if exist_volume['name'] == volume['name']:
  1363. volume_found = True
  1364. break
  1365. return volume_found
  1366. def find_volume_by_name(self, volume, mounts=False):
  1367. ''' return the index of a volume '''
  1368. volumes = []
  1369. if mounts:
  1370. volumes = self.get_volume_mounts()
  1371. else:
  1372. volumes = self.get_volumes()
  1373. for exist_volume in volumes:
  1374. if exist_volume['name'] == volume['name']:
  1375. return exist_volume
  1376. return None
  1377. def get_replicas(self):
  1378. ''' return replicas setting '''
  1379. return self.get(DeploymentConfig.replicas_path)
  1380. def get_volume_mounts(self):
  1381. '''return volume mount information '''
  1382. return self.get_volumes(mounts=True)
  1383. def get_volumes(self, mounts=False):
  1384. '''return volume mount information '''
  1385. if mounts:
  1386. return self.get(DeploymentConfig.volume_mounts_path) or []
  1387. return self.get(DeploymentConfig.volumes_path) or []
  1388. def delete_volume_by_name(self, volume):
  1389. '''delete a volume '''
  1390. modified = False
  1391. exist_volume_mounts = self.get_volume_mounts()
  1392. exist_volumes = self.get_volumes()
  1393. del_idx = None
  1394. for idx, exist_volume in enumerate(exist_volumes):
  1395. if 'name' in exist_volume and exist_volume['name'] == volume['name']:
  1396. del_idx = idx
  1397. break
  1398. if del_idx != None:
  1399. del exist_volumes[del_idx]
  1400. modified = True
  1401. del_idx = None
  1402. for idx, exist_volume_mount in enumerate(exist_volume_mounts):
  1403. if 'name' in exist_volume_mount and exist_volume_mount['name'] == volume['name']:
  1404. del_idx = idx
  1405. break
  1406. if del_idx != None:
  1407. del exist_volume_mounts[idx]
  1408. modified = True
  1409. return modified
  1410. def add_volume_mount(self, volume_mount):
  1411. ''' add a volume or volume mount to the proper location '''
  1412. exist_volume_mounts = self.get_volume_mounts()
  1413. if not exist_volume_mounts and volume_mount:
  1414. self.put(DeploymentConfig.volume_mounts_path, [volume_mount])
  1415. else:
  1416. exist_volume_mounts.append(volume_mount)
  1417. def add_volume(self, volume):
  1418. ''' add a volume or volume mount to the proper location '''
  1419. exist_volumes = self.get_volumes()
  1420. if not volume:
  1421. return
  1422. if not exist_volumes:
  1423. self.put(DeploymentConfig.volumes_path, [volume])
  1424. else:
  1425. exist_volumes.append(volume)
  1426. def update_replicas(self, replicas):
  1427. ''' update replicas value '''
  1428. self.put(DeploymentConfig.replicas_path, replicas)
  1429. def update_volume(self, volume):
  1430. '''place an env in the env var list'''
  1431. exist_volumes = self.get_volumes()
  1432. if not volume:
  1433. return False
  1434. # update the volume
  1435. update_idx = None
  1436. for idx, exist_vol in enumerate(exist_volumes):
  1437. if exist_vol['name'] == volume['name']:
  1438. update_idx = idx
  1439. break
  1440. if update_idx != None:
  1441. exist_volumes[update_idx] = volume
  1442. else:
  1443. self.add_volume(volume)
  1444. return True
  1445. def update_volume_mount(self, volume_mount):
  1446. '''place an env in the env var list'''
  1447. modified = False
  1448. exist_volume_mounts = self.get_volume_mounts()
  1449. if not volume_mount:
  1450. return False
  1451. # update the volume mount
  1452. for exist_vol_mount in exist_volume_mounts:
  1453. if exist_vol_mount['name'] == volume_mount['name']:
  1454. if 'mountPath' in exist_vol_mount and \
  1455. str(exist_vol_mount['mountPath']) != str(volume_mount['mountPath']):
  1456. exist_vol_mount['mountPath'] = volume_mount['mountPath']
  1457. modified = True
  1458. break
  1459. if not modified:
  1460. self.add_volume_mount(volume_mount)
  1461. modified = True
  1462. return modified
  1463. def needs_update_volume(self, volume, volume_mount):
  1464. ''' verify a volume update is needed '''
  1465. exist_volume = self.find_volume_by_name(volume)
  1466. exist_volume_mount = self.find_volume_by_name(volume, mounts=True)
  1467. results = []
  1468. results.append(exist_volume['name'] == volume['name'])
  1469. if 'secret' in volume:
  1470. results.append('secret' in exist_volume)
  1471. results.append(exist_volume['secret']['secretName'] == volume['secret']['secretName'])
  1472. results.append(exist_volume_mount['name'] == volume_mount['name'])
  1473. results.append(exist_volume_mount['mountPath'] == volume_mount['mountPath'])
  1474. elif 'emptyDir' in volume:
  1475. results.append(exist_volume_mount['name'] == volume['name'])
  1476. results.append(exist_volume_mount['mountPath'] == volume_mount['mountPath'])
  1477. elif 'persistentVolumeClaim' in volume:
  1478. pvc = 'persistentVolumeClaim'
  1479. results.append(pvc in exist_volume)
  1480. if results[-1]:
  1481. results.append(exist_volume[pvc]['claimName'] == volume[pvc]['claimName'])
  1482. if 'claimSize' in volume[pvc]:
  1483. results.append(exist_volume[pvc]['claimSize'] == volume[pvc]['claimSize'])
  1484. elif 'hostpath' in volume:
  1485. results.append('hostPath' in exist_volume)
  1486. results.append(exist_volume['hostPath']['path'] == volume_mount['mountPath'])
  1487. return not all(results)
  1488. def needs_update_replicas(self, replicas):
  1489. ''' verify whether a replica update is needed '''
  1490. current_reps = self.get(DeploymentConfig.replicas_path)
  1491. return not current_reps == replicas
  1492. # -*- -*- -*- End included fragment: lib/deploymentconfig.py -*- -*- -*-
  1493. # -*- -*- -*- Begin included fragment: lib/secret.py -*- -*- -*-
  1494. # pylint: disable=too-many-instance-attributes
  1495. class SecretConfig(object):
  1496. ''' Handle secret options '''
  1497. # pylint: disable=too-many-arguments
  1498. def __init__(self,
  1499. sname,
  1500. namespace,
  1501. kubeconfig,
  1502. secrets=None):
  1503. ''' constructor for handling secret options '''
  1504. self.kubeconfig = kubeconfig
  1505. self.name = sname
  1506. self.namespace = namespace
  1507. self.secrets = secrets
  1508. self.data = {}
  1509. self.create_dict()
  1510. def create_dict(self):
  1511. ''' assign the correct properties for a secret dict '''
  1512. self.data['apiVersion'] = 'v1'
  1513. self.data['kind'] = 'Secret'
  1514. self.data['metadata'] = {}
  1515. self.data['metadata']['name'] = self.name
  1516. self.data['metadata']['namespace'] = self.namespace
  1517. self.data['data'] = {}
  1518. if self.secrets:
  1519. for key, value in self.secrets.items():
  1520. self.data['data'][key] = value
  1521. # pylint: disable=too-many-instance-attributes
  1522. class Secret(Yedit):
  1523. ''' Class to wrap the oc command line tools '''
  1524. secret_path = "data"
  1525. kind = 'secret'
  1526. def __init__(self, content):
  1527. '''secret constructor'''
  1528. super(Secret, self).__init__(content=content)
  1529. self._secrets = None
  1530. @property
  1531. def secrets(self):
  1532. '''secret property getter'''
  1533. if self._secrets is None:
  1534. self._secrets = self.get_secrets()
  1535. return self._secrets
  1536. @secrets.setter
  1537. def secrets(self):
  1538. '''secret property setter'''
  1539. if self._secrets is None:
  1540. self._secrets = self.get_secrets()
  1541. return self._secrets
  1542. def get_secrets(self):
  1543. ''' returns all of the defined secrets '''
  1544. return self.get(Secret.secret_path) or {}
  1545. def add_secret(self, key, value):
  1546. ''' add a secret '''
  1547. if self.secrets:
  1548. self.secrets[key] = value
  1549. else:
  1550. self.put(Secret.secret_path, {key: value})
  1551. return True
  1552. def delete_secret(self, key):
  1553. ''' delete secret'''
  1554. try:
  1555. del self.secrets[key]
  1556. except KeyError as _:
  1557. return False
  1558. return True
  1559. def find_secret(self, key):
  1560. ''' find secret'''
  1561. rval = None
  1562. try:
  1563. rval = self.secrets[key]
  1564. except KeyError as _:
  1565. return None
  1566. return {'key': key, 'value': rval}
  1567. def update_secret(self, key, value):
  1568. ''' update a secret'''
  1569. if key in self.secrets:
  1570. self.secrets[key] = value
  1571. else:
  1572. self.add_secret(key, value)
  1573. return True
  1574. # -*- -*- -*- End included fragment: lib/secret.py -*- -*- -*-
  1575. # -*- -*- -*- Begin included fragment: lib/service.py -*- -*- -*-
  1576. # pylint: disable=too-many-instance-attributes
  1577. class ServiceConfig(object):
  1578. ''' Handle service options '''
  1579. # pylint: disable=too-many-arguments
  1580. def __init__(self,
  1581. sname,
  1582. namespace,
  1583. ports,
  1584. selector=None,
  1585. labels=None,
  1586. cluster_ip=None,
  1587. portal_ip=None,
  1588. session_affinity=None,
  1589. service_type=None):
  1590. ''' constructor for handling service options '''
  1591. self.name = sname
  1592. self.namespace = namespace
  1593. self.ports = ports
  1594. self.selector = selector
  1595. self.labels = labels
  1596. self.cluster_ip = cluster_ip
  1597. self.portal_ip = portal_ip
  1598. self.session_affinity = session_affinity
  1599. self.service_type = service_type
  1600. self.data = {}
  1601. self.create_dict()
  1602. def create_dict(self):
  1603. ''' instantiates a service dict '''
  1604. self.data['apiVersion'] = 'v1'
  1605. self.data['kind'] = 'Service'
  1606. self.data['metadata'] = {}
  1607. self.data['metadata']['name'] = self.name
  1608. self.data['metadata']['namespace'] = self.namespace
  1609. if self.labels:
  1610. for lab, lab_value in self.labels.items():
  1611. self.data['metadata'][lab] = lab_value
  1612. self.data['spec'] = {}
  1613. if self.ports:
  1614. self.data['spec']['ports'] = self.ports
  1615. else:
  1616. self.data['spec']['ports'] = []
  1617. if self.selector:
  1618. self.data['spec']['selector'] = self.selector
  1619. self.data['spec']['sessionAffinity'] = self.session_affinity or 'None'
  1620. if self.cluster_ip:
  1621. self.data['spec']['clusterIP'] = self.cluster_ip
  1622. if self.portal_ip:
  1623. self.data['spec']['portalIP'] = self.portal_ip
  1624. if self.service_type:
  1625. self.data['spec']['type'] = self.service_type
  1626. # pylint: disable=too-many-instance-attributes,too-many-public-methods
  1627. class Service(Yedit):
  1628. ''' Class to model the oc service object '''
  1629. port_path = "spec.ports"
  1630. portal_ip = "spec.portalIP"
  1631. cluster_ip = "spec.clusterIP"
  1632. selector_path = 'spec.selector'
  1633. kind = 'Service'
  1634. def __init__(self, content):
  1635. '''Service constructor'''
  1636. super(Service, self).__init__(content=content)
  1637. def get_ports(self):
  1638. ''' get a list of ports '''
  1639. return self.get(Service.port_path) or []
  1640. def get_selector(self):
  1641. ''' get the service selector'''
  1642. return self.get(Service.selector_path) or {}
  1643. def add_ports(self, inc_ports):
  1644. ''' add a port object to the ports list '''
  1645. if not isinstance(inc_ports, list):
  1646. inc_ports = [inc_ports]
  1647. ports = self.get_ports()
  1648. if not ports:
  1649. self.put(Service.port_path, inc_ports)
  1650. else:
  1651. ports.extend(inc_ports)
  1652. return True
  1653. def find_ports(self, inc_port):
  1654. ''' find a specific port '''
  1655. for port in self.get_ports():
  1656. if port['port'] == inc_port['port']:
  1657. return port
  1658. return None
  1659. def delete_ports(self, inc_ports):
  1660. ''' remove a port from a service '''
  1661. if not isinstance(inc_ports, list):
  1662. inc_ports = [inc_ports]
  1663. ports = self.get(Service.port_path) or []
  1664. if not ports:
  1665. return True
  1666. removed = False
  1667. for inc_port in inc_ports:
  1668. port = self.find_ports(inc_port)
  1669. if port:
  1670. ports.remove(port)
  1671. removed = True
  1672. return removed
  1673. def add_cluster_ip(self, sip):
  1674. '''add cluster ip'''
  1675. self.put(Service.cluster_ip, sip)
  1676. def add_portal_ip(self, pip):
  1677. '''add cluster ip'''
  1678. self.put(Service.portal_ip, pip)
  1679. # -*- -*- -*- End included fragment: lib/service.py -*- -*- -*-
  1680. # -*- -*- -*- Begin included fragment: lib/volume.py -*- -*- -*-
  1681. class Volume(object):
  1682. ''' Class to model an openshift volume object'''
  1683. volume_mounts_path = {"pod": "spec.containers[0].volumeMounts",
  1684. "dc": "spec.template.spec.containers[0].volumeMounts",
  1685. "rc": "spec.template.spec.containers[0].volumeMounts",
  1686. }
  1687. volumes_path = {"pod": "spec.volumes",
  1688. "dc": "spec.template.spec.volumes",
  1689. "rc": "spec.template.spec.volumes",
  1690. }
  1691. @staticmethod
  1692. def create_volume_structure(volume_info):
  1693. ''' return a properly structured volume '''
  1694. volume_mount = None
  1695. volume = {'name': volume_info['name']}
  1696. volume_type = volume_info['type'].lower()
  1697. if volume_type == 'secret':
  1698. volume['secret'] = {}
  1699. volume[volume_info['type']] = {'secretName': volume_info['secret_name']}
  1700. volume_mount = {'mountPath': volume_info['path'],
  1701. 'name': volume_info['name']}
  1702. elif volume_type == 'emptydir':
  1703. volume['emptyDir'] = {}
  1704. volume_mount = {'mountPath': volume_info['path'],
  1705. 'name': volume_info['name']}
  1706. elif volume_type == 'pvc' or volume_type == 'persistentvolumeclaim':
  1707. volume['persistentVolumeClaim'] = {}
  1708. volume['persistentVolumeClaim']['claimName'] = volume_info['claimName']
  1709. volume['persistentVolumeClaim']['claimSize'] = volume_info['claimSize']
  1710. elif volume_type == 'hostpath':
  1711. volume['hostPath'] = {}
  1712. volume['hostPath']['path'] = volume_info['path']
  1713. return (volume, volume_mount)
  1714. # -*- -*- -*- End included fragment: lib/volume.py -*- -*- -*-
  1715. # -*- -*- -*- Begin included fragment: class/oc_version.py -*- -*- -*-
  1716. # pylint: disable=too-many-instance-attributes
  1717. class OCVersion(OpenShiftCLI):
  1718. ''' Class to wrap the oc command line tools '''
  1719. # pylint allows 5
  1720. # pylint: disable=too-many-arguments
  1721. def __init__(self,
  1722. config,
  1723. debug):
  1724. ''' Constructor for OCVersion '''
  1725. super(OCVersion, self).__init__(None, config)
  1726. self.debug = debug
  1727. def get(self):
  1728. '''get and return version information '''
  1729. results = {}
  1730. version_results = self._version()
  1731. if version_results['returncode'] == 0:
  1732. filtered_vers = Utils.filter_versions(version_results['results'])
  1733. custom_vers = Utils.add_custom_versions(filtered_vers)
  1734. results['returncode'] = version_results['returncode']
  1735. results.update(filtered_vers)
  1736. results.update(custom_vers)
  1737. return results
  1738. raise OpenShiftCLIError('Problem detecting openshift version.')
  1739. @staticmethod
  1740. def run_ansible(params):
  1741. '''run the idempotent ansible code'''
  1742. oc_version = OCVersion(params['kubeconfig'], params['debug'])
  1743. if params['state'] == 'list':
  1744. #pylint: disable=protected-access
  1745. result = oc_version.get()
  1746. return {'state': params['state'],
  1747. 'results': result,
  1748. 'changed': False}
  1749. # -*- -*- -*- End included fragment: class/oc_version.py -*- -*- -*-
  1750. # -*- -*- -*- Begin included fragment: class/oc_adm_registry.py -*- -*- -*-
  1751. class RegistryException(Exception):
  1752. ''' Registry Exception Class '''
  1753. pass
  1754. class RegistryConfig(OpenShiftCLIConfig):
  1755. ''' RegistryConfig is a DTO for the registry. '''
  1756. def __init__(self, rname, namespace, kubeconfig, registry_options):
  1757. super(RegistryConfig, self).__init__(rname, namespace, kubeconfig, registry_options)
  1758. class Registry(OpenShiftCLI):
  1759. ''' Class to wrap the oc command line tools '''
  1760. volume_mount_path = 'spec.template.spec.containers[0].volumeMounts'
  1761. volume_path = 'spec.template.spec.volumes'
  1762. env_path = 'spec.template.spec.containers[0].env'
  1763. def __init__(self,
  1764. registry_config,
  1765. verbose=False):
  1766. ''' Constructor for Registry
  1767. a registry consists of 3 or more parts
  1768. - dc/docker-registry
  1769. - svc/docker-registry
  1770. Parameters:
  1771. :registry_config:
  1772. :verbose:
  1773. '''
  1774. super(Registry, self).__init__(registry_config.namespace, registry_config.kubeconfig, verbose)
  1775. self.version = OCVersion(registry_config.kubeconfig, verbose)
  1776. self.svc_ip = None
  1777. self.portal_ip = None
  1778. self.config = registry_config
  1779. self.verbose = verbose
  1780. self.registry_parts = [{'kind': 'dc', 'name': self.config.name},
  1781. {'kind': 'svc', 'name': self.config.name},
  1782. ]
  1783. self.__prepared_registry = None
  1784. self.volume_mounts = []
  1785. self.volumes = []
  1786. if self.config.config_options['volume_mounts']['value']:
  1787. for volume in self.config.config_options['volume_mounts']['value']:
  1788. volume_info = {'secret_name': volume.get('secret_name', None),
  1789. 'name': volume.get('name', None),
  1790. 'type': volume.get('type', None),
  1791. 'path': volume.get('path', None),
  1792. 'claimName': volume.get('claim_name', None),
  1793. 'claimSize': volume.get('claim_size', None),
  1794. }
  1795. vol, vol_mount = Volume.create_volume_structure(volume_info)
  1796. self.volumes.append(vol)
  1797. self.volume_mounts.append(vol_mount)
  1798. self.dconfig = None
  1799. self.svc = None
  1800. @property
  1801. def deploymentconfig(self):
  1802. ''' deploymentconfig property '''
  1803. return self.dconfig
  1804. @deploymentconfig.setter
  1805. def deploymentconfig(self, config):
  1806. ''' setter for deploymentconfig property '''
  1807. self.dconfig = config
  1808. @property
  1809. def service(self):
  1810. ''' service property '''
  1811. return self.svc
  1812. @service.setter
  1813. def service(self, config):
  1814. ''' setter for service property '''
  1815. self.svc = config
  1816. @property
  1817. def prepared_registry(self):
  1818. ''' prepared_registry property '''
  1819. if not self.__prepared_registry:
  1820. results = self.prepare_registry()
  1821. if not results:
  1822. raise RegistryException('Could not perform registry preparation.')
  1823. self.__prepared_registry = results
  1824. return self.__prepared_registry
  1825. @prepared_registry.setter
  1826. def prepared_registry(self, data):
  1827. ''' setter method for prepared_registry attribute '''
  1828. self.__prepared_registry = data
  1829. def get(self):
  1830. ''' return the self.registry_parts '''
  1831. self.deploymentconfig = None
  1832. self.service = None
  1833. rval = 0
  1834. for part in self.registry_parts:
  1835. result = self._get(part['kind'], rname=part['name'])
  1836. if result['returncode'] == 0 and part['kind'] == 'dc':
  1837. self.deploymentconfig = DeploymentConfig(result['results'][0])
  1838. elif result['returncode'] == 0 and part['kind'] == 'svc':
  1839. self.service = Service(result['results'][0])
  1840. if result['returncode'] != 0:
  1841. rval = result['returncode']
  1842. return {'returncode': rval, 'deploymentconfig': self.deploymentconfig, 'service': self.service}
  1843. def exists(self):
  1844. '''does the object exist?'''
  1845. if self.deploymentconfig and self.service:
  1846. return True
  1847. return False
  1848. def delete(self, complete=True):
  1849. '''return all pods '''
  1850. parts = []
  1851. for part in self.registry_parts:
  1852. if not complete and part['kind'] == 'svc':
  1853. continue
  1854. parts.append(self._delete(part['kind'], part['name']))
  1855. # Clean up returned results
  1856. rval = 0
  1857. for part in parts:
  1858. # pylint: disable=invalid-sequence-index
  1859. if 'returncode' in part and part['returncode'] != 0:
  1860. rval = part['returncode']
  1861. return {'returncode': rval, 'results': parts}
  1862. def prepare_registry(self):
  1863. ''' prepare a registry for instantiation '''
  1864. options = self.config.to_option_list()
  1865. cmd = ['registry']
  1866. cmd.extend(options)
  1867. cmd.extend(['--dry-run=True', '-o', 'json'])
  1868. results = self.openshift_cmd(cmd, oadm=True, output=True, output_type='json')
  1869. # probably need to parse this
  1870. # pylint thinks results is a string
  1871. # pylint: disable=no-member
  1872. if results['returncode'] != 0 and 'items' in results['results']:
  1873. return results
  1874. service = None
  1875. deploymentconfig = None
  1876. # pylint: disable=invalid-sequence-index
  1877. for res in results['results']['items']:
  1878. if res['kind'] == 'DeploymentConfig':
  1879. deploymentconfig = DeploymentConfig(res)
  1880. elif res['kind'] == 'Service':
  1881. service = Service(res)
  1882. # Verify we got a service and a deploymentconfig
  1883. if not service or not deploymentconfig:
  1884. return results
  1885. # results will need to get parsed here and modifications added
  1886. deploymentconfig = DeploymentConfig(self.add_modifications(deploymentconfig))
  1887. # modify service ip
  1888. if self.svc_ip:
  1889. service.put('spec.clusterIP', self.svc_ip)
  1890. if self.portal_ip:
  1891. service.put('spec.portalIP', self.portal_ip)
  1892. # the dry-run doesn't apply the selector correctly
  1893. if self.service:
  1894. service.put('spec.selector', self.service.get_selector())
  1895. # need to create the service and the deploymentconfig
  1896. service_file = Utils.create_tmp_file_from_contents('service', service.yaml_dict)
  1897. deployment_file = Utils.create_tmp_file_from_contents('deploymentconfig', deploymentconfig.yaml_dict)
  1898. return {"service": service,
  1899. "service_file": service_file,
  1900. "service_update": False,
  1901. "deployment": deploymentconfig,
  1902. "deployment_file": deployment_file,
  1903. "deployment_update": False}
  1904. def create(self):
  1905. '''Create a registry'''
  1906. results = []
  1907. self.needs_update()
  1908. # if the object is none, then we need to create it
  1909. # if the object needs an update, then we should call replace
  1910. # Handle the deploymentconfig
  1911. if self.deploymentconfig is None:
  1912. results.append(self._create(self.prepared_registry['deployment_file']))
  1913. elif self.prepared_registry['deployment_update']:
  1914. results.append(self._replace(self.prepared_registry['deployment_file']))
  1915. # Handle the service
  1916. if self.service is None:
  1917. results.append(self._create(self.prepared_registry['service_file']))
  1918. elif self.prepared_registry['service_update']:
  1919. results.append(self._replace(self.prepared_registry['service_file']))
  1920. # Clean up returned results
  1921. rval = 0
  1922. for result in results:
  1923. # pylint: disable=invalid-sequence-index
  1924. if 'returncode' in result and result['returncode'] != 0:
  1925. rval = result['returncode']
  1926. return {'returncode': rval, 'results': results}
  1927. def update(self):
  1928. '''run update for the registry. This performs a replace if required'''
  1929. # Store the current service IP
  1930. if self.service:
  1931. svcip = self.service.get('spec.clusterIP')
  1932. if svcip:
  1933. self.svc_ip = svcip
  1934. portip = self.service.get('spec.portalIP')
  1935. if portip:
  1936. self.portal_ip = portip
  1937. results = []
  1938. if self.prepared_registry['deployment_update']:
  1939. results.append(self._replace(self.prepared_registry['deployment_file']))
  1940. if self.prepared_registry['service_update']:
  1941. results.append(self._replace(self.prepared_registry['service_file']))
  1942. # Clean up returned results
  1943. rval = 0
  1944. for result in results:
  1945. if result['returncode'] != 0:
  1946. rval = result['returncode']
  1947. return {'returncode': rval, 'results': results}
  1948. def add_modifications(self, deploymentconfig):
  1949. ''' update a deployment config with changes '''
  1950. # The environment variable for REGISTRY_HTTP_SECRET is autogenerated
  1951. # We should set the generated deploymentconfig to the in memory version
  1952. # the following modifications will overwrite if needed
  1953. if self.deploymentconfig:
  1954. result = self.deploymentconfig.get_env_var('REGISTRY_HTTP_SECRET')
  1955. if result:
  1956. deploymentconfig.update_env_var('REGISTRY_HTTP_SECRET', result['value'])
  1957. # Currently we know that our deployment of a registry requires a few extra modifications
  1958. # Modification 1
  1959. # we need specific environment variables to be set
  1960. for key, value in self.config.config_options['env_vars'].get('value', {}).items():
  1961. if not deploymentconfig.exists_env_key(key):
  1962. deploymentconfig.add_env_value(key, value)
  1963. else:
  1964. deploymentconfig.update_env_var(key, value)
  1965. # Modification 2
  1966. # we need specific volume variables to be set
  1967. for volume in self.volumes:
  1968. deploymentconfig.update_volume(volume)
  1969. for vol_mount in self.volume_mounts:
  1970. deploymentconfig.update_volume_mount(vol_mount)
  1971. # Modification 3
  1972. # Edits
  1973. edit_results = []
  1974. for edit in self.config.config_options['edits'].get('value', []):
  1975. if edit['action'] == 'put':
  1976. edit_results.append(deploymentconfig.put(edit['key'],
  1977. edit['value']))
  1978. if edit['action'] == 'update':
  1979. edit_results.append(deploymentconfig.update(edit['key'],
  1980. edit['value'],
  1981. edit.get('index', None),
  1982. edit.get('curr_value', None)))
  1983. if edit['action'] == 'append':
  1984. edit_results.append(deploymentconfig.append(edit['key'],
  1985. edit['value']))
  1986. if edit_results and not any([res[0] for res in edit_results]):
  1987. return None
  1988. return deploymentconfig.yaml_dict
  1989. def needs_update(self):
  1990. ''' check to see if we need to update '''
  1991. exclude_list = ['clusterIP', 'portalIP', 'type', 'protocol']
  1992. if self.service is None or \
  1993. not Utils.check_def_equal(self.prepared_registry['service'].yaml_dict,
  1994. self.service.yaml_dict,
  1995. exclude_list,
  1996. debug=self.verbose):
  1997. self.prepared_registry['service_update'] = True
  1998. exclude_list = ['dnsPolicy',
  1999. 'terminationGracePeriodSeconds',
  2000. 'restartPolicy', 'timeoutSeconds',
  2001. 'livenessProbe', 'readinessProbe',
  2002. 'terminationMessagePath',
  2003. 'securityContext',
  2004. 'imagePullPolicy',
  2005. 'protocol', # ports.portocol: TCP
  2006. 'type', # strategy: {'type': 'rolling'}
  2007. 'defaultMode', # added on secrets
  2008. 'activeDeadlineSeconds', # added in 1.5 for timeouts
  2009. ]
  2010. if self.deploymentconfig is None or \
  2011. not Utils.check_def_equal(self.prepared_registry['deployment'].yaml_dict,
  2012. self.deploymentconfig.yaml_dict,
  2013. exclude_list,
  2014. debug=self.verbose):
  2015. self.prepared_registry['deployment_update'] = True
  2016. return self.prepared_registry['deployment_update'] or self.prepared_registry['service_update'] or False
  2017. # In the future, we would like to break out each ansible state into a function.
  2018. # pylint: disable=too-many-branches,too-many-return-statements
  2019. @staticmethod
  2020. def run_ansible(params, check_mode):
  2021. '''run idempotent ansible code'''
  2022. rconfig = RegistryConfig(params['name'],
  2023. params['namespace'],
  2024. params['kubeconfig'],
  2025. {'images': {'value': params['images'], 'include': True},
  2026. 'latest_images': {'value': params['latest_images'], 'include': True},
  2027. 'labels': {'value': params['labels'], 'include': True},
  2028. 'ports': {'value': ','.join(params['ports']), 'include': True},
  2029. 'replicas': {'value': params['replicas'], 'include': True},
  2030. 'selector': {'value': params['selector'], 'include': True},
  2031. 'service_account': {'value': params['service_account'], 'include': True},
  2032. 'mount_host': {'value': params['mount_host'], 'include': True},
  2033. 'env_vars': {'value': params['env_vars'], 'include': False},
  2034. 'volume_mounts': {'value': params['volume_mounts'], 'include': False},
  2035. 'edits': {'value': params['edits'], 'include': False},
  2036. 'enforce_quota': {'value': params['enforce_quota'], 'include': True},
  2037. 'daemonset': {'value': params['daemonset'], 'include': True},
  2038. 'tls_key': {'value': params['tls_key'], 'include': True},
  2039. 'tls_certificate': {'value': params['tls_certificate'], 'include': True},
  2040. })
  2041. ocregistry = Registry(rconfig, params['debug'])
  2042. api_rval = ocregistry.get()
  2043. state = params['state']
  2044. ########
  2045. # get
  2046. ########
  2047. if state == 'list':
  2048. if api_rval['returncode'] != 0:
  2049. return {'failed': True, 'msg': api_rval}
  2050. return {'changed': False, 'results': api_rval, 'state': state}
  2051. ########
  2052. # Delete
  2053. ########
  2054. if state == 'absent':
  2055. if not ocregistry.exists():
  2056. return {'changed': False, 'state': state}
  2057. if check_mode:
  2058. return {'changed': True, 'msg': 'CHECK_MODE: Would have performed a delete.'}
  2059. # Unsure as to why this is angry with the return type.
  2060. # pylint: disable=redefined-variable-type
  2061. api_rval = ocregistry.delete()
  2062. if api_rval['returncode'] != 0:
  2063. return {'failed': True, 'msg': api_rval}
  2064. return {'changed': True, 'results': api_rval, 'state': state}
  2065. if state == 'present':
  2066. ########
  2067. # Create
  2068. ########
  2069. if not ocregistry.exists():
  2070. if check_mode:
  2071. return {'changed': True, 'msg': 'CHECK_MODE: Would have performed a create.'}
  2072. api_rval = ocregistry.create()
  2073. if api_rval['returncode'] != 0:
  2074. return {'failed': True, 'msg': api_rval}
  2075. return {'changed': True, 'results': api_rval, 'state': state}
  2076. ########
  2077. # Update
  2078. ########
  2079. if not params['force'] and not ocregistry.needs_update():
  2080. return {'changed': False, 'state': state}
  2081. if check_mode:
  2082. return {'changed': True, 'msg': 'CHECK_MODE: Would have performed an update.'}
  2083. api_rval = ocregistry.update()
  2084. if api_rval['returncode'] != 0:
  2085. return {'failed': True, 'msg': api_rval}
  2086. return {'changed': True, 'results': api_rval, 'state': state}
  2087. return {'failed': True, 'msg': 'Unknown state passed. %s' % state}
  2088. # -*- -*- -*- End included fragment: class/oc_adm_registry.py -*- -*- -*-
  2089. # -*- -*- -*- Begin included fragment: ansible/oc_adm_registry.py -*- -*- -*-
  2090. def main():
  2091. '''
  2092. ansible oc module for registry
  2093. '''
  2094. module = AnsibleModule(
  2095. argument_spec=dict(
  2096. state=dict(default='present', type='str',
  2097. choices=['present', 'absent']),
  2098. debug=dict(default=False, type='bool'),
  2099. namespace=dict(default='default', type='str'),
  2100. name=dict(default=None, required=True, type='str'),
  2101. kubeconfig=dict(default='/etc/origin/master/admin.kubeconfig', type='str'),
  2102. images=dict(default=None, type='str'),
  2103. latest_images=dict(default=False, type='bool'),
  2104. labels=dict(default=None, type='list'),
  2105. ports=dict(default=['5000'], type='list'),
  2106. replicas=dict(default=1, type='int'),
  2107. selector=dict(default=None, type='str'),
  2108. service_account=dict(default='registry', type='str'),
  2109. mount_host=dict(default=None, type='str'),
  2110. volume_mounts=dict(default=None, type='list'),
  2111. env_vars=dict(default={}, type='dict'),
  2112. edits=dict(default=[], type='list'),
  2113. enforce_quota=dict(default=False, type='bool'),
  2114. force=dict(default=False, type='bool'),
  2115. daemonset=dict(default=False, type='bool'),
  2116. tls_key=dict(default=None, type='str'),
  2117. tls_certificate=dict(default=None, type='str'),
  2118. ),
  2119. supports_check_mode=True,
  2120. )
  2121. results = Registry.run_ansible(module.params, module.check_mode)
  2122. if 'failed' in results:
  2123. module.fail_json(**results)
  2124. module.exit_json(**results)
  2125. if __name__ == '__main__':
  2126. main()
  2127. # -*- -*- -*- End included fragment: ansible/oc_adm_registry.py -*- -*- -*-