oc_adm_registry.py 94 KB

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