oc_adm_router.py 99 KB

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