oc_service.py 58 KB

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