server-list.py 4.8 KB
Newer Older
Giorgos Verigakis's avatar
Giorgos Verigakis committed
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
# Copyright 2012 GRNET S.A. All rights reserved.
#
# Redistribution and use in source and binary forms, with or
# without modification, are permitted provided that the following
# conditions are met:
#
#   1. Redistributions of source code must retain the above
#      copyright notice, this list of conditions and the following
#      disclaimer.
#
#   2. Redistributions in binary form must reproduce the above
#      copyright notice, this list of conditions and the following
#      disclaimer in the documentation and/or other materials
#      provided with the distribution.
#
# THIS SOFTWARE IS PROVIDED BY GRNET S.A. ``AS IS'' AND ANY EXPRESS
# OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
# WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
# PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL GRNET S.A OR
# CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
# SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
# LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF
# USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED
# AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
# LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN
# ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
# POSSIBILITY OF SUCH DAMAGE.
#
# The views and conclusions contained in the software and
# documentation are those of the authors and should not be
# interpreted as representing official policies, either expressed
# or implied, of GRNET S.A.

from optparse import make_option

from django.core.management.base import BaseCommand, CommandError

from synnefo.api.util import get_image
39
from synnefo.db.models import VirtualMachine, Backend
40
from ._common import format_vm_state
Giorgos Verigakis's avatar
Giorgos Verigakis committed
41
42
43
44


class Command(BaseCommand):
    help = "List servers"
45

Giorgos Verigakis's avatar
Giorgos Verigakis committed
46
47
48
49
50
51
    option_list = BaseCommand.option_list + (
        make_option('-c',
            action='store_true',
            dest='csv',
            default=False,
            help="Use pipes to separate values"),
52
53
54
55
56
        make_option('--suspended',
            action='store_true',
            dest='suspended',
            default=False,
            help="List only suspended servers"),
Giorgos Verigakis's avatar
Giorgos Verigakis committed
57
58
59
60
61
        make_option('--build',
            action='store_true',
            dest='build',
            default=False,
            help="List only servers in the building state"),
62
        make_option('--deleted', action='store_true', dest='deleted',
63
                    default=False,
64
                    help="Include deletd servers"),
65
        make_option('--backend-id', dest='backend_id',
66
                    help="List only servers of the specified backend")
Giorgos Verigakis's avatar
Giorgos Verigakis committed
67
        )
68

Giorgos Verigakis's avatar
Giorgos Verigakis committed
69
70
71
    def handle(self, *args, **options):
        if args:
            raise CommandError("Command doesn't accept any arguments")
72
73

        if options['backend_id']:
74
75
76
77
78
            try:
                servers = Backend.objects.get(id=options['backend_id'])\
                                         .virtual_machines
            except Backend.DoesNotExist:
                raise CommandError("Backend not found in DB")
79
80
81
        else:
            servers = VirtualMachine.objects

82
        if options['deleted']:
83
            servers = servers.all()
84
85
        else:
            servers = servers.filter(deleted=False)
86

87
88
89
        if options['suspended']:
            servers = servers.filter(suspended=True)

Giorgos Verigakis's avatar
Giorgos Verigakis committed
90
91
        if options['build']:
            servers = servers.filter(operstate='BUILD')
92

93
94
95
        labels = ('id', 'name', 'owner', 'flavor', 'image', 'state',
                  'backend')
        columns = (3, 12, 20, 11, 12, 9, 40)
96

Giorgos Verigakis's avatar
Giorgos Verigakis committed
97
98
99
100
101
        if not options['csv']:
            line = ' '.join(l.rjust(w) for l, w in zip(labels, columns))
            self.stdout.write(line + '\n')
            sep = '-' * len(line)
            self.stdout.write(sep + '\n')
102
103
104

        cache = ImageCache()

105
        for server in servers.order_by('id'):
Giorgos Verigakis's avatar
Giorgos Verigakis committed
106
            id = str(server.id)
107
108
109
110
            try:
                name = server.name.decode('utf8')
            except UnicodeEncodeError:
                name = server.name
Giorgos Verigakis's avatar
Giorgos Verigakis committed
111
            flavor = server.flavor.name
112
            try:
113
                image = cache.get_image(server.imageid, server.userid)['name']
114
115
            except:
                image = server.imageid
116
117
118

            state = format_vm_state(server)
            fields = (id, name, server.userid, flavor, image, state,
119
                      str(server.backend))
120

Giorgos Verigakis's avatar
Giorgos Verigakis committed
121
122
123
124
            if options['csv']:
                line = '|'.join(fields)
            else:
                line = ' '.join(f.rjust(w) for f, w in zip(fields, columns))
125

Giorgos Verigakis's avatar
Giorgos Verigakis committed
126
            self.stdout.write(line.encode('utf8') + '\n')
127
128
129
130
131
132
133
134
135
136


class ImageCache(object):
    def __init__(self):
        self.images = {}

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