oc_adm_registry.py 89 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305230623072308230923102311231223132314231523162317231823192320232123222323232423252326232723282329233023312332233323342335233623372338233923402341234223432344234523462347234823492350235123522353235423552356235723582359236023612362236323642365236623672368236923702371237223732374237523762377237823792380238123822383238423852386238723882389239023912392239323942395239623972398239924002401240224032404240524062407240824092410241124122413241424152416241724182419242024212422242324242425242624272428242924302431243224332434243524362437243824392440244124422443244424452446244724482449245024512452245324542455245624572458245924602461246224632464246524662467246824692470247124722473247424752476247724782479248024812482248324842485248624872488248924902491249224932494249524962497249824992500250125022503250425052506250725082509251025112512251325142515251625172518251925202521252225232524252525262527252825292530253125322533253425352536253725382539254025412542254325442545254625472548254925502551255225532554255525562557255825592560256125622563256425652566256725682569257025712572257325742575257625772578257925802581258225832584258525862587258825892590259125922593259425952596259725982599260026012602260326042605260626072608260926102611261226132614261526162617261826192620262126222623262426252626262726282629263026312632263326342635263626372638263926402641264226432644264526462647264826492650265126522653265426552656265726582659266026612662266326642665266626672668
  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):
  238. ''' Exception class for Yedit '''
  239. pass
  240. # pylint: disable=too-many-public-methods
  241. class Yedit(object):
  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%s/_-]+)"
  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. cmd = ['replace', '-f', fname]
  832. if force:
  833. cmd.append('--force')
  834. return self.openshift_cmd(cmd)
  835. def _create_from_content(self, rname, content):
  836. '''create a temporary file and then call oc create on it'''
  837. fname = Utils.create_tmpfile(rname + '-')
  838. yed = Yedit(fname, content=content)
  839. yed.write()
  840. atexit.register(Utils.cleanup, [fname])
  841. return self._create(fname)
  842. def _create(self, fname):
  843. '''call oc create on a filename'''
  844. return self.openshift_cmd(['create', '-f', fname])
  845. def _delete(self, resource, rname, selector=None):
  846. '''call oc delete on a resource'''
  847. cmd = ['delete', resource, rname]
  848. if selector:
  849. cmd.append('--selector=%s' % selector)
  850. return self.openshift_cmd(cmd)
  851. def _process(self, template_name, create=False, params=None, template_data=None): # noqa: E501
  852. '''process a template
  853. template_name: the name of the template to process
  854. create: whether to send to oc create after processing
  855. params: the parameters for the template
  856. template_data: the incoming template's data; instead of a file
  857. '''
  858. cmd = ['process']
  859. if template_data:
  860. cmd.extend(['-f', '-'])
  861. else:
  862. cmd.append(template_name)
  863. if params:
  864. param_str = ["%s=%s" % (key, value) for key, value in params.items()]
  865. cmd.append('-v')
  866. cmd.extend(param_str)
  867. results = self.openshift_cmd(cmd, output=True, input_data=template_data)
  868. if results['returncode'] != 0 or not create:
  869. return results
  870. fname = Utils.create_tmpfile(template_name + '-')
  871. yed = Yedit(fname, results['results'])
  872. yed.write()
  873. atexit.register(Utils.cleanup, [fname])
  874. return self.openshift_cmd(['create', '-f', fname])
  875. def _get(self, resource, rname=None, selector=None):
  876. '''return a resource by name '''
  877. cmd = ['get', resource]
  878. if selector:
  879. cmd.append('--selector=%s' % selector)
  880. elif rname:
  881. cmd.append(rname)
  882. cmd.extend(['-o', 'json'])
  883. rval = self.openshift_cmd(cmd, output=True)
  884. # Ensure results are retuned in an array
  885. if 'items' in rval:
  886. rval['results'] = rval['items']
  887. elif not isinstance(rval['results'], list):
  888. rval['results'] = [rval['results']]
  889. return rval
  890. def _schedulable(self, node=None, selector=None, schedulable=True):
  891. ''' perform oadm manage-node scheduable '''
  892. cmd = ['manage-node']
  893. if node:
  894. cmd.extend(node)
  895. else:
  896. cmd.append('--selector=%s' % selector)
  897. cmd.append('--schedulable=%s' % schedulable)
  898. return self.openshift_cmd(cmd, oadm=True, output=True, output_type='raw') # noqa: E501
  899. def _list_pods(self, node=None, selector=None, pod_selector=None):
  900. ''' perform oadm list pods
  901. node: the node in which to list pods
  902. selector: the label selector filter if provided
  903. pod_selector: the pod selector filter if provided
  904. '''
  905. cmd = ['manage-node']
  906. if node:
  907. cmd.extend(node)
  908. else:
  909. cmd.append('--selector=%s' % selector)
  910. if pod_selector:
  911. cmd.append('--pod-selector=%s' % pod_selector)
  912. cmd.extend(['--list-pods', '-o', 'json'])
  913. return self.openshift_cmd(cmd, oadm=True, output=True, output_type='raw')
  914. # pylint: disable=too-many-arguments
  915. def _evacuate(self, node=None, selector=None, pod_selector=None, dry_run=False, grace_period=None, force=False):
  916. ''' perform oadm manage-node evacuate '''
  917. cmd = ['manage-node']
  918. if node:
  919. cmd.extend(node)
  920. else:
  921. cmd.append('--selector=%s' % selector)
  922. if dry_run:
  923. cmd.append('--dry-run')
  924. if pod_selector:
  925. cmd.append('--pod-selector=%s' % pod_selector)
  926. if grace_period:
  927. cmd.append('--grace-period=%s' % int(grace_period))
  928. if force:
  929. cmd.append('--force')
  930. cmd.append('--evacuate')
  931. return self.openshift_cmd(cmd, oadm=True, output=True, output_type='raw')
  932. def _version(self):
  933. ''' return the openshift version'''
  934. return self.openshift_cmd(['version'], output=True, output_type='raw')
  935. def _import_image(self, url=None, name=None, tag=None):
  936. ''' perform image import '''
  937. cmd = ['import-image']
  938. image = '{0}'.format(name)
  939. if tag:
  940. image += ':{0}'.format(tag)
  941. cmd.append(image)
  942. if url:
  943. cmd.append('--from={0}/{1}'.format(url, image))
  944. cmd.append('-n{0}'.format(self.namespace))
  945. cmd.append('--confirm')
  946. return self.openshift_cmd(cmd)
  947. def _run(self, cmds, input_data):
  948. ''' Actually executes the command. This makes mocking easier. '''
  949. curr_env = os.environ.copy()
  950. curr_env.update({'KUBECONFIG': self.kubeconfig})
  951. proc = subprocess.Popen(cmds,
  952. stdin=subprocess.PIPE,
  953. stdout=subprocess.PIPE,
  954. stderr=subprocess.PIPE,
  955. env=curr_env)
  956. stdout, stderr = proc.communicate(input_data)
  957. return proc.returncode, stdout.decode(), stderr.decode()
  958. # pylint: disable=too-many-arguments,too-many-branches
  959. def openshift_cmd(self, cmd, oadm=False, output=False, output_type='json', input_data=None):
  960. '''Base command for oc '''
  961. cmds = [self.oc_binary]
  962. if oadm:
  963. cmds.append('adm')
  964. cmds.extend(cmd)
  965. if self.all_namespaces:
  966. cmds.extend(['--all-namespaces'])
  967. elif self.namespace is not None and self.namespace.lower() not in ['none', 'emtpy']: # E501
  968. cmds.extend(['-n', self.namespace])
  969. rval = {}
  970. results = ''
  971. err = None
  972. if self.verbose:
  973. print(' '.join(cmds))
  974. try:
  975. returncode, stdout, stderr = self._run(cmds, input_data)
  976. except OSError as ex:
  977. returncode, stdout, stderr = 1, '', 'Failed to execute {}: {}'.format(subprocess.list2cmdline(cmds), ex)
  978. rval = {"returncode": returncode,
  979. "results": results,
  980. "cmd": ' '.join(cmds)}
  981. if returncode == 0:
  982. if output:
  983. if output_type == 'json':
  984. try:
  985. rval['results'] = json.loads(stdout)
  986. except ValueError as verr:
  987. if "No JSON object could be decoded" in verr.args:
  988. err = verr.args
  989. elif output_type == 'raw':
  990. rval['results'] = stdout
  991. if self.verbose:
  992. print("STDOUT: {0}".format(stdout))
  993. print("STDERR: {0}".format(stderr))
  994. if err:
  995. rval.update({"err": err,
  996. "stderr": stderr,
  997. "stdout": stdout,
  998. "cmd": cmds})
  999. else:
  1000. rval.update({"stderr": stderr,
  1001. "stdout": stdout,
  1002. "results": {}})
  1003. return rval
  1004. class Utils(object):
  1005. ''' utilities for openshiftcli modules '''
  1006. @staticmethod
  1007. def _write(filename, contents):
  1008. ''' Actually write the file contents to disk. This helps with mocking. '''
  1009. with open(filename, 'w') as sfd:
  1010. sfd.write(contents)
  1011. @staticmethod
  1012. def create_tmp_file_from_contents(rname, data, ftype='yaml'):
  1013. ''' create a file in tmp with name and contents'''
  1014. tmp = Utils.create_tmpfile(prefix=rname)
  1015. if ftype == 'yaml':
  1016. # AUDIT:no-member makes sense here due to ruamel.YAML/PyYAML usage
  1017. # pylint: disable=no-member
  1018. if hasattr(yaml, 'RoundTripDumper'):
  1019. Utils._write(tmp, yaml.dump(data, Dumper=yaml.RoundTripDumper))
  1020. else:
  1021. Utils._write(tmp, yaml.safe_dump(data, default_flow_style=False))
  1022. elif ftype == 'json':
  1023. Utils._write(tmp, json.dumps(data))
  1024. else:
  1025. Utils._write(tmp, data)
  1026. # Register cleanup when module is done
  1027. atexit.register(Utils.cleanup, [tmp])
  1028. return tmp
  1029. @staticmethod
  1030. def create_tmpfile_copy(inc_file):
  1031. '''create a temporary copy of a file'''
  1032. tmpfile = Utils.create_tmpfile('lib_openshift-')
  1033. Utils._write(tmpfile, open(inc_file).read())
  1034. # Cleanup the tmpfile
  1035. atexit.register(Utils.cleanup, [tmpfile])
  1036. return tmpfile
  1037. @staticmethod
  1038. def create_tmpfile(prefix='tmp'):
  1039. ''' Generates and returns a temporary file name '''
  1040. with tempfile.NamedTemporaryFile(prefix=prefix, delete=False) as tmp:
  1041. return tmp.name
  1042. @staticmethod
  1043. def create_tmp_files_from_contents(content, content_type=None):
  1044. '''Turn an array of dict: filename, content into a files array'''
  1045. if not isinstance(content, list):
  1046. content = [content]
  1047. files = []
  1048. for item in content:
  1049. path = Utils.create_tmp_file_from_contents(item['path'] + '-',
  1050. item['data'],
  1051. ftype=content_type)
  1052. files.append({'name': os.path.basename(item['path']),
  1053. 'path': path})
  1054. return files
  1055. @staticmethod
  1056. def cleanup(files):
  1057. '''Clean up on exit '''
  1058. for sfile in files:
  1059. if os.path.exists(sfile):
  1060. if os.path.isdir(sfile):
  1061. shutil.rmtree(sfile)
  1062. elif os.path.isfile(sfile):
  1063. os.remove(sfile)
  1064. @staticmethod
  1065. def exists(results, _name):
  1066. ''' Check to see if the results include the name '''
  1067. if not results:
  1068. return False
  1069. if Utils.find_result(results, _name):
  1070. return True
  1071. return False
  1072. @staticmethod
  1073. def find_result(results, _name):
  1074. ''' Find the specified result by name'''
  1075. rval = None
  1076. for result in results:
  1077. if 'metadata' in result and result['metadata']['name'] == _name:
  1078. rval = result
  1079. break
  1080. return rval
  1081. @staticmethod
  1082. def get_resource_file(sfile, sfile_type='yaml'):
  1083. ''' return the service file '''
  1084. contents = None
  1085. with open(sfile) as sfd:
  1086. contents = sfd.read()
  1087. if sfile_type == 'yaml':
  1088. # AUDIT:no-member makes sense here due to ruamel.YAML/PyYAML usage
  1089. # pylint: disable=no-member
  1090. if hasattr(yaml, 'RoundTripLoader'):
  1091. contents = yaml.load(contents, yaml.RoundTripLoader)
  1092. else:
  1093. contents = yaml.safe_load(contents)
  1094. elif sfile_type == 'json':
  1095. contents = json.loads(contents)
  1096. return contents
  1097. @staticmethod
  1098. def filter_versions(stdout):
  1099. ''' filter the oc version output '''
  1100. version_dict = {}
  1101. version_search = ['oc', 'openshift', 'kubernetes']
  1102. for line in stdout.strip().split('\n'):
  1103. for term in version_search:
  1104. if not line:
  1105. continue
  1106. if line.startswith(term):
  1107. version_dict[term] = line.split()[-1]
  1108. # horrible hack to get openshift version in Openshift 3.2
  1109. # By default "oc version in 3.2 does not return an "openshift" version
  1110. if "openshift" not in version_dict:
  1111. version_dict["openshift"] = version_dict["oc"]
  1112. return version_dict
  1113. @staticmethod
  1114. def add_custom_versions(versions):
  1115. ''' create custom versions strings '''
  1116. versions_dict = {}
  1117. for tech, version in versions.items():
  1118. # clean up "-" from version
  1119. if "-" in version:
  1120. version = version.split("-")[0]
  1121. if version.startswith('v'):
  1122. versions_dict[tech + '_numeric'] = version[1:].split('+')[0]
  1123. # "v3.3.0.33" is what we have, we want "3.3"
  1124. versions_dict[tech + '_short'] = version[1:4]
  1125. return versions_dict
  1126. @staticmethod
  1127. def openshift_installed():
  1128. ''' check if openshift is installed '''
  1129. import yum
  1130. yum_base = yum.YumBase()
  1131. if yum_base.rpmdb.searchNevra(name='atomic-openshift'):
  1132. return True
  1133. return False
  1134. # Disabling too-many-branches. This is a yaml dictionary comparison function
  1135. # pylint: disable=too-many-branches,too-many-return-statements,too-many-statements
  1136. @staticmethod
  1137. def check_def_equal(user_def, result_def, skip_keys=None, debug=False):
  1138. ''' Given a user defined definition, compare it with the results given back by our query. '''
  1139. # Currently these values are autogenerated and we do not need to check them
  1140. skip = ['metadata', 'status']
  1141. if skip_keys:
  1142. skip.extend(skip_keys)
  1143. for key, value in result_def.items():
  1144. if key in skip:
  1145. continue
  1146. # Both are lists
  1147. if isinstance(value, list):
  1148. if key not in user_def:
  1149. if debug:
  1150. print('User data does not have key [%s]' % key)
  1151. print('User data: %s' % user_def)
  1152. return False
  1153. if not isinstance(user_def[key], list):
  1154. if debug:
  1155. print('user_def[key] is not a list key=[%s] user_def[key]=%s' % (key, user_def[key]))
  1156. return False
  1157. if len(user_def[key]) != len(value):
  1158. if debug:
  1159. print("List lengths are not equal.")
  1160. print("key=[%s]: user_def[%s] != value[%s]" % (key, len(user_def[key]), len(value)))
  1161. print("user_def: %s" % user_def[key])
  1162. print("value: %s" % value)
  1163. return False
  1164. for values in zip(user_def[key], value):
  1165. if isinstance(values[0], dict) and isinstance(values[1], dict):
  1166. if debug:
  1167. print('sending list - list')
  1168. print(type(values[0]))
  1169. print(type(values[1]))
  1170. result = Utils.check_def_equal(values[0], values[1], skip_keys=skip_keys, debug=debug)
  1171. if not result:
  1172. print('list compare returned false')
  1173. return False
  1174. elif value != user_def[key]:
  1175. if debug:
  1176. print('value should be identical')
  1177. print(user_def[key])
  1178. print(value)
  1179. return False
  1180. # recurse on a dictionary
  1181. elif isinstance(value, dict):
  1182. if key not in user_def:
  1183. if debug:
  1184. print("user_def does not have key [%s]" % key)
  1185. return False
  1186. if not isinstance(user_def[key], dict):
  1187. if debug:
  1188. print("dict returned false: not instance of dict")
  1189. return False
  1190. # before passing ensure keys match
  1191. api_values = set(value.keys()) - set(skip)
  1192. user_values = set(user_def[key].keys()) - set(skip)
  1193. if api_values != user_values:
  1194. if debug:
  1195. print("keys are not equal in dict")
  1196. print(user_values)
  1197. print(api_values)
  1198. return False
  1199. result = Utils.check_def_equal(user_def[key], value, skip_keys=skip_keys, debug=debug)
  1200. if not result:
  1201. if debug:
  1202. print("dict returned false")
  1203. print(result)
  1204. return False
  1205. # Verify each key, value pair is the same
  1206. else:
  1207. if key not in user_def or value != user_def[key]:
  1208. if debug:
  1209. print("value not equal; user_def does not have key")
  1210. print(key)
  1211. print(value)
  1212. if key in user_def:
  1213. print(user_def[key])
  1214. return False
  1215. if debug:
  1216. print('returning true')
  1217. return True
  1218. class OpenShiftCLIConfig(object):
  1219. '''Generic Config'''
  1220. def __init__(self, rname, namespace, kubeconfig, options):
  1221. self.kubeconfig = kubeconfig
  1222. self.name = rname
  1223. self.namespace = namespace
  1224. self._options = options
  1225. @property
  1226. def config_options(self):
  1227. ''' return config options '''
  1228. return self._options
  1229. def to_option_list(self):
  1230. '''return all options as a string'''
  1231. return self.stringify()
  1232. def stringify(self):
  1233. ''' return the options hash as cli params in a string '''
  1234. rval = []
  1235. for key in sorted(self.config_options.keys()):
  1236. data = self.config_options[key]
  1237. if data['include'] \
  1238. and (data['value'] or isinstance(data['value'], int)):
  1239. rval.append('--{}={}'.format(key.replace('_', '-'), data['value']))
  1240. return rval
  1241. # -*- -*- -*- End included fragment: lib/base.py -*- -*- -*-
  1242. # -*- -*- -*- Begin included fragment: lib/deploymentconfig.py -*- -*- -*-
  1243. # pylint: disable=too-many-public-methods
  1244. class DeploymentConfig(Yedit):
  1245. ''' Class to model an openshift DeploymentConfig'''
  1246. default_deployment_config = '''
  1247. apiVersion: v1
  1248. kind: DeploymentConfig
  1249. metadata:
  1250. name: default_dc
  1251. namespace: default
  1252. spec:
  1253. replicas: 0
  1254. selector:
  1255. default_dc: default_dc
  1256. strategy:
  1257. resources: {}
  1258. rollingParams:
  1259. intervalSeconds: 1
  1260. maxSurge: 0
  1261. maxUnavailable: 25%
  1262. timeoutSeconds: 600
  1263. updatePercent: -25
  1264. updatePeriodSeconds: 1
  1265. type: Rolling
  1266. template:
  1267. metadata:
  1268. spec:
  1269. containers:
  1270. - env:
  1271. - name: default
  1272. value: default
  1273. image: default
  1274. imagePullPolicy: IfNotPresent
  1275. name: default_dc
  1276. ports:
  1277. - containerPort: 8000
  1278. hostPort: 8000
  1279. protocol: TCP
  1280. name: default_port
  1281. resources: {}
  1282. terminationMessagePath: /dev/termination-log
  1283. dnsPolicy: ClusterFirst
  1284. hostNetwork: true
  1285. nodeSelector:
  1286. type: compute
  1287. restartPolicy: Always
  1288. securityContext: {}
  1289. serviceAccount: default
  1290. serviceAccountName: default
  1291. terminationGracePeriodSeconds: 30
  1292. triggers:
  1293. - type: ConfigChange
  1294. '''
  1295. replicas_path = "spec.replicas"
  1296. env_path = "spec.template.spec.containers[0].env"
  1297. volumes_path = "spec.template.spec.volumes"
  1298. container_path = "spec.template.spec.containers"
  1299. volume_mounts_path = "spec.template.spec.containers[0].volumeMounts"
  1300. def __init__(self, content=None):
  1301. ''' Constructor for deploymentconfig '''
  1302. if not content:
  1303. content = DeploymentConfig.default_deployment_config
  1304. super(DeploymentConfig, self).__init__(content=content)
  1305. def add_env_value(self, key, value):
  1306. ''' add key, value pair to env array '''
  1307. rval = False
  1308. env = self.get_env_vars()
  1309. if env:
  1310. env.append({'name': key, 'value': value})
  1311. rval = True
  1312. else:
  1313. result = self.put(DeploymentConfig.env_path, {'name': key, 'value': value})
  1314. rval = result[0]
  1315. return rval
  1316. def exists_env_value(self, key, value):
  1317. ''' return whether a key, value pair exists '''
  1318. results = self.get_env_vars()
  1319. if not results:
  1320. return False
  1321. for result in results:
  1322. if result['name'] == key and result['value'] == value:
  1323. return True
  1324. return False
  1325. def exists_env_key(self, key):
  1326. ''' return whether a key, value pair exists '''
  1327. results = self.get_env_vars()
  1328. if not results:
  1329. return False
  1330. for result in results:
  1331. if result['name'] == key:
  1332. return True
  1333. return False
  1334. def get_env_var(self, key):
  1335. '''return a environment variables '''
  1336. results = self.get(DeploymentConfig.env_path) or []
  1337. if not results:
  1338. return None
  1339. for env_var in results:
  1340. if env_var['name'] == key:
  1341. return env_var
  1342. return None
  1343. def get_env_vars(self):
  1344. '''return a environment variables '''
  1345. return self.get(DeploymentConfig.env_path) or []
  1346. def delete_env_var(self, keys):
  1347. '''delete a list of keys '''
  1348. if not isinstance(keys, list):
  1349. keys = [keys]
  1350. env_vars_array = self.get_env_vars()
  1351. modified = False
  1352. idx = None
  1353. for key in keys:
  1354. for env_idx, env_var in enumerate(env_vars_array):
  1355. if env_var['name'] == key:
  1356. idx = env_idx
  1357. break
  1358. if idx:
  1359. modified = True
  1360. del env_vars_array[idx]
  1361. if modified:
  1362. return True
  1363. return False
  1364. def update_env_var(self, key, value):
  1365. '''place an env in the env var list'''
  1366. env_vars_array = self.get_env_vars()
  1367. idx = None
  1368. for env_idx, env_var in enumerate(env_vars_array):
  1369. if env_var['name'] == key:
  1370. idx = env_idx
  1371. break
  1372. if idx:
  1373. env_vars_array[idx]['value'] = value
  1374. else:
  1375. self.add_env_value(key, value)
  1376. return True
  1377. def exists_volume_mount(self, volume_mount):
  1378. ''' return whether a volume mount exists '''
  1379. exist_volume_mounts = self.get_volume_mounts()
  1380. if not exist_volume_mounts:
  1381. return False
  1382. volume_mount_found = False
  1383. for exist_volume_mount in exist_volume_mounts:
  1384. if exist_volume_mount['name'] == volume_mount['name']:
  1385. volume_mount_found = True
  1386. break
  1387. return volume_mount_found
  1388. def exists_volume(self, volume):
  1389. ''' return whether a volume exists '''
  1390. exist_volumes = self.get_volumes()
  1391. volume_found = False
  1392. for exist_volume in exist_volumes:
  1393. if exist_volume['name'] == volume['name']:
  1394. volume_found = True
  1395. break
  1396. return volume_found
  1397. def find_volume_by_name(self, volume, mounts=False):
  1398. ''' return the index of a volume '''
  1399. volumes = []
  1400. if mounts:
  1401. volumes = self.get_volume_mounts()
  1402. else:
  1403. volumes = self.get_volumes()
  1404. for exist_volume in volumes:
  1405. if exist_volume['name'] == volume['name']:
  1406. return exist_volume
  1407. return None
  1408. def get_replicas(self):
  1409. ''' return replicas setting '''
  1410. return self.get(DeploymentConfig.replicas_path)
  1411. def get_volume_mounts(self):
  1412. '''return volume mount information '''
  1413. return self.get_volumes(mounts=True)
  1414. def get_volumes(self, mounts=False):
  1415. '''return volume mount information '''
  1416. if mounts:
  1417. return self.get(DeploymentConfig.volume_mounts_path) or []
  1418. return self.get(DeploymentConfig.volumes_path) or []
  1419. def delete_volume_by_name(self, volume):
  1420. '''delete a volume '''
  1421. modified = False
  1422. exist_volume_mounts = self.get_volume_mounts()
  1423. exist_volumes = self.get_volumes()
  1424. del_idx = None
  1425. for idx, exist_volume in enumerate(exist_volumes):
  1426. if 'name' in exist_volume and exist_volume['name'] == volume['name']:
  1427. del_idx = idx
  1428. break
  1429. if del_idx != None:
  1430. del exist_volumes[del_idx]
  1431. modified = True
  1432. del_idx = None
  1433. for idx, exist_volume_mount in enumerate(exist_volume_mounts):
  1434. if 'name' in exist_volume_mount and exist_volume_mount['name'] == volume['name']:
  1435. del_idx = idx
  1436. break
  1437. if del_idx != None:
  1438. del exist_volume_mounts[idx]
  1439. modified = True
  1440. return modified
  1441. def add_volume_mount(self, volume_mount):
  1442. ''' add a volume or volume mount to the proper location '''
  1443. exist_volume_mounts = self.get_volume_mounts()
  1444. if not exist_volume_mounts and volume_mount:
  1445. self.put(DeploymentConfig.volume_mounts_path, [volume_mount])
  1446. else:
  1447. exist_volume_mounts.append(volume_mount)
  1448. def add_volume(self, volume):
  1449. ''' add a volume or volume mount to the proper location '''
  1450. exist_volumes = self.get_volumes()
  1451. if not volume:
  1452. return
  1453. if not exist_volumes:
  1454. self.put(DeploymentConfig.volumes_path, [volume])
  1455. else:
  1456. exist_volumes.append(volume)
  1457. def update_replicas(self, replicas):
  1458. ''' update replicas value '''
  1459. self.put(DeploymentConfig.replicas_path, replicas)
  1460. def update_volume(self, volume):
  1461. '''place an env in the env var list'''
  1462. exist_volumes = self.get_volumes()
  1463. if not volume:
  1464. return False
  1465. # update the volume
  1466. update_idx = None
  1467. for idx, exist_vol in enumerate(exist_volumes):
  1468. if exist_vol['name'] == volume['name']:
  1469. update_idx = idx
  1470. break
  1471. if update_idx != None:
  1472. exist_volumes[update_idx] = volume
  1473. else:
  1474. self.add_volume(volume)
  1475. return True
  1476. def update_volume_mount(self, volume_mount):
  1477. '''place an env in the env var list'''
  1478. modified = False
  1479. exist_volume_mounts = self.get_volume_mounts()
  1480. if not volume_mount:
  1481. return False
  1482. # update the volume mount
  1483. for exist_vol_mount in exist_volume_mounts:
  1484. if exist_vol_mount['name'] == volume_mount['name']:
  1485. if 'mountPath' in exist_vol_mount and \
  1486. str(exist_vol_mount['mountPath']) != str(volume_mount['mountPath']):
  1487. exist_vol_mount['mountPath'] = volume_mount['mountPath']
  1488. modified = True
  1489. break
  1490. if not modified:
  1491. self.add_volume_mount(volume_mount)
  1492. modified = True
  1493. return modified
  1494. def needs_update_volume(self, volume, volume_mount):
  1495. ''' verify a volume update is needed '''
  1496. exist_volume = self.find_volume_by_name(volume)
  1497. exist_volume_mount = self.find_volume_by_name(volume, mounts=True)
  1498. results = []
  1499. results.append(exist_volume['name'] == volume['name'])
  1500. if 'secret' in volume:
  1501. results.append('secret' in exist_volume)
  1502. results.append(exist_volume['secret']['secretName'] == volume['secret']['secretName'])
  1503. results.append(exist_volume_mount['name'] == volume_mount['name'])
  1504. results.append(exist_volume_mount['mountPath'] == volume_mount['mountPath'])
  1505. elif 'emptyDir' in volume:
  1506. results.append(exist_volume_mount['name'] == volume['name'])
  1507. results.append(exist_volume_mount['mountPath'] == volume_mount['mountPath'])
  1508. elif 'persistentVolumeClaim' in volume:
  1509. pvc = 'persistentVolumeClaim'
  1510. results.append(pvc in exist_volume)
  1511. if results[-1]:
  1512. results.append(exist_volume[pvc]['claimName'] == volume[pvc]['claimName'])
  1513. if 'claimSize' in volume[pvc]:
  1514. results.append(exist_volume[pvc]['claimSize'] == volume[pvc]['claimSize'])
  1515. elif 'hostpath' in volume:
  1516. results.append('hostPath' in exist_volume)
  1517. results.append(exist_volume['hostPath']['path'] == volume_mount['mountPath'])
  1518. return not all(results)
  1519. def needs_update_replicas(self, replicas):
  1520. ''' verify whether a replica update is needed '''
  1521. current_reps = self.get(DeploymentConfig.replicas_path)
  1522. return not current_reps == replicas
  1523. # -*- -*- -*- End included fragment: lib/deploymentconfig.py -*- -*- -*-
  1524. # -*- -*- -*- Begin included fragment: lib/secret.py -*- -*- -*-
  1525. # pylint: disable=too-many-instance-attributes
  1526. class SecretConfig(object):
  1527. ''' Handle secret options '''
  1528. # pylint: disable=too-many-arguments
  1529. def __init__(self,
  1530. sname,
  1531. namespace,
  1532. kubeconfig,
  1533. secrets=None):
  1534. ''' constructor for handling secret options '''
  1535. self.kubeconfig = kubeconfig
  1536. self.name = sname
  1537. self.namespace = namespace
  1538. self.secrets = secrets
  1539. self.data = {}
  1540. self.create_dict()
  1541. def create_dict(self):
  1542. ''' assign the correct properties for a secret dict '''
  1543. self.data['apiVersion'] = 'v1'
  1544. self.data['kind'] = 'Secret'
  1545. self.data['metadata'] = {}
  1546. self.data['metadata']['name'] = self.name
  1547. self.data['metadata']['namespace'] = self.namespace
  1548. self.data['data'] = {}
  1549. if self.secrets:
  1550. for key, value in self.secrets.items():
  1551. self.data['data'][key] = value
  1552. # pylint: disable=too-many-instance-attributes
  1553. class Secret(Yedit):
  1554. ''' Class to wrap the oc command line tools '''
  1555. secret_path = "data"
  1556. kind = 'secret'
  1557. def __init__(self, content):
  1558. '''secret constructor'''
  1559. super(Secret, self).__init__(content=content)
  1560. self._secrets = None
  1561. @property
  1562. def secrets(self):
  1563. '''secret property getter'''
  1564. if self._secrets is None:
  1565. self._secrets = self.get_secrets()
  1566. return self._secrets
  1567. @secrets.setter
  1568. def secrets(self):
  1569. '''secret property setter'''
  1570. if self._secrets is None:
  1571. self._secrets = self.get_secrets()
  1572. return self._secrets
  1573. def get_secrets(self):
  1574. ''' returns all of the defined secrets '''
  1575. return self.get(Secret.secret_path) or {}
  1576. def add_secret(self, key, value):
  1577. ''' add a secret '''
  1578. if self.secrets:
  1579. self.secrets[key] = value
  1580. else:
  1581. self.put(Secret.secret_path, {key: value})
  1582. return True
  1583. def delete_secret(self, key):
  1584. ''' delete secret'''
  1585. try:
  1586. del self.secrets[key]
  1587. except KeyError as _:
  1588. return False
  1589. return True
  1590. def find_secret(self, key):
  1591. ''' find secret'''
  1592. rval = None
  1593. try:
  1594. rval = self.secrets[key]
  1595. except KeyError as _:
  1596. return None
  1597. return {'key': key, 'value': rval}
  1598. def update_secret(self, key, value):
  1599. ''' update a secret'''
  1600. if key in self.secrets:
  1601. self.secrets[key] = value
  1602. else:
  1603. self.add_secret(key, value)
  1604. return True
  1605. # -*- -*- -*- End included fragment: lib/secret.py -*- -*- -*-
  1606. # -*- -*- -*- Begin included fragment: lib/service.py -*- -*- -*-
  1607. # pylint: disable=too-many-instance-attributes
  1608. class ServiceConfig(object):
  1609. ''' Handle service options '''
  1610. # pylint: disable=too-many-arguments
  1611. def __init__(self,
  1612. sname,
  1613. namespace,
  1614. ports,
  1615. selector=None,
  1616. labels=None,
  1617. cluster_ip=None,
  1618. portal_ip=None,
  1619. session_affinity=None,
  1620. service_type=None):
  1621. ''' constructor for handling service options '''
  1622. self.name = sname
  1623. self.namespace = namespace
  1624. self.ports = ports
  1625. self.selector = selector
  1626. self.labels = labels
  1627. self.cluster_ip = cluster_ip
  1628. self.portal_ip = portal_ip
  1629. self.session_affinity = session_affinity
  1630. self.service_type = service_type
  1631. self.data = {}
  1632. self.create_dict()
  1633. def create_dict(self):
  1634. ''' instantiates a service dict '''
  1635. self.data['apiVersion'] = 'v1'
  1636. self.data['kind'] = 'Service'
  1637. self.data['metadata'] = {}
  1638. self.data['metadata']['name'] = self.name
  1639. self.data['metadata']['namespace'] = self.namespace
  1640. if self.labels:
  1641. for lab, lab_value in self.labels.items():
  1642. self.data['metadata'][lab] = lab_value
  1643. self.data['spec'] = {}
  1644. if self.ports:
  1645. self.data['spec']['ports'] = self.ports
  1646. else:
  1647. self.data['spec']['ports'] = []
  1648. if self.selector:
  1649. self.data['spec']['selector'] = self.selector
  1650. self.data['spec']['sessionAffinity'] = self.session_affinity or 'None'
  1651. if self.cluster_ip:
  1652. self.data['spec']['clusterIP'] = self.cluster_ip
  1653. if self.portal_ip:
  1654. self.data['spec']['portalIP'] = self.portal_ip
  1655. if self.service_type:
  1656. self.data['spec']['type'] = self.service_type
  1657. # pylint: disable=too-many-instance-attributes,too-many-public-methods
  1658. class Service(Yedit):
  1659. ''' Class to model the oc service object '''
  1660. port_path = "spec.ports"
  1661. portal_ip = "spec.portalIP"
  1662. cluster_ip = "spec.clusterIP"
  1663. selector_path = 'spec.selector'
  1664. kind = 'Service'
  1665. def __init__(self, content):
  1666. '''Service constructor'''
  1667. super(Service, self).__init__(content=content)
  1668. def get_ports(self):
  1669. ''' get a list of ports '''
  1670. return self.get(Service.port_path) or []
  1671. def get_selector(self):
  1672. ''' get the service selector'''
  1673. return self.get(Service.selector_path) or {}
  1674. def add_ports(self, inc_ports):
  1675. ''' add a port object to the ports list '''
  1676. if not isinstance(inc_ports, list):
  1677. inc_ports = [inc_ports]
  1678. ports = self.get_ports()
  1679. if not ports:
  1680. self.put(Service.port_path, inc_ports)
  1681. else:
  1682. ports.extend(inc_ports)
  1683. return True
  1684. def find_ports(self, inc_port):
  1685. ''' find a specific port '''
  1686. for port in self.get_ports():
  1687. if port['port'] == inc_port['port']:
  1688. return port
  1689. return None
  1690. def delete_ports(self, inc_ports):
  1691. ''' remove a port from a service '''
  1692. if not isinstance(inc_ports, list):
  1693. inc_ports = [inc_ports]
  1694. ports = self.get(Service.port_path) or []
  1695. if not ports:
  1696. return True
  1697. removed = False
  1698. for inc_port in inc_ports:
  1699. port = self.find_ports(inc_port)
  1700. if port:
  1701. ports.remove(port)
  1702. removed = True
  1703. return removed
  1704. def add_cluster_ip(self, sip):
  1705. '''add cluster ip'''
  1706. self.put(Service.cluster_ip, sip)
  1707. def add_portal_ip(self, pip):
  1708. '''add cluster ip'''
  1709. self.put(Service.portal_ip, pip)
  1710. # -*- -*- -*- End included fragment: lib/service.py -*- -*- -*-
  1711. # -*- -*- -*- Begin included fragment: lib/volume.py -*- -*- -*-
  1712. class Volume(object):
  1713. ''' Class to represent an openshift volume object'''
  1714. volume_mounts_path = {"pod": "spec.containers[0].volumeMounts",
  1715. "dc": "spec.template.spec.containers[0].volumeMounts",
  1716. "rc": "spec.template.spec.containers[0].volumeMounts",
  1717. }
  1718. volumes_path = {"pod": "spec.volumes",
  1719. "dc": "spec.template.spec.volumes",
  1720. "rc": "spec.template.spec.volumes",
  1721. }
  1722. @staticmethod
  1723. def create_volume_structure(volume_info):
  1724. ''' return a properly structured volume '''
  1725. volume_mount = None
  1726. volume = {'name': volume_info['name']}
  1727. volume_type = volume_info['type'].lower()
  1728. if volume_type == 'secret':
  1729. volume['secret'] = {}
  1730. volume[volume_info['type']] = {'secretName': volume_info['secret_name']}
  1731. volume_mount = {'mountPath': volume_info['path'],
  1732. 'name': volume_info['name']}
  1733. elif volume_type == 'emptydir':
  1734. volume['emptyDir'] = {}
  1735. volume_mount = {'mountPath': volume_info['path'],
  1736. 'name': volume_info['name']}
  1737. elif volume_type == 'pvc' or volume_type == 'persistentvolumeclaim':
  1738. volume['persistentVolumeClaim'] = {}
  1739. volume['persistentVolumeClaim']['claimName'] = volume_info['claimName']
  1740. volume['persistentVolumeClaim']['claimSize'] = volume_info['claimSize']
  1741. elif volume_type == 'hostpath':
  1742. volume['hostPath'] = {}
  1743. volume['hostPath']['path'] = volume_info['path']
  1744. elif volume_type == 'configmap':
  1745. volume['configMap'] = {}
  1746. volume['configMap']['name'] = volume_info['configmap_name']
  1747. volume_mount = {'mountPath': volume_info['path'],
  1748. 'name': volume_info['name']}
  1749. return (volume, volume_mount)
  1750. # -*- -*- -*- End included fragment: lib/volume.py -*- -*- -*-
  1751. # -*- -*- -*- Begin included fragment: class/oc_version.py -*- -*- -*-
  1752. # pylint: disable=too-many-instance-attributes
  1753. class OCVersion(OpenShiftCLI):
  1754. ''' Class to wrap the oc command line tools '''
  1755. # pylint allows 5
  1756. # pylint: disable=too-many-arguments
  1757. def __init__(self,
  1758. config,
  1759. debug):
  1760. ''' Constructor for OCVersion '''
  1761. super(OCVersion, self).__init__(None, config)
  1762. self.debug = debug
  1763. def get(self):
  1764. '''get and return version information '''
  1765. results = {}
  1766. version_results = self._version()
  1767. if version_results['returncode'] == 0:
  1768. filtered_vers = Utils.filter_versions(version_results['results'])
  1769. custom_vers = Utils.add_custom_versions(filtered_vers)
  1770. results['returncode'] = version_results['returncode']
  1771. results.update(filtered_vers)
  1772. results.update(custom_vers)
  1773. return results
  1774. raise OpenShiftCLIError('Problem detecting openshift version.')
  1775. @staticmethod
  1776. def run_ansible(params):
  1777. '''run the idempotent ansible code'''
  1778. oc_version = OCVersion(params['kubeconfig'], params['debug'])
  1779. if params['state'] == 'list':
  1780. #pylint: disable=protected-access
  1781. result = oc_version.get()
  1782. return {'state': params['state'],
  1783. 'results': result,
  1784. 'changed': False}
  1785. # -*- -*- -*- End included fragment: class/oc_version.py -*- -*- -*-
  1786. # -*- -*- -*- Begin included fragment: class/oc_adm_registry.py -*- -*- -*-
  1787. class RegistryException(Exception):
  1788. ''' Registry Exception Class '''
  1789. pass
  1790. class RegistryConfig(OpenShiftCLIConfig):
  1791. ''' RegistryConfig is a DTO for the registry. '''
  1792. def __init__(self, rname, namespace, kubeconfig, registry_options):
  1793. super(RegistryConfig, self).__init__(rname, namespace, kubeconfig, registry_options)
  1794. class Registry(OpenShiftCLI):
  1795. ''' Class to wrap the oc command line tools '''
  1796. volume_mount_path = 'spec.template.spec.containers[0].volumeMounts'
  1797. volume_path = 'spec.template.spec.volumes'
  1798. env_path = 'spec.template.spec.containers[0].env'
  1799. def __init__(self,
  1800. registry_config,
  1801. verbose=False):
  1802. ''' Constructor for Registry
  1803. a registry consists of 3 or more parts
  1804. - dc/docker-registry
  1805. - svc/docker-registry
  1806. Parameters:
  1807. :registry_config:
  1808. :verbose:
  1809. '''
  1810. super(Registry, self).__init__(registry_config.namespace, registry_config.kubeconfig, verbose)
  1811. self.version = OCVersion(registry_config.kubeconfig, verbose)
  1812. self.svc_ip = None
  1813. self.portal_ip = None
  1814. self.config = registry_config
  1815. self.verbose = verbose
  1816. self.registry_parts = [{'kind': 'dc', 'name': self.config.name},
  1817. {'kind': 'svc', 'name': self.config.name},
  1818. ]
  1819. self.__prepared_registry = None
  1820. self.volume_mounts = []
  1821. self.volumes = []
  1822. if self.config.config_options['volume_mounts']['value']:
  1823. for volume in self.config.config_options['volume_mounts']['value']:
  1824. volume_info = {'secret_name': volume.get('secret_name', None),
  1825. 'name': volume.get('name', None),
  1826. 'type': volume.get('type', None),
  1827. 'path': volume.get('path', None),
  1828. 'claimName': volume.get('claim_name', None),
  1829. 'claimSize': volume.get('claim_size', None),
  1830. }
  1831. vol, vol_mount = Volume.create_volume_structure(volume_info)
  1832. self.volumes.append(vol)
  1833. self.volume_mounts.append(vol_mount)
  1834. self.dconfig = None
  1835. self.svc = None
  1836. @property
  1837. def deploymentconfig(self):
  1838. ''' deploymentconfig property '''
  1839. return self.dconfig
  1840. @deploymentconfig.setter
  1841. def deploymentconfig(self, config):
  1842. ''' setter for deploymentconfig property '''
  1843. self.dconfig = config
  1844. @property
  1845. def service(self):
  1846. ''' service property '''
  1847. return self.svc
  1848. @service.setter
  1849. def service(self, config):
  1850. ''' setter for service property '''
  1851. self.svc = config
  1852. @property
  1853. def prepared_registry(self):
  1854. ''' prepared_registry property '''
  1855. if not self.__prepared_registry:
  1856. results = self.prepare_registry()
  1857. if not results or ('returncode' in results and results['returncode'] != 0):
  1858. raise RegistryException('Could not perform registry preparation. {}'.format(results))
  1859. self.__prepared_registry = results
  1860. return self.__prepared_registry
  1861. @prepared_registry.setter
  1862. def prepared_registry(self, data):
  1863. ''' setter method for prepared_registry attribute '''
  1864. self.__prepared_registry = data
  1865. def get(self):
  1866. ''' return the self.registry_parts '''
  1867. self.deploymentconfig = None
  1868. self.service = None
  1869. rval = 0
  1870. for part in self.registry_parts:
  1871. result = self._get(part['kind'], rname=part['name'])
  1872. if result['returncode'] == 0 and part['kind'] == 'dc':
  1873. self.deploymentconfig = DeploymentConfig(result['results'][0])
  1874. elif result['returncode'] == 0 and part['kind'] == 'svc':
  1875. self.service = Service(result['results'][0])
  1876. if result['returncode'] != 0:
  1877. rval = result['returncode']
  1878. return {'returncode': rval, 'deploymentconfig': self.deploymentconfig, 'service': self.service}
  1879. def exists(self):
  1880. '''does the object exist?'''
  1881. if self.deploymentconfig and self.service:
  1882. return True
  1883. return False
  1884. def delete(self, complete=True):
  1885. '''return all pods '''
  1886. parts = []
  1887. for part in self.registry_parts:
  1888. if not complete and part['kind'] == 'svc':
  1889. continue
  1890. parts.append(self._delete(part['kind'], part['name']))
  1891. # Clean up returned results
  1892. rval = 0
  1893. for part in parts:
  1894. # pylint: disable=invalid-sequence-index
  1895. if 'returncode' in part and part['returncode'] != 0:
  1896. rval = part['returncode']
  1897. return {'returncode': rval, 'results': parts}
  1898. def prepare_registry(self):
  1899. ''' prepare a registry for instantiation '''
  1900. options = self.config.to_option_list()
  1901. cmd = ['registry']
  1902. cmd.extend(options)
  1903. cmd.extend(['--dry-run=True', '-o', 'json'])
  1904. results = self.openshift_cmd(cmd, oadm=True, output=True, output_type='json')
  1905. # probably need to parse this
  1906. # pylint thinks results is a string
  1907. # pylint: disable=no-member
  1908. if results['returncode'] != 0 and 'items' not in results['results']:
  1909. raise RegistryException('Could not perform registry preparation. {}'.format(results))
  1910. service = None
  1911. deploymentconfig = None
  1912. # pylint: disable=invalid-sequence-index
  1913. for res in results['results']['items']:
  1914. if res['kind'] == 'DeploymentConfig':
  1915. deploymentconfig = DeploymentConfig(res)
  1916. elif res['kind'] == 'Service':
  1917. service = Service(res)
  1918. # Verify we got a service and a deploymentconfig
  1919. if not service or not deploymentconfig:
  1920. return results
  1921. # results will need to get parsed here and modifications added
  1922. deploymentconfig = DeploymentConfig(self.add_modifications(deploymentconfig))
  1923. # modify service ip
  1924. if self.svc_ip:
  1925. service.put('spec.clusterIP', self.svc_ip)
  1926. if self.portal_ip:
  1927. service.put('spec.portalIP', self.portal_ip)
  1928. # the dry-run doesn't apply the selector correctly
  1929. if self.service:
  1930. service.put('spec.selector', self.service.get_selector())
  1931. # need to create the service and the deploymentconfig
  1932. service_file = Utils.create_tmp_file_from_contents('service', service.yaml_dict)
  1933. deployment_file = Utils.create_tmp_file_from_contents('deploymentconfig', deploymentconfig.yaml_dict)
  1934. return {"service": service,
  1935. "service_file": service_file,
  1936. "service_update": False,
  1937. "deployment": deploymentconfig,
  1938. "deployment_file": deployment_file,
  1939. "deployment_update": False}
  1940. def create(self):
  1941. '''Create a registry'''
  1942. results = []
  1943. self.needs_update()
  1944. # if the object is none, then we need to create it
  1945. # if the object needs an update, then we should call replace
  1946. # Handle the deploymentconfig
  1947. if self.deploymentconfig is None:
  1948. results.append(self._create(self.prepared_registry['deployment_file']))
  1949. elif self.prepared_registry['deployment_update']:
  1950. results.append(self._replace(self.prepared_registry['deployment_file']))
  1951. # Handle the service
  1952. if self.service is None:
  1953. results.append(self._create(self.prepared_registry['service_file']))
  1954. elif self.prepared_registry['service_update']:
  1955. results.append(self._replace(self.prepared_registry['service_file']))
  1956. # Clean up returned results
  1957. rval = 0
  1958. for result in results:
  1959. # pylint: disable=invalid-sequence-index
  1960. if 'returncode' in result and result['returncode'] != 0:
  1961. rval = result['returncode']
  1962. return {'returncode': rval, 'results': results}
  1963. def update(self):
  1964. '''run update for the registry. This performs a replace if required'''
  1965. # Store the current service IP
  1966. if self.service:
  1967. svcip = self.service.get('spec.clusterIP')
  1968. if svcip:
  1969. self.svc_ip = svcip
  1970. portip = self.service.get('spec.portalIP')
  1971. if portip:
  1972. self.portal_ip = portip
  1973. results = []
  1974. if self.prepared_registry['deployment_update']:
  1975. results.append(self._replace(self.prepared_registry['deployment_file']))
  1976. if self.prepared_registry['service_update']:
  1977. results.append(self._replace(self.prepared_registry['service_file']))
  1978. # Clean up returned results
  1979. rval = 0
  1980. for result in results:
  1981. if result['returncode'] != 0:
  1982. rval = result['returncode']
  1983. return {'returncode': rval, 'results': results}
  1984. def add_modifications(self, deploymentconfig):
  1985. ''' update a deployment config with changes '''
  1986. # The environment variable for REGISTRY_HTTP_SECRET is autogenerated
  1987. # We should set the generated deploymentconfig to the in memory version
  1988. # the following modifications will overwrite if needed
  1989. if self.deploymentconfig:
  1990. result = self.deploymentconfig.get_env_var('REGISTRY_HTTP_SECRET')
  1991. if result:
  1992. deploymentconfig.update_env_var('REGISTRY_HTTP_SECRET', result['value'])
  1993. # Currently we know that our deployment of a registry requires a few extra modifications
  1994. # Modification 1
  1995. # we need specific environment variables to be set
  1996. for key, value in self.config.config_options['env_vars'].get('value', {}).items():
  1997. if not deploymentconfig.exists_env_key(key):
  1998. deploymentconfig.add_env_value(key, value)
  1999. else:
  2000. deploymentconfig.update_env_var(key, value)
  2001. # Modification 2
  2002. # we need specific volume variables to be set
  2003. for volume in self.volumes:
  2004. deploymentconfig.update_volume(volume)
  2005. for vol_mount in self.volume_mounts:
  2006. deploymentconfig.update_volume_mount(vol_mount)
  2007. # Modification 3
  2008. # Edits
  2009. edit_results = []
  2010. for edit in self.config.config_options['edits'].get('value', []):
  2011. if edit['action'] == 'put':
  2012. edit_results.append(deploymentconfig.put(edit['key'],
  2013. edit['value']))
  2014. if edit['action'] == 'update':
  2015. edit_results.append(deploymentconfig.update(edit['key'],
  2016. edit['value'],
  2017. edit.get('index', None),
  2018. edit.get('curr_value', None)))
  2019. if edit['action'] == 'append':
  2020. edit_results.append(deploymentconfig.append(edit['key'],
  2021. edit['value']))
  2022. if edit_results and not any([res[0] for res in edit_results]):
  2023. return None
  2024. return deploymentconfig.yaml_dict
  2025. def needs_update(self):
  2026. ''' check to see if we need to update '''
  2027. exclude_list = ['clusterIP', 'portalIP', 'type', 'protocol']
  2028. if self.service is None or \
  2029. not Utils.check_def_equal(self.prepared_registry['service'].yaml_dict,
  2030. self.service.yaml_dict,
  2031. exclude_list,
  2032. debug=self.verbose):
  2033. self.prepared_registry['service_update'] = True
  2034. exclude_list = ['dnsPolicy',
  2035. 'terminationGracePeriodSeconds',
  2036. 'restartPolicy', 'timeoutSeconds',
  2037. 'livenessProbe', 'readinessProbe',
  2038. 'terminationMessagePath',
  2039. 'securityContext',
  2040. 'imagePullPolicy',
  2041. 'protocol', # ports.portocol: TCP
  2042. 'type', # strategy: {'type': 'rolling'}
  2043. 'defaultMode', # added on secrets
  2044. 'activeDeadlineSeconds', # added in 1.5 for timeouts
  2045. ]
  2046. if self.deploymentconfig is None or \
  2047. not Utils.check_def_equal(self.prepared_registry['deployment'].yaml_dict,
  2048. self.deploymentconfig.yaml_dict,
  2049. exclude_list,
  2050. debug=self.verbose):
  2051. self.prepared_registry['deployment_update'] = True
  2052. return self.prepared_registry['deployment_update'] or self.prepared_registry['service_update'] or False
  2053. # In the future, we would like to break out each ansible state into a function.
  2054. # pylint: disable=too-many-branches,too-many-return-statements
  2055. @staticmethod
  2056. def run_ansible(params, check_mode):
  2057. '''run idempotent ansible code'''
  2058. rconfig = RegistryConfig(params['name'],
  2059. params['namespace'],
  2060. params['kubeconfig'],
  2061. {'images': {'value': params['images'], 'include': True},
  2062. 'latest_images': {'value': params['latest_images'], 'include': True},
  2063. 'labels': {'value': params['labels'], 'include': True},
  2064. 'ports': {'value': ','.join(params['ports']), 'include': True},
  2065. 'replicas': {'value': params['replicas'], 'include': True},
  2066. 'selector': {'value': params['selector'], 'include': True},
  2067. 'service_account': {'value': params['service_account'], 'include': True},
  2068. 'mount_host': {'value': params['mount_host'], 'include': True},
  2069. 'env_vars': {'value': params['env_vars'], 'include': False},
  2070. 'volume_mounts': {'value': params['volume_mounts'], 'include': False},
  2071. 'edits': {'value': params['edits'], 'include': False},
  2072. 'enforce_quota': {'value': params['enforce_quota'], 'include': True},
  2073. 'daemonset': {'value': params['daemonset'], 'include': True},
  2074. 'tls_key': {'value': params['tls_key'], 'include': True},
  2075. 'tls_certificate': {'value': params['tls_certificate'], 'include': True},
  2076. })
  2077. ocregistry = Registry(rconfig, params['debug'])
  2078. api_rval = ocregistry.get()
  2079. state = params['state']
  2080. ########
  2081. # get
  2082. ########
  2083. if state == 'list':
  2084. if api_rval['returncode'] != 0:
  2085. return {'failed': True, 'msg': api_rval}
  2086. return {'changed': False, 'results': api_rval, 'state': state}
  2087. ########
  2088. # Delete
  2089. ########
  2090. if state == 'absent':
  2091. if not ocregistry.exists():
  2092. return {'changed': False, 'state': state}
  2093. if check_mode:
  2094. return {'changed': True, 'msg': 'CHECK_MODE: Would have performed a delete.'}
  2095. # Unsure as to why this is angry with the return type.
  2096. # pylint: disable=redefined-variable-type
  2097. api_rval = ocregistry.delete()
  2098. if api_rval['returncode'] != 0:
  2099. return {'failed': True, 'msg': api_rval}
  2100. return {'changed': True, 'results': api_rval, 'state': state}
  2101. if state == 'present':
  2102. ########
  2103. # Create
  2104. ########
  2105. if not ocregistry.exists():
  2106. if check_mode:
  2107. return {'changed': True, 'msg': 'CHECK_MODE: Would have performed a create.'}
  2108. api_rval = ocregistry.create()
  2109. if api_rval['returncode'] != 0:
  2110. return {'failed': True, 'msg': api_rval}
  2111. return {'changed': True, 'results': api_rval, 'state': state}
  2112. ########
  2113. # Update
  2114. ########
  2115. if not params['force'] and not ocregistry.needs_update():
  2116. return {'changed': False, 'state': state}
  2117. if check_mode:
  2118. return {'changed': True, 'msg': 'CHECK_MODE: Would have performed an update.'}
  2119. api_rval = ocregistry.update()
  2120. if api_rval['returncode'] != 0:
  2121. return {'failed': True, 'msg': api_rval}
  2122. return {'changed': True, 'results': api_rval, 'state': state}
  2123. return {'failed': True, 'msg': 'Unknown state passed. %s' % state}
  2124. # -*- -*- -*- End included fragment: class/oc_adm_registry.py -*- -*- -*-
  2125. # -*- -*- -*- Begin included fragment: ansible/oc_adm_registry.py -*- -*- -*-
  2126. def main():
  2127. '''
  2128. ansible oc module for registry
  2129. '''
  2130. module = AnsibleModule(
  2131. argument_spec=dict(
  2132. state=dict(default='present', type='str',
  2133. choices=['present', 'absent']),
  2134. debug=dict(default=False, type='bool'),
  2135. namespace=dict(default='default', type='str'),
  2136. name=dict(default=None, required=True, type='str'),
  2137. kubeconfig=dict(default='/etc/origin/master/admin.kubeconfig', type='str'),
  2138. images=dict(default=None, type='str'),
  2139. latest_images=dict(default=False, type='bool'),
  2140. labels=dict(default=None, type='list'),
  2141. ports=dict(default=['5000'], type='list'),
  2142. replicas=dict(default=1, type='int'),
  2143. selector=dict(default=None, type='str'),
  2144. service_account=dict(default='registry', type='str'),
  2145. mount_host=dict(default=None, type='str'),
  2146. volume_mounts=dict(default=None, type='list'),
  2147. env_vars=dict(default={}, type='dict'),
  2148. edits=dict(default=[], type='list'),
  2149. enforce_quota=dict(default=False, type='bool'),
  2150. force=dict(default=False, type='bool'),
  2151. daemonset=dict(default=False, type='bool'),
  2152. tls_key=dict(default=None, type='str'),
  2153. tls_certificate=dict(default=None, type='str'),
  2154. ),
  2155. supports_check_mode=True,
  2156. )
  2157. results = Registry.run_ansible(module.params, module.check_mode)
  2158. if 'failed' in results:
  2159. module.fail_json(**results)
  2160. module.exit_json(**results)
  2161. if __name__ == '__main__':
  2162. main()
  2163. # -*- -*- -*- End included fragment: ansible/oc_adm_registry.py -*- -*- -*-