oc_adm_registry.py 87 KB

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