oc_service.py 54 KB

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