oc_adm_router.py 102 KB

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