root / kamaki / cli / config.py @ 6144f3d4
History | View | Annotate | Download (13.5 kB)
1 |
# Copyright 2011-2012 GRNET S.A. All rights reserved.
|
---|---|
2 |
#
|
3 |
# Redistribution and use in source and binary forms, with or
|
4 |
# without modification, are permitted provided that the following
|
5 |
# conditions are met:
|
6 |
#
|
7 |
# 1. Redistributions of source code must retain the above
|
8 |
# copyright notice, this list of conditions and the following
|
9 |
# disclaimer.
|
10 |
#
|
11 |
# 2. Redistributions in binary form must reproduce the above
|
12 |
# copyright notice, this list of conditions and the following
|
13 |
# disclaimer in the documentation and/or other materials
|
14 |
# provided with the distribution.
|
15 |
#
|
16 |
# THIS SOFTWARE IS PROVIDED BY GRNET S.A. ``AS IS'' AND ANY EXPRESS
|
17 |
# OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
|
18 |
# WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
|
19 |
# PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL GRNET S.A OR
|
20 |
# CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
|
21 |
# SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
|
22 |
# LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF
|
23 |
# USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED
|
24 |
# AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
|
25 |
# LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN
|
26 |
# ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
|
27 |
# POSSIBILITY OF SUCH DAMAGE.
|
28 |
#
|
29 |
# The views and conclusions contained in the software and
|
30 |
# documentation are those of the authors and should not be
|
31 |
# interpreted as representing official policies, either expressed
|
32 |
# or implied, of GRNET S.A.
|
33 |
|
34 |
import os |
35 |
from logging import getLogger |
36 |
|
37 |
from collections import defaultdict |
38 |
from ConfigParser import RawConfigParser, NoOptionError, NoSectionError |
39 |
from re import match |
40 |
|
41 |
from kamaki.cli.errors import CLISyntaxError |
42 |
from kamaki import __version__ |
43 |
|
44 |
try:
|
45 |
from collections import OrderedDict |
46 |
except ImportError: |
47 |
from kamaki.clients.utils.ordereddict import OrderedDict |
48 |
|
49 |
|
50 |
log = getLogger(__name__) |
51 |
|
52 |
# Path to the file that stores the configuration
|
53 |
CONFIG_PATH = os.path.expanduser('~/.kamakirc')
|
54 |
HISTORY_PATH = os.path.expanduser('~/.kamaki.history')
|
55 |
CLOUD_PREFIX = 'cloud'
|
56 |
|
57 |
# Name of a shell variable to bypass the CONFIG_PATH value
|
58 |
CONFIG_ENV = 'KAMAKI_CONFIG'
|
59 |
|
60 |
version = ''
|
61 |
for c in '%s' % __version__: |
62 |
if c not in '0.123456789': |
63 |
break
|
64 |
version += c |
65 |
HEADER = '# Kamaki configuration file v%s\n' % version
|
66 |
|
67 |
DEFAULTS = { |
68 |
'global': {
|
69 |
'default_cloud': '', |
70 |
'colors': 'off', |
71 |
'log_file': os.path.expanduser('~/.kamaki.log'), |
72 |
'log_token': 'off', |
73 |
'log_data': 'off', |
74 |
'max_threads': 7, |
75 |
'history_file': HISTORY_PATH,
|
76 |
'user_cli': 'astakos', |
77 |
'file_cli': 'pithos', |
78 |
'server_cli': 'cyclades', |
79 |
'flavor_cli': 'cyclades', |
80 |
'network_cli': 'cyclades', |
81 |
'image_cli': 'image', |
82 |
'config_cli': 'config', |
83 |
'history_cli': 'history' |
84 |
# Optional command specs:
|
85 |
# 'livetest_cli': 'livetest',
|
86 |
# 'astakos_cli': 'snf-astakos'
|
87 |
}, |
88 |
CLOUD_PREFIX: |
89 |
{ |
90 |
#'default': {
|
91 |
# 'url': '',
|
92 |
# 'token': ''
|
93 |
# 'pithos_type': 'object-store',
|
94 |
# 'pithos_version': 'v1',
|
95 |
# 'cyclades_type': 'compute',
|
96 |
# 'cyclades_version': 'v2.0',
|
97 |
# 'plankton_type': 'image',
|
98 |
# 'plankton_version': '',
|
99 |
# 'astakos_type': 'identity',
|
100 |
# 'astakos_version': 'v2.0'
|
101 |
#}
|
102 |
} |
103 |
} |
104 |
|
105 |
|
106 |
try:
|
107 |
import astakosclient |
108 |
DEFAULTS['global'].update(dict(astakos_cli='snf-astakos')) |
109 |
except ImportError: |
110 |
pass
|
111 |
|
112 |
|
113 |
class Config(RawConfigParser): |
114 |
def __init__(self, path=None, with_defaults=True): |
115 |
RawConfigParser.__init__(self, dict_type=OrderedDict)
|
116 |
self.path = path or os.environ.get(CONFIG_ENV, CONFIG_PATH) |
117 |
self._overrides = defaultdict(dict) |
118 |
if with_defaults:
|
119 |
self._load_defaults()
|
120 |
self.read(self.path) |
121 |
|
122 |
for section in self.sections(): |
123 |
r = self._cloud_name(section)
|
124 |
if r:
|
125 |
for k, v in self.items(section): |
126 |
self.set_cloud(r, k, v)
|
127 |
self.remove_section(section)
|
128 |
|
129 |
@staticmethod
|
130 |
def _cloud_name(full_section_name): |
131 |
matcher = match(CLOUD_PREFIX + ' "(\w+)"', full_section_name)
|
132 |
return matcher.groups()[0] if matcher else None |
133 |
|
134 |
def rescue_old_file(self): |
135 |
lost_terms = [] |
136 |
global_terms = DEFAULTS['global'].keys()
|
137 |
translations = dict(
|
138 |
config=dict(serv='', cmd='config'), |
139 |
history=dict(serv='', cmd='history'), |
140 |
pithos=dict(serv='pithos', cmd='file'), |
141 |
file=dict(serv='pithos', cmd='file'), |
142 |
store=dict(serv='pithos', cmd='file'), |
143 |
storage=dict(serv='pithos', cmd='file'), |
144 |
image=dict(serv='plankton', cmd='image'), |
145 |
plankton=dict(serv='plankton', cmd='image'), |
146 |
compute=dict(serv='compute', cmd=''), |
147 |
cyclades=dict(serv='compute', cmd='server'), |
148 |
server=dict(serv='compute', cmd='server'), |
149 |
flavor=dict(serv='compute', cmd='flavor'), |
150 |
network=dict(serv='compute', cmd='network'), |
151 |
astakos=dict(serv='astakos', cmd='user'), |
152 |
user=dict(serv='astakos', cmd='user'), |
153 |
) |
154 |
|
155 |
self.set('global', 'default_' + CLOUD_PREFIX, 'default') |
156 |
for s in self.sections(): |
157 |
if s in ('global'): |
158 |
# global.url, global.token -->
|
159 |
# cloud.default.url, cloud.default.token
|
160 |
for term in set(self.keys(s)).difference(global_terms): |
161 |
if term not in ('url', 'token'): |
162 |
lost_terms.append('%s.%s = %s' % (
|
163 |
s, term, self.get(s, term)))
|
164 |
self.remove_option(s, term)
|
165 |
continue
|
166 |
gval = self.get(s, term)
|
167 |
try:
|
168 |
cval = self.get_cloud('default', term) |
169 |
except KeyError: |
170 |
cval = ''
|
171 |
if gval and cval and ( |
172 |
gval.lower().strip('/') != cval.lower().strip('/')): |
173 |
raise CLISyntaxError(
|
174 |
'Conflicting values for default %s' % term,
|
175 |
importance=2, details=[
|
176 |
' global.%s: %s' % (term, gval),
|
177 |
' %s.default.%s: %s' % (
|
178 |
CLOUD_PREFIX, term, cval), |
179 |
'Please remove one of them manually:',
|
180 |
' /config delete global.%s' % term,
|
181 |
' or'
|
182 |
' /config delete %s.default.%s' % (
|
183 |
CLOUD_PREFIX, term), |
184 |
'and try again'])
|
185 |
elif gval:
|
186 |
print('... rescue %s.%s => %s.default.%s' % (
|
187 |
s, term, CLOUD_PREFIX, term)) |
188 |
self.set_cloud('default', term, gval) |
189 |
self.remove_option(s, term)
|
190 |
# translation for <service> or <command> settings
|
191 |
# <service> or <command group> settings --> translation --> global
|
192 |
elif s in translations: |
193 |
|
194 |
if s in ('history',): |
195 |
k = 'file'
|
196 |
v = self.get(s, k)
|
197 |
if v:
|
198 |
print('... rescue %s.%s => global.%s_%s' % (
|
199 |
s, k, s, k)) |
200 |
self.set('global', '%s_%s' % (s, k), v) |
201 |
self.remove_option(s, k)
|
202 |
|
203 |
trn = translations[s] |
204 |
for k, v in self.items(s, False): |
205 |
if v and k in ('cli',): |
206 |
print('... rescue %s.%s => global.%s_cli' % (
|
207 |
s, k, trn['cmd']))
|
208 |
self.set('global', '%s_cli' % trn['cmd'], v) |
209 |
elif k in ('container',) and trn['serv'] in ('pithos',): |
210 |
print('... rescue %s.%s => %s.default.pithos_%s' % (
|
211 |
s, k, CLOUD_PREFIX, k)) |
212 |
self.set_cloud('default', 'pithos_%s' % k, v) |
213 |
else:
|
214 |
lost_terms.append('%s.%s = %s' % (s, k, v))
|
215 |
self.remove_section(s)
|
216 |
# self.pretty_print()
|
217 |
return lost_terms
|
218 |
|
219 |
def pretty_print(self): |
220 |
for s in self.sections(): |
221 |
print s
|
222 |
for k, v in self.items(s): |
223 |
if isinstance(v, dict): |
224 |
print '\t', k, '=> {' |
225 |
for ki, vi in v.items(): |
226 |
print '\t\t', ki, '=>', vi |
227 |
print('\t}')
|
228 |
else:
|
229 |
print '\t', k, '=>', v |
230 |
|
231 |
def guess_version(self): |
232 |
"""
|
233 |
:returns: (float) version of the config file or 0.0 if unrecognized
|
234 |
"""
|
235 |
checker = Config(self.path, with_defaults=False) |
236 |
sections = checker.sections() |
237 |
log.warning('Config file heuristic 1: old global section ?')
|
238 |
if 'global' in sections: |
239 |
if checker.get('global', 'url') or checker.get('global', 'token'): |
240 |
log.warning('..... config file has an old global section')
|
241 |
return 0.8 |
242 |
log.warning('........ nope')
|
243 |
log.warning('Config file heuristic 2: Any cloud sections ?')
|
244 |
if CLOUD_PREFIX in sections: |
245 |
for r in self.keys(CLOUD_PREFIX): |
246 |
log.warning('... found cloud "%s"' % r)
|
247 |
return 0.9 |
248 |
log.warning('........ nope')
|
249 |
log.warning('All heuristics failed, cannot decide')
|
250 |
return 0.9 |
251 |
|
252 |
def get_cloud(self, cloud, option): |
253 |
"""
|
254 |
:param cloud: (str) cloud alias
|
255 |
|
256 |
:param option: (str) option in cloud section
|
257 |
|
258 |
:returns: (str) the value assigned on this option
|
259 |
|
260 |
:raises KeyError: if cloud or cloud's option does not exist
|
261 |
"""
|
262 |
r = self.get(CLOUD_PREFIX, cloud)
|
263 |
if not r: |
264 |
raise KeyError('Cloud "%s" does not exist' % cloud) |
265 |
return r[option]
|
266 |
|
267 |
def get_global(self, option): |
268 |
return self.get('global', option) |
269 |
|
270 |
def set_cloud(self, cloud, option, value): |
271 |
try:
|
272 |
d = self.get(CLOUD_PREFIX, cloud) or dict() |
273 |
except KeyError: |
274 |
d = dict()
|
275 |
d[option] = value |
276 |
self.set(CLOUD_PREFIX, cloud, d)
|
277 |
|
278 |
def set_global(self, option, value): |
279 |
self.set('global', option, value) |
280 |
|
281 |
def _load_defaults(self): |
282 |
for section, options in DEFAULTS.items(): |
283 |
for option, val in options.items(): |
284 |
self.set(section, option, val)
|
285 |
|
286 |
def _get_dict(self, section, include_defaults=True): |
287 |
try:
|
288 |
d = dict(DEFAULTS[section]) if include_defaults else {} |
289 |
except KeyError: |
290 |
d = {} |
291 |
try:
|
292 |
d.update(RawConfigParser.items(self, section))
|
293 |
except NoSectionError:
|
294 |
pass
|
295 |
return d
|
296 |
|
297 |
def reload(self): |
298 |
self = self.__init__(self.path) |
299 |
|
300 |
def get(self, section, option): |
301 |
"""
|
302 |
:param section: (str) HINT: for clouds, use cloud.<section>
|
303 |
|
304 |
:param option: (str)
|
305 |
|
306 |
:returns: (str) the value stored at section: {option: value}
|
307 |
"""
|
308 |
value = self._overrides.get(section, {}).get(option)
|
309 |
if value is not None: |
310 |
return value
|
311 |
prefix = CLOUD_PREFIX + '.'
|
312 |
if section.startswith(prefix): |
313 |
return self.get_cloud(section[len(prefix):], option) |
314 |
try:
|
315 |
return RawConfigParser.get(self, section, option) |
316 |
except (NoSectionError, NoOptionError):
|
317 |
return DEFAULTS.get(section, {}).get(option)
|
318 |
|
319 |
def set(self, section, option, value): |
320 |
"""
|
321 |
:param section: (str) HINT: for remotes use cloud.<section>
|
322 |
|
323 |
:param option: (str)
|
324 |
|
325 |
:param value: str
|
326 |
"""
|
327 |
prefix = CLOUD_PREFIX + '.'
|
328 |
if section.startswith(prefix): |
329 |
return self.set_cloud(section[len(prefix)], option, value) |
330 |
if section not in RawConfigParser.sections(self): |
331 |
self.add_section(section)
|
332 |
RawConfigParser.set(self, section, option, value)
|
333 |
|
334 |
def remove_option(self, section, option, also_remove_default=False): |
335 |
try:
|
336 |
if also_remove_default:
|
337 |
DEFAULTS[section].pop(option) |
338 |
RawConfigParser.remove_option(self, section, option)
|
339 |
except NoSectionError:
|
340 |
pass
|
341 |
|
342 |
def remote_from_cloud(self, cloud, option): |
343 |
d = self.get(CLOUD_PREFIX, cloud)
|
344 |
if isinstance(d, dict): |
345 |
d.pop(option) |
346 |
|
347 |
def keys(self, section, include_defaults=True): |
348 |
d = self._get_dict(section, include_defaults)
|
349 |
return d.keys()
|
350 |
|
351 |
def items(self, section, include_defaults=True): |
352 |
d = self._get_dict(section, include_defaults)
|
353 |
return d.items()
|
354 |
|
355 |
def override(self, section, option, value): |
356 |
self._overrides[section][option] = value
|
357 |
|
358 |
def write(self): |
359 |
cld_bu = dict(self._get_dict(CLOUD_PREFIX)) |
360 |
try:
|
361 |
for r, d in self.items(CLOUD_PREFIX): |
362 |
for k, v in d.items(): |
363 |
self.set(CLOUD_PREFIX + ' "%s"' % r, k, v) |
364 |
self.remove_section(CLOUD_PREFIX)
|
365 |
|
366 |
with open(self.path, 'w') as f: |
367 |
os.chmod(self.path, 0600) |
368 |
f.write(HEADER.lstrip()) |
369 |
f.flush() |
370 |
RawConfigParser.write(self, f)
|
371 |
finally:
|
372 |
if CLOUD_PREFIX not in self.sections(): |
373 |
self.add_section(CLOUD_PREFIX)
|
374 |
self._get_dict(CLOUD_PREFIX).update(cld_bu)
|