oc_adm_router.py 104 KB

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