oc_service.py 63 KB

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