oc_service.py 62 KB

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