oc_adm_router.py 104 KB

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