oc_adm_router.py 102 KB

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