oc_adm_registry.py 89 KB

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