Statistics
| Branch: | Tag: | Revision:

root / kamaki / cli / commands / __init__.py @ 60c42f9f

History | View | Annotate | Download (6.5 kB)

1
# Copyright 2011-2013 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
        try:
70
            arguments.update(self.wait_arguments)
71
        except AttributeError:
72
            pass
73
        self.arguments = dict(arguments)
74
        try:
75
            self.config = self['config']
76
        except KeyError:
77
            pass
78
        self.auth_base = auth_base or getattr(self, 'auth_base', None)
79
        self.cloud = cloud or getattr(self, 'cloud', None)
80

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

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

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

    
93
    @DontRaiseKeyError
94
    def _custom_version(self, service):
95
        return self.config.get_cloud(self.cloud, '%s_version' % service)
96

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

    
106
    def _update_max_threads(self):
107
        if getattr(self, 'client', None):
108
            max_threads = int(self['config'].get_global('max_threads'))
109
            assert max_threads > 0
110
            self.client.MAX_THREADS = max_threads
111

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

    
121
    def _safe_progress_bar_finish(self, progress_bar):
122
        try:
123
            progress_bar.finish()
124
        except Exception:
125
            pass
126

    
127
    def __getitem__(self, argterm):
128
        """
129
        :param argterm: (str) the name/label of an argument in self.arguments
130

131
        :returns: the value of the corresponding Argument (not the argument
132
            object)
133

134
        :raises KeyError: if argterm not in self.arguments of this object
135
        """
136
        return self.arguments[argterm].value
137

    
138
    def __setitem__(self, argterm, arg):
139
        """Install an argument as argterm
140
        If argterm points to another argument, the other argument is lost
141

142
        :param argterm: (str)
143

144
        :param arg: (Argument)
145
        """
146
        if not hasattr(self, 'arguments'):
147
            self.arguments = {}
148
        self.arguments[argterm] = arg
149

    
150
    def get_argument_object(self, argterm):
151
        """
152
        :param argterm: (str) the name/label of an argument in self.arguments
153

154
        :returns: the arument object
155

156
        :raises KeyError: if argterm not in self.arguments of this object
157
        """
158
        return self.arguments[argterm]
159

    
160
    def get_argument(self, argterm):
161
        """
162
        :param argterm: (str) the name/label of an argument in self.arguments
163

164
        :returns: the value of the arument object
165

166
        :raises KeyError: if argterm not in self.arguments of this object
167
        """
168
        return self[argterm]
169

    
170

    
171
#  feature classes - inherit them to get special features for your commands
172

    
173

    
174
class _optional_output_cmd(object):
175

    
176
    oo_arguments = dict(
177
        with_output=FlagArgument('show response headers', ('--with-output')),
178
        json_output=FlagArgument('show headers in json', ('-j', '--json'))
179
    )
180

    
181
    def _optional_output(self, r):
182
        if self['json_output']:
183
            print_json(r)
184
        elif self['with_output']:
185
            print_items([r] if isinstance(r, dict) else r)
186

    
187

    
188
class _optional_json(object):
189

    
190
    oj_arguments = dict(
191
        json_output=FlagArgument('show headers in json', ('-j', '--json'))
192
    )
193

    
194
    def _print(self, output, print_method=print_items, **print_method_kwargs):
195
        if self['json_output']:
196
            print_json(output)
197
        else:
198
            print_method(output, **print_method_kwargs)