oc_adm_router.py 108 KB

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