oc_adm_router.py 108 KB

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