oc_service.py 58 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793
  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):
  169. ''' Exception class for Yedit '''
  170. pass
  171. # pylint: disable=too-many-public-methods
  172. class Yedit(object):
  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 % ''.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 % ''.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, None)
  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, None)
  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. %s' % 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 ' +
  486. 'dict with non-dict type. value=[%s] [%s]' % (value, type(value))) # noqa: E501
  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=[%s] vtype=[%s]' % (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 ' +
  603. 'value. value=[%s] vtype=[%s]'
  604. % (type(inc_value), vtype))
  605. return inc_value
  606. @staticmethod
  607. def process_edits(edits, yamlfile):
  608. '''run through a list of edits and process them one-by-one'''
  609. results = []
  610. for edit in edits:
  611. value = Yedit.parse_value(edit['value'], edit.get('value_type', ''))
  612. if 'action' in edit and edit['action'] == 'update':
  613. # pylint: disable=line-too-long
  614. curr_value = Yedit.get_curr_value(Yedit.parse_value(edit.get('curr_value', None)), # noqa: E501
  615. edit.get('curr_value_format', None)) # noqa: E501
  616. rval = yamlfile.update(edit['key'],
  617. value,
  618. edit.get('index', None),
  619. curr_value)
  620. elif 'action' in edit and edit['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 [%s]. Verify that the ' +
  640. 'file exists, that it is has correct' +
  641. ' permissions, and is valid yaml.'}
  642. if state == 'list':
  643. if params['content']:
  644. content = Yedit.parse_value(params['content'], params['content_type'])
  645. yamlfile.yaml_dict = content
  646. if params['key']:
  647. rval = yamlfile.get(params['key']) or {}
  648. return {'changed': False, 'result': rval, 'state': state}
  649. elif state == 'absent':
  650. if params['content']:
  651. content = Yedit.parse_value(params['content'], params['content_type'])
  652. yamlfile.yaml_dict = content
  653. if params['update']:
  654. rval = yamlfile.pop(params['key'], params['value'])
  655. else:
  656. rval = yamlfile.delete(params['key'])
  657. if rval[0] and params['src']:
  658. yamlfile.write()
  659. return {'changed': rval[0], 'result': rval[1], 'state': state}
  660. elif state == 'present':
  661. # check if content is different than what is in the file
  662. if params['content']:
  663. content = Yedit.parse_value(params['content'], params['content_type'])
  664. # We had no edits to make and the contents are the same
  665. if yamlfile.yaml_dict == content and \
  666. params['value'] is None:
  667. return {'changed': False, 'result': yamlfile.yaml_dict, 'state': state}
  668. yamlfile.yaml_dict = content
  669. # If we were passed a key, value then
  670. # we enapsulate it in a list and process it
  671. # Key, Value passed to the module : Converted to Edits list #
  672. edits = []
  673. _edit = {}
  674. if params['value'] is not None:
  675. _edit['value'] = params['value']
  676. _edit['value_type'] = params['value_type']
  677. _edit['key'] = params['key']
  678. if params['update']:
  679. _edit['action'] = 'update'
  680. _edit['curr_value'] = params['curr_value']
  681. _edit['curr_value_format'] = params['curr_value_format']
  682. _edit['index'] = params['index']
  683. elif params['append']:
  684. _edit['action'] = 'append'
  685. edits.append(_edit)
  686. elif params['edits'] is not None:
  687. edits = params['edits']
  688. if edits:
  689. results = Yedit.process_edits(edits, yamlfile)
  690. # if there were changes and a src provided to us we need to write
  691. if results['changed'] and params['src']:
  692. yamlfile.write()
  693. return {'changed': results['changed'], 'result': results['results'], 'state': state}
  694. # no edits to make
  695. if params['src']:
  696. # pylint: disable=redefined-variable-type
  697. rval = yamlfile.write()
  698. return {'changed': rval[0],
  699. 'result': rval[1],
  700. 'state': state}
  701. # We were passed content but no src, key or value, or edits. Return contents in memory
  702. return {'changed': False, 'result': yamlfile.yaml_dict, 'state': state}
  703. return {'failed': True, 'msg': 'Unkown state passed'}
  704. # -*- -*- -*- End included fragment: ../../lib_utils/src/class/yedit.py -*- -*- -*-
  705. # -*- -*- -*- Begin included fragment: lib/base.py -*- -*- -*-
  706. # pylint: disable=too-many-lines
  707. # noqa: E301,E302,E303,T001
  708. class OpenShiftCLIError(Exception):
  709. '''Exception class for openshiftcli'''
  710. pass
  711. ADDITIONAL_PATH_LOOKUPS = ['/usr/local/bin', os.path.expanduser('~/bin')]
  712. def locate_oc_binary():
  713. ''' Find and return oc binary file '''
  714. # https://github.com/openshift/openshift-ansible/issues/3410
  715. # oc can be in /usr/local/bin in some cases, but that may not
  716. # be in $PATH due to ansible/sudo
  717. paths = os.environ.get("PATH", os.defpath).split(os.pathsep) + ADDITIONAL_PATH_LOOKUPS
  718. oc_binary = 'oc'
  719. # Use shutil.which if it is available, otherwise fallback to a naive path search
  720. try:
  721. which_result = shutil.which(oc_binary, path=os.pathsep.join(paths))
  722. if which_result is not None:
  723. oc_binary = which_result
  724. except AttributeError:
  725. for path in paths:
  726. if os.path.exists(os.path.join(path, oc_binary)):
  727. oc_binary = os.path.join(path, oc_binary)
  728. break
  729. return oc_binary
  730. # pylint: disable=too-few-public-methods
  731. class OpenShiftCLI(object):
  732. ''' Class to wrap the command line tools '''
  733. def __init__(self,
  734. namespace,
  735. kubeconfig='/etc/origin/master/admin.kubeconfig',
  736. verbose=False,
  737. all_namespaces=False):
  738. ''' Constructor for OpenshiftCLI '''
  739. self.namespace = namespace
  740. self.verbose = verbose
  741. self.kubeconfig = Utils.create_tmpfile_copy(kubeconfig)
  742. self.all_namespaces = all_namespaces
  743. self.oc_binary = locate_oc_binary()
  744. # Pylint allows only 5 arguments to be passed.
  745. # pylint: disable=too-many-arguments
  746. def _replace_content(self, resource, rname, content, force=False, sep='.'):
  747. ''' replace the current object with the content '''
  748. res = self._get(resource, rname)
  749. if not res['results']:
  750. return res
  751. fname = Utils.create_tmpfile(rname + '-')
  752. yed = Yedit(fname, res['results'][0], separator=sep)
  753. changes = []
  754. for key, value in content.items():
  755. changes.append(yed.put(key, value))
  756. if any([change[0] for change in changes]):
  757. yed.write()
  758. atexit.register(Utils.cleanup, [fname])
  759. return self._replace(fname, force)
  760. return {'returncode': 0, 'updated': False}
  761. def _replace(self, fname, force=False):
  762. '''replace the current object with oc replace'''
  763. cmd = ['replace', '-f', fname]
  764. if force:
  765. cmd.append('--force')
  766. return self.openshift_cmd(cmd)
  767. def _create_from_content(self, rname, content):
  768. '''create a temporary file and then call oc create on it'''
  769. fname = Utils.create_tmpfile(rname + '-')
  770. yed = Yedit(fname, content=content)
  771. yed.write()
  772. atexit.register(Utils.cleanup, [fname])
  773. return self._create(fname)
  774. def _create(self, fname):
  775. '''call oc create on a filename'''
  776. return self.openshift_cmd(['create', '-f', fname])
  777. def _delete(self, resource, rname, selector=None):
  778. '''call oc delete on a resource'''
  779. cmd = ['delete', resource, rname]
  780. if selector:
  781. cmd.append('--selector=%s' % selector)
  782. return self.openshift_cmd(cmd)
  783. def _process(self, template_name, create=False, params=None, template_data=None): # noqa: E501
  784. '''process a template
  785. template_name: the name of the template to process
  786. create: whether to send to oc create after processing
  787. params: the parameters for the template
  788. template_data: the incoming template's data; instead of a file
  789. '''
  790. cmd = ['process']
  791. if template_data:
  792. cmd.extend(['-f', '-'])
  793. else:
  794. cmd.append(template_name)
  795. if params:
  796. param_str = ["%s=%s" % (key, value) for key, value in params.items()]
  797. cmd.append('-v')
  798. cmd.extend(param_str)
  799. results = self.openshift_cmd(cmd, output=True, input_data=template_data)
  800. if results['returncode'] != 0 or not create:
  801. return results
  802. fname = Utils.create_tmpfile(template_name + '-')
  803. yed = Yedit(fname, results['results'])
  804. yed.write()
  805. atexit.register(Utils.cleanup, [fname])
  806. return self.openshift_cmd(['create', '-f', fname])
  807. def _get(self, resource, rname=None, selector=None):
  808. '''return a resource by name '''
  809. cmd = ['get', resource]
  810. if selector:
  811. cmd.append('--selector=%s' % selector)
  812. elif rname:
  813. cmd.append(rname)
  814. cmd.extend(['-o', 'json'])
  815. rval = self.openshift_cmd(cmd, output=True)
  816. # Ensure results are retuned in an array
  817. if 'items' in rval:
  818. rval['results'] = rval['items']
  819. elif not isinstance(rval['results'], list):
  820. rval['results'] = [rval['results']]
  821. return rval
  822. def _schedulable(self, node=None, selector=None, schedulable=True):
  823. ''' perform oadm manage-node scheduable '''
  824. cmd = ['manage-node']
  825. if node:
  826. cmd.extend(node)
  827. else:
  828. cmd.append('--selector=%s' % selector)
  829. cmd.append('--schedulable=%s' % schedulable)
  830. return self.openshift_cmd(cmd, oadm=True, output=True, output_type='raw') # noqa: E501
  831. def _list_pods(self, node=None, selector=None, pod_selector=None):
  832. ''' perform oadm list pods
  833. node: the node in which to list pods
  834. selector: the label selector filter if provided
  835. pod_selector: the pod selector filter if provided
  836. '''
  837. cmd = ['manage-node']
  838. if node:
  839. cmd.extend(node)
  840. else:
  841. cmd.append('--selector=%s' % selector)
  842. if pod_selector:
  843. cmd.append('--pod-selector=%s' % pod_selector)
  844. cmd.extend(['--list-pods', '-o', 'json'])
  845. return self.openshift_cmd(cmd, oadm=True, output=True, output_type='raw')
  846. # pylint: disable=too-many-arguments
  847. def _evacuate(self, node=None, selector=None, pod_selector=None, dry_run=False, grace_period=None, force=False):
  848. ''' perform oadm manage-node evacuate '''
  849. cmd = ['manage-node']
  850. if node:
  851. cmd.extend(node)
  852. else:
  853. cmd.append('--selector=%s' % selector)
  854. if dry_run:
  855. cmd.append('--dry-run')
  856. if pod_selector:
  857. cmd.append('--pod-selector=%s' % pod_selector)
  858. if grace_period:
  859. cmd.append('--grace-period=%s' % int(grace_period))
  860. if force:
  861. cmd.append('--force')
  862. cmd.append('--evacuate')
  863. return self.openshift_cmd(cmd, oadm=True, output=True, output_type='raw')
  864. def _version(self):
  865. ''' return the openshift version'''
  866. return self.openshift_cmd(['version'], output=True, output_type='raw')
  867. def _import_image(self, url=None, name=None, tag=None):
  868. ''' perform image import '''
  869. cmd = ['import-image']
  870. image = '{0}'.format(name)
  871. if tag:
  872. image += ':{0}'.format(tag)
  873. cmd.append(image)
  874. if url:
  875. cmd.append('--from={0}/{1}'.format(url, image))
  876. cmd.append('-n{0}'.format(self.namespace))
  877. cmd.append('--confirm')
  878. return self.openshift_cmd(cmd)
  879. def _run(self, cmds, input_data):
  880. ''' Actually executes the command. This makes mocking easier. '''
  881. curr_env = os.environ.copy()
  882. curr_env.update({'KUBECONFIG': self.kubeconfig})
  883. proc = subprocess.Popen(cmds,
  884. stdin=subprocess.PIPE,
  885. stdout=subprocess.PIPE,
  886. stderr=subprocess.PIPE,
  887. env=curr_env)
  888. stdout, stderr = proc.communicate(input_data)
  889. return proc.returncode, stdout.decode(), stderr.decode()
  890. # pylint: disable=too-many-arguments,too-many-branches
  891. def openshift_cmd(self, cmd, oadm=False, output=False, output_type='json', input_data=None):
  892. '''Base command for oc '''
  893. cmds = [self.oc_binary]
  894. if oadm:
  895. cmds.append('adm')
  896. cmds.extend(cmd)
  897. if self.all_namespaces:
  898. cmds.extend(['--all-namespaces'])
  899. elif self.namespace is not None and self.namespace.lower() not in ['none', 'emtpy']: # E501
  900. cmds.extend(['-n', self.namespace])
  901. rval = {}
  902. results = ''
  903. err = None
  904. if self.verbose:
  905. print(' '.join(cmds))
  906. try:
  907. returncode, stdout, stderr = self._run(cmds, input_data)
  908. except OSError as ex:
  909. returncode, stdout, stderr = 1, '', 'Failed to execute {}: {}'.format(subprocess.list2cmdline(cmds), ex)
  910. rval = {"returncode": returncode,
  911. "results": results,
  912. "cmd": ' '.join(cmds)}
  913. if returncode == 0:
  914. if output:
  915. if output_type == 'json':
  916. try:
  917. rval['results'] = json.loads(stdout)
  918. except ValueError as verr:
  919. if "No JSON object could be decoded" in verr.args:
  920. err = verr.args
  921. elif output_type == 'raw':
  922. rval['results'] = stdout
  923. if self.verbose:
  924. print("STDOUT: {0}".format(stdout))
  925. print("STDERR: {0}".format(stderr))
  926. if err:
  927. rval.update({"err": err,
  928. "stderr": stderr,
  929. "stdout": stdout,
  930. "cmd": cmds})
  931. else:
  932. rval.update({"stderr": stderr,
  933. "stdout": stdout,
  934. "results": {}})
  935. return rval
  936. class Utils(object):
  937. ''' utilities for openshiftcli modules '''
  938. @staticmethod
  939. def _write(filename, contents):
  940. ''' Actually write the file contents to disk. This helps with mocking. '''
  941. with open(filename, 'w') as sfd:
  942. sfd.write(contents)
  943. @staticmethod
  944. def create_tmp_file_from_contents(rname, data, ftype='yaml'):
  945. ''' create a file in tmp with name and contents'''
  946. tmp = Utils.create_tmpfile(prefix=rname)
  947. if ftype == 'yaml':
  948. # AUDIT:no-member makes sense here due to ruamel.YAML/PyYAML usage
  949. # pylint: disable=no-member
  950. if hasattr(yaml, 'RoundTripDumper'):
  951. Utils._write(tmp, yaml.dump(data, Dumper=yaml.RoundTripDumper))
  952. else:
  953. Utils._write(tmp, yaml.safe_dump(data, default_flow_style=False))
  954. elif ftype == 'json':
  955. Utils._write(tmp, json.dumps(data))
  956. else:
  957. Utils._write(tmp, data)
  958. # Register cleanup when module is done
  959. atexit.register(Utils.cleanup, [tmp])
  960. return tmp
  961. @staticmethod
  962. def create_tmpfile_copy(inc_file):
  963. '''create a temporary copy of a file'''
  964. tmpfile = Utils.create_tmpfile('lib_openshift-')
  965. Utils._write(tmpfile, open(inc_file).read())
  966. # Cleanup the tmpfile
  967. atexit.register(Utils.cleanup, [tmpfile])
  968. return tmpfile
  969. @staticmethod
  970. def create_tmpfile(prefix='tmp'):
  971. ''' Generates and returns a temporary file name '''
  972. with tempfile.NamedTemporaryFile(prefix=prefix, delete=False) as tmp:
  973. return tmp.name
  974. @staticmethod
  975. def create_tmp_files_from_contents(content, content_type=None):
  976. '''Turn an array of dict: filename, content into a files array'''
  977. if not isinstance(content, list):
  978. content = [content]
  979. files = []
  980. for item in content:
  981. path = Utils.create_tmp_file_from_contents(item['path'] + '-',
  982. item['data'],
  983. ftype=content_type)
  984. files.append({'name': os.path.basename(item['path']),
  985. 'path': path})
  986. return files
  987. @staticmethod
  988. def cleanup(files):
  989. '''Clean up on exit '''
  990. for sfile in files:
  991. if os.path.exists(sfile):
  992. if os.path.isdir(sfile):
  993. shutil.rmtree(sfile)
  994. elif os.path.isfile(sfile):
  995. os.remove(sfile)
  996. @staticmethod
  997. def exists(results, _name):
  998. ''' Check to see if the results include the name '''
  999. if not results:
  1000. return False
  1001. if Utils.find_result(results, _name):
  1002. return True
  1003. return False
  1004. @staticmethod
  1005. def find_result(results, _name):
  1006. ''' Find the specified result by name'''
  1007. rval = None
  1008. for result in results:
  1009. if 'metadata' in result and result['metadata']['name'] == _name:
  1010. rval = result
  1011. break
  1012. return rval
  1013. @staticmethod
  1014. def get_resource_file(sfile, sfile_type='yaml'):
  1015. ''' return the service file '''
  1016. contents = None
  1017. with open(sfile) as sfd:
  1018. contents = sfd.read()
  1019. if sfile_type == 'yaml':
  1020. # AUDIT:no-member makes sense here due to ruamel.YAML/PyYAML usage
  1021. # pylint: disable=no-member
  1022. if hasattr(yaml, 'RoundTripLoader'):
  1023. contents = yaml.load(contents, yaml.RoundTripLoader)
  1024. else:
  1025. contents = yaml.safe_load(contents)
  1026. elif sfile_type == 'json':
  1027. contents = json.loads(contents)
  1028. return contents
  1029. @staticmethod
  1030. def filter_versions(stdout):
  1031. ''' filter the oc version output '''
  1032. version_dict = {}
  1033. version_search = ['oc', 'openshift', 'kubernetes']
  1034. for line in stdout.strip().split('\n'):
  1035. for term in version_search:
  1036. if not line:
  1037. continue
  1038. if line.startswith(term):
  1039. version_dict[term] = line.split()[-1]
  1040. # horrible hack to get openshift version in Openshift 3.2
  1041. # By default "oc version in 3.2 does not return an "openshift" version
  1042. if "openshift" not in version_dict:
  1043. version_dict["openshift"] = version_dict["oc"]
  1044. return version_dict
  1045. @staticmethod
  1046. def add_custom_versions(versions):
  1047. ''' create custom versions strings '''
  1048. versions_dict = {}
  1049. for tech, version in versions.items():
  1050. # clean up "-" from version
  1051. if "-" in version:
  1052. version = version.split("-")[0]
  1053. if version.startswith('v'):
  1054. versions_dict[tech + '_numeric'] = version[1:].split('+')[0]
  1055. # "v3.3.0.33" is what we have, we want "3.3"
  1056. versions_dict[tech + '_short'] = version[1:4]
  1057. return versions_dict
  1058. @staticmethod
  1059. def openshift_installed():
  1060. ''' check if openshift is installed '''
  1061. import yum
  1062. yum_base = yum.YumBase()
  1063. if yum_base.rpmdb.searchNevra(name='atomic-openshift'):
  1064. return True
  1065. return False
  1066. # Disabling too-many-branches. This is a yaml dictionary comparison function
  1067. # pylint: disable=too-many-branches,too-many-return-statements,too-many-statements
  1068. @staticmethod
  1069. def check_def_equal(user_def, result_def, skip_keys=None, debug=False):
  1070. ''' Given a user defined definition, compare it with the results given back by our query. '''
  1071. # Currently these values are autogenerated and we do not need to check them
  1072. skip = ['metadata', 'status']
  1073. if skip_keys:
  1074. skip.extend(skip_keys)
  1075. for key, value in result_def.items():
  1076. if key in skip:
  1077. continue
  1078. # Both are lists
  1079. if isinstance(value, list):
  1080. if key not in user_def:
  1081. if debug:
  1082. print('User data does not have key [%s]' % key)
  1083. print('User data: %s' % user_def)
  1084. return False
  1085. if not isinstance(user_def[key], list):
  1086. if debug:
  1087. print('user_def[key] is not a list key=[%s] user_def[key]=%s' % (key, user_def[key]))
  1088. return False
  1089. if len(user_def[key]) != len(value):
  1090. if debug:
  1091. print("List lengths are not equal.")
  1092. print("key=[%s]: user_def[%s] != value[%s]" % (key, len(user_def[key]), len(value)))
  1093. print("user_def: %s" % user_def[key])
  1094. print("value: %s" % value)
  1095. return False
  1096. for values in zip(user_def[key], value):
  1097. if isinstance(values[0], dict) and isinstance(values[1], dict):
  1098. if debug:
  1099. print('sending list - list')
  1100. print(type(values[0]))
  1101. print(type(values[1]))
  1102. result = Utils.check_def_equal(values[0], values[1], skip_keys=skip_keys, debug=debug)
  1103. if not result:
  1104. print('list compare returned false')
  1105. return False
  1106. elif value != user_def[key]:
  1107. if debug:
  1108. print('value should be identical')
  1109. print(user_def[key])
  1110. print(value)
  1111. return False
  1112. # recurse on a dictionary
  1113. elif isinstance(value, dict):
  1114. if key not in user_def:
  1115. if debug:
  1116. print("user_def does not have key [%s]" % key)
  1117. return False
  1118. if not isinstance(user_def[key], dict):
  1119. if debug:
  1120. print("dict returned false: not instance of dict")
  1121. return False
  1122. # before passing ensure keys match
  1123. api_values = set(value.keys()) - set(skip)
  1124. user_values = set(user_def[key].keys()) - set(skip)
  1125. if api_values != user_values:
  1126. if debug:
  1127. print("keys are not equal in dict")
  1128. print(user_values)
  1129. print(api_values)
  1130. return False
  1131. result = Utils.check_def_equal(user_def[key], value, skip_keys=skip_keys, debug=debug)
  1132. if not result:
  1133. if debug:
  1134. print("dict returned false")
  1135. print(result)
  1136. return False
  1137. # Verify each key, value pair is the same
  1138. else:
  1139. if key not in user_def or value != user_def[key]:
  1140. if debug:
  1141. print("value not equal; user_def does not have key")
  1142. print(key)
  1143. print(value)
  1144. if key in user_def:
  1145. print(user_def[key])
  1146. return False
  1147. if debug:
  1148. print('returning true')
  1149. return True
  1150. class OpenShiftCLIConfig(object):
  1151. '''Generic Config'''
  1152. def __init__(self, rname, namespace, kubeconfig, options):
  1153. self.kubeconfig = kubeconfig
  1154. self.name = rname
  1155. self.namespace = namespace
  1156. self._options = options
  1157. @property
  1158. def config_options(self):
  1159. ''' return config options '''
  1160. return self._options
  1161. def to_option_list(self):
  1162. '''return all options as a string'''
  1163. return self.stringify()
  1164. def stringify(self):
  1165. ''' return the options hash as cli params in a string '''
  1166. rval = []
  1167. for key in sorted(self.config_options.keys()):
  1168. data = self.config_options[key]
  1169. if data['include'] \
  1170. and (data['value'] or isinstance(data['value'], int)):
  1171. rval.append('--{}={}'.format(key.replace('_', '-'), data['value']))
  1172. return rval
  1173. # -*- -*- -*- End included fragment: lib/base.py -*- -*- -*-
  1174. # -*- -*- -*- Begin included fragment: lib/service.py -*- -*- -*-
  1175. # pylint: disable=too-many-instance-attributes
  1176. class ServiceConfig(object):
  1177. ''' Handle service options '''
  1178. # pylint: disable=too-many-arguments
  1179. def __init__(self,
  1180. sname,
  1181. namespace,
  1182. ports,
  1183. selector=None,
  1184. labels=None,
  1185. cluster_ip=None,
  1186. portal_ip=None,
  1187. session_affinity=None,
  1188. service_type=None):
  1189. ''' constructor for handling service options '''
  1190. self.name = sname
  1191. self.namespace = namespace
  1192. self.ports = ports
  1193. self.selector = selector
  1194. self.labels = labels
  1195. self.cluster_ip = cluster_ip
  1196. self.portal_ip = portal_ip
  1197. self.session_affinity = session_affinity
  1198. self.service_type = service_type
  1199. self.data = {}
  1200. self.create_dict()
  1201. def create_dict(self):
  1202. ''' instantiates a service dict '''
  1203. self.data['apiVersion'] = 'v1'
  1204. self.data['kind'] = 'Service'
  1205. self.data['metadata'] = {}
  1206. self.data['metadata']['name'] = self.name
  1207. self.data['metadata']['namespace'] = self.namespace
  1208. if self.labels:
  1209. for lab, lab_value in self.labels.items():
  1210. self.data['metadata'][lab] = lab_value
  1211. self.data['spec'] = {}
  1212. if self.ports:
  1213. self.data['spec']['ports'] = self.ports
  1214. else:
  1215. self.data['spec']['ports'] = []
  1216. if self.selector:
  1217. self.data['spec']['selector'] = self.selector
  1218. self.data['spec']['sessionAffinity'] = self.session_affinity or 'None'
  1219. if self.cluster_ip:
  1220. self.data['spec']['clusterIP'] = self.cluster_ip
  1221. if self.portal_ip:
  1222. self.data['spec']['portalIP'] = self.portal_ip
  1223. if self.service_type:
  1224. self.data['spec']['type'] = self.service_type
  1225. # pylint: disable=too-many-instance-attributes,too-many-public-methods
  1226. class Service(Yedit):
  1227. ''' Class to model the oc service object '''
  1228. port_path = "spec.ports"
  1229. portal_ip = "spec.portalIP"
  1230. cluster_ip = "spec.clusterIP"
  1231. selector_path = 'spec.selector'
  1232. kind = 'Service'
  1233. def __init__(self, content):
  1234. '''Service constructor'''
  1235. super(Service, self).__init__(content=content)
  1236. def get_ports(self):
  1237. ''' get a list of ports '''
  1238. return self.get(Service.port_path) or []
  1239. def get_selector(self):
  1240. ''' get the service selector'''
  1241. return self.get(Service.selector_path) or {}
  1242. def add_ports(self, inc_ports):
  1243. ''' add a port object to the ports list '''
  1244. if not isinstance(inc_ports, list):
  1245. inc_ports = [inc_ports]
  1246. ports = self.get_ports()
  1247. if not ports:
  1248. self.put(Service.port_path, inc_ports)
  1249. else:
  1250. ports.extend(inc_ports)
  1251. return True
  1252. def find_ports(self, inc_port):
  1253. ''' find a specific port '''
  1254. for port in self.get_ports():
  1255. if port['port'] == inc_port['port']:
  1256. return port
  1257. return None
  1258. def delete_ports(self, inc_ports):
  1259. ''' remove a port from a service '''
  1260. if not isinstance(inc_ports, list):
  1261. inc_ports = [inc_ports]
  1262. ports = self.get(Service.port_path) or []
  1263. if not ports:
  1264. return True
  1265. removed = False
  1266. for inc_port in inc_ports:
  1267. port = self.find_ports(inc_port)
  1268. if port:
  1269. ports.remove(port)
  1270. removed = True
  1271. return removed
  1272. def add_cluster_ip(self, sip):
  1273. '''add cluster ip'''
  1274. self.put(Service.cluster_ip, sip)
  1275. def add_portal_ip(self, pip):
  1276. '''add cluster ip'''
  1277. self.put(Service.portal_ip, pip)
  1278. # -*- -*- -*- End included fragment: lib/service.py -*- -*- -*-
  1279. # -*- -*- -*- Begin included fragment: class/oc_service.py -*- -*- -*-
  1280. # pylint: disable=too-many-instance-attributes
  1281. class OCService(OpenShiftCLI):
  1282. ''' Class to wrap the oc command line tools '''
  1283. kind = 'service'
  1284. # pylint allows 5
  1285. # pylint: disable=too-many-arguments
  1286. def __init__(self,
  1287. sname,
  1288. namespace,
  1289. labels,
  1290. selector,
  1291. cluster_ip,
  1292. portal_ip,
  1293. ports,
  1294. session_affinity,
  1295. service_type,
  1296. kubeconfig='/etc/origin/master/admin.kubeconfig',
  1297. verbose=False):
  1298. ''' Constructor for OCVolume '''
  1299. super(OCService, self).__init__(namespace, kubeconfig, verbose)
  1300. self.namespace = namespace
  1301. self.config = ServiceConfig(sname, namespace, ports, selector, labels,
  1302. cluster_ip, portal_ip, session_affinity, service_type)
  1303. self.user_svc = Service(content=self.config.data)
  1304. self.svc = None
  1305. @property
  1306. def service(self):
  1307. ''' property function service'''
  1308. if not self.svc:
  1309. self.get()
  1310. return self.svc
  1311. @service.setter
  1312. def service(self, data):
  1313. ''' setter function for service var '''
  1314. self.svc = data
  1315. def exists(self):
  1316. ''' return whether a service exists '''
  1317. if self.service:
  1318. return True
  1319. return False
  1320. def get(self):
  1321. '''return service information '''
  1322. result = self._get(self.kind, self.config.name)
  1323. if result['returncode'] == 0:
  1324. self.service = Service(content=result['results'][0])
  1325. result['clusterip'] = self.service.get('spec.clusterIP')
  1326. elif 'services \"%s\" not found' % self.config.name in result['stderr']:
  1327. result['clusterip'] = ''
  1328. result['returncode'] = 0
  1329. return result
  1330. def delete(self):
  1331. '''delete the service'''
  1332. return self._delete(self.kind, self.config.name)
  1333. def create(self):
  1334. '''create a service '''
  1335. return self._create_from_content(self.config.name, self.user_svc.yaml_dict)
  1336. def update(self):
  1337. '''create a service '''
  1338. # Need to copy over the portalIP and the serviceIP settings
  1339. self.user_svc.add_cluster_ip(self.service.get('spec.clusterIP'))
  1340. self.user_svc.add_portal_ip(self.service.get('spec.portalIP'))
  1341. return self._replace_content(self.kind, self.config.name, self.user_svc.yaml_dict)
  1342. def needs_update(self):
  1343. ''' verify an update is needed '''
  1344. skip = ['clusterIP', 'portalIP']
  1345. return not Utils.check_def_equal(self.user_svc.yaml_dict, self.service.yaml_dict, skip_keys=skip, debug=True)
  1346. # pylint: disable=too-many-return-statements,too-many-branches
  1347. @staticmethod
  1348. def run_ansible(params, check_mode):
  1349. '''Run the idempotent ansible code'''
  1350. oc_svc = OCService(params['name'],
  1351. params['namespace'],
  1352. params['labels'],
  1353. params['selector'],
  1354. params['clusterip'],
  1355. params['portalip'],
  1356. params['ports'],
  1357. params['session_affinity'],
  1358. params['service_type'],
  1359. params['kubeconfig'],
  1360. params['debug'])
  1361. state = params['state']
  1362. api_rval = oc_svc.get()
  1363. if api_rval['returncode'] != 0:
  1364. return {'failed': True, 'msg': api_rval}
  1365. #####
  1366. # Get
  1367. #####
  1368. if state == 'list':
  1369. return {'changed': False, 'results': api_rval, 'state': state}
  1370. ########
  1371. # Delete
  1372. ########
  1373. if state == 'absent':
  1374. if oc_svc.exists():
  1375. if check_mode:
  1376. return {'changed': True,
  1377. 'msg': 'CHECK_MODE: Would have performed a delete.'} # noqa: E501
  1378. api_rval = oc_svc.delete()
  1379. return {'changed': True, 'results': api_rval, 'state': state}
  1380. return {'changed': False, 'state': state}
  1381. if state == 'present':
  1382. ########
  1383. # Create
  1384. ########
  1385. if not oc_svc.exists():
  1386. if check_mode:
  1387. return {'changed': True,
  1388. 'msg': 'CHECK_MODE: Would have performed a create.'} # noqa: E501
  1389. # Create it here
  1390. api_rval = oc_svc.create()
  1391. if api_rval['returncode'] != 0:
  1392. return {'failed': True, 'msg': api_rval}
  1393. # return the created object
  1394. api_rval = oc_svc.get()
  1395. if api_rval['returncode'] != 0:
  1396. return {'failed': True, 'msg': api_rval}
  1397. return {'changed': True, 'results': api_rval, 'state': state}
  1398. ########
  1399. # Update
  1400. ########
  1401. if oc_svc.needs_update():
  1402. api_rval = oc_svc.update()
  1403. if api_rval['returncode'] != 0:
  1404. return {'failed': True, 'msg': api_rval}
  1405. # return the created object
  1406. api_rval = oc_svc.get()
  1407. if api_rval['returncode'] != 0:
  1408. return {'failed': True, 'msg': api_rval}
  1409. return {'changed': True, 'results': api_rval, 'state': state}
  1410. return {'changed': False, 'results': api_rval, 'state': state}
  1411. return {'failed': True, 'msg': 'UNKNOWN state passed. [%s]' % state}
  1412. # -*- -*- -*- End included fragment: class/oc_service.py -*- -*- -*-
  1413. # -*- -*- -*- Begin included fragment: ansible/oc_service.py -*- -*- -*-
  1414. def main():
  1415. '''
  1416. ansible oc module for services
  1417. '''
  1418. module = AnsibleModule(
  1419. argument_spec=dict(
  1420. kubeconfig=dict(default='/etc/origin/master/admin.kubeconfig', type='str'),
  1421. state=dict(default='present', type='str',
  1422. choices=['present', 'absent', 'list']),
  1423. debug=dict(default=False, type='bool'),
  1424. namespace=dict(default='default', type='str'),
  1425. name=dict(default=None, type='str'),
  1426. labels=dict(default=None, type='dict'),
  1427. selector=dict(default=None, type='dict'),
  1428. clusterip=dict(default=None, type='str'),
  1429. portalip=dict(default=None, type='str'),
  1430. ports=dict(default=None, type='list'),
  1431. session_affinity=dict(default='None', type='str'),
  1432. service_type=dict(default='ClusterIP', type='str'),
  1433. ),
  1434. supports_check_mode=True,
  1435. )
  1436. rval = OCService.run_ansible(module.params, module.check_mode)
  1437. if 'failed' in rval:
  1438. return module.fail_json(**rval)
  1439. return module.exit_json(**rval)
  1440. if __name__ == '__main__':
  1441. main()
  1442. # -*- -*- -*- End included fragment: ansible/oc_service.py -*- -*- -*-