Statistics
| Branch: | Tag: | Revision:

root / snf-cyclades-app / synnefo / api / management / commands / server-list.py @ 9621c777

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

    
34
from optparse import make_option
35

    
36
from django.core.management.base import BaseCommand, CommandError
37
from synnefo.management.common import (format_vm_state, get_backend,
38
                                       filter_results, pprint_table, UUIDCache)
39
from synnefo.api.util import get_image
40
from synnefo.db.models import VirtualMachine
41

    
42

    
43
FIELDS = VirtualMachine._meta.get_all_field_names()
44

    
45

    
46
class Command(BaseCommand):
47
    help = "List servers"
48

    
49
    option_list = BaseCommand.option_list + (
50
        make_option(
51
            '-c',
52
            action='store_true',
53
            dest='csv',
54
            default=False,
55
            help="Use pipes to separate values"),
56
        make_option(
57
            '--suspended',
58
            action='store_true',
59
            dest='suspended',
60
            default=False,
61
            help="List only suspended servers"),
62
        make_option(
63
            '--build',
64
            action='store_true',
65
            dest='build',
66
            default=False,
67
            help="List only servers in the building state"),
68
        make_option(
69
            '--deleted',
70
            action='store_true',
71
            dest='deleted',
72
            default=False,
73
            help="Include deleted servers"),
74
        make_option(
75
            '--backend-id',
76
            dest='backend_id',
77
            help="List only servers of the specified backend"),
78
        make_option(
79
            '--filter-by',
80
            dest='filter_by',
81
            help="Filter results. Comma seperated list of key `cond` val pairs"
82
                 " that displayed entries must satisfy. e.g."
83
                 " --filter-by \"operstate=STARTED,id>=22\"."
84
                 " Available keys are: %s" % ", ".join(FIELDS)),
85
        make_option(
86
            '--uuids',
87
            action='store_true',
88
            dest='use_uuids',
89
            default=False,
90
            help="Display UUIDs instead of user emails"),
91
    )
92

    
93
    def handle(self, *args, **options):
94
        if args:
95
            raise CommandError("Command doesn't accept any arguments")
96

    
97
        use_uuids = options["use_uuids"]
98
        if options['backend_id']:
99
            backend = get_backend(options['backend_id'])
100
            servers = backend.virtual_machines
101
        else:
102
            servers = VirtualMachine.objects
103

    
104
        if options['deleted']:
105
            servers = servers.all()
106
        else:
107
            servers = servers.filter(deleted=False)
108

    
109
        if options['suspended']:
110
            servers = servers.filter(suspended=True)
111

    
112
        if options['build']:
113
            servers = servers.filter(operstate='BUILD')
114

    
115
        filter_by = options['filter_by']
116
        if filter_by:
117
            servers = filter_results(servers, filter_by)
118

    
119
        cache = ImageCache()
120
        if not use_uuids:
121
            ucache = UUIDCache()
122

    
123
        headers = ('id', 'name', 'owner', 'flavor', 'image', 'state',
124
                   'backend')
125

    
126
        table = []
127
        for server in servers.order_by('id'):
128
            try:
129
                name = server.name.decode('utf8')
130
            except UnicodeEncodeError:
131
                name = server.name
132

    
133
            flavor = server.flavor.name
134

    
135
            try:
136
                image = cache.get_image(server.imageid, server.userid)['name']
137
            except:
138
                image = server.imageid
139

    
140
            state = format_vm_state(server)
141

    
142
            user = server.userid
143
            if not use_uuids:
144
                user = ucache.get_user(server.userid)
145

    
146
            fields = (str(server.id), name, user, flavor, image,
147
                      state, str(server.backend))
148
            table.append(fields)
149

    
150
        separator = " | " if options['csv'] else None
151
        pprint_table(self.stdout, table, headers, separator)
152

    
153

    
154
class ImageCache(object):
155
    def __init__(self):
156
        self.images = {}
157

    
158
    def get_image(self, imageid, userid):
159
        if not imageid in self.images:
160
            self.images[imageid] = get_image(imageid, userid)
161
        return self.images[imageid]