oc_adm_registry.py 85 KB

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