oc_service.py 61 KB

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