Statistics
| Branch: | Tag: | Revision:

root / kamaki / cli / commands / image_cli.py @ 236e7d08

History | View | Annotate | Download (12.9 kB)

1
# Copyright 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 import command
35
from kamaki.cli.command_tree import CommandTree
36
from kamaki.cli.errors import raiseCLIError
37
from kamaki.cli.utils import print_dict, print_items
38
from kamaki.clients.image import ImageClient, ClientError
39
from kamaki.cli.argument import FlagArgument, ValueArgument, KeyValueArgument
40
from kamaki.cli.argument import IntArgument
41
from kamaki.cli.commands.cyclades_cli import _init_cyclades
42
from kamaki.cli.commands.cyclades_cli import raise_if_connection_error
43
from kamaki.cli.commands import _command_init, errors
44

    
45

    
46
image_cmds = CommandTree(
47
    'image',
48
    'Compute/Cyclades or Glance API image commands')
49
_commands = [image_cmds]
50

    
51

    
52
about_image_id = ['To see a list of available image ids: /image list']
53

    
54

    
55
class _init_image(_command_init):
56
    @errors.generic.all
57
    def _run(self):
58
        token = self.config.get('image', 'token')\
59
            or self.config.get('compute', 'token')\
60
            or self.config.get('global', 'token')
61
        base_url = self.config.get('image', 'url')\
62
            or self.config.get('compute', 'url')\
63
            or self.config.get('global', 'url')
64
        self.client = ImageClient(base_url=base_url, token=token)
65

    
66
    def main(self):
67
        self._run()
68

    
69

    
70
@command(image_cmds)
71
class image_public(_init_image):
72
    """List public images"""
73

    
74
    arguments = dict(
75
        detail=FlagArgument('show detailed output', '-l'),
76
        container_format=ValueArgument(
77
            'filter by container format',
78
            '--container-format'),
79
        disk_format=ValueArgument('filter by disk format', '--disk-format'),
80
        name=ValueArgument('filter by name', '--name'),
81
        size_min=IntArgument('filter by minimum size', '--size-min'),
82
        size_max=IntArgument('filter by maximum size', '--size-max'),
83
        status=ValueArgument('filter by status', '--status'),
84
        order=ValueArgument(
85
            'order by FIELD ( - to reverse order)',
86
            '--order',
87
            default=''),
88
        limit=IntArgument('limit the number of images in list', '-n'),
89
        more=FlagArgument(
90
            'output results in pages (-n to set items per page, default 10)',
91
            '--more')
92
    )
93

    
94
    @errors.generic.all
95
    @errors.cyclades.connection
96
    def _run(self):
97
        super(self.__class__, self)._run()
98
        filters = {}
99
        for arg in set([
100
                'container_format',
101
                'disk_format',
102
                'name',
103
                'size_min',
104
                'size_max',
105
                'status'
106
            ]).intersection(self.arguments):
107
            filters[arg] = self[arg]
108

    
109
        order = self['order']
110
        detail = self['detail']
111
        images = self.client.list_public(detail, filters, order)
112
        if self['more']:
113
            print_items(
114
                images,
115
                title=('name',),
116
                with_enumeration=True,
117
                page_size=self['limit'] if self['limit'] else 10)
118
        elif self['limit']:
119
            print_items(
120
                images[:self['limit']],
121
                title=('name',),
122
                with_enumeration=True)
123
        else:
124
            print_items(images, title=('name',), with_enumeration=True)
125

    
126
    def main(self):
127
        super(self.__class__, self)._run()
128
        self._run()
129

    
130

    
131
@command(image_cmds)
132
class image_meta(_init_image):
133
    """Get image metadata
134
    Image metadata include:
135
    - image file information (location, size, etc.)
136
    - image information (id, name, etc.)
137
    - image os properties (os, fs, etc.)
138
    """
139

    
140
    @errors.generic.all
141
    @errors.plankton.connection
142
    @errors.plankton.id
143
    def _run(self, image_id):
144
        image = self.client.get_meta(image_id)
145
        print_dict(image)
146

    
147
    def main(self, image_id):
148
        super(self.__class__, self)._run()
149
        self._run(image_id)
150

    
151

    
152
@command(image_cmds)
153
class image_register(_init_image):
154
    """(Re)Register an image"""
155

    
156
    arguments = dict(
157
        checksum=ValueArgument('set image checksum', '--checksum'),
158
        container_format=ValueArgument(
159
            'set container format',
160
            '--container-format'),
161
        disk_format=ValueArgument('set disk format', '--disk-format'),
162
        id=ValueArgument('set image ID', '--id'),
163
        owner=ValueArgument('set image owner (admin only)', '--owner'),
164
        properties=KeyValueArgument(
165
            'add property in key=value form (can be repeated)',
166
            '--property'),
167
        is_public=FlagArgument('mark image as public', '--public'),
168
        size=IntArgument('set image size', '--size'),
169
        update=FlagArgument('update existing image properties', '--update')
170
    )
171

    
172
    @errors.generic.all
173
    @errors.plankton.connection
174
    def _run(self, name, location):
175
        if not location.startswith('pithos://'):
176
            account = self.config.get('store', 'account') \
177
                or self.config.get('global', 'account')
178
            if account[-1] == '/':
179
                account = account[:-1]
180
            container = self.config.get('store', 'container') \
181
                or self.config.get('global', 'container')
182
            if container is None or len(container) == 0:
183
                location = 'pithos://%s/%s' % (account, location)
184
            else:
185
                location = 'pithos://%s/%s/%s' % (account, container, location)
186

    
187
        params = {}
188
        for key in set(
189
            [
190
                'checksum',
191
                'container_format',
192
                'disk_format',
193
                'id',
194
                'owner',
195
                'size',
196
                'is_public'
197
            ]).intersection(self.arguments):
198
            params[key] = self[key]
199

    
200
            properties = self['properties']
201
        if self['update']:
202
            self.client.reregister(location, name, params, properties)
203
        else:
204
            self.client.register(name, location, params, properties)
205

    
206
    def main(self, name, location):
207
        super(self.__class__, self)._run()
208
        self._run(name, location)
209

    
210

    
211
@command(image_cmds)
212
class image_members(_init_image):
213
    """Get image members"""
214

    
215
    @errors.generic.all
216
    @errors.plankton.connection
217
    @errors.plankton.id
218
    def _run(self, image_id):
219
        members = self.client.list_members(image_id)
220
        print_items(members)
221

    
222
    def main(self, image_id):
223
        super(self.__class__, self)._run()
224
        self._run(image_id)
225

    
226

    
227
@command(image_cmds)
228
class image_shared(_init_image):
229
    """List images shared by a member"""
230

    
231
    @errors.generic.all
232
    @errors.plankton.connection
233
    def _run(self, member):
234
        images = self.client.list_shared(member)
235
        print_items(images)
236

    
237
    def main(self, member):
238
        super(self.__class__, self)._run()
239
        self._run(member)
240

    
241

    
242
@command(image_cmds)
243
class image_addmember(_init_image):
244
    """Add a member to an image"""
245

    
246
    @errors.generic.all
247
    @errors.plankton.connection
248
    @errors.plankton.id
249
    def _run(self, image_id, member):
250
            self.client.add_member(image_id, member)
251

    
252
    def main(self, image_id, member):
253
        super(self.__class__, self)._run()
254
        self._run(image_id, member)
255

    
256

    
257
@command(image_cmds)
258
class image_delmember(_init_image):
259
    """Remove a member from an image"""
260

    
261
    @errors.generic.all
262
    @errors.plankton.connection
263
    @errors.plankton.id
264
    def _run(self, image_id, member):
265
            self.client.remove_member(image_id, member)
266

    
267
    def main(self, image_id, member):
268
        super(self.__class__, self)._run()
269
        self._run(image_id, member)
270

    
271

    
272
@command(image_cmds)
273
class image_setmembers(_init_image):
274
    """Set the members of an image"""
275

    
276
    @errors.generic.all
277
    @errors.plankton.connection
278
    @errors.plankton.id
279
    def _run(self, image_id, *members):
280
            self.client.set_members(image_id, members)
281

    
282
    def main(self, image_id, *members):
283
        super(self.__class__, self)._run()
284
        self._run(image_id, members)
285

    
286

    
287
@command(image_cmds)
288
class image_list(_init_cyclades):
289
    """List images"""
290

    
291
    arguments = dict(
292
        detail=FlagArgument('show detailed output', '-l'),
293
        limit=IntArgument('limit the number of VMs to list', '-n'),
294
        more=FlagArgument(
295
            'output results in pages (-n to set items per page, default 10)',
296
            '--more')
297
    )
298

    
299
    def _make_results_pretty(self, images):
300
        for img in images:
301
            if 'metadata' in img:
302
                img['metadata'] = img['metadata']['values']
303

    
304
    @errors.generic.all
305
    @errors.cyclades.connection
306
    def _run(self):
307
        images = self.client.list_images(self['detail'])
308
        if self['detail']:
309
            self._make_results_pretty(images)
310
        if self['more']:
311
            print_items(images,
312
                page_size=self['limit'] if self['limit'] else 10)
313
        elif self['limit']:
314
            print_items(images[:self['limit']])
315
        else:
316
            print_items(images)
317

    
318
    def main(self):
319
        super(self.__class__, self)._run()
320
        self._run()
321

    
322

    
323
@command(image_cmds)
324
class image_info(_init_cyclades):
325
    """Get detailed information on an image"""
326

    
327
    @errors.generic.all
328
    @errors.cyclades.connection
329
    @errors.plankton.id
330
    def _run(self, image_id):
331
        image = self.client.get_image_details(image_id)
332
        if 'metadata' in image:
333
            image['metadata'] = image['metadata']['values']
334
        print_dict(image)
335

    
336
    def main(self, image_id):
337
        super(self.__class__, self)._run()
338
        self._run(image_id)
339

    
340

    
341
@command(image_cmds)
342
class image_delete(_init_cyclades):
343
    """Delete an image (image file remains intact)"""
344

    
345
    @errors.generic.all
346
    @errors.cyclades.connection
347
    @errors.plankton.id
348
    def _run(self, image_id):
349
        self.client.delete_image(image_id)
350

    
351
    def main(self, image_id):
352
        super(self.__class__, self)._run()
353
        self._run(image_id)
354

    
355

    
356
@command(image_cmds)
357
class image_properties(_init_cyclades):
358
    """Get properties related to OS installation in an image"""
359

    
360
    @errors.generic.all
361
    @errors.cyclades.connection
362
    @errors.plankton.id
363
    @errors.plankton.metadata
364
    def _run(self, image_id, key):
365
        r = self.client.get_image_metadata(image_id, key)
366
        print_dict(r)
367

    
368
    def main(self, image_id, key=''):
369
        super(self.__class__, self)._run()
370
        self._run(image_id, key)
371

    
372

    
373
@command(image_cmds)
374
class image_addproperty(_init_cyclades):
375
    """Add an OS-related property to an image"""
376

    
377
    @errors.generic.all
378
    @errors.cyclades.connection
379
    @errors.plankton.id
380
    def _run(self, image_id, key, val):
381
        r = self.client.create_image_metadata(image_id, key, val)
382
        print_dict(r)
383

    
384
    def main(self, image_id, key, val):
385
        super(self.__class__, self)._run()
386
        self._run(image_id, key, val)
387

    
388

    
389
@command(image_cmds)
390
class image_setproperty(_init_cyclades):
391
    """Update an existing property in an image"""
392

    
393
    @errors.generic.all
394
    @errors.cyclades.connection
395
    @errors.plankton.id
396
    def _run(self, image_id, key, val):
397
        metadata = {key: val}
398
        r = self.client.update_image_metadata(image_id, **metadata)
399
        print_dict(r)
400

    
401
    def main(self, image_id, key, val):
402
        super(self.__class__, self)._run()
403
        self._run(image_id, key, val)
404

    
405

    
406
@command(image_cmds)
407
class image_delproperty(_init_cyclades):
408
    """Delete a property of an image"""
409

    
410
    @errors.generic.all
411
    @errors.cyclades.connection
412
    @errors.plankton.id
413
    @errors.plankton.metadata
414
    def _run(self, image_id, key):
415
        self.client.delete_image_metadata(image_id, key)
416

    
417
    def main(self, image_id, key):
418
        super(self.__class__, self)._run()
419
        self._run(image_id, key)