oc_service.py 56 KB

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