oc_image.py 50 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529
  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/image -*- -*- -*-
  49. DOCUMENTATION = '''
  50. ---
  51. module: oc_image
  52. short_description: Create, modify, and idempotently manage openshift labels.
  53. description:
  54. - Modify openshift labels programmatically.
  55. options:
  56. state:
  57. description:
  58. - State controls the action that will be taken with resource
  59. - 'present' will create. Does _not_ support update.
  60. - 'list' will read the labels
  61. default: present
  62. choices: ["present", "list"]
  63. aliases: []
  64. kubeconfig:
  65. description:
  66. - The path for the kubeconfig file to use for authentication
  67. required: false
  68. default: /etc/origin/master/admin.kubeconfig
  69. aliases: []
  70. namespace:
  71. description:
  72. - The namespace where this object lives
  73. required: false
  74. default: default
  75. aliases: []
  76. debug:
  77. description:
  78. - Turn on debug output.
  79. required: false
  80. default: False
  81. aliases: []
  82. registry_url:
  83. description:
  84. - The url for the registry so that openshift can pull the image
  85. required: false
  86. default: None
  87. aliases: []
  88. image_name:
  89. description:
  90. - The name of the image being imported
  91. required: false
  92. default: False
  93. aliases: []
  94. image_tag:
  95. description:
  96. - The tag of the image being imported
  97. required: false
  98. default: None
  99. aliases: []
  100. author:
  101. - "Ivan Horvath<ihorvath@redhat.com>"
  102. extends_documentation_fragment: []
  103. '''
  104. EXAMPLES = '''
  105. - name: Get an imagestream
  106. oc_image:
  107. name: php55
  108. state: list
  109. register: imageout
  110. - name: create an imagestream
  111. oc_image:
  112. state: present
  113. image_name: php55
  114. image_tag: int
  115. registry_url: registry.example.com
  116. namespace: default
  117. register: imageout
  118. '''
  119. # -*- -*- -*- End included fragment: doc/image -*- -*- -*-
  120. # -*- -*- -*- Begin included fragment: ../../lib_utils/src/class/yedit.py -*- -*- -*-
  121. class YeditException(Exception):
  122. ''' Exception class for Yedit '''
  123. pass
  124. # pylint: disable=too-many-public-methods
  125. class Yedit(object):
  126. ''' Class to modify yaml files '''
  127. re_valid_key = r"(((\[-?\d+\])|([0-9a-zA-Z%s/_-]+)).?)+$"
  128. re_key = r"(?:\[(-?\d+)\])|([0-9a-zA-Z%s/_-]+)"
  129. com_sep = set(['.', '#', '|', ':'])
  130. # pylint: disable=too-many-arguments
  131. def __init__(self,
  132. filename=None,
  133. content=None,
  134. content_type='yaml',
  135. separator='.',
  136. backup=False):
  137. self.content = content
  138. self._separator = separator
  139. self.filename = filename
  140. self.__yaml_dict = content
  141. self.content_type = content_type
  142. self.backup = backup
  143. self.load(content_type=self.content_type)
  144. if self.__yaml_dict is None:
  145. self.__yaml_dict = {}
  146. @property
  147. def separator(self):
  148. ''' getter method for separator '''
  149. return self._separator
  150. @separator.setter
  151. def separator(self, inc_sep):
  152. ''' setter method for separator '''
  153. self._separator = inc_sep
  154. @property
  155. def yaml_dict(self):
  156. ''' getter method for yaml_dict '''
  157. return self.__yaml_dict
  158. @yaml_dict.setter
  159. def yaml_dict(self, value):
  160. ''' setter method for yaml_dict '''
  161. self.__yaml_dict = value
  162. @staticmethod
  163. def parse_key(key, sep='.'):
  164. '''parse the key allowing the appropriate separator'''
  165. common_separators = list(Yedit.com_sep - set([sep]))
  166. return re.findall(Yedit.re_key.format(''.join(common_separators)), key)
  167. @staticmethod
  168. def valid_key(key, sep='.'):
  169. '''validate the incoming key'''
  170. common_separators = list(Yedit.com_sep - set([sep]))
  171. if not re.match(Yedit.re_valid_key.format(''.join(common_separators)), key):
  172. return False
  173. return True
  174. @staticmethod
  175. def remove_entry(data, key, sep='.'):
  176. ''' remove data at location key '''
  177. if key == '' and isinstance(data, dict):
  178. data.clear()
  179. return True
  180. elif key == '' and isinstance(data, list):
  181. del data[:]
  182. return True
  183. if not (key and Yedit.valid_key(key, sep)) and \
  184. isinstance(data, (list, dict)):
  185. return None
  186. key_indexes = Yedit.parse_key(key, sep)
  187. for arr_ind, dict_key in key_indexes[:-1]:
  188. if dict_key and isinstance(data, dict):
  189. data = data.get(dict_key)
  190. elif (arr_ind and isinstance(data, list) and
  191. int(arr_ind) <= len(data) - 1):
  192. data = data[int(arr_ind)]
  193. else:
  194. return None
  195. # process last index for remove
  196. # expected list entry
  197. if key_indexes[-1][0]:
  198. if isinstance(data, list) and int(key_indexes[-1][0]) <= len(data) - 1: # noqa: E501
  199. del data[int(key_indexes[-1][0])]
  200. return True
  201. # expected dict entry
  202. elif key_indexes[-1][1]:
  203. if isinstance(data, dict):
  204. del data[key_indexes[-1][1]]
  205. return True
  206. @staticmethod
  207. def add_entry(data, key, item=None, sep='.'):
  208. ''' Get an item from a dictionary with key notation a.b.c
  209. d = {'a': {'b': 'c'}}}
  210. key = a#b
  211. return c
  212. '''
  213. if key == '':
  214. pass
  215. elif (not (key and Yedit.valid_key(key, sep)) and
  216. isinstance(data, (list, dict))):
  217. return None
  218. key_indexes = Yedit.parse_key(key, sep)
  219. for arr_ind, dict_key in key_indexes[:-1]:
  220. if dict_key:
  221. if isinstance(data, dict) and dict_key in data and data[dict_key]: # noqa: E501
  222. data = data[dict_key]
  223. continue
  224. elif data and not isinstance(data, dict):
  225. raise YeditException("Unexpected item type found while going through key " +
  226. "path: {} (at key: {})".format(key, dict_key))
  227. data[dict_key] = {}
  228. data = data[dict_key]
  229. elif (arr_ind and isinstance(data, list) and
  230. int(arr_ind) <= len(data) - 1):
  231. data = data[int(arr_ind)]
  232. else:
  233. raise YeditException("Unexpected item type found while going through key path: {}".format(key))
  234. if key == '':
  235. data = item
  236. # process last index for add
  237. # expected list entry
  238. elif key_indexes[-1][0] and isinstance(data, list) and int(key_indexes[-1][0]) <= len(data) - 1: # noqa: E501
  239. data[int(key_indexes[-1][0])] = item
  240. # expected dict entry
  241. elif key_indexes[-1][1] and isinstance(data, dict):
  242. data[key_indexes[-1][1]] = item
  243. # didn't add/update to an existing list, nor add/update key to a dict
  244. # so we must have been provided some syntax like a.b.c[<int>] = "data" for a
  245. # non-existent array
  246. else:
  247. raise YeditException("Error adding to object at path: {}".format(key))
  248. return data
  249. @staticmethod
  250. def get_entry(data, key, sep='.'):
  251. ''' Get an item from a dictionary with key notation a.b.c
  252. d = {'a': {'b': 'c'}}}
  253. key = a.b
  254. return c
  255. '''
  256. if key == '':
  257. pass
  258. elif (not (key and Yedit.valid_key(key, sep)) and
  259. isinstance(data, (list, dict))):
  260. return None
  261. key_indexes = Yedit.parse_key(key, sep)
  262. for arr_ind, dict_key in key_indexes:
  263. if dict_key and isinstance(data, dict):
  264. data = data.get(dict_key)
  265. elif (arr_ind and isinstance(data, list) and
  266. int(arr_ind) <= len(data) - 1):
  267. data = data[int(arr_ind)]
  268. else:
  269. return None
  270. return data
  271. @staticmethod
  272. def _write(filename, contents):
  273. ''' Actually write the file contents to disk. This helps with mocking. '''
  274. tmp_filename = filename + '.yedit'
  275. with open(tmp_filename, 'w') as yfd:
  276. yfd.write(contents)
  277. os.rename(tmp_filename, filename)
  278. def write(self):
  279. ''' write to file '''
  280. if not self.filename:
  281. raise YeditException('Please specify a filename.')
  282. if self.backup and self.file_exists():
  283. shutil.copy(self.filename, self.filename + '.orig')
  284. # Try to set format attributes if supported
  285. try:
  286. self.yaml_dict.fa.set_block_style()
  287. except AttributeError:
  288. pass
  289. # Try to use RoundTripDumper if supported.
  290. try:
  291. Yedit._write(self.filename, yaml.dump(self.yaml_dict, Dumper=yaml.RoundTripDumper))
  292. except AttributeError:
  293. Yedit._write(self.filename, yaml.safe_dump(self.yaml_dict, default_flow_style=False))
  294. return (True, self.yaml_dict)
  295. def read(self):
  296. ''' read from file '''
  297. # check if it exists
  298. if self.filename is None or not self.file_exists():
  299. return None
  300. contents = None
  301. with open(self.filename) as yfd:
  302. contents = yfd.read()
  303. return contents
  304. def file_exists(self):
  305. ''' return whether file exists '''
  306. if os.path.exists(self.filename):
  307. return True
  308. return False
  309. def load(self, content_type='yaml'):
  310. ''' return yaml file '''
  311. contents = self.read()
  312. if not contents and not self.content:
  313. return None
  314. if self.content:
  315. if isinstance(self.content, dict):
  316. self.yaml_dict = self.content
  317. return self.yaml_dict
  318. elif isinstance(self.content, str):
  319. contents = self.content
  320. # check if it is yaml
  321. try:
  322. if content_type == 'yaml' and contents:
  323. # Try to set format attributes if supported
  324. try:
  325. self.yaml_dict.fa.set_block_style()
  326. except AttributeError:
  327. pass
  328. # Try to use RoundTripLoader if supported.
  329. try:
  330. self.yaml_dict = yaml.safe_load(contents, yaml.RoundTripLoader)
  331. except AttributeError:
  332. self.yaml_dict = yaml.safe_load(contents)
  333. # Try to set format attributes if supported
  334. try:
  335. self.yaml_dict.fa.set_block_style()
  336. except AttributeError:
  337. pass
  338. elif content_type == 'json' and contents:
  339. self.yaml_dict = json.loads(contents)
  340. except yaml.YAMLError as err:
  341. # Error loading yaml or json
  342. raise YeditException('Problem with loading yaml file. {}'.format(err))
  343. return self.yaml_dict
  344. def get(self, key):
  345. ''' get a specified key'''
  346. try:
  347. entry = Yedit.get_entry(self.yaml_dict, key, self.separator)
  348. except KeyError:
  349. entry = None
  350. return entry
  351. def pop(self, path, key_or_item):
  352. ''' remove a key, value pair from a dict or an item for a list'''
  353. try:
  354. entry = Yedit.get_entry(self.yaml_dict, path, self.separator)
  355. except KeyError:
  356. entry = None
  357. if entry is None:
  358. return (False, self.yaml_dict)
  359. if isinstance(entry, dict):
  360. # AUDIT:maybe-no-member makes sense due to fuzzy types
  361. # pylint: disable=maybe-no-member
  362. if key_or_item in entry:
  363. entry.pop(key_or_item)
  364. return (True, self.yaml_dict)
  365. return (False, self.yaml_dict)
  366. elif isinstance(entry, list):
  367. # AUDIT:maybe-no-member makes sense due to fuzzy types
  368. # pylint: disable=maybe-no-member
  369. ind = None
  370. try:
  371. ind = entry.index(key_or_item)
  372. except ValueError:
  373. return (False, self.yaml_dict)
  374. entry.pop(ind)
  375. return (True, self.yaml_dict)
  376. return (False, self.yaml_dict)
  377. def delete(self, path):
  378. ''' remove path from a dict'''
  379. try:
  380. entry = Yedit.get_entry(self.yaml_dict, path, self.separator)
  381. except KeyError:
  382. entry = None
  383. if entry is None:
  384. return (False, self.yaml_dict)
  385. result = Yedit.remove_entry(self.yaml_dict, path, self.separator)
  386. if not result:
  387. return (False, self.yaml_dict)
  388. return (True, self.yaml_dict)
  389. def exists(self, path, value):
  390. ''' check if value exists at path'''
  391. try:
  392. entry = Yedit.get_entry(self.yaml_dict, path, self.separator)
  393. except KeyError:
  394. entry = None
  395. if isinstance(entry, list):
  396. if value in entry:
  397. return True
  398. return False
  399. elif isinstance(entry, dict):
  400. if isinstance(value, dict):
  401. rval = False
  402. for key, val in value.items():
  403. if entry[key] != val:
  404. rval = False
  405. break
  406. else:
  407. rval = True
  408. return rval
  409. return value in entry
  410. return entry == value
  411. def append(self, path, value):
  412. '''append value to a list'''
  413. try:
  414. entry = Yedit.get_entry(self.yaml_dict, path, self.separator)
  415. except KeyError:
  416. entry = None
  417. if entry is None:
  418. self.put(path, [])
  419. entry = Yedit.get_entry(self.yaml_dict, path, self.separator)
  420. if not isinstance(entry, list):
  421. return (False, self.yaml_dict)
  422. # AUDIT:maybe-no-member makes sense due to loading data from
  423. # a serialized format.
  424. # pylint: disable=maybe-no-member
  425. entry.append(value)
  426. return (True, self.yaml_dict)
  427. # pylint: disable=too-many-arguments
  428. def update(self, path, value, index=None, curr_value=None):
  429. ''' put path, value into a dict '''
  430. try:
  431. entry = Yedit.get_entry(self.yaml_dict, path, self.separator)
  432. except KeyError:
  433. entry = None
  434. if isinstance(entry, dict):
  435. # AUDIT:maybe-no-member makes sense due to fuzzy types
  436. # pylint: disable=maybe-no-member
  437. if not isinstance(value, dict):
  438. raise YeditException('Cannot replace key, value entry in dict with non-dict type. ' +
  439. 'value=[{}] type=[{}]'.format(value, type(value)))
  440. entry.update(value)
  441. return (True, self.yaml_dict)
  442. elif isinstance(entry, list):
  443. # AUDIT:maybe-no-member makes sense due to fuzzy types
  444. # pylint: disable=maybe-no-member
  445. ind = None
  446. if curr_value:
  447. try:
  448. ind = entry.index(curr_value)
  449. except ValueError:
  450. return (False, self.yaml_dict)
  451. elif index is not None:
  452. ind = index
  453. if ind is not None and entry[ind] != value:
  454. entry[ind] = value
  455. return (True, self.yaml_dict)
  456. # see if it exists in the list
  457. try:
  458. ind = entry.index(value)
  459. except ValueError:
  460. # doesn't exist, append it
  461. entry.append(value)
  462. return (True, self.yaml_dict)
  463. # already exists, return
  464. if ind is not None:
  465. return (False, self.yaml_dict)
  466. return (False, self.yaml_dict)
  467. def put(self, path, value):
  468. ''' put path, value into a dict '''
  469. try:
  470. entry = Yedit.get_entry(self.yaml_dict, path, self.separator)
  471. except KeyError:
  472. entry = None
  473. if entry == value:
  474. return (False, self.yaml_dict)
  475. # deepcopy didn't work
  476. # Try to use ruamel.yaml and fallback to pyyaml
  477. try:
  478. tmp_copy = yaml.load(yaml.round_trip_dump(self.yaml_dict,
  479. default_flow_style=False),
  480. yaml.RoundTripLoader)
  481. except AttributeError:
  482. tmp_copy = copy.deepcopy(self.yaml_dict)
  483. # set the format attributes if available
  484. try:
  485. tmp_copy.fa.set_block_style()
  486. except AttributeError:
  487. pass
  488. result = Yedit.add_entry(tmp_copy, path, value, self.separator)
  489. if result is None:
  490. return (False, self.yaml_dict)
  491. # When path equals "" it is a special case.
  492. # "" refers to the root of the document
  493. # Only update the root path (entire document) when its a list or dict
  494. if path == '':
  495. if isinstance(result, list) or isinstance(result, dict):
  496. self.yaml_dict = result
  497. return (True, self.yaml_dict)
  498. return (False, self.yaml_dict)
  499. self.yaml_dict = tmp_copy
  500. return (True, self.yaml_dict)
  501. def create(self, path, value):
  502. ''' create a yaml file '''
  503. if not self.file_exists():
  504. # deepcopy didn't work
  505. # Try to use ruamel.yaml and fallback to pyyaml
  506. try:
  507. tmp_copy = yaml.load(yaml.round_trip_dump(self.yaml_dict,
  508. default_flow_style=False),
  509. yaml.RoundTripLoader)
  510. except AttributeError:
  511. tmp_copy = copy.deepcopy(self.yaml_dict)
  512. # set the format attributes if available
  513. try:
  514. tmp_copy.fa.set_block_style()
  515. except AttributeError:
  516. pass
  517. result = Yedit.add_entry(tmp_copy, path, value, self.separator)
  518. if result is not None:
  519. self.yaml_dict = tmp_copy
  520. return (True, self.yaml_dict)
  521. return (False, self.yaml_dict)
  522. @staticmethod
  523. def get_curr_value(invalue, val_type):
  524. '''return the current value'''
  525. if invalue is None:
  526. return None
  527. curr_value = invalue
  528. if val_type == 'yaml':
  529. curr_value = yaml.load(invalue)
  530. elif val_type == 'json':
  531. curr_value = json.loads(invalue)
  532. return curr_value
  533. @staticmethod
  534. def parse_value(inc_value, vtype=''):
  535. '''determine value type passed'''
  536. true_bools = ['y', 'Y', 'yes', 'Yes', 'YES', 'true', 'True', 'TRUE',
  537. 'on', 'On', 'ON', ]
  538. false_bools = ['n', 'N', 'no', 'No', 'NO', 'false', 'False', 'FALSE',
  539. 'off', 'Off', 'OFF']
  540. # It came in as a string but you didn't specify value_type as string
  541. # we will convert to bool if it matches any of the above cases
  542. if isinstance(inc_value, str) and 'bool' in vtype:
  543. if inc_value not in true_bools and inc_value not in false_bools:
  544. raise YeditException('Not a boolean type. str=[{}] vtype=[{}]'.format(inc_value, vtype))
  545. elif isinstance(inc_value, bool) and 'str' in vtype:
  546. inc_value = str(inc_value)
  547. # There is a special case where '' will turn into None after yaml loading it so skip
  548. if isinstance(inc_value, str) and inc_value == '':
  549. pass
  550. # If vtype is not str then go ahead and attempt to yaml load it.
  551. elif isinstance(inc_value, str) and 'str' not in vtype:
  552. try:
  553. inc_value = yaml.safe_load(inc_value)
  554. except Exception:
  555. raise YeditException('Could not determine type of incoming value. ' +
  556. 'value=[{}] vtype=[{}]'.format(type(inc_value), vtype))
  557. return inc_value
  558. @staticmethod
  559. def process_edits(edits, yamlfile):
  560. '''run through a list of edits and process them one-by-one'''
  561. results = []
  562. for edit in edits:
  563. value = Yedit.parse_value(edit['value'], edit.get('value_type', ''))
  564. if edit.get('action') == 'update':
  565. # pylint: disable=line-too-long
  566. curr_value = Yedit.get_curr_value(
  567. Yedit.parse_value(edit.get('curr_value')),
  568. edit.get('curr_value_format'))
  569. rval = yamlfile.update(edit['key'],
  570. value,
  571. edit.get('index'),
  572. curr_value)
  573. elif edit.get('action') == 'append':
  574. rval = yamlfile.append(edit['key'], value)
  575. else:
  576. rval = yamlfile.put(edit['key'], value)
  577. if rval[0]:
  578. results.append({'key': edit['key'], 'edit': rval[1]})
  579. return {'changed': len(results) > 0, 'results': results}
  580. # pylint: disable=too-many-return-statements,too-many-branches
  581. @staticmethod
  582. def run_ansible(params):
  583. '''perform the idempotent crud operations'''
  584. yamlfile = Yedit(filename=params['src'],
  585. backup=params['backup'],
  586. separator=params['separator'])
  587. state = params['state']
  588. if params['src']:
  589. rval = yamlfile.load()
  590. if yamlfile.yaml_dict is None and state != 'present':
  591. return {'failed': True,
  592. 'msg': 'Error opening file [{}]. Verify that the '.format(params['src']) +
  593. 'file exists, that it is has correct permissions, and is valid yaml.'}
  594. if state == 'list':
  595. if params['content']:
  596. content = Yedit.parse_value(params['content'], params['content_type'])
  597. yamlfile.yaml_dict = content
  598. if params['key']:
  599. rval = yamlfile.get(params['key']) or {}
  600. return {'changed': False, 'result': rval, 'state': state}
  601. elif state == 'absent':
  602. if params['content']:
  603. content = Yedit.parse_value(params['content'], params['content_type'])
  604. yamlfile.yaml_dict = content
  605. if params['update']:
  606. rval = yamlfile.pop(params['key'], params['value'])
  607. else:
  608. rval = yamlfile.delete(params['key'])
  609. if rval[0] and params['src']:
  610. yamlfile.write()
  611. return {'changed': rval[0], 'result': rval[1], 'state': state}
  612. elif state == 'present':
  613. # check if content is different than what is in the file
  614. if params['content']:
  615. content = Yedit.parse_value(params['content'], params['content_type'])
  616. # We had no edits to make and the contents are the same
  617. if yamlfile.yaml_dict == content and \
  618. params['value'] is None:
  619. return {'changed': False, 'result': yamlfile.yaml_dict, 'state': state}
  620. yamlfile.yaml_dict = content
  621. # If we were passed a key, value then
  622. # we enapsulate it in a list and process it
  623. # Key, Value passed to the module : Converted to Edits list #
  624. edits = []
  625. _edit = {}
  626. if params['value'] is not None:
  627. _edit['value'] = params['value']
  628. _edit['value_type'] = params['value_type']
  629. _edit['key'] = params['key']
  630. if params['update']:
  631. _edit['action'] = 'update'
  632. _edit['curr_value'] = params['curr_value']
  633. _edit['curr_value_format'] = params['curr_value_format']
  634. _edit['index'] = params['index']
  635. elif params['append']:
  636. _edit['action'] = 'append'
  637. edits.append(_edit)
  638. elif params['edits'] is not None:
  639. edits = params['edits']
  640. if edits:
  641. results = Yedit.process_edits(edits, yamlfile)
  642. # if there were changes and a src provided to us we need to write
  643. if results['changed'] and params['src']:
  644. yamlfile.write()
  645. return {'changed': results['changed'], 'result': results['results'], 'state': state}
  646. # no edits to make
  647. if params['src']:
  648. # pylint: disable=redefined-variable-type
  649. rval = yamlfile.write()
  650. return {'changed': rval[0],
  651. 'result': rval[1],
  652. 'state': state}
  653. # We were passed content but no src, key or value, or edits. Return contents in memory
  654. return {'changed': False, 'result': yamlfile.yaml_dict, 'state': state}
  655. return {'failed': True, 'msg': 'Unkown state passed'}
  656. # -*- -*- -*- End included fragment: ../../lib_utils/src/class/yedit.py -*- -*- -*-
  657. # -*- -*- -*- Begin included fragment: lib/base.py -*- -*- -*-
  658. # pylint: disable=too-many-lines
  659. # noqa: E301,E302,E303,T001
  660. class OpenShiftCLIError(Exception):
  661. '''Exception class for openshiftcli'''
  662. pass
  663. ADDITIONAL_PATH_LOOKUPS = ['/usr/local/bin', os.path.expanduser('~/bin')]
  664. def locate_oc_binary():
  665. ''' Find and return oc binary file '''
  666. # https://github.com/openshift/openshift-ansible/issues/3410
  667. # oc can be in /usr/local/bin in some cases, but that may not
  668. # be in $PATH due to ansible/sudo
  669. paths = os.environ.get("PATH", os.defpath).split(os.pathsep) + ADDITIONAL_PATH_LOOKUPS
  670. oc_binary = 'oc'
  671. # Use shutil.which if it is available, otherwise fallback to a naive path search
  672. try:
  673. which_result = shutil.which(oc_binary, path=os.pathsep.join(paths))
  674. if which_result is not None:
  675. oc_binary = which_result
  676. except AttributeError:
  677. for path in paths:
  678. if os.path.exists(os.path.join(path, oc_binary)):
  679. oc_binary = os.path.join(path, oc_binary)
  680. break
  681. return oc_binary
  682. # pylint: disable=too-few-public-methods
  683. class OpenShiftCLI(object):
  684. ''' Class to wrap the command line tools '''
  685. def __init__(self,
  686. namespace,
  687. kubeconfig='/etc/origin/master/admin.kubeconfig',
  688. verbose=False,
  689. all_namespaces=False):
  690. ''' Constructor for OpenshiftCLI '''
  691. self.namespace = namespace
  692. self.verbose = verbose
  693. self.kubeconfig = Utils.create_tmpfile_copy(kubeconfig)
  694. self.all_namespaces = all_namespaces
  695. self.oc_binary = locate_oc_binary()
  696. # Pylint allows only 5 arguments to be passed.
  697. # pylint: disable=too-many-arguments
  698. def _replace_content(self, resource, rname, content, force=False, sep='.'):
  699. ''' replace the current object with the content '''
  700. res = self._get(resource, rname)
  701. if not res['results']:
  702. return res
  703. fname = Utils.create_tmpfile(rname + '-')
  704. yed = Yedit(fname, res['results'][0], separator=sep)
  705. changes = []
  706. for key, value in content.items():
  707. changes.append(yed.put(key, value))
  708. if any([change[0] for change in changes]):
  709. yed.write()
  710. atexit.register(Utils.cleanup, [fname])
  711. return self._replace(fname, force)
  712. return {'returncode': 0, 'updated': False}
  713. def _replace(self, fname, force=False):
  714. '''replace the current object with oc replace'''
  715. cmd = ['replace', '-f', fname]
  716. if force:
  717. cmd.append('--force')
  718. return self.openshift_cmd(cmd)
  719. def _create_from_content(self, rname, content):
  720. '''create a temporary file and then call oc create on it'''
  721. fname = Utils.create_tmpfile(rname + '-')
  722. yed = Yedit(fname, content=content)
  723. yed.write()
  724. atexit.register(Utils.cleanup, [fname])
  725. return self._create(fname)
  726. def _create(self, fname):
  727. '''call oc create on a filename'''
  728. return self.openshift_cmd(['create', '-f', fname])
  729. def _delete(self, resource, rname, selector=None):
  730. '''call oc delete on a resource'''
  731. cmd = ['delete', resource, rname]
  732. if selector:
  733. cmd.append('--selector=%s' % selector)
  734. return self.openshift_cmd(cmd)
  735. def _process(self, template_name, create=False, params=None, template_data=None): # noqa: E501
  736. '''process a template
  737. template_name: the name of the template to process
  738. create: whether to send to oc create after processing
  739. params: the parameters for the template
  740. template_data: the incoming template's data; instead of a file
  741. '''
  742. cmd = ['process']
  743. if template_data:
  744. cmd.extend(['-f', '-'])
  745. else:
  746. cmd.append(template_name)
  747. if params:
  748. param_str = ["%s=%s" % (key, value) for key, value in params.items()]
  749. cmd.append('-v')
  750. cmd.extend(param_str)
  751. results = self.openshift_cmd(cmd, output=True, input_data=template_data)
  752. if results['returncode'] != 0 or not create:
  753. return results
  754. fname = Utils.create_tmpfile(template_name + '-')
  755. yed = Yedit(fname, results['results'])
  756. yed.write()
  757. atexit.register(Utils.cleanup, [fname])
  758. return self.openshift_cmd(['create', '-f', fname])
  759. def _get(self, resource, rname=None, selector=None):
  760. '''return a resource by name '''
  761. cmd = ['get', resource]
  762. if selector:
  763. cmd.append('--selector=%s' % selector)
  764. elif rname:
  765. cmd.append(rname)
  766. cmd.extend(['-o', 'json'])
  767. rval = self.openshift_cmd(cmd, output=True)
  768. # Ensure results are retuned in an array
  769. if 'items' in rval:
  770. rval['results'] = rval['items']
  771. elif not isinstance(rval['results'], list):
  772. rval['results'] = [rval['results']]
  773. return rval
  774. def _schedulable(self, node=None, selector=None, schedulable=True):
  775. ''' perform oadm manage-node scheduable '''
  776. cmd = ['manage-node']
  777. if node:
  778. cmd.extend(node)
  779. else:
  780. cmd.append('--selector=%s' % selector)
  781. cmd.append('--schedulable=%s' % schedulable)
  782. return self.openshift_cmd(cmd, oadm=True, output=True, output_type='raw') # noqa: E501
  783. def _list_pods(self, node=None, selector=None, pod_selector=None):
  784. ''' perform oadm list pods
  785. node: the node in which to list pods
  786. selector: the label selector filter if provided
  787. pod_selector: the pod selector filter if provided
  788. '''
  789. cmd = ['manage-node']
  790. if node:
  791. cmd.extend(node)
  792. else:
  793. cmd.append('--selector=%s' % selector)
  794. if pod_selector:
  795. cmd.append('--pod-selector=%s' % pod_selector)
  796. cmd.extend(['--list-pods', '-o', 'json'])
  797. return self.openshift_cmd(cmd, oadm=True, output=True, output_type='raw')
  798. # pylint: disable=too-many-arguments
  799. def _evacuate(self, node=None, selector=None, pod_selector=None, dry_run=False, grace_period=None, force=False):
  800. ''' perform oadm manage-node evacuate '''
  801. cmd = ['manage-node']
  802. if node:
  803. cmd.extend(node)
  804. else:
  805. cmd.append('--selector=%s' % selector)
  806. if dry_run:
  807. cmd.append('--dry-run')
  808. if pod_selector:
  809. cmd.append('--pod-selector=%s' % pod_selector)
  810. if grace_period:
  811. cmd.append('--grace-period=%s' % int(grace_period))
  812. if force:
  813. cmd.append('--force')
  814. cmd.append('--evacuate')
  815. return self.openshift_cmd(cmd, oadm=True, output=True, output_type='raw')
  816. def _version(self):
  817. ''' return the openshift version'''
  818. return self.openshift_cmd(['version'], output=True, output_type='raw')
  819. def _import_image(self, url=None, name=None, tag=None):
  820. ''' perform image import '''
  821. cmd = ['import-image']
  822. image = '{0}'.format(name)
  823. if tag:
  824. image += ':{0}'.format(tag)
  825. cmd.append(image)
  826. if url:
  827. cmd.append('--from={0}/{1}'.format(url, image))
  828. cmd.append('-n{0}'.format(self.namespace))
  829. cmd.append('--confirm')
  830. return self.openshift_cmd(cmd)
  831. def _run(self, cmds, input_data):
  832. ''' Actually executes the command. This makes mocking easier. '''
  833. curr_env = os.environ.copy()
  834. curr_env.update({'KUBECONFIG': self.kubeconfig})
  835. proc = subprocess.Popen(cmds,
  836. stdin=subprocess.PIPE,
  837. stdout=subprocess.PIPE,
  838. stderr=subprocess.PIPE,
  839. env=curr_env)
  840. stdout, stderr = proc.communicate(input_data)
  841. return proc.returncode, stdout.decode(), stderr.decode()
  842. # pylint: disable=too-many-arguments,too-many-branches
  843. def openshift_cmd(self, cmd, oadm=False, output=False, output_type='json', input_data=None):
  844. '''Base command for oc '''
  845. cmds = [self.oc_binary]
  846. if oadm:
  847. cmds.append('adm')
  848. cmds.extend(cmd)
  849. if self.all_namespaces:
  850. cmds.extend(['--all-namespaces'])
  851. elif self.namespace is not None and self.namespace.lower() not in ['none', 'emtpy']: # E501
  852. cmds.extend(['-n', self.namespace])
  853. rval = {}
  854. results = ''
  855. err = None
  856. if self.verbose:
  857. print(' '.join(cmds))
  858. try:
  859. returncode, stdout, stderr = self._run(cmds, input_data)
  860. except OSError as ex:
  861. returncode, stdout, stderr = 1, '', 'Failed to execute {}: {}'.format(subprocess.list2cmdline(cmds), ex)
  862. rval = {"returncode": returncode,
  863. "results": results,
  864. "cmd": ' '.join(cmds)}
  865. if returncode == 0:
  866. if output:
  867. if output_type == 'json':
  868. try:
  869. rval['results'] = json.loads(stdout)
  870. except ValueError as verr:
  871. if "No JSON object could be decoded" in verr.args:
  872. err = verr.args
  873. elif output_type == 'raw':
  874. rval['results'] = stdout
  875. if self.verbose:
  876. print("STDOUT: {0}".format(stdout))
  877. print("STDERR: {0}".format(stderr))
  878. if err:
  879. rval.update({"err": err,
  880. "stderr": stderr,
  881. "stdout": stdout,
  882. "cmd": cmds})
  883. else:
  884. rval.update({"stderr": stderr,
  885. "stdout": stdout,
  886. "results": {}})
  887. return rval
  888. class Utils(object):
  889. ''' utilities for openshiftcli modules '''
  890. @staticmethod
  891. def _write(filename, contents):
  892. ''' Actually write the file contents to disk. This helps with mocking. '''
  893. with open(filename, 'w') as sfd:
  894. sfd.write(contents)
  895. @staticmethod
  896. def create_tmp_file_from_contents(rname, data, ftype='yaml'):
  897. ''' create a file in tmp with name and contents'''
  898. tmp = Utils.create_tmpfile(prefix=rname)
  899. if ftype == 'yaml':
  900. # AUDIT:no-member makes sense here due to ruamel.YAML/PyYAML usage
  901. # pylint: disable=no-member
  902. if hasattr(yaml, 'RoundTripDumper'):
  903. Utils._write(tmp, yaml.dump(data, Dumper=yaml.RoundTripDumper))
  904. else:
  905. Utils._write(tmp, yaml.safe_dump(data, default_flow_style=False))
  906. elif ftype == 'json':
  907. Utils._write(tmp, json.dumps(data))
  908. else:
  909. Utils._write(tmp, data)
  910. # Register cleanup when module is done
  911. atexit.register(Utils.cleanup, [tmp])
  912. return tmp
  913. @staticmethod
  914. def create_tmpfile_copy(inc_file):
  915. '''create a temporary copy of a file'''
  916. tmpfile = Utils.create_tmpfile('lib_openshift-')
  917. Utils._write(tmpfile, open(inc_file).read())
  918. # Cleanup the tmpfile
  919. atexit.register(Utils.cleanup, [tmpfile])
  920. return tmpfile
  921. @staticmethod
  922. def create_tmpfile(prefix='tmp'):
  923. ''' Generates and returns a temporary file name '''
  924. with tempfile.NamedTemporaryFile(prefix=prefix, delete=False) as tmp:
  925. return tmp.name
  926. @staticmethod
  927. def create_tmp_files_from_contents(content, content_type=None):
  928. '''Turn an array of dict: filename, content into a files array'''
  929. if not isinstance(content, list):
  930. content = [content]
  931. files = []
  932. for item in content:
  933. path = Utils.create_tmp_file_from_contents(item['path'] + '-',
  934. item['data'],
  935. ftype=content_type)
  936. files.append({'name': os.path.basename(item['path']),
  937. 'path': path})
  938. return files
  939. @staticmethod
  940. def cleanup(files):
  941. '''Clean up on exit '''
  942. for sfile in files:
  943. if os.path.exists(sfile):
  944. if os.path.isdir(sfile):
  945. shutil.rmtree(sfile)
  946. elif os.path.isfile(sfile):
  947. os.remove(sfile)
  948. @staticmethod
  949. def exists(results, _name):
  950. ''' Check to see if the results include the name '''
  951. if not results:
  952. return False
  953. if Utils.find_result(results, _name):
  954. return True
  955. return False
  956. @staticmethod
  957. def find_result(results, _name):
  958. ''' Find the specified result by name'''
  959. rval = None
  960. for result in results:
  961. if 'metadata' in result and result['metadata']['name'] == _name:
  962. rval = result
  963. break
  964. return rval
  965. @staticmethod
  966. def get_resource_file(sfile, sfile_type='yaml'):
  967. ''' return the service file '''
  968. contents = None
  969. with open(sfile) as sfd:
  970. contents = sfd.read()
  971. if sfile_type == 'yaml':
  972. # AUDIT:no-member makes sense here due to ruamel.YAML/PyYAML usage
  973. # pylint: disable=no-member
  974. if hasattr(yaml, 'RoundTripLoader'):
  975. contents = yaml.load(contents, yaml.RoundTripLoader)
  976. else:
  977. contents = yaml.safe_load(contents)
  978. elif sfile_type == 'json':
  979. contents = json.loads(contents)
  980. return contents
  981. @staticmethod
  982. def filter_versions(stdout):
  983. ''' filter the oc version output '''
  984. version_dict = {}
  985. version_search = ['oc', 'openshift', 'kubernetes']
  986. for line in stdout.strip().split('\n'):
  987. for term in version_search:
  988. if not line:
  989. continue
  990. if line.startswith(term):
  991. version_dict[term] = line.split()[-1]
  992. # horrible hack to get openshift version in Openshift 3.2
  993. # By default "oc version in 3.2 does not return an "openshift" version
  994. if "openshift" not in version_dict:
  995. version_dict["openshift"] = version_dict["oc"]
  996. return version_dict
  997. @staticmethod
  998. def add_custom_versions(versions):
  999. ''' create custom versions strings '''
  1000. versions_dict = {}
  1001. for tech, version in versions.items():
  1002. # clean up "-" from version
  1003. if "-" in version:
  1004. version = version.split("-")[0]
  1005. if version.startswith('v'):
  1006. versions_dict[tech + '_numeric'] = version[1:].split('+')[0]
  1007. # "v3.3.0.33" is what we have, we want "3.3"
  1008. versions_dict[tech + '_short'] = version[1:4]
  1009. return versions_dict
  1010. @staticmethod
  1011. def openshift_installed():
  1012. ''' check if openshift is installed '''
  1013. import yum
  1014. yum_base = yum.YumBase()
  1015. if yum_base.rpmdb.searchNevra(name='atomic-openshift'):
  1016. return True
  1017. return False
  1018. # Disabling too-many-branches. This is a yaml dictionary comparison function
  1019. # pylint: disable=too-many-branches,too-many-return-statements,too-many-statements
  1020. @staticmethod
  1021. def check_def_equal(user_def, result_def, skip_keys=None, debug=False):
  1022. ''' Given a user defined definition, compare it with the results given back by our query. '''
  1023. # Currently these values are autogenerated and we do not need to check them
  1024. skip = ['metadata', 'status']
  1025. if skip_keys:
  1026. skip.extend(skip_keys)
  1027. for key, value in result_def.items():
  1028. if key in skip:
  1029. continue
  1030. # Both are lists
  1031. if isinstance(value, list):
  1032. if key not in user_def:
  1033. if debug:
  1034. print('User data does not have key [%s]' % key)
  1035. print('User data: %s' % user_def)
  1036. return False
  1037. if not isinstance(user_def[key], list):
  1038. if debug:
  1039. print('user_def[key] is not a list key=[%s] user_def[key]=%s' % (key, user_def[key]))
  1040. return False
  1041. if len(user_def[key]) != len(value):
  1042. if debug:
  1043. print("List lengths are not equal.")
  1044. print("key=[%s]: user_def[%s] != value[%s]" % (key, len(user_def[key]), len(value)))
  1045. print("user_def: %s" % user_def[key])
  1046. print("value: %s" % value)
  1047. return False
  1048. for values in zip(user_def[key], value):
  1049. if isinstance(values[0], dict) and isinstance(values[1], dict):
  1050. if debug:
  1051. print('sending list - list')
  1052. print(type(values[0]))
  1053. print(type(values[1]))
  1054. result = Utils.check_def_equal(values[0], values[1], skip_keys=skip_keys, debug=debug)
  1055. if not result:
  1056. print('list compare returned false')
  1057. return False
  1058. elif value != user_def[key]:
  1059. if debug:
  1060. print('value should be identical')
  1061. print(user_def[key])
  1062. print(value)
  1063. return False
  1064. # recurse on a dictionary
  1065. elif isinstance(value, dict):
  1066. if key not in user_def:
  1067. if debug:
  1068. print("user_def does not have key [%s]" % key)
  1069. return False
  1070. if not isinstance(user_def[key], dict):
  1071. if debug:
  1072. print("dict returned false: not instance of dict")
  1073. return False
  1074. # before passing ensure keys match
  1075. api_values = set(value.keys()) - set(skip)
  1076. user_values = set(user_def[key].keys()) - set(skip)
  1077. if api_values != user_values:
  1078. if debug:
  1079. print("keys are not equal in dict")
  1080. print(user_values)
  1081. print(api_values)
  1082. return False
  1083. result = Utils.check_def_equal(user_def[key], value, skip_keys=skip_keys, debug=debug)
  1084. if not result:
  1085. if debug:
  1086. print("dict returned false")
  1087. print(result)
  1088. return False
  1089. # Verify each key, value pair is the same
  1090. else:
  1091. if key not in user_def or value != user_def[key]:
  1092. if debug:
  1093. print("value not equal; user_def does not have key")
  1094. print(key)
  1095. print(value)
  1096. if key in user_def:
  1097. print(user_def[key])
  1098. return False
  1099. if debug:
  1100. print('returning true')
  1101. return True
  1102. class OpenShiftCLIConfig(object):
  1103. '''Generic Config'''
  1104. def __init__(self, rname, namespace, kubeconfig, options):
  1105. self.kubeconfig = kubeconfig
  1106. self.name = rname
  1107. self.namespace = namespace
  1108. self._options = options
  1109. @property
  1110. def config_options(self):
  1111. ''' return config options '''
  1112. return self._options
  1113. def to_option_list(self):
  1114. '''return all options as a string'''
  1115. return self.stringify()
  1116. def stringify(self):
  1117. ''' return the options hash as cli params in a string '''
  1118. rval = []
  1119. for key in sorted(self.config_options.keys()):
  1120. data = self.config_options[key]
  1121. if data['include'] \
  1122. and (data['value'] or isinstance(data['value'], int)):
  1123. rval.append('--{}={}'.format(key.replace('_', '-'), data['value']))
  1124. return rval
  1125. # -*- -*- -*- End included fragment: lib/base.py -*- -*- -*-
  1126. # -*- -*- -*- Begin included fragment: class/oc_image.py -*- -*- -*-
  1127. # pylint: disable=too-many-arguments
  1128. class OCImage(OpenShiftCLI):
  1129. ''' Class to import and create an imagestream object'''
  1130. def __init__(self,
  1131. namespace,
  1132. registry_url,
  1133. image_name,
  1134. image_tag,
  1135. kubeconfig='/etc/origin/master/admin.kubeconfig',
  1136. verbose=False):
  1137. ''' Constructor for OCImage'''
  1138. super(OCImage, self).__init__(namespace, kubeconfig)
  1139. self.registry_url = registry_url
  1140. self.image_name = image_name
  1141. self.image_tag = image_tag
  1142. self.verbose = verbose
  1143. def get(self):
  1144. '''return a image by name '''
  1145. results = self._get('imagestream', self.image_name)
  1146. results['exists'] = False
  1147. if results['returncode'] == 0 and results['results'][0]:
  1148. results['exists'] = True
  1149. if results['returncode'] != 0 and '"{}" not found'.format(self.image_name) in results['stderr']:
  1150. results['returncode'] = 0
  1151. return results
  1152. def create(self, url=None, name=None, tag=None):
  1153. '''Create an image '''
  1154. return self._import_image(url, name, tag)
  1155. # pylint: disable=too-many-return-statements
  1156. @staticmethod
  1157. def run_ansible(params, check_mode):
  1158. ''' run the ansible idempotent code '''
  1159. ocimage = OCImage(params['namespace'],
  1160. params['registry_url'],
  1161. params['image_name'],
  1162. params['image_tag'],
  1163. kubeconfig=params['kubeconfig'],
  1164. verbose=params['debug'])
  1165. state = params['state']
  1166. api_rval = ocimage.get()
  1167. #####
  1168. # Get
  1169. #####
  1170. if state == 'list':
  1171. if api_rval['returncode'] != 0:
  1172. return {"failed": True, "msg": api_rval}
  1173. return {"changed": False, "results": api_rval, "state": "list"}
  1174. ########
  1175. # Create
  1176. ########
  1177. if state == 'present':
  1178. if not Utils.exists(api_rval['results'], params['image_name']):
  1179. if check_mode:
  1180. return {"changed": False, "msg": 'CHECK_MODE: Would have performed a create'}
  1181. api_rval = ocimage.create(params['registry_url'],
  1182. params['image_name'],
  1183. params['image_tag'])
  1184. if api_rval['returncode'] != 0:
  1185. return {"failed": True, "msg": api_rval}
  1186. # return the newly created object
  1187. api_rval = ocimage.get()
  1188. if api_rval['returncode'] != 0:
  1189. return {"failed": True, "msg": api_rval}
  1190. return {"changed": True, "results": api_rval, "state": "present"}
  1191. # image exists, no change
  1192. return {"changed": False, "results": api_rval, "state": "present"}
  1193. return {"failed": True, "changed": False, "msg": "Unknown state passed. {0}".format(state)}
  1194. # -*- -*- -*- End included fragment: class/oc_image.py -*- -*- -*-
  1195. # -*- -*- -*- Begin included fragment: ansible/oc_image.py -*- -*- -*-
  1196. def main():
  1197. '''
  1198. ansible oc module for image import
  1199. '''
  1200. module = AnsibleModule(
  1201. argument_spec=dict(
  1202. kubeconfig=dict(default='/etc/origin/master/admin.kubeconfig', type='str'),
  1203. state=dict(default='present', type='str',
  1204. choices=['present', 'list']),
  1205. debug=dict(default=False, type='bool'),
  1206. namespace=dict(default='default', type='str'),
  1207. registry_url=dict(default=None, type='str'),
  1208. image_name=dict(default=None, required=True, type='str'),
  1209. image_tag=dict(default=None, type='str'),
  1210. force=dict(default=False, type='bool'),
  1211. ),
  1212. supports_check_mode=True,
  1213. )
  1214. rval = OCImage.run_ansible(module.params, module.check_mode)
  1215. if 'failed' in rval:
  1216. module.fail_json(**rval)
  1217. module.exit_json(**rval)
  1218. if __name__ == '__main__':
  1219. main()
  1220. # -*- -*- -*- End included fragment: ansible/oc_image.py -*- -*- -*-