oc_service.py 52 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634
  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 = 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(prefix=None):
  858. ''' Generates and returns a temporary file name '''
  859. with tempfile.NamedTemporaryFile(prefix=prefix, delete=False) as tmp:
  860. return tmp.name
  861. @staticmethod
  862. def create_tmp_files_from_contents(content, content_type=None):
  863. '''Turn an array of dict: filename, content into a files array'''
  864. if not isinstance(content, list):
  865. content = [content]
  866. files = []
  867. for item in content:
  868. path = Utils.create_tmp_file_from_contents(item['path'] + '-',
  869. item['data'],
  870. ftype=content_type)
  871. files.append({'name': os.path.basename(item['path']),
  872. 'path': path})
  873. return files
  874. @staticmethod
  875. def cleanup(files):
  876. '''Clean up on exit '''
  877. for sfile in files:
  878. if os.path.exists(sfile):
  879. if os.path.isdir(sfile):
  880. shutil.rmtree(sfile)
  881. elif os.path.isfile(sfile):
  882. os.remove(sfile)
  883. @staticmethod
  884. def exists(results, _name):
  885. ''' Check to see if the results include the name '''
  886. if not results:
  887. return False
  888. if Utils.find_result(results, _name):
  889. return True
  890. return False
  891. @staticmethod
  892. def find_result(results, _name):
  893. ''' Find the specified result by name'''
  894. rval = None
  895. for result in results:
  896. if 'metadata' in result and result['metadata']['name'] == _name:
  897. rval = result
  898. break
  899. return rval
  900. @staticmethod
  901. def get_resource_file(sfile, sfile_type='yaml'):
  902. ''' return the service file '''
  903. contents = None
  904. with open(sfile) as sfd:
  905. contents = sfd.read()
  906. if sfile_type == 'yaml':
  907. contents = yaml.load(contents, yaml.RoundTripLoader)
  908. elif sfile_type == 'json':
  909. contents = json.loads(contents)
  910. return contents
  911. @staticmethod
  912. def filter_versions(stdout):
  913. ''' filter the oc version output '''
  914. version_dict = {}
  915. version_search = ['oc', 'openshift', 'kubernetes']
  916. for line in stdout.strip().split('\n'):
  917. for term in version_search:
  918. if not line:
  919. continue
  920. if line.startswith(term):
  921. version_dict[term] = line.split()[-1]
  922. # horrible hack to get openshift version in Openshift 3.2
  923. # By default "oc version in 3.2 does not return an "openshift" version
  924. if "openshift" not in version_dict:
  925. version_dict["openshift"] = version_dict["oc"]
  926. return version_dict
  927. @staticmethod
  928. def add_custom_versions(versions):
  929. ''' create custom versions strings '''
  930. versions_dict = {}
  931. for tech, version in versions.items():
  932. # clean up "-" from version
  933. if "-" in version:
  934. version = version.split("-")[0]
  935. if version.startswith('v'):
  936. versions_dict[tech + '_numeric'] = version[1:].split('+')[0]
  937. # "v3.3.0.33" is what we have, we want "3.3"
  938. versions_dict[tech + '_short'] = version[1:4]
  939. return versions_dict
  940. @staticmethod
  941. def openshift_installed():
  942. ''' check if openshift is installed '''
  943. import yum
  944. yum_base = yum.YumBase()
  945. if yum_base.rpmdb.searchNevra(name='atomic-openshift'):
  946. return True
  947. return False
  948. # Disabling too-many-branches. This is a yaml dictionary comparison function
  949. # pylint: disable=too-many-branches,too-many-return-statements,too-many-statements
  950. @staticmethod
  951. def check_def_equal(user_def, result_def, skip_keys=None, debug=False):
  952. ''' Given a user defined definition, compare it with the results given back by our query. '''
  953. # Currently these values are autogenerated and we do not need to check them
  954. skip = ['metadata', 'status']
  955. if skip_keys:
  956. skip.extend(skip_keys)
  957. for key, value in result_def.items():
  958. if key in skip:
  959. continue
  960. # Both are lists
  961. if isinstance(value, list):
  962. if key not in user_def:
  963. if debug:
  964. print('User data does not have key [%s]' % key)
  965. print('User data: %s' % user_def)
  966. return False
  967. if not isinstance(user_def[key], list):
  968. if debug:
  969. print('user_def[key] is not a list key=[%s] user_def[key]=%s' % (key, user_def[key]))
  970. return False
  971. if len(user_def[key]) != len(value):
  972. if debug:
  973. print("List lengths are not equal.")
  974. print("key=[%s]: user_def[%s] != value[%s]" % (key, len(user_def[key]), len(value)))
  975. print("user_def: %s" % user_def[key])
  976. print("value: %s" % value)
  977. return False
  978. for values in zip(user_def[key], value):
  979. if isinstance(values[0], dict) and isinstance(values[1], dict):
  980. if debug:
  981. print('sending list - list')
  982. print(type(values[0]))
  983. print(type(values[1]))
  984. result = Utils.check_def_equal(values[0], values[1], skip_keys=skip_keys, debug=debug)
  985. if not result:
  986. print('list compare returned false')
  987. return False
  988. elif value != user_def[key]:
  989. if debug:
  990. print('value should be identical')
  991. print(value)
  992. print(user_def[key])
  993. return False
  994. # recurse on a dictionary
  995. elif isinstance(value, dict):
  996. if key not in user_def:
  997. if debug:
  998. print("user_def does not have key [%s]" % key)
  999. return False
  1000. if not isinstance(user_def[key], dict):
  1001. if debug:
  1002. print("dict returned false: not instance of dict")
  1003. return False
  1004. # before passing ensure keys match
  1005. api_values = set(value.keys()) - set(skip)
  1006. user_values = set(user_def[key].keys()) - set(skip)
  1007. if api_values != user_values:
  1008. if debug:
  1009. print("keys are not equal in dict")
  1010. print(api_values)
  1011. print(user_values)
  1012. return False
  1013. result = Utils.check_def_equal(user_def[key], value, skip_keys=skip_keys, debug=debug)
  1014. if not result:
  1015. if debug:
  1016. print("dict returned false")
  1017. print(result)
  1018. return False
  1019. # Verify each key, value pair is the same
  1020. else:
  1021. if key not in user_def or value != user_def[key]:
  1022. if debug:
  1023. print("value not equal; user_def does not have key")
  1024. print(key)
  1025. print(value)
  1026. if key in user_def:
  1027. print(user_def[key])
  1028. return False
  1029. if debug:
  1030. print('returning true')
  1031. return True
  1032. class OpenShiftCLIConfig(object):
  1033. '''Generic Config'''
  1034. def __init__(self, rname, namespace, kubeconfig, options):
  1035. self.kubeconfig = kubeconfig
  1036. self.name = rname
  1037. self.namespace = namespace
  1038. self._options = options
  1039. @property
  1040. def config_options(self):
  1041. ''' return config options '''
  1042. return self._options
  1043. def to_option_list(self):
  1044. '''return all options as a string'''
  1045. return self.stringify()
  1046. def stringify(self):
  1047. ''' return the options hash as cli params in a string '''
  1048. rval = []
  1049. for key, data in self.config_options.items():
  1050. if data['include'] \
  1051. and (data['value'] or isinstance(data['value'], int)):
  1052. rval.append('--%s=%s' % (key.replace('_', '-'), data['value']))
  1053. return rval
  1054. # -*- -*- -*- End included fragment: lib/base.py -*- -*- -*-
  1055. # -*- -*- -*- Begin included fragment: lib/service.py -*- -*- -*-
  1056. # pylint: disable=too-many-instance-attributes
  1057. class ServiceConfig(object):
  1058. ''' Handle service options '''
  1059. # pylint: disable=too-many-arguments
  1060. def __init__(self,
  1061. sname,
  1062. namespace,
  1063. ports,
  1064. selector=None,
  1065. labels=None,
  1066. cluster_ip=None,
  1067. portal_ip=None,
  1068. session_affinity=None,
  1069. service_type=None):
  1070. ''' constructor for handling service options '''
  1071. self.name = sname
  1072. self.namespace = namespace
  1073. self.ports = ports
  1074. self.selector = selector
  1075. self.labels = labels
  1076. self.cluster_ip = cluster_ip
  1077. self.portal_ip = portal_ip
  1078. self.session_affinity = session_affinity
  1079. self.service_type = service_type
  1080. self.data = {}
  1081. self.create_dict()
  1082. def create_dict(self):
  1083. ''' instantiates a service dict '''
  1084. self.data['apiVersion'] = 'v1'
  1085. self.data['kind'] = 'Service'
  1086. self.data['metadata'] = {}
  1087. self.data['metadata']['name'] = self.name
  1088. self.data['metadata']['namespace'] = self.namespace
  1089. if self.labels:
  1090. for lab, lab_value in self.labels.items():
  1091. self.data['metadata'][lab] = lab_value
  1092. self.data['spec'] = {}
  1093. if self.ports:
  1094. self.data['spec']['ports'] = self.ports
  1095. else:
  1096. self.data['spec']['ports'] = []
  1097. if self.selector:
  1098. self.data['spec']['selector'] = self.selector
  1099. self.data['spec']['sessionAffinity'] = self.session_affinity or 'None'
  1100. if self.cluster_ip:
  1101. self.data['spec']['clusterIP'] = self.cluster_ip
  1102. if self.portal_ip:
  1103. self.data['spec']['portalIP'] = self.portal_ip
  1104. if self.service_type:
  1105. self.data['spec']['type'] = self.service_type
  1106. # pylint: disable=too-many-instance-attributes,too-many-public-methods
  1107. class Service(Yedit):
  1108. ''' Class to model the oc service object '''
  1109. port_path = "spec.ports"
  1110. portal_ip = "spec.portalIP"
  1111. cluster_ip = "spec.clusterIP"
  1112. kind = 'Service'
  1113. def __init__(self, content):
  1114. '''Service constructor'''
  1115. super(Service, self).__init__(content=content)
  1116. def get_ports(self):
  1117. ''' get a list of ports '''
  1118. return self.get(Service.port_path) or []
  1119. def add_ports(self, inc_ports):
  1120. ''' add a port object to the ports list '''
  1121. if not isinstance(inc_ports, list):
  1122. inc_ports = [inc_ports]
  1123. ports = self.get_ports()
  1124. if not ports:
  1125. self.put(Service.port_path, inc_ports)
  1126. else:
  1127. ports.extend(inc_ports)
  1128. return True
  1129. def find_ports(self, inc_port):
  1130. ''' find a specific port '''
  1131. for port in self.get_ports():
  1132. if port['port'] == inc_port['port']:
  1133. return port
  1134. return None
  1135. def delete_ports(self, inc_ports):
  1136. ''' remove a port from a service '''
  1137. if not isinstance(inc_ports, list):
  1138. inc_ports = [inc_ports]
  1139. ports = self.get(Service.port_path) or []
  1140. if not ports:
  1141. return True
  1142. removed = False
  1143. for inc_port in inc_ports:
  1144. port = self.find_ports(inc_port)
  1145. if port:
  1146. ports.remove(port)
  1147. removed = True
  1148. return removed
  1149. def add_cluster_ip(self, sip):
  1150. '''add cluster ip'''
  1151. self.put(Service.cluster_ip, sip)
  1152. def add_portal_ip(self, pip):
  1153. '''add cluster ip'''
  1154. self.put(Service.portal_ip, pip)
  1155. # -*- -*- -*- End included fragment: lib/service.py -*- -*- -*-
  1156. # -*- -*- -*- Begin included fragment: class/oc_service.py -*- -*- -*-
  1157. # pylint: disable=too-many-instance-attributes
  1158. class OCService(OpenShiftCLI):
  1159. ''' Class to wrap the oc command line tools '''
  1160. kind = 'service'
  1161. # pylint allows 5
  1162. # pylint: disable=too-many-arguments
  1163. def __init__(self,
  1164. sname,
  1165. namespace,
  1166. labels,
  1167. selector,
  1168. cluster_ip,
  1169. portal_ip,
  1170. ports,
  1171. session_affinity,
  1172. service_type,
  1173. kubeconfig='/etc/origin/master/admin.kubeconfig',
  1174. verbose=False):
  1175. ''' Constructor for OCVolume '''
  1176. super(OCService, self).__init__(namespace, kubeconfig)
  1177. self.namespace = namespace
  1178. self.config = ServiceConfig(sname, namespace, ports, selector, labels,
  1179. cluster_ip, portal_ip, session_affinity, service_type)
  1180. self.user_svc = Service(content=self.config.data)
  1181. self.svc = None
  1182. @property
  1183. def service(self):
  1184. ''' property function service'''
  1185. if not self.svc:
  1186. self.get()
  1187. return self.svc
  1188. @service.setter
  1189. def service(self, data):
  1190. ''' setter function for service var '''
  1191. self.svc = data
  1192. def exists(self):
  1193. ''' return whether a service exists '''
  1194. if self.service:
  1195. return True
  1196. return False
  1197. def get(self):
  1198. '''return service information '''
  1199. result = self._get(self.kind, self.config.name)
  1200. if result['returncode'] == 0:
  1201. self.service = Service(content=result['results'][0])
  1202. result['clusterip'] = self.service.get('spec.clusterIP')
  1203. elif 'services \"%s\" not found' % self.config.name in result['stderr']:
  1204. result['clusterip'] = ''
  1205. result['returncode'] = 0
  1206. return result
  1207. def delete(self):
  1208. '''delete the service'''
  1209. return self._delete(self.kind, self.config.name)
  1210. def create(self):
  1211. '''create a service '''
  1212. return self._create_from_content(self.config.name, self.user_svc.yaml_dict)
  1213. def update(self):
  1214. '''create a service '''
  1215. # Need to copy over the portalIP and the serviceIP settings
  1216. self.user_svc.add_cluster_ip(self.service.get('spec.clusterIP'))
  1217. self.user_svc.add_portal_ip(self.service.get('spec.portalIP'))
  1218. return self._replace_content(self.kind, self.config.name, self.user_svc.yaml_dict)
  1219. def needs_update(self):
  1220. ''' verify an update is needed '''
  1221. skip = ['clusterIP', 'portalIP']
  1222. return not Utils.check_def_equal(self.user_svc.yaml_dict, self.service.yaml_dict, skip_keys=skip, debug=True)
  1223. # pylint: disable=too-many-return-statements,too-many-branches
  1224. @staticmethod
  1225. def run_ansible(params, check_mode):
  1226. '''Run the idempotent ansible code'''
  1227. oc_svc = OCService(params['name'],
  1228. params['namespace'],
  1229. params['labels'],
  1230. params['selector'],
  1231. params['clusterip'],
  1232. params['portalip'],
  1233. params['ports'],
  1234. params['session_affinity'],
  1235. params['service_type'])
  1236. state = params['state']
  1237. api_rval = oc_svc.get()
  1238. if api_rval['returncode'] != 0:
  1239. return {'failed': True, 'msg': api_rval}
  1240. #####
  1241. # Get
  1242. #####
  1243. if state == 'list':
  1244. return {'changed': False, 'results': api_rval, 'state': state}
  1245. ########
  1246. # Delete
  1247. ########
  1248. if state == 'absent':
  1249. if oc_svc.exists():
  1250. if check_mode:
  1251. return {'changed': True,
  1252. 'msg': 'CHECK_MODE: Would have performed a delete.'} # noqa: E501
  1253. api_rval = oc_svc.delete()
  1254. return {'changed': True, 'results': api_rval, 'state': state}
  1255. return {'changed': False, 'state': state}
  1256. if state == 'present':
  1257. ########
  1258. # Create
  1259. ########
  1260. if not oc_svc.exists():
  1261. if check_mode:
  1262. return {'changed': True,
  1263. 'msg': 'CHECK_MODE: Would have performed a create.'} # noqa: E501
  1264. # Create it here
  1265. api_rval = oc_svc.create()
  1266. if api_rval['returncode'] != 0:
  1267. return {'failed': True, 'msg': api_rval}
  1268. # return the created object
  1269. api_rval = oc_svc.get()
  1270. if api_rval['returncode'] != 0:
  1271. return {'failed': True, 'msg': api_rval}
  1272. return {'changed': True, 'results': api_rval, 'state': state}
  1273. ########
  1274. # Update
  1275. ########
  1276. if oc_svc.needs_update():
  1277. api_rval = oc_svc.update()
  1278. if api_rval['returncode'] != 0:
  1279. return {'failed': True, 'msg': api_rval}
  1280. # return the created object
  1281. api_rval = oc_svc.get()
  1282. if api_rval['returncode'] != 0:
  1283. return {'failed': True, 'msg': api_rval}
  1284. return {'changed': True, 'results': api_rval, 'state': state}
  1285. return {'changed': False, 'results': api_rval, 'state': state}
  1286. return {'failed': True, 'msg': 'UNKNOWN state passed. [%s]' % state}
  1287. # -*- -*- -*- End included fragment: class/oc_service.py -*- -*- -*-
  1288. # -*- -*- -*- Begin included fragment: ansible/oc_service.py -*- -*- -*-
  1289. def main():
  1290. '''
  1291. ansible oc module for services
  1292. '''
  1293. module = AnsibleModule(
  1294. argument_spec=dict(
  1295. kubeconfig=dict(default='/etc/origin/master/admin.kubeconfig', type='str'),
  1296. state=dict(default='present', type='str',
  1297. choices=['present', 'absent', 'list']),
  1298. debug=dict(default=False, type='bool'),
  1299. namespace=dict(default='default', type='str'),
  1300. name=dict(default=None, type='str'),
  1301. labels=dict(default=None, type='dict'),
  1302. selector=dict(default=None, type='dict'),
  1303. clusterip=dict(default=None, type='str'),
  1304. portalip=dict(default=None, type='str'),
  1305. ports=dict(default=None, type='list'),
  1306. session_affinity=dict(default='None', type='str'),
  1307. service_type=dict(default='ClusterIP', type='str'),
  1308. ),
  1309. supports_check_mode=True,
  1310. )
  1311. rval = OCService.run_ansible(module.params, module.check_mode)
  1312. if 'failed' in rval:
  1313. return module.fail_json(**rval)
  1314. return module.exit_json(**rval)
  1315. if __name__ == '__main__':
  1316. main()
  1317. # -*- -*- -*- End included fragment: ansible/oc_service.py -*- -*- -*-