oc_adm_registry.py 84 KB

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