oc_adm_router.py 108 KB

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