oc_adm_registry.py 87 KB

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