oc_service.py 63 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915
  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 fcntl
  36. import json
  37. import os
  38. import re
  39. import shutil
  40. import subprocess
  41. import tempfile
  42. # pylint: disable=import-error
  43. try:
  44. import ruamel.yaml as yaml
  45. except ImportError:
  46. import yaml
  47. from ansible.module_utils.basic import AnsibleModule
  48. # -*- -*- -*- End included fragment: lib/import.py -*- -*- -*-
  49. # -*- -*- -*- Begin included fragment: doc/service -*- -*- -*-
  50. DOCUMENTATION = '''
  51. ---
  52. module: oc_service
  53. short_description: Create, modify, and idempotently manage openshift services.
  54. description:
  55. - Manage openshift service objects programmatically.
  56. options:
  57. state:
  58. description:
  59. - State represents whether to create, modify, delete, or list
  60. required: False
  61. default: present
  62. choices: ["present", "absent", "list"]
  63. aliases: []
  64. kubeconfig:
  65. description:
  66. - The path for the kubeconfig file to use for authentication
  67. required: false
  68. default: /etc/origin/master/admin.kubeconfig
  69. aliases: []
  70. debug:
  71. description:
  72. - Turn on debug output.
  73. required: false
  74. default: False
  75. aliases: []
  76. name:
  77. description:
  78. - Name of the object that is being queried.
  79. required: false
  80. default: None
  81. aliases: []
  82. namespace:
  83. description:
  84. - The namespace where the object lives.
  85. required: false
  86. default: default
  87. aliases: []
  88. annotations:
  89. description:
  90. - Annotations to apply to the object
  91. required: false
  92. default: None
  93. aliases: []
  94. selector:
  95. description:
  96. - The selector to apply when filtering for services.
  97. required: false
  98. default: None
  99. aliases: []
  100. labels:
  101. description:
  102. - The labels to apply on the service.
  103. required: false
  104. default: None
  105. aliases: []
  106. clusterip:
  107. description:
  108. - The cluster ip address to use with this service.
  109. required: false
  110. default: None
  111. aliases: []
  112. portalip:
  113. description:
  114. - The portal ip(virtual ip) address to use with this service.
  115. - "https://docs.openshift.com/enterprise/3.0/architecture/core_concepts/pods_and_services.html#services"
  116. required: false
  117. default: None
  118. aliases: []
  119. ports:
  120. description:
  121. - A list of the ports that are used for this service. This includes name, port, protocol, and targetPort.
  122. - See examples.
  123. required: false
  124. default: None
  125. aliases: []
  126. session_affinity:
  127. description:
  128. - The type of session affinity to use.
  129. required: false
  130. default: 'None'
  131. aliases: []
  132. service_type:
  133. description:
  134. - The type of service desired. Each option tells the service to behave accordingly.
  135. - https://kubernetes.io/docs/user-guide/services/
  136. required: false
  137. default: ClusterIP
  138. choices:
  139. - ClusterIP
  140. - NodePort
  141. - LoadBalancer
  142. - ExternalName
  143. aliases: []
  144. externalips:
  145. description:
  146. - A list of the external IPs that are exposed for this service.
  147. - https://kubernetes.io/docs/concepts/services-networking/service/#external-ips
  148. required: false
  149. default: None
  150. aliases: []
  151. author:
  152. - "Kenny Woodson <kwoodson@redhat.com>"
  153. extends_documentation_fragment: []
  154. '''
  155. EXAMPLES = '''
  156. - name: get docker-registry service
  157. run_once: true
  158. oc_service:
  159. namespace: default
  160. name: docker-registry
  161. state: list
  162. register: registry_service_out
  163. - name: create the docker-registry service
  164. oc_service:
  165. namespace: default
  166. name: docker-registry
  167. ports:
  168. - name: 5000-tcp
  169. port: 5000
  170. protocol: TCP
  171. targetPort: 5000
  172. selector:
  173. docker-registry: default
  174. session_affinity: ClientIP
  175. service_type: ClusterIP
  176. register: svc_out
  177. notify:
  178. - restart openshift master services
  179. '''
  180. # -*- -*- -*- End included fragment: doc/service -*- -*- -*-
  181. # -*- -*- -*- Begin included fragment: ../../lib_utils/src/class/yedit.py -*- -*- -*-
  182. class YeditException(Exception): # pragma: no cover
  183. ''' Exception class for Yedit '''
  184. pass
  185. # pylint: disable=too-many-public-methods
  186. class Yedit(object): # pragma: no cover
  187. ''' Class to modify yaml files '''
  188. re_valid_key = r"(((\[-?\d+\])|([0-9a-zA-Z%s/_-]+)).?)+$"
  189. re_key = r"(?:\[(-?\d+)\])|([0-9a-zA-Z{}/_-]+)"
  190. com_sep = set(['.', '#', '|', ':'])
  191. # pylint: disable=too-many-arguments
  192. def __init__(self,
  193. filename=None,
  194. content=None,
  195. content_type='yaml',
  196. separator='.',
  197. backup=False):
  198. self.content = content
  199. self._separator = separator
  200. self.filename = filename
  201. self.__yaml_dict = content
  202. self.content_type = content_type
  203. self.backup = backup
  204. self.load(content_type=self.content_type)
  205. if self.__yaml_dict is None:
  206. self.__yaml_dict = {}
  207. @property
  208. def separator(self):
  209. ''' getter method for separator '''
  210. return self._separator
  211. @separator.setter
  212. def separator(self, inc_sep):
  213. ''' setter method for separator '''
  214. self._separator = inc_sep
  215. @property
  216. def yaml_dict(self):
  217. ''' getter method for yaml_dict '''
  218. return self.__yaml_dict
  219. @yaml_dict.setter
  220. def yaml_dict(self, value):
  221. ''' setter method for yaml_dict '''
  222. self.__yaml_dict = value
  223. @staticmethod
  224. def parse_key(key, sep='.'):
  225. '''parse the key allowing the appropriate separator'''
  226. common_separators = list(Yedit.com_sep - set([sep]))
  227. return re.findall(Yedit.re_key.format(''.join(common_separators)), key)
  228. @staticmethod
  229. def valid_key(key, sep='.'):
  230. '''validate the incoming key'''
  231. common_separators = list(Yedit.com_sep - set([sep]))
  232. if not re.match(Yedit.re_valid_key.format(''.join(common_separators)), key):
  233. return False
  234. return True
  235. # pylint: disable=too-many-return-statements,too-many-branches
  236. @staticmethod
  237. def remove_entry(data, key, index=None, value=None, sep='.'):
  238. ''' remove data at location key '''
  239. if key == '' and isinstance(data, dict):
  240. if value is not None:
  241. data.pop(value)
  242. elif index is not None:
  243. raise YeditException("remove_entry for a dictionary does not have an index {}".format(index))
  244. else:
  245. data.clear()
  246. return True
  247. elif key == '' and isinstance(data, list):
  248. ind = None
  249. if value is not None:
  250. try:
  251. ind = data.index(value)
  252. except ValueError:
  253. return False
  254. elif index is not None:
  255. ind = index
  256. else:
  257. del data[:]
  258. if ind is not None:
  259. data.pop(ind)
  260. return True
  261. if not (key and Yedit.valid_key(key, sep)) and \
  262. isinstance(data, (list, dict)):
  263. return None
  264. key_indexes = Yedit.parse_key(key, sep)
  265. for arr_ind, dict_key in key_indexes[:-1]:
  266. if dict_key and isinstance(data, dict):
  267. data = data.get(dict_key)
  268. elif (arr_ind and isinstance(data, list) and
  269. int(arr_ind) <= len(data) - 1):
  270. data = data[int(arr_ind)]
  271. else:
  272. return None
  273. # process last index for remove
  274. # expected list entry
  275. if key_indexes[-1][0]:
  276. if isinstance(data, list) and int(key_indexes[-1][0]) <= len(data) - 1: # noqa: E501
  277. del data[int(key_indexes[-1][0])]
  278. return True
  279. # expected dict entry
  280. elif key_indexes[-1][1]:
  281. if isinstance(data, dict):
  282. del data[key_indexes[-1][1]]
  283. return True
  284. @staticmethod
  285. def add_entry(data, key, item=None, sep='.'):
  286. ''' Get an item from a dictionary with key notation a.b.c
  287. d = {'a': {'b': 'c'}}}
  288. key = a#b
  289. return c
  290. '''
  291. if key == '':
  292. pass
  293. elif (not (key and Yedit.valid_key(key, sep)) and
  294. isinstance(data, (list, dict))):
  295. return None
  296. key_indexes = Yedit.parse_key(key, sep)
  297. for arr_ind, dict_key in key_indexes[:-1]:
  298. if dict_key:
  299. if isinstance(data, dict) and dict_key in data and data[dict_key]: # noqa: E501
  300. data = data[dict_key]
  301. continue
  302. elif data and not isinstance(data, dict):
  303. raise YeditException("Unexpected item type found while going through key " +
  304. "path: {} (at key: {})".format(key, dict_key))
  305. data[dict_key] = {}
  306. data = data[dict_key]
  307. elif (arr_ind and isinstance(data, list) and
  308. int(arr_ind) <= len(data) - 1):
  309. data = data[int(arr_ind)]
  310. else:
  311. raise YeditException("Unexpected item type found while going through key path: {}".format(key))
  312. if key == '':
  313. data = item
  314. # process last index for add
  315. # expected list entry
  316. elif key_indexes[-1][0] and isinstance(data, list) and int(key_indexes[-1][0]) <= len(data) - 1: # noqa: E501
  317. data[int(key_indexes[-1][0])] = item
  318. # expected dict entry
  319. elif key_indexes[-1][1] and isinstance(data, dict):
  320. data[key_indexes[-1][1]] = item
  321. # didn't add/update to an existing list, nor add/update key to a dict
  322. # so we must have been provided some syntax like a.b.c[<int>] = "data" for a
  323. # non-existent array
  324. else:
  325. raise YeditException("Error adding to object at path: {}".format(key))
  326. return data
  327. @staticmethod
  328. def get_entry(data, key, sep='.'):
  329. ''' Get an item from a dictionary with key notation a.b.c
  330. d = {'a': {'b': 'c'}}}
  331. key = a.b
  332. return c
  333. '''
  334. if key == '':
  335. pass
  336. elif (not (key and Yedit.valid_key(key, sep)) and
  337. isinstance(data, (list, dict))):
  338. return None
  339. key_indexes = Yedit.parse_key(key, sep)
  340. for arr_ind, dict_key in key_indexes:
  341. if dict_key and isinstance(data, dict):
  342. data = data.get(dict_key)
  343. elif (arr_ind and isinstance(data, list) and
  344. int(arr_ind) <= len(data) - 1):
  345. data = data[int(arr_ind)]
  346. else:
  347. return None
  348. return data
  349. @staticmethod
  350. def _write(filename, contents):
  351. ''' Actually write the file contents to disk. This helps with mocking. '''
  352. tmp_filename = filename + '.yedit'
  353. with open(tmp_filename, 'w') as yfd:
  354. fcntl.flock(yfd, fcntl.LOCK_EX | fcntl.LOCK_NB)
  355. yfd.write(contents)
  356. fcntl.flock(yfd, fcntl.LOCK_UN)
  357. os.rename(tmp_filename, filename)
  358. def write(self):
  359. ''' write to file '''
  360. if not self.filename:
  361. raise YeditException('Please specify a filename.')
  362. if self.backup and self.file_exists():
  363. shutil.copy(self.filename, self.filename + '.orig')
  364. # Try to set format attributes if supported
  365. try:
  366. self.yaml_dict.fa.set_block_style()
  367. except AttributeError:
  368. pass
  369. # Try to use RoundTripDumper if supported.
  370. if self.content_type == 'yaml':
  371. try:
  372. Yedit._write(self.filename, yaml.dump(self.yaml_dict, Dumper=yaml.RoundTripDumper))
  373. except AttributeError:
  374. Yedit._write(self.filename, yaml.safe_dump(self.yaml_dict, default_flow_style=False))
  375. elif self.content_type == 'json':
  376. Yedit._write(self.filename, json.dumps(self.yaml_dict, indent=4, sort_keys=True))
  377. else:
  378. raise YeditException('Unsupported content_type: {}.'.format(self.content_type) +
  379. 'Please specify a content_type of yaml or json.')
  380. return (True, self.yaml_dict)
  381. def read(self):
  382. ''' read from file '''
  383. # check if it exists
  384. if self.filename is None or not self.file_exists():
  385. return None
  386. contents = None
  387. with open(self.filename) as yfd:
  388. contents = yfd.read()
  389. return contents
  390. def file_exists(self):
  391. ''' return whether file exists '''
  392. if os.path.exists(self.filename):
  393. return True
  394. return False
  395. def load(self, content_type='yaml'):
  396. ''' return yaml file '''
  397. contents = self.read()
  398. if not contents and not self.content:
  399. return None
  400. if self.content:
  401. if isinstance(self.content, dict):
  402. self.yaml_dict = self.content
  403. return self.yaml_dict
  404. elif isinstance(self.content, str):
  405. contents = self.content
  406. # check if it is yaml
  407. try:
  408. if content_type == 'yaml' and contents:
  409. # Try to set format attributes if supported
  410. try:
  411. self.yaml_dict.fa.set_block_style()
  412. except AttributeError:
  413. pass
  414. # Try to use RoundTripLoader if supported.
  415. try:
  416. self.yaml_dict = yaml.load(contents, yaml.RoundTripLoader)
  417. except AttributeError:
  418. self.yaml_dict = yaml.safe_load(contents)
  419. # Try to set format attributes if supported
  420. try:
  421. self.yaml_dict.fa.set_block_style()
  422. except AttributeError:
  423. pass
  424. elif content_type == 'json' and contents:
  425. self.yaml_dict = json.loads(contents)
  426. except yaml.YAMLError as err:
  427. # Error loading yaml or json
  428. raise YeditException('Problem with loading yaml file. {}'.format(err))
  429. return self.yaml_dict
  430. def get(self, key):
  431. ''' get a specified key'''
  432. try:
  433. entry = Yedit.get_entry(self.yaml_dict, key, self.separator)
  434. except KeyError:
  435. entry = None
  436. return entry
  437. def pop(self, path, key_or_item):
  438. ''' remove a key, value pair from a dict or an item for a list'''
  439. try:
  440. entry = Yedit.get_entry(self.yaml_dict, path, self.separator)
  441. except KeyError:
  442. entry = None
  443. if entry is None:
  444. return (False, self.yaml_dict)
  445. if isinstance(entry, dict):
  446. # AUDIT:maybe-no-member makes sense due to fuzzy types
  447. # pylint: disable=maybe-no-member
  448. if key_or_item in entry:
  449. entry.pop(key_or_item)
  450. return (True, self.yaml_dict)
  451. return (False, self.yaml_dict)
  452. elif isinstance(entry, list):
  453. # AUDIT:maybe-no-member makes sense due to fuzzy types
  454. # pylint: disable=maybe-no-member
  455. ind = None
  456. try:
  457. ind = entry.index(key_or_item)
  458. except ValueError:
  459. return (False, self.yaml_dict)
  460. entry.pop(ind)
  461. return (True, self.yaml_dict)
  462. return (False, self.yaml_dict)
  463. def delete(self, path, index=None, value=None):
  464. ''' remove path from a dict'''
  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. result = Yedit.remove_entry(self.yaml_dict, path, index, value, self.separator)
  472. if not result:
  473. return (False, self.yaml_dict)
  474. return (True, self.yaml_dict)
  475. def exists(self, path, value):
  476. ''' check if value exists at path'''
  477. try:
  478. entry = Yedit.get_entry(self.yaml_dict, path, self.separator)
  479. except KeyError:
  480. entry = None
  481. if isinstance(entry, list):
  482. if value in entry:
  483. return True
  484. return False
  485. elif isinstance(entry, dict):
  486. if isinstance(value, dict):
  487. rval = False
  488. for key, val in value.items():
  489. if entry[key] != val:
  490. rval = False
  491. break
  492. else:
  493. rval = True
  494. return rval
  495. return value in entry
  496. return entry == value
  497. def append(self, path, value):
  498. '''append value to a list'''
  499. try:
  500. entry = Yedit.get_entry(self.yaml_dict, path, self.separator)
  501. except KeyError:
  502. entry = None
  503. if entry is None:
  504. self.put(path, [])
  505. entry = Yedit.get_entry(self.yaml_dict, path, self.separator)
  506. if not isinstance(entry, list):
  507. return (False, self.yaml_dict)
  508. # AUDIT:maybe-no-member makes sense due to loading data from
  509. # a serialized format.
  510. # pylint: disable=maybe-no-member
  511. entry.append(value)
  512. return (True, self.yaml_dict)
  513. # pylint: disable=too-many-arguments
  514. def update(self, path, value, index=None, curr_value=None):
  515. ''' put path, value into a dict '''
  516. try:
  517. entry = Yedit.get_entry(self.yaml_dict, path, self.separator)
  518. except KeyError:
  519. entry = None
  520. if isinstance(entry, dict):
  521. # AUDIT:maybe-no-member makes sense due to fuzzy types
  522. # pylint: disable=maybe-no-member
  523. if not isinstance(value, dict):
  524. raise YeditException('Cannot replace key, value entry in dict with non-dict type. ' +
  525. 'value=[{}] type=[{}]'.format(value, type(value)))
  526. entry.update(value)
  527. return (True, self.yaml_dict)
  528. elif isinstance(entry, list):
  529. # AUDIT:maybe-no-member makes sense due to fuzzy types
  530. # pylint: disable=maybe-no-member
  531. ind = None
  532. if curr_value:
  533. try:
  534. ind = entry.index(curr_value)
  535. except ValueError:
  536. return (False, self.yaml_dict)
  537. elif index is not None:
  538. ind = index
  539. if ind is not None and entry[ind] != value:
  540. entry[ind] = value
  541. return (True, self.yaml_dict)
  542. # see if it exists in the list
  543. try:
  544. ind = entry.index(value)
  545. except ValueError:
  546. # doesn't exist, append it
  547. entry.append(value)
  548. return (True, self.yaml_dict)
  549. # already exists, return
  550. if ind is not None:
  551. return (False, self.yaml_dict)
  552. return (False, self.yaml_dict)
  553. def put(self, path, value):
  554. ''' put path, value into a dict '''
  555. try:
  556. entry = Yedit.get_entry(self.yaml_dict, path, self.separator)
  557. except KeyError:
  558. entry = None
  559. if entry == value:
  560. return (False, self.yaml_dict)
  561. # deepcopy didn't work
  562. # Try to use ruamel.yaml and fallback to pyyaml
  563. try:
  564. tmp_copy = yaml.load(yaml.round_trip_dump(self.yaml_dict,
  565. default_flow_style=False),
  566. yaml.RoundTripLoader)
  567. except AttributeError:
  568. tmp_copy = copy.deepcopy(self.yaml_dict)
  569. # set the format attributes if available
  570. try:
  571. tmp_copy.fa.set_block_style()
  572. except AttributeError:
  573. pass
  574. result = Yedit.add_entry(tmp_copy, path, value, self.separator)
  575. if result is None:
  576. return (False, self.yaml_dict)
  577. # When path equals "" it is a special case.
  578. # "" refers to the root of the document
  579. # Only update the root path (entire document) when its a list or dict
  580. if path == '':
  581. if isinstance(result, list) or isinstance(result, dict):
  582. self.yaml_dict = result
  583. return (True, self.yaml_dict)
  584. return (False, self.yaml_dict)
  585. self.yaml_dict = tmp_copy
  586. return (True, self.yaml_dict)
  587. def create(self, path, value):
  588. ''' create a yaml file '''
  589. if not self.file_exists():
  590. # deepcopy didn't work
  591. # Try to use ruamel.yaml and fallback to pyyaml
  592. try:
  593. tmp_copy = yaml.load(yaml.round_trip_dump(self.yaml_dict,
  594. default_flow_style=False),
  595. yaml.RoundTripLoader)
  596. except AttributeError:
  597. tmp_copy = copy.deepcopy(self.yaml_dict)
  598. # set the format attributes if available
  599. try:
  600. tmp_copy.fa.set_block_style()
  601. except AttributeError:
  602. pass
  603. result = Yedit.add_entry(tmp_copy, path, value, self.separator)
  604. if result is not None:
  605. self.yaml_dict = tmp_copy
  606. return (True, self.yaml_dict)
  607. return (False, self.yaml_dict)
  608. @staticmethod
  609. def get_curr_value(invalue, val_type):
  610. '''return the current value'''
  611. if invalue is None:
  612. return None
  613. curr_value = invalue
  614. if val_type == 'yaml':
  615. try:
  616. # AUDIT:maybe-no-member makes sense due to different yaml libraries
  617. # pylint: disable=maybe-no-member
  618. curr_value = yaml.safe_load(invalue, Loader=yaml.RoundTripLoader)
  619. except AttributeError:
  620. curr_value = yaml.safe_load(invalue)
  621. elif val_type == 'json':
  622. curr_value = json.loads(invalue)
  623. return curr_value
  624. @staticmethod
  625. def parse_value(inc_value, vtype=''):
  626. '''determine value type passed'''
  627. true_bools = ['y', 'Y', 'yes', 'Yes', 'YES', 'true', 'True', 'TRUE',
  628. 'on', 'On', 'ON', ]
  629. false_bools = ['n', 'N', 'no', 'No', 'NO', 'false', 'False', 'FALSE',
  630. 'off', 'Off', 'OFF']
  631. # It came in as a string but you didn't specify value_type as string
  632. # we will convert to bool if it matches any of the above cases
  633. if isinstance(inc_value, str) and 'bool' in vtype:
  634. if inc_value not in true_bools and inc_value not in false_bools:
  635. raise YeditException('Not a boolean type. str=[{}] vtype=[{}]'.format(inc_value, vtype))
  636. elif isinstance(inc_value, bool) and 'str' in vtype:
  637. inc_value = str(inc_value)
  638. # There is a special case where '' will turn into None after yaml loading it so skip
  639. if isinstance(inc_value, str) and inc_value == '':
  640. pass
  641. # If vtype is not str then go ahead and attempt to yaml load it.
  642. elif isinstance(inc_value, str) and 'str' not in vtype:
  643. try:
  644. inc_value = yaml.safe_load(inc_value)
  645. except Exception:
  646. raise YeditException('Could not determine type of incoming value. ' +
  647. 'value=[{}] vtype=[{}]'.format(type(inc_value), vtype))
  648. return inc_value
  649. @staticmethod
  650. def process_edits(edits, yamlfile):
  651. '''run through a list of edits and process them one-by-one'''
  652. results = []
  653. for edit in edits:
  654. value = Yedit.parse_value(edit['value'], edit.get('value_type', ''))
  655. if edit.get('action') == 'update':
  656. # pylint: disable=line-too-long
  657. curr_value = Yedit.get_curr_value(
  658. Yedit.parse_value(edit.get('curr_value')),
  659. edit.get('curr_value_format'))
  660. rval = yamlfile.update(edit['key'],
  661. value,
  662. edit.get('index'),
  663. curr_value)
  664. elif edit.get('action') == 'append':
  665. rval = yamlfile.append(edit['key'], value)
  666. else:
  667. rval = yamlfile.put(edit['key'], value)
  668. if rval[0]:
  669. results.append({'key': edit['key'], 'edit': rval[1]})
  670. return {'changed': len(results) > 0, 'results': results}
  671. # pylint: disable=too-many-return-statements,too-many-branches
  672. @staticmethod
  673. def run_ansible(params):
  674. '''perform the idempotent crud operations'''
  675. yamlfile = Yedit(filename=params['src'],
  676. backup=params['backup'],
  677. content_type=params['content_type'],
  678. separator=params['separator'])
  679. state = params['state']
  680. if params['src']:
  681. rval = yamlfile.load()
  682. if yamlfile.yaml_dict is None and state != 'present':
  683. return {'failed': True,
  684. 'msg': 'Error opening file [{}]. Verify that the '.format(params['src']) +
  685. 'file exists, that it is has correct permissions, and is valid yaml.'}
  686. if state == 'list':
  687. if params['content']:
  688. content = Yedit.parse_value(params['content'], params['content_type'])
  689. yamlfile.yaml_dict = content
  690. if params['key']:
  691. rval = yamlfile.get(params['key'])
  692. return {'changed': False, 'result': rval, 'state': state}
  693. elif state == 'absent':
  694. if params['content']:
  695. content = Yedit.parse_value(params['content'], params['content_type'])
  696. yamlfile.yaml_dict = content
  697. if params['update']:
  698. rval = yamlfile.pop(params['key'], params['value'])
  699. else:
  700. rval = yamlfile.delete(params['key'], params['index'], params['value'])
  701. if rval[0] and params['src']:
  702. yamlfile.write()
  703. return {'changed': rval[0], 'result': rval[1], 'state': state}
  704. elif state == 'present':
  705. # check if content is different than what is in the file
  706. if params['content']:
  707. content = Yedit.parse_value(params['content'], params['content_type'])
  708. # We had no edits to make and the contents are the same
  709. if yamlfile.yaml_dict == content and \
  710. params['value'] is None:
  711. return {'changed': False, 'result': yamlfile.yaml_dict, 'state': state}
  712. yamlfile.yaml_dict = content
  713. # If we were passed a key, value then
  714. # we enapsulate it in a list and process it
  715. # Key, Value passed to the module : Converted to Edits list #
  716. edits = []
  717. _edit = {}
  718. if params['value'] is not None:
  719. _edit['value'] = params['value']
  720. _edit['value_type'] = params['value_type']
  721. _edit['key'] = params['key']
  722. if params['update']:
  723. _edit['action'] = 'update'
  724. _edit['curr_value'] = params['curr_value']
  725. _edit['curr_value_format'] = params['curr_value_format']
  726. _edit['index'] = params['index']
  727. elif params['append']:
  728. _edit['action'] = 'append'
  729. edits.append(_edit)
  730. elif params['edits'] is not None:
  731. edits = params['edits']
  732. if edits:
  733. results = Yedit.process_edits(edits, yamlfile)
  734. # if there were changes and a src provided to us we need to write
  735. if results['changed'] and params['src']:
  736. yamlfile.write()
  737. return {'changed': results['changed'], 'result': results['results'], 'state': state}
  738. # no edits to make
  739. if params['src']:
  740. # pylint: disable=redefined-variable-type
  741. rval = yamlfile.write()
  742. return {'changed': rval[0],
  743. 'result': rval[1],
  744. 'state': state}
  745. # We were passed content but no src, key or value, or edits. Return contents in memory
  746. return {'changed': False, 'result': yamlfile.yaml_dict, 'state': state}
  747. return {'failed': True, 'msg': 'Unkown state passed'}
  748. # -*- -*- -*- End included fragment: ../../lib_utils/src/class/yedit.py -*- -*- -*-
  749. # -*- -*- -*- Begin included fragment: lib/base.py -*- -*- -*-
  750. # pylint: disable=too-many-lines
  751. # noqa: E301,E302,E303,T001
  752. class OpenShiftCLIError(Exception):
  753. '''Exception class for openshiftcli'''
  754. pass
  755. ADDITIONAL_PATH_LOOKUPS = ['/usr/local/bin', os.path.expanduser('~/bin')]
  756. def locate_oc_binary():
  757. ''' Find and return oc binary file '''
  758. # https://github.com/openshift/openshift-ansible/issues/3410
  759. # oc can be in /usr/local/bin in some cases, but that may not
  760. # be in $PATH due to ansible/sudo
  761. paths = os.environ.get("PATH", os.defpath).split(os.pathsep) + ADDITIONAL_PATH_LOOKUPS
  762. oc_binary = 'oc'
  763. # Use shutil.which if it is available, otherwise fallback to a naive path search
  764. try:
  765. which_result = shutil.which(oc_binary, path=os.pathsep.join(paths))
  766. if which_result is not None:
  767. oc_binary = which_result
  768. except AttributeError:
  769. for path in paths:
  770. if os.path.exists(os.path.join(path, oc_binary)):
  771. oc_binary = os.path.join(path, oc_binary)
  772. break
  773. return oc_binary
  774. # pylint: disable=too-few-public-methods
  775. class OpenShiftCLI(object):
  776. ''' Class to wrap the command line tools '''
  777. def __init__(self,
  778. namespace,
  779. kubeconfig='/etc/origin/master/admin.kubeconfig',
  780. verbose=False,
  781. all_namespaces=False):
  782. ''' Constructor for OpenshiftCLI '''
  783. self.namespace = namespace
  784. self.verbose = verbose
  785. self.kubeconfig = Utils.create_tmpfile_copy(kubeconfig)
  786. self.all_namespaces = all_namespaces
  787. self.oc_binary = locate_oc_binary()
  788. # Pylint allows only 5 arguments to be passed.
  789. # pylint: disable=too-many-arguments
  790. def _replace_content(self, resource, rname, content, force=False, sep='.'):
  791. ''' replace the current object with the content '''
  792. res = self._get(resource, rname)
  793. if not res['results']:
  794. return res
  795. fname = Utils.create_tmpfile(rname + '-')
  796. yed = Yedit(fname, res['results'][0], separator=sep)
  797. changes = []
  798. for key, value in content.items():
  799. changes.append(yed.put(key, value))
  800. if any([change[0] for change in changes]):
  801. yed.write()
  802. atexit.register(Utils.cleanup, [fname])
  803. return self._replace(fname, force)
  804. return {'returncode': 0, 'updated': False}
  805. def _replace(self, fname, force=False):
  806. '''replace the current object with oc replace'''
  807. # We are removing the 'resourceVersion' to handle
  808. # a race condition when modifying oc objects
  809. yed = Yedit(fname)
  810. results = yed.delete('metadata.resourceVersion')
  811. if results[0]:
  812. yed.write()
  813. cmd = ['replace', '-f', fname]
  814. if force:
  815. cmd.append('--force')
  816. return self.openshift_cmd(cmd)
  817. def _create_from_content(self, rname, content):
  818. '''create a temporary file and then call oc create on it'''
  819. fname = Utils.create_tmpfile(rname + '-')
  820. yed = Yedit(fname, content=content)
  821. yed.write()
  822. atexit.register(Utils.cleanup, [fname])
  823. return self._create(fname)
  824. def _create(self, fname):
  825. '''call oc create on a filename'''
  826. return self.openshift_cmd(['create', '-f', fname])
  827. def _delete(self, resource, name=None, selector=None):
  828. '''call oc delete on a resource'''
  829. cmd = ['delete', resource]
  830. if selector is not None:
  831. cmd.append('--selector={}'.format(selector))
  832. elif name is not None:
  833. cmd.append(name)
  834. else:
  835. raise OpenShiftCLIError('Either name or selector is required when calling delete.')
  836. return self.openshift_cmd(cmd)
  837. def _process(self, template_name, create=False, params=None, template_data=None): # noqa: E501
  838. '''process a template
  839. template_name: the name of the template to process
  840. create: whether to send to oc create after processing
  841. params: the parameters for the template
  842. template_data: the incoming template's data; instead of a file
  843. '''
  844. cmd = ['process']
  845. if template_data:
  846. cmd.extend(['-f', '-'])
  847. else:
  848. cmd.append(template_name)
  849. if params:
  850. param_str = ["{}={}".format(key, str(value).replace("'", r'"')) for key, value in params.items()]
  851. cmd.append('-v')
  852. cmd.extend(param_str)
  853. results = self.openshift_cmd(cmd, output=True, input_data=template_data)
  854. if results['returncode'] != 0 or not create:
  855. return results
  856. fname = Utils.create_tmpfile(template_name + '-')
  857. yed = Yedit(fname, results['results'])
  858. yed.write()
  859. atexit.register(Utils.cleanup, [fname])
  860. return self.openshift_cmd(['create', '-f', fname])
  861. def _get(self, resource, name=None, selector=None):
  862. '''return a resource by name '''
  863. cmd = ['get', resource]
  864. if selector is not None:
  865. cmd.append('--selector={}'.format(selector))
  866. elif name is not None:
  867. cmd.append(name)
  868. cmd.extend(['-o', 'json'])
  869. rval = self.openshift_cmd(cmd, output=True)
  870. # Ensure results are retuned in an array
  871. if 'items' in rval:
  872. rval['results'] = rval['items']
  873. elif not isinstance(rval['results'], list):
  874. rval['results'] = [rval['results']]
  875. return rval
  876. def _schedulable(self, node=None, selector=None, schedulable=True):
  877. ''' perform oadm manage-node scheduable '''
  878. cmd = ['manage-node']
  879. if node:
  880. cmd.extend(node)
  881. else:
  882. cmd.append('--selector={}'.format(selector))
  883. cmd.append('--schedulable={}'.format(schedulable))
  884. return self.openshift_cmd(cmd, oadm=True, output=True, output_type='raw') # noqa: E501
  885. def _list_pods(self, node=None, selector=None, pod_selector=None):
  886. ''' perform oadm list pods
  887. node: the node in which to list pods
  888. selector: the label selector filter if provided
  889. pod_selector: the pod selector filter if provided
  890. '''
  891. cmd = ['manage-node']
  892. if node:
  893. cmd.extend(node)
  894. else:
  895. cmd.append('--selector={}'.format(selector))
  896. if pod_selector:
  897. cmd.append('--pod-selector={}'.format(pod_selector))
  898. cmd.extend(['--list-pods', '-o', 'json'])
  899. return self.openshift_cmd(cmd, oadm=True, output=True, output_type='raw')
  900. # pylint: disable=too-many-arguments
  901. def _evacuate(self, node=None, selector=None, pod_selector=None, dry_run=False, grace_period=None, force=False):
  902. ''' perform oadm manage-node evacuate '''
  903. cmd = ['manage-node']
  904. if node:
  905. cmd.extend(node)
  906. else:
  907. cmd.append('--selector={}'.format(selector))
  908. if dry_run:
  909. cmd.append('--dry-run')
  910. if pod_selector:
  911. cmd.append('--pod-selector={}'.format(pod_selector))
  912. if grace_period:
  913. cmd.append('--grace-period={}'.format(int(grace_period)))
  914. if force:
  915. cmd.append('--force')
  916. cmd.append('--evacuate')
  917. return self.openshift_cmd(cmd, oadm=True, output=True, output_type='raw')
  918. def _version(self):
  919. ''' return the openshift version'''
  920. return self.openshift_cmd(['version'], output=True, output_type='raw')
  921. def _import_image(self, url=None, name=None, tag=None):
  922. ''' perform image import '''
  923. cmd = ['import-image']
  924. image = '{0}'.format(name)
  925. if tag:
  926. image += ':{0}'.format(tag)
  927. cmd.append(image)
  928. if url:
  929. cmd.append('--from={0}/{1}'.format(url, image))
  930. cmd.append('-n{0}'.format(self.namespace))
  931. cmd.append('--confirm')
  932. return self.openshift_cmd(cmd)
  933. def _run(self, cmds, input_data):
  934. ''' Actually executes the command. This makes mocking easier. '''
  935. curr_env = os.environ.copy()
  936. curr_env.update({'KUBECONFIG': self.kubeconfig})
  937. proc = subprocess.Popen(cmds,
  938. stdin=subprocess.PIPE,
  939. stdout=subprocess.PIPE,
  940. stderr=subprocess.PIPE,
  941. env=curr_env)
  942. stdout, stderr = proc.communicate(input_data)
  943. return proc.returncode, stdout.decode('utf-8'), stderr.decode('utf-8')
  944. # pylint: disable=too-many-arguments,too-many-branches
  945. def openshift_cmd(self, cmd, oadm=False, output=False, output_type='json', input_data=None):
  946. '''Base command for oc '''
  947. cmds = [self.oc_binary]
  948. if oadm:
  949. cmds.append('adm')
  950. cmds.extend(cmd)
  951. if self.all_namespaces:
  952. cmds.extend(['--all-namespaces'])
  953. elif self.namespace is not None and self.namespace.lower() not in ['none', 'emtpy']: # E501
  954. cmds.extend(['-n', self.namespace])
  955. if self.verbose:
  956. print(' '.join(cmds))
  957. try:
  958. returncode, stdout, stderr = self._run(cmds, input_data)
  959. except OSError as ex:
  960. returncode, stdout, stderr = 1, '', 'Failed to execute {}: {}'.format(subprocess.list2cmdline(cmds), ex)
  961. rval = {"returncode": returncode,
  962. "cmd": ' '.join(cmds)}
  963. if output_type == 'json':
  964. rval['results'] = {}
  965. if output and stdout:
  966. try:
  967. rval['results'] = json.loads(stdout)
  968. except ValueError as verr:
  969. if "No JSON object could be decoded" in verr.args:
  970. rval['err'] = verr.args
  971. elif output_type == 'raw':
  972. rval['results'] = stdout if output else ''
  973. if self.verbose:
  974. print("STDOUT: {0}".format(stdout))
  975. print("STDERR: {0}".format(stderr))
  976. if 'err' in rval or returncode != 0:
  977. rval.update({"stderr": stderr,
  978. "stdout": stdout})
  979. return rval
  980. class Utils(object): # pragma: no cover
  981. ''' utilities for openshiftcli modules '''
  982. @staticmethod
  983. def _write(filename, contents):
  984. ''' Actually write the file contents to disk. This helps with mocking. '''
  985. with open(filename, 'w') as sfd:
  986. sfd.write(str(contents))
  987. @staticmethod
  988. def create_tmp_file_from_contents(rname, data, ftype='yaml'):
  989. ''' create a file in tmp with name and contents'''
  990. tmp = Utils.create_tmpfile(prefix=rname)
  991. if ftype == 'yaml':
  992. # AUDIT:no-member makes sense here due to ruamel.YAML/PyYAML usage
  993. # pylint: disable=no-member
  994. if hasattr(yaml, 'RoundTripDumper'):
  995. Utils._write(tmp, yaml.dump(data, Dumper=yaml.RoundTripDumper))
  996. else:
  997. Utils._write(tmp, yaml.safe_dump(data, default_flow_style=False))
  998. elif ftype == 'json':
  999. Utils._write(tmp, json.dumps(data))
  1000. else:
  1001. Utils._write(tmp, data)
  1002. # Register cleanup when module is done
  1003. atexit.register(Utils.cleanup, [tmp])
  1004. return tmp
  1005. @staticmethod
  1006. def create_tmpfile_copy(inc_file):
  1007. '''create a temporary copy of a file'''
  1008. tmpfile = Utils.create_tmpfile('lib_openshift-')
  1009. Utils._write(tmpfile, open(inc_file).read())
  1010. # Cleanup the tmpfile
  1011. atexit.register(Utils.cleanup, [tmpfile])
  1012. return tmpfile
  1013. @staticmethod
  1014. def create_tmpfile(prefix='tmp'):
  1015. ''' Generates and returns a temporary file name '''
  1016. with tempfile.NamedTemporaryFile(prefix=prefix, delete=False) as tmp:
  1017. return tmp.name
  1018. @staticmethod
  1019. def create_tmp_files_from_contents(content, content_type=None):
  1020. '''Turn an array of dict: filename, content into a files array'''
  1021. if not isinstance(content, list):
  1022. content = [content]
  1023. files = []
  1024. for item in content:
  1025. path = Utils.create_tmp_file_from_contents(item['path'] + '-',
  1026. item['data'],
  1027. ftype=content_type)
  1028. files.append({'name': os.path.basename(item['path']),
  1029. 'path': path})
  1030. return files
  1031. @staticmethod
  1032. def cleanup(files):
  1033. '''Clean up on exit '''
  1034. for sfile in files:
  1035. if os.path.exists(sfile):
  1036. if os.path.isdir(sfile):
  1037. shutil.rmtree(sfile)
  1038. elif os.path.isfile(sfile):
  1039. os.remove(sfile)
  1040. @staticmethod
  1041. def exists(results, _name):
  1042. ''' Check to see if the results include the name '''
  1043. if not results:
  1044. return False
  1045. if Utils.find_result(results, _name):
  1046. return True
  1047. return False
  1048. @staticmethod
  1049. def find_result(results, _name):
  1050. ''' Find the specified result by name'''
  1051. rval = None
  1052. for result in results:
  1053. if 'metadata' in result and result['metadata']['name'] == _name:
  1054. rval = result
  1055. break
  1056. return rval
  1057. @staticmethod
  1058. def get_resource_file(sfile, sfile_type='yaml'):
  1059. ''' return the service file '''
  1060. contents = None
  1061. with open(sfile) as sfd:
  1062. contents = sfd.read()
  1063. if sfile_type == 'yaml':
  1064. # AUDIT:no-member makes sense here due to ruamel.YAML/PyYAML usage
  1065. # pylint: disable=no-member
  1066. if hasattr(yaml, 'RoundTripLoader'):
  1067. contents = yaml.load(contents, yaml.RoundTripLoader)
  1068. else:
  1069. contents = yaml.safe_load(contents)
  1070. elif sfile_type == 'json':
  1071. contents = json.loads(contents)
  1072. return contents
  1073. @staticmethod
  1074. def filter_versions(stdout):
  1075. ''' filter the oc version output '''
  1076. version_dict = {}
  1077. version_search = ['oc', 'openshift', 'kubernetes']
  1078. for line in stdout.strip().split('\n'):
  1079. for term in version_search:
  1080. if not line:
  1081. continue
  1082. if line.startswith(term):
  1083. version_dict[term] = line.split()[-1]
  1084. # horrible hack to get openshift version in Openshift 3.2
  1085. # By default "oc version in 3.2 does not return an "openshift" version
  1086. if "openshift" not in version_dict:
  1087. version_dict["openshift"] = version_dict["oc"]
  1088. return version_dict
  1089. @staticmethod
  1090. def add_custom_versions(versions):
  1091. ''' create custom versions strings '''
  1092. versions_dict = {}
  1093. for tech, version in versions.items():
  1094. # clean up "-" from version
  1095. if "-" in version:
  1096. version = version.split("-")[0]
  1097. if version.startswith('v'):
  1098. versions_dict[tech + '_numeric'] = version[1:].split('+')[0]
  1099. # "v3.3.0.33" is what we have, we want "3.3"
  1100. versions_dict[tech + '_short'] = version[1:4]
  1101. return versions_dict
  1102. @staticmethod
  1103. def openshift_installed():
  1104. ''' check if openshift is installed '''
  1105. import rpm
  1106. transaction_set = rpm.TransactionSet()
  1107. rpmquery = transaction_set.dbMatch("name", "atomic-openshift")
  1108. return rpmquery.count() > 0
  1109. # Disabling too-many-branches. This is a yaml dictionary comparison function
  1110. # pylint: disable=too-many-branches,too-many-return-statements,too-many-statements
  1111. @staticmethod
  1112. def check_def_equal(user_def, result_def, skip_keys=None, debug=False):
  1113. ''' Given a user defined definition, compare it with the results given back by our query. '''
  1114. # Currently these values are autogenerated and we do not need to check them
  1115. skip = ['metadata', 'status']
  1116. if skip_keys:
  1117. skip.extend(skip_keys)
  1118. for key, value in result_def.items():
  1119. if key in skip:
  1120. continue
  1121. # Both are lists
  1122. if isinstance(value, list):
  1123. if key not in user_def:
  1124. if debug:
  1125. print('User data does not have key [%s]' % key)
  1126. print('User data: %s' % user_def)
  1127. return False
  1128. if not isinstance(user_def[key], list):
  1129. if debug:
  1130. print('user_def[key] is not a list key=[%s] user_def[key]=%s' % (key, user_def[key]))
  1131. return False
  1132. if len(user_def[key]) != len(value):
  1133. if debug:
  1134. print("List lengths are not equal.")
  1135. print("key=[%s]: user_def[%s] != value[%s]" % (key, len(user_def[key]), len(value)))
  1136. print("user_def: %s" % user_def[key])
  1137. print("value: %s" % value)
  1138. return False
  1139. for values in zip(user_def[key], value):
  1140. if isinstance(values[0], dict) and isinstance(values[1], dict):
  1141. if debug:
  1142. print('sending list - list')
  1143. print(type(values[0]))
  1144. print(type(values[1]))
  1145. result = Utils.check_def_equal(values[0], values[1], skip_keys=skip_keys, debug=debug)
  1146. if not result:
  1147. print('list compare returned false')
  1148. return False
  1149. elif value != user_def[key]:
  1150. if debug:
  1151. print('value should be identical')
  1152. print(user_def[key])
  1153. print(value)
  1154. return False
  1155. # recurse on a dictionary
  1156. elif isinstance(value, dict):
  1157. if key not in user_def:
  1158. if debug:
  1159. print("user_def does not have key [%s]" % key)
  1160. return False
  1161. if not isinstance(user_def[key], dict):
  1162. if debug:
  1163. print("dict returned false: not instance of dict")
  1164. return False
  1165. # before passing ensure keys match
  1166. api_values = set(value.keys()) - set(skip)
  1167. user_values = set(user_def[key].keys()) - set(skip)
  1168. if api_values != user_values:
  1169. if debug:
  1170. print("keys are not equal in dict")
  1171. print(user_values)
  1172. print(api_values)
  1173. return False
  1174. result = Utils.check_def_equal(user_def[key], value, skip_keys=skip_keys, debug=debug)
  1175. if not result:
  1176. if debug:
  1177. print("dict returned false")
  1178. print(result)
  1179. return False
  1180. # Verify each key, value pair is the same
  1181. else:
  1182. if key not in user_def or value != user_def[key]:
  1183. if debug:
  1184. print("value not equal; user_def does not have key")
  1185. print(key)
  1186. print(value)
  1187. if key in user_def:
  1188. print(user_def[key])
  1189. return False
  1190. if debug:
  1191. print('returning true')
  1192. return True
  1193. class OpenShiftCLIConfig(object):
  1194. '''Generic Config'''
  1195. def __init__(self, rname, namespace, kubeconfig, options):
  1196. self.kubeconfig = kubeconfig
  1197. self.name = rname
  1198. self.namespace = namespace
  1199. self._options = options
  1200. @property
  1201. def config_options(self):
  1202. ''' return config options '''
  1203. return self._options
  1204. def to_option_list(self, ascommalist=''):
  1205. '''return all options as a string
  1206. if ascommalist is set to the name of a key, and
  1207. the value of that key is a dict, format the dict
  1208. as a list of comma delimited key=value pairs'''
  1209. return self.stringify(ascommalist)
  1210. def stringify(self, ascommalist=''):
  1211. ''' return the options hash as cli params in a string
  1212. if ascommalist is set to the name of a key, and
  1213. the value of that key is a dict, format the dict
  1214. as a list of comma delimited key=value pairs '''
  1215. rval = []
  1216. for key in sorted(self.config_options.keys()):
  1217. data = self.config_options[key]
  1218. if data['include'] \
  1219. and (data['value'] is not None or isinstance(data['value'], int)):
  1220. if key == ascommalist:
  1221. val = ','.join(['{}={}'.format(kk, vv) for kk, vv in sorted(data['value'].items())])
  1222. else:
  1223. val = data['value']
  1224. rval.append('--{}={}'.format(key.replace('_', '-'), val))
  1225. return rval
  1226. # -*- -*- -*- End included fragment: lib/base.py -*- -*- -*-
  1227. # -*- -*- -*- Begin included fragment: lib/service.py -*- -*- -*-
  1228. # pylint: disable=too-many-instance-attributes
  1229. class ServiceConfig(object):
  1230. ''' Handle service options '''
  1231. # pylint: disable=too-many-arguments
  1232. def __init__(self,
  1233. sname,
  1234. namespace,
  1235. ports,
  1236. annotations=None,
  1237. selector=None,
  1238. labels=None,
  1239. cluster_ip=None,
  1240. portal_ip=None,
  1241. session_affinity=None,
  1242. service_type=None,
  1243. external_ips=None):
  1244. ''' constructor for handling service options '''
  1245. self.name = sname
  1246. self.namespace = namespace
  1247. self.ports = ports
  1248. self.annotations = annotations
  1249. self.selector = selector
  1250. self.labels = labels
  1251. self.cluster_ip = cluster_ip
  1252. self.portal_ip = portal_ip
  1253. self.session_affinity = session_affinity
  1254. self.service_type = service_type
  1255. self.external_ips = external_ips
  1256. self.data = {}
  1257. self.create_dict()
  1258. def create_dict(self):
  1259. ''' instantiates a service dict '''
  1260. self.data['apiVersion'] = 'v1'
  1261. self.data['kind'] = 'Service'
  1262. self.data['metadata'] = {}
  1263. self.data['metadata']['name'] = self.name
  1264. self.data['metadata']['namespace'] = self.namespace
  1265. if self.labels:
  1266. self.data['metadata']['labels'] = {}
  1267. for lab, lab_value in self.labels.items():
  1268. self.data['metadata']['labels'][lab] = lab_value
  1269. if self.annotations:
  1270. self.data['metadata']['annotations'] = self.annotations
  1271. self.data['spec'] = {}
  1272. if self.ports:
  1273. self.data['spec']['ports'] = self.ports
  1274. else:
  1275. self.data['spec']['ports'] = []
  1276. if self.selector:
  1277. self.data['spec']['selector'] = self.selector
  1278. self.data['spec']['sessionAffinity'] = self.session_affinity or 'None'
  1279. if self.cluster_ip:
  1280. self.data['spec']['clusterIP'] = self.cluster_ip
  1281. if self.portal_ip:
  1282. self.data['spec']['portalIP'] = self.portal_ip
  1283. if self.service_type:
  1284. self.data['spec']['type'] = self.service_type
  1285. if self.external_ips:
  1286. self.data['spec']['externalIPs'] = self.external_ips
  1287. # pylint: disable=too-many-instance-attributes,too-many-public-methods
  1288. class Service(Yedit):
  1289. ''' Class to model the oc service object '''
  1290. port_path = "spec.ports"
  1291. portal_ip = "spec.portalIP"
  1292. cluster_ip = "spec.clusterIP"
  1293. selector_path = 'spec.selector'
  1294. kind = 'Service'
  1295. external_ips = "spec.externalIPs"
  1296. def __init__(self, content):
  1297. '''Service constructor'''
  1298. super(Service, self).__init__(content=content)
  1299. def get_ports(self):
  1300. ''' get a list of ports '''
  1301. return self.get(Service.port_path) or []
  1302. def get_selector(self):
  1303. ''' get the service selector'''
  1304. return self.get(Service.selector_path) or {}
  1305. def add_ports(self, inc_ports):
  1306. ''' add a port object to the ports list '''
  1307. if not isinstance(inc_ports, list):
  1308. inc_ports = [inc_ports]
  1309. ports = self.get_ports()
  1310. if not ports:
  1311. self.put(Service.port_path, inc_ports)
  1312. else:
  1313. ports.extend(inc_ports)
  1314. return True
  1315. def find_ports(self, inc_port):
  1316. ''' find a specific port '''
  1317. for port in self.get_ports():
  1318. if port['port'] == inc_port['port']:
  1319. return port
  1320. return None
  1321. def delete_ports(self, inc_ports):
  1322. ''' remove a port from a service '''
  1323. if not isinstance(inc_ports, list):
  1324. inc_ports = [inc_ports]
  1325. ports = self.get(Service.port_path) or []
  1326. if not ports:
  1327. return True
  1328. removed = False
  1329. for inc_port in inc_ports:
  1330. port = self.find_ports(inc_port)
  1331. if port:
  1332. ports.remove(port)
  1333. removed = True
  1334. return removed
  1335. def add_cluster_ip(self, sip):
  1336. '''add cluster ip'''
  1337. self.put(Service.cluster_ip, sip)
  1338. def add_portal_ip(self, pip):
  1339. '''add cluster ip'''
  1340. self.put(Service.portal_ip, pip)
  1341. def get_external_ips(self):
  1342. ''' get a list of external_ips '''
  1343. return self.get(Service.external_ips) or []
  1344. def add_external_ips(self, inc_external_ips):
  1345. ''' add an external_ip to the external_ips list '''
  1346. if not isinstance(inc_external_ips, list):
  1347. inc_external_ips = [inc_external_ips]
  1348. external_ips = self.get_external_ips()
  1349. if not external_ips:
  1350. self.put(Service.external_ips, inc_external_ips)
  1351. else:
  1352. external_ips.extend(inc_external_ips)
  1353. return True
  1354. def find_external_ips(self, inc_external_ip):
  1355. ''' find a specific external IP '''
  1356. val = None
  1357. try:
  1358. idx = self.get_external_ips().index(inc_external_ip)
  1359. val = self.get_external_ips()[idx]
  1360. except ValueError:
  1361. pass
  1362. return val
  1363. def delete_external_ips(self, inc_external_ips):
  1364. ''' remove an external IP from a service '''
  1365. if not isinstance(inc_external_ips, list):
  1366. inc_external_ips = [inc_external_ips]
  1367. external_ips = self.get(Service.external_ips) or []
  1368. if not external_ips:
  1369. return True
  1370. removed = False
  1371. for inc_external_ip in inc_external_ips:
  1372. external_ip = self.find_external_ips(inc_external_ip)
  1373. if external_ip:
  1374. external_ips.remove(external_ip)
  1375. removed = True
  1376. return removed
  1377. # -*- -*- -*- End included fragment: lib/service.py -*- -*- -*-
  1378. # -*- -*- -*- Begin included fragment: class/oc_service.py -*- -*- -*-
  1379. # pylint: disable=too-many-instance-attributes
  1380. class OCService(OpenShiftCLI):
  1381. ''' Class to wrap the oc command line tools '''
  1382. kind = 'service'
  1383. # pylint allows 5
  1384. # pylint: disable=too-many-arguments
  1385. def __init__(self,
  1386. sname,
  1387. namespace,
  1388. labels,
  1389. annotations,
  1390. selector,
  1391. cluster_ip,
  1392. portal_ip,
  1393. ports,
  1394. session_affinity,
  1395. service_type,
  1396. external_ips,
  1397. kubeconfig='/etc/origin/master/admin.kubeconfig',
  1398. verbose=False):
  1399. ''' Constructor for OCVolume '''
  1400. super(OCService, self).__init__(namespace, kubeconfig, verbose)
  1401. self.namespace = namespace
  1402. self.config = ServiceConfig(sname, namespace, ports, annotations, selector, labels,
  1403. cluster_ip, portal_ip, session_affinity, service_type,
  1404. external_ips)
  1405. self.user_svc = Service(content=self.config.data)
  1406. self.svc = None
  1407. @property
  1408. def service(self):
  1409. ''' property function service'''
  1410. if not self.svc:
  1411. self.get()
  1412. return self.svc
  1413. @service.setter
  1414. def service(self, data):
  1415. ''' setter function for service var '''
  1416. self.svc = data
  1417. def exists(self):
  1418. ''' return whether a service exists '''
  1419. if self.service:
  1420. return True
  1421. return False
  1422. def get(self):
  1423. '''return service information '''
  1424. result = self._get(self.kind, self.config.name)
  1425. if result['returncode'] == 0:
  1426. self.service = Service(content=result['results'][0])
  1427. result['clusterip'] = self.service.get('spec.clusterIP')
  1428. elif 'services \"%s\" not found' % self.config.name in result['stderr']:
  1429. result['clusterip'] = ''
  1430. result['returncode'] = 0
  1431. return result
  1432. def delete(self):
  1433. '''delete the service'''
  1434. return self._delete(self.kind, self.config.name)
  1435. def create(self):
  1436. '''create a service '''
  1437. return self._create_from_content(self.config.name, self.user_svc.yaml_dict)
  1438. def update(self):
  1439. '''create a service '''
  1440. # Need to copy over the portalIP and the serviceIP settings
  1441. self.user_svc.add_cluster_ip(self.service.get('spec.clusterIP'))
  1442. self.user_svc.add_portal_ip(self.service.get('spec.portalIP'))
  1443. return self._replace_content(self.kind, self.config.name, self.user_svc.yaml_dict)
  1444. def needs_update(self):
  1445. ''' verify an update is needed '''
  1446. skip = ['clusterIP', 'portalIP']
  1447. return not Utils.check_def_equal(self.user_svc.yaml_dict, self.service.yaml_dict, skip_keys=skip, debug=True)
  1448. # pylint: disable=too-many-return-statements,too-many-branches
  1449. @staticmethod
  1450. def run_ansible(params, check_mode):
  1451. '''Run the idempotent ansible code'''
  1452. oc_svc = OCService(params['name'],
  1453. params['namespace'],
  1454. params['labels'],
  1455. params['annotations'],
  1456. params['selector'],
  1457. params['clusterip'],
  1458. params['portalip'],
  1459. params['ports'],
  1460. params['session_affinity'],
  1461. params['service_type'],
  1462. params['external_ips'],
  1463. params['kubeconfig'],
  1464. params['debug'])
  1465. state = params['state']
  1466. api_rval = oc_svc.get()
  1467. if api_rval['returncode'] != 0:
  1468. return {'failed': True, 'msg': api_rval}
  1469. #####
  1470. # Get
  1471. #####
  1472. if state == 'list':
  1473. return {'changed': False, 'results': api_rval, 'state': state}
  1474. ########
  1475. # Delete
  1476. ########
  1477. if state == 'absent':
  1478. if oc_svc.exists():
  1479. if check_mode:
  1480. return {'changed': True,
  1481. 'msg': 'CHECK_MODE: Would have performed a delete.'} # noqa: E501
  1482. api_rval = oc_svc.delete()
  1483. return {'changed': True, 'results': api_rval, 'state': state}
  1484. return {'changed': False, 'state': state}
  1485. if state == 'present':
  1486. ########
  1487. # Create
  1488. ########
  1489. if not oc_svc.exists():
  1490. if check_mode:
  1491. return {'changed': True,
  1492. 'msg': 'CHECK_MODE: Would have performed a create.'} # noqa: E501
  1493. # Create it here
  1494. api_rval = oc_svc.create()
  1495. if api_rval['returncode'] != 0:
  1496. return {'failed': True, 'msg': api_rval}
  1497. # return the created object
  1498. api_rval = oc_svc.get()
  1499. if api_rval['returncode'] != 0:
  1500. return {'failed': True, 'msg': api_rval}
  1501. return {'changed': True, 'results': api_rval, 'state': state}
  1502. ########
  1503. # Update
  1504. ########
  1505. if oc_svc.needs_update():
  1506. api_rval = oc_svc.update()
  1507. if api_rval['returncode'] != 0:
  1508. return {'failed': True, 'msg': api_rval}
  1509. # return the created object
  1510. api_rval = oc_svc.get()
  1511. if api_rval['returncode'] != 0:
  1512. return {'failed': True, 'msg': api_rval}
  1513. return {'changed': True, 'results': api_rval, 'state': state}
  1514. return {'changed': False, 'results': api_rval, 'state': state}
  1515. return {'failed': True, 'msg': 'UNKNOWN state passed. [%s]' % state}
  1516. # -*- -*- -*- End included fragment: class/oc_service.py -*- -*- -*-
  1517. # -*- -*- -*- Begin included fragment: ansible/oc_service.py -*- -*- -*-
  1518. def main():
  1519. '''
  1520. ansible oc module for services
  1521. '''
  1522. module = AnsibleModule(
  1523. argument_spec=dict(
  1524. kubeconfig=dict(default='/etc/origin/master/admin.kubeconfig', type='str'),
  1525. state=dict(default='present', type='str',
  1526. choices=['present', 'absent', 'list']),
  1527. debug=dict(default=False, type='bool'),
  1528. namespace=dict(default='default', type='str'),
  1529. name=dict(default=None, type='str'),
  1530. annotations=dict(default=None, type='dict'),
  1531. labels=dict(default=None, type='dict'),
  1532. selector=dict(default=None, type='dict'),
  1533. clusterip=dict(default=None, type='str'),
  1534. portalip=dict(default=None, type='str'),
  1535. ports=dict(default=None, type='list'),
  1536. session_affinity=dict(default='None', type='str'),
  1537. service_type=dict(default='ClusterIP', type='str'),
  1538. external_ips=dict(default=None, type='list'),
  1539. ),
  1540. supports_check_mode=True,
  1541. )
  1542. rval = OCService.run_ansible(module.params, module.check_mode)
  1543. if 'failed' in rval:
  1544. return module.fail_json(**rval)
  1545. return module.exit_json(**rval)
  1546. if __name__ == '__main__':
  1547. main()
  1548. # -*- -*- -*- End included fragment: ansible/oc_service.py -*- -*- -*-