oc_adm_registry.py 83 KB

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