oc_adm_router.py 97 KB

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