oc_service.py 58 KB

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