oc_service.py 62 KB

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