oc_adm_registry.py 92 KB

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