Statistics
| Branch: | Tag: | Revision:

root / kamaki / cli / commands / __init__.py @ 47f37f7c

History | View | Annotate | Download (6.4 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.command
33

    
34
from kamaki.cli.logger import get_logger
35
from kamaki.cli.utils import print_json, print_items
36
from kamaki.cli.argument import FlagArgument
37

    
38
log = get_logger(__name__)
39

    
40

    
41
def DontRaiseKeyError(foo):
42
    def wrap(*args, **kwargs):
43
        try:
44
            return foo(*args, **kwargs)
45
        except KeyError:
46
            return None
47
    return wrap
48

    
49

    
50
def addLogSettings(foo):
51
    def wrap(self, *args, **kwargs):
52
        try:
53
            return foo(self, *args, **kwargs)
54
        finally:
55
            self._set_log_params()
56
            self._update_max_threads
57
    return wrap
58

    
59

    
60
class _command_init(object):
61

    
62
    def __init__(self, arguments={}, auth_base=None, cloud=None):
63
        if hasattr(self, 'arguments'):
64
            arguments.update(self.arguments)
65
        if isinstance(self, _optional_output_cmd):
66
            arguments.update(self.oo_arguments)
67
        if isinstance(self, _optional_json):
68
            arguments.update(self.oj_arguments)
69
        self.arguments = dict(arguments)
70
        try:
71
            self.config = self['config']
72
        except KeyError:
73
            pass
74
        self.auth_base = auth_base or getattr(self, 'auth_base', None)
75
        self.cloud = cloud or getattr(self, 'cloud', None)
76

    
77
    @DontRaiseKeyError
78
    def _custom_url(self, service):
79
        return self.config.get_cloud(self.cloud, '%s_url' % service)
80

    
81
    @DontRaiseKeyError
82
    def _custom_token(self, service):
83
        return self.config.get_cloud(self.cloud, '%s_token' % service)
84

    
85
    @DontRaiseKeyError
86
    def _custom_type(self, service):
87
        return self.config.get_cloud(self.cloud, '%s_type' % service)
88

    
89
    @DontRaiseKeyError
90
    def _custom_version(self, service):
91
        return self.config.get_cloud(self.cloud, '%s_version' % service)
92

    
93
    def _set_log_params(self):
94
        try:
95
            self.client.LOG_TOKEN, self.client.LOG_DATA = (
96
                self['config'].get_global('log_token').lower() == 'on',
97
                self['config'].get_global('log_data').lower() == 'on')
98
        except Exception as e:
99
            log.debug('Failed to read custom log settings:'
100
                '%s\n defaults for token and data logging are off' % e)
101

    
102
    def _update_max_threads(self):
103
        if getattr(self, 'client', None):
104
            max_threads = int(self['config'].get_global('max_threads'))
105
            assert max_threads > 0
106
            self.client.MAX_THREADS = max_threads
107

    
108
    def _safe_progress_bar(self, msg, arg='progress_bar'):
109
        """Try to get a progress bar, but do not raise errors"""
110
        try:
111
            progress_bar = self.arguments[arg]
112
            gen = progress_bar.get_generator(msg)
113
        except Exception:
114
            return (None, None)
115
        return (progress_bar, gen)
116

    
117
    def _safe_progress_bar_finish(self, progress_bar):
118
        try:
119
            progress_bar.finish()
120
        except Exception:
121
            pass
122

    
123
    def __getitem__(self, argterm):
124
        """
125
        :param argterm: (str) the name/label of an argument in self.arguments
126

127
        :returns: the value of the corresponding Argument (not the argument
128
            object)
129

130
        :raises KeyError: if argterm not in self.arguments of this object
131
        """
132
        return self.arguments[argterm].value
133

    
134
    def __setitem__(self, argterm, arg):
135
        """Install an argument as argterm
136
        If argterm points to another argument, the other argument is lost
137

138
        :param argterm: (str)
139

140
        :param arg: (Argument)
141
        """
142
        if not hasattr(self, 'arguments'):
143
            self.arguments = {}
144
        self.arguments[argterm] = arg
145

    
146
    def get_argument_object(self, argterm):
147
        """
148
        :param argterm: (str) the name/label of an argument in self.arguments
149

150
        :returns: the arument object
151

152
        :raises KeyError: if argterm not in self.arguments of this object
153
        """
154
        return self.arguments[argterm]
155

    
156
    def get_argument(self, argterm):
157
        """
158
        :param argterm: (str) the name/label of an argument in self.arguments
159

160
        :returns: the value of the arument object
161

162
        :raises KeyError: if argterm not in self.arguments of this object
163
        """
164
        return self[argterm]
165

    
166

    
167
#  feature classes - inherit them to get special features for your commands
168

    
169

    
170
class _optional_output_cmd(object):
171

    
172
    oo_arguments = dict(
173
        with_output=FlagArgument('show response headers', ('--with-output')),
174
        json_output=FlagArgument('show headers in json', ('-j', '--json'))
175
    )
176

    
177
    def _optional_output(self, r):
178
        if self['json_output']:
179
            print_json(r)
180
        elif self['with_output']:
181
            print_items([r] if isinstance(r, dict) else r)
182

    
183

    
184
class _optional_json(object):
185

    
186
    oj_arguments = dict(
187
        json_output=FlagArgument('show headers in json', ('-j', '--json'))
188
    )
189

    
190
    def _print(self, output, print_method=print_items, **print_method_kwargs):
191
        if self['json_output']:
192
            print_json(output)
193
        else:
194
            print_method(output, **print_method_kwargs)