oc_service.py 53 KB

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