oc_service.py 61 KB

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