oc_adm_registry.py 89 KB

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