Revision b0e7f310 snf-cyclades-app/synnefo/api/management/commands/network-list.py

b/snf-cyclades-app/synnefo/api/management/commands/network-list.py
1
# Copyright 2012 GRNET S.A. All rights reserved.
1
# Copyright 2012-2013 GRNET S.A. All rights reserved.
2 2
#
3 3
# Redistribution and use in source and binary forms, with or
4 4
# without modification, are permitted provided that the following
......
33 33

  
34 34
from optparse import make_option
35 35

  
36
from django.core.management.base import BaseCommand, CommandError
37
from synnefo.management.common import (format_bool, filter_results, UserCache,
38
                                       Omit)
36
from synnefo.webproject.management.commands import ListCommand
39 37
from synnefo.db.models import Network
40
from synnefo.management.common import pprint_table
41 38

  
42
FIELDS = Network._meta.get_all_field_names()
39
from logging import getLogger
40
log = getLogger(__name__)
43 41

  
44 42

  
45
class Command(BaseCommand):
46
    help = "List networks"
47

  
48
    option_list = BaseCommand.option_list + (
49
        make_option(
50
            '-c',
51
            action='store_true',
52
            dest='csv',
53
            default=False,
54
            help="Use pipes to separate values"),
55
        make_option(
56
            '--deleted',
57
            action='store_true',
58
            dest='deleted',
59
            default=False,
60
            help="Include deleted networks"),
43
class Command(ListCommand):
44
    option_list = ListCommand.option_list + (
61 45
        make_option(
62 46
            '--public',
63 47
            action='store_true',
......
65 49
            default=False,
66 50
            help="List only public networks"),
67 51
        make_option(
68
            '--user',
69
            dest='user',
70
            help="List only networks of the specified user"
71
                 " (uuid or display name"),
72
        make_option('--ipv6',
52
            '--ipv6',
73 53
            action='store_true',
74 54
            dest='ipv6',
75 55
            default=False,
76
            help="Show IPv6 information of the network"),
77
        make_option(
78
            '--filter-by',
79
            dest='filter_by',
80
            help="Filter results. Comma seperated list of key 'cond' val pairs"
81
                 " that displayed entries must satisfy. e.g."
82
                 " --filter-by \"name=Network-1,link!=prv0\"."
83
                 " Available keys are: %s" % ", ".join(FIELDS)),
84
        make_option(
85
            '--displayname',
86
            action='store_true',
87
            dest='displayname',
88
            default=False,
89
            help="Display both uuid and display name"),
56
            help="Include IPv6 information"),
90 57
    )
91 58

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

  
96
        ucache = UserCache()
97

  
98
        if options['deleted']:
99
            networks = Network.objects.all()
100
        else:
101
            networks = Network.objects.filter(deleted=False)
102

  
103
        if options['public']:
104
            networks = networks.filter(public=True)
105

  
106
        user = options['user']
107
        if user:
108
            if '@' in user:
109
                user = ucache.get_uuid(user)
110
            networks = networks.filter(userid=user)
111

  
112
        filter_by = options['filter_by']
113
        if filter_by:
114
            networks = filter_results(networks, filter_by)
115

  
116
        displayname = options['displayname']
117

  
118
        headers = filter(lambda x: x is not Omit,
119
                         ['id',
120
                          'name',
121
                          'flavor',
122
                          'owner_uuid',
123
                          'owner_name' if displayname else Omit,
124
                          'mac_prefix',
125
                          'dhcp',
126
                          'state',
127
                          'link',
128
                          'vms',
129
                          'public',
130
                          ])
131

  
132
        if options['ipv6']:
133
            headers.extend(['IPv6 Subnet', 'IPv6 Gateway'])
134
        else:
135
            headers.extend(['IPv4 Subnet', 'IPv4 Gateway'])
136

  
137
        if displayname:
138
            uuids = list(set([network.userid for network in networks]))
139
            ucache.fetch_names(uuids)
140

  
141
        table = []
142
        for network in networks.order_by("id"):
143
            uuid = network.userid
144
            if displayname:
145
                dname = ucache.get_name(uuid)
146

  
147
            fields = filter(lambda x: x is not Omit,
148
                            [str(network.id),
149
                             network.name,
150
                             network.flavor,
151
                             uuid or '-',
152
                             dname or '-' if displayname else Omit,
153
                             network.mac_prefix or '-',
154
                             str(network.dhcp),
155
                             network.state,
156
                             network.link or '-',
157
                             str(network.machines.count()),
158
                             format_bool(network.public),
159
                             ])
160

  
161
            if options['ipv6']:
162
                fields.extend([network.subnet6 or '', network.gateway6 or ''])
163
            else:
164
                fields.extend([network.subnet, network.gateway or ''])
165
            table.append(fields)
166

  
167
        separator = " | " if options['csv'] else None
168
        pprint_table(self.stdout, table, headers, separator)
59
    object_class = Network
60
    deleted_field = "deleted"
61
    user_uuid_field = "userid"
62

  
63
    def get_machines(network):
64
        return network.machines.filter(deleted=False).count()
65

  
66
    def get_backends(network):
67
        return network.backend_networks.values_list("backend_id", flat=True)
68

  
69
    FIELDS = {
70
        "id": ("id", "The ID of the network"),
71
        "name": ("name", "The name of the network"),
72
        "user.uuid": ("userid", "The UUID of the network's owner"),
73
        "public": ("public", "Whether network is public or private"),
74
        "flavor": ("flavor", "The network's flavor"),
75
        "state": ("state", "The network's state"),
76
        "dhcp": ("dhcp", "Whether network uses nfdhcpd or not"),
77
        "subnet.ipv4": ("subnet", "The IPv4 subnet of the network"),
78
        "gateway.ipv4": ("gateway", "The IPv4 gateway of the network"),
79
        "subnet.ipv6": ("subnet", "The IPv6 subnet of the network"),
80
        "gateway.ipv6": ("gateway", "The IPv6 gateway of the network"),
81
        "created": ("created", "The date the network was created"),
82
        "updated": ("created", "The date the network was updated"),
83
        "deleted": ("deleted", "Whether the network is deleted or not"),
84
        "mode": ("mode", "The mode of the network"),
85
        "link": ("link", "The link of the network"),
86
        "mac_prefix": ("mac_prefix", "The network's MAC prefix"),
87
        "vms": (get_machines, "Number of connected servers"),
88
        "backends": (get_backends, "IDs of Ganeti backends that the network is"
89
                                   " connected to"),
90
    }
91

  
92
    fields = ["id", "name", "user.uuid", "state", "public", "subnet.ipv4",
93
              "gateway.ipv4", "link", "mac_prefix"]
94

  
95
    def handle_args(self, *args, **options):
96
        if options["public"]:
97
            self.filters["public"] = True
98
        if options["ipv6"]:
99
            self.fields.extend(["subnet.ipv6", "gateway.ipv6"])

Also available in: Unified diff