Revision a6e6fe48

b/snf-cyclades-app/synnefo/db/models.py
384 384
        return u"<vm:%s@backend:%s>" % (self.id, self.backend_id)
385 385

  
386 386
    # Error classes
387
    class InvalidBackendIdError(Exception):
387
    class InvalidBackendIdError(ValueError):
388 388
        def __init__(self, value):
389 389
            self.value = value
390 390

  
......
587 587
            free += ip_pool.count_available()
588 588
        return total, free
589 589

  
590
    class InvalidBackendIdError(Exception):
590
    class InvalidBackendIdError(ValueError):
591 591
        def __init__(self, value):
592 592
            self.value = value
593 593

  
b/snf-cyclades-app/synnefo/logic/management/commands/backend-modify.py
1
# Copyright 2012 GRNET S.A. All rights reserved.
1
# Copyright 2012-2014 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
......
35 35
from django.core.management.base import BaseCommand, CommandError
36 36
from synnefo.db.models import Backend
37 37
from snf_django.management.utils import parse_bool
38
from synnefo.management.common import (get_backend, check_backend_credentials)
38
from synnefo.management import common
39 39

  
40 40
HYPERVISORS = [h[0] for h in Backend.HYPERVISORS]
41 41

  
......
82 82
        if len(args) != 1:
83 83
            raise CommandError("Please provide a backend ID")
84 84

  
85
        backend = get_backend(args[0])
85
        backend = common.get_resource("backend", args[0], for_update=True)
86 86

  
87 87
        # Ensure fields correspondence with options and Backend model
88 88
        credentials_changed = False
......
95 95

  
96 96
        if credentials_changed:
97 97
                # check credentials, if any of them changed!
98
                check_backend_credentials(backend.clustername, backend.port,
99
                                          backend.username, backend.password)
98
                common.check_backend_credentials(backend.clustername,
99
                                                 backend.port,
100
                                                 backend.username,
101
                                                 backend.password)
100 102
        if options['drained']:
101 103
            backend.drained = parse_bool(options['drained'], strict=True)
102 104
        if options['offline']:
b/snf-cyclades-app/synnefo/logic/management/commands/backend-remove.py
1
# Copyright 2011-2012 GRNET S.A. All rights reserved.
1
# Copyright 2011-2014 GRNET S.A. All rights reserved.
2 2
#
3 3
# Redistribution and use in source and binary forms, with or without
4 4
# modification, are permitted provided that the following conditions
......
29 29
#
30 30

  
31 31
from django.core.management.base import BaseCommand, CommandError
32
from synnefo.management.common import get_backend
32
from synnefo.management import common
33 33
from synnefo.logic import backend as backend_mod
34 34
from synnefo.db.models import Backend
35 35
from django.db import transaction, models
......
50 50
        if len(args) < 1:
51 51
            raise CommandError("Please provide a backend ID")
52 52

  
53
        backend = get_backend(args[0])
53
        backend = common.get_resource("backend", args[0], for_update=True)
54 54

  
55 55
        write("Trying to remove backend: %s\n" % backend.clustername)
56 56

  
b/snf-cyclades-app/synnefo/logic/management/commands/flavor-modify.py
1
# Copyright 2012 GRNET S.A. All rights reserved.
1
# Copyright 2012-2014 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
......
34 34
from optparse import make_option
35 35

  
36 36
from django.core.management.base import BaseCommand, CommandError
37
from synnefo.management.common import get_flavor
37
from synnefo.management.common import get_resource
38 38
from snf_django.management.utils import parse_bool
39 39

  
40 40

  
......
67 67
        if len(args) != 1:
68 68
            raise CommandError("Please provide a flavor ID")
69 69

  
70
        flavor = get_flavor(args[0], for_update=True)
70
        flavor = get_resource("flavor", args[0], for_update=True)
71 71

  
72 72
        deleted = options['deleted']
73 73

  
b/snf-cyclades-app/synnefo/logic/management/commands/floating-ip-attach.py
1
# Copyright 2012 GRNET S.A. All rights reserved.
1
# Copyright 2012-2014 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
......
61 61
            raise CommandError('Please give either a server or a router id')
62 62

  
63 63
        #get the vm
64
        vm = common.get_vm(device, for_update=True)
65
        floating_ip = common.get_floating_ip_by_id(floating_ip_id,
66
                                                   for_update=True)
64
        vm = common.get_resource("server", device, for_update=True)
65
        floating_ip = common.get_resource("floating-ip", floating_ip_id,
66
                                          for_update=True)
67 67
        servers.create_port(vm.userid, floating_ip.network,
68 68
                            use_ipaddress=floating_ip, machine=vm)
69 69

  
b/snf-cyclades-app/synnefo/logic/management/commands/floating-ip-create.py
1
# Copyright 2012 GRNET S.A. All rights reserved.
1
# Copyright 2012-2014 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
......
71 71
            raise CommandError("'owner' is required for floating IP creation")
72 72

  
73 73
        if network_id is not None:
74
            network = util.get_network(network_id, owner, for_update=True,
75
                                       non_deleted=True)
74
            network = util.get_resource("network", network_id, for_update=True)
75
            if network.deleted:
76
                raise CommandError("Network '%s' is deleted" % network.id)
76 77
            if not network.floating_ip_pool:
77 78
                raise CommandError("Network '%s' is not a floating IP pool."
78 79
                                   % network)
b/snf-cyclades-app/synnefo/logic/management/commands/floating-ip-detach.py
1
# Copyright 2012 GRNET S.A. All rights reserved.
1
# Copyright 2012-2014 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
......
49 49
        floating_ip_id = args[0]
50 50

  
51 51
        #get the floating-ip
52
        floating_ip = common.get_floating_ip_by_id(floating_ip_id,
53
                                                   for_update=True)
52
        floating_ip = common.get_resource("floating-ip", floating_ip_id,
53
                                          for_update=True)
54 54

  
55 55
        if not floating_ip.nic:
56 56
            raise CommandError('This floating IP is not attached to a device')
b/snf-cyclades-app/synnefo/logic/management/commands/floating-ip-remove.py
1
# Copyright 2013 GRNET S.A. All rights reserved.
1
# Copyright 2013-2014 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
......
57 57
        for floating_ip_id in args:
58 58
            self.stdout.write("\n")
59 59
            try:
60
                floating_ip = common.get_floating_ip_by_id(floating_ip_id,
61
                                                           for_update=True)
60
                floating_ip = common.get_resource("floating-ip",
61
                                                  floating_ip_id,
62
                                                  for_update=True)
62 63
                ips.delete_floating_ip(floating_ip)
63 64
                self.stdout.write("Deleted floating IP '%s'.\n" %
64 65
                                  floating_ip_id)
b/snf-cyclades-app/synnefo/logic/management/commands/network-inspect.py
1
# Copyright 2012-2013 GRNET S.A. All rights reserved.
1
# Copyright 2012-2014 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
......
54 54
        if len(args) != 1:
55 55
            raise CommandError("Please provide a network ID.")
56 56

  
57
        network = common.get_network(args[0])
57
        network = common.get_resource("network", args[0])
58 58
        displayname = options['displayname']
59 59

  
60 60
        pprint.pprint_network(network, display_mails=displayname,
b/snf-cyclades-app/synnefo/logic/management/commands/network-modify.py
1
# Copyright 2012-2013 GRNET S.A. All rights reserved.
1
# Copyright 2012-2014 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
......
36 36
from django.core.management.base import BaseCommand, CommandError
37 37

  
38 38
from synnefo.db.models import Backend
39
from synnefo.management.common import (get_network, get_backend)
39
from synnefo.management.common import get_resource
40 40
from snf_django.management.utils import parse_bool
41 41
from synnefo.logic import networks, backend as backend_mod
42 42
from django.db import transaction
......
95 95
        if len(args) != 1:
96 96
            raise CommandError("Please provide a network ID")
97 97

  
98
        network = get_network(args[0])
98
        network = get_resource("network", args[0])
99 99

  
100 100
        new_name = options.get("name")
101 101
        if new_name is not None:
......
159 159

  
160 160
        add_to_backend = options["add_to_backend"]
161 161
        if add_to_backend is not None:
162
            backend = get_backend(add_to_backend)
162
            backend = get_resource("backend", add_to_backend)
163 163
            bnet, jobs = backend_mod.ensure_network_is_active(backend,
164 164
                                                              network.id)
165 165
            if jobs:
......
168 168

  
169 169
        remove_from_backend = options["remove_from_backend"]
170 170
        if remove_from_backend is not None:
171
            backend = get_backend(remove_from_backend)
171
            backend = get_resource("backend", remove_from_backend)
172 172
            if network.nics.filter(machine__backend=backend,
173 173
                                   machine__deleted=False).exists():
174 174
                msg = "Cannot remove. There are still connected VMs to this"\
b/snf-cyclades-app/synnefo/logic/management/commands/network-remove.py
1
# Copyright 2011-2013 GRNET S.A. All rights reserved.
1
# Copyright 2011-2014 GRNET S.A. All rights reserved.
2 2
#
3 3
# Redistribution and use in source and binary forms, with or without
4 4
# modification, are permitted provided that the following conditions
......
32 32
from snf_django.management.commands import RemoveCommand
33 33
from snf_django.lib.api import faults
34 34
from synnefo.logic import networks
35
from synnefo.management.common import get_network, convert_api_faults
35
from synnefo.management import common
36 36

  
37 37

  
38 38
class Command(RemoveCommand):
......
40 40
    args = "<Network ID> [<Network ID> ...]"
41 41
    help = "Remove a network from the Database, and Ganeti"
42 42

  
43
    @convert_api_faults
43
    @common.convert_api_faults
44 44
    def handle(self, *args, **options):
45 45
        if not args:
46 46
            raise CommandError("Please provide a network ID")
......
52 52
        for network_id in args:
53 53
            self.stdout.write("\n")
54 54
            try:
55
                network = get_network(network_id, for_update=True)
55
                network = common.get_resource("network", network_id,
56
                                              for_update=True)
56 57
                self.stdout.write('Removing network: %s\n' %
57 58
                                  network.backend_id)
58 59

  
b/snf-cyclades-app/synnefo/logic/management/commands/port-create.py
1
# Copyright 2013 GRNET S.A. All rights reserved.
1
# Copyright 2013-2014 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
......
127 127
        owner = None
128 128
        if server_id:
129 129
            owner = "vm"
130
            vm = common.get_vm(server_id, for_update=True)
130
            vm = common.get_resource("server", server_id, for_update=True)
131 131
            #if vm.router:
132 132
            #    raise CommandError("Server '%s' does not exist." % server_id)
133 133
        elif router_id:
134 134
            owner = "router"
135
            vm = common.get_vm(router_id, for_update=True)
135
            vm = common.get_resource("server", router_id, for_update=True)
136 136
            if not vm.router:
137 137
                raise CommandError("Router '%s' does not exist." % router_id)
138 138

  
......
143 143
                raise CommandError("Please specify the owner of the port.")
144 144

  
145 145
        # get the network
146
        network = common.get_network(network_id)
146
        network = common.get_resource("network", network_id)
147 147

  
148 148
        # Get either floating IP or fixed ip address
149 149
        ipaddress = None
150 150
        floating_ip_id = options["floating_ip_id"]
151 151
        ipv4_address = options["ipv4_address"]
152 152
        if floating_ip_id:
153
            ipaddress = common.get_floating_ip_by_id(floating_ip_id,
154
                                                     for_update=True)
153
            ipaddress = common.get_resource("floating-ip", floating_ip_id,
154
                                            for_update=True)
155 155
            if ipv4_address is not None and ipaddress.address != ipv4_address:
156 156
                raise CommandError("Floating IP address '%s' is different from"
157 157
                                   " specified address '%s'" %
158 158
                                   (ipaddress.address, ipv4_address))
159 159

  
160

  
161 160
        # validate security groups
162 161
        sg_list = []
163 162
        if security_group_ids:
b/snf-cyclades-app/synnefo/logic/management/commands/port-inspect.py
1
# Copyright 2013 GRNET S.A. All rights reserved.
1
# Copyright 2013-2014 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
......
62 62
        if len(args) != 1:
63 63
            raise CommandError("Please provide a port ID")
64 64

  
65
        port = common.get_port(args[0])
65
        port = common.get_resource("port", args[0])
66 66

  
67 67
        pprint.pprint_port(port, stdout=self.stdout)
68 68
        self.stdout.write('\n\n')
b/snf-cyclades-app/synnefo/logic/management/commands/port-remove.py
1
# Copyright 2011-2013 GRNET S.A. All rights reserved.
1
# Copyright 2011-2014 GRNET S.A. All rights reserved.
2 2
#
3 3
# Redistribution and use in source and binary forms, with or without
4 4
# modification, are permitted provided that the following conditions
......
62 62
        for port_id in args:
63 63
            self.stdout.write("\n")
64 64
            try:
65
                port = common.get_port(port_id, for_update=True)
65
                port = common.get_resource("port", port_id, for_update=True)
66 66

  
67 67
                servers.delete_port(port)
68 68

  
b/snf-cyclades-app/synnefo/logic/management/commands/reconcile-servers.py
1
# Copyright 2011-2013 GRNET S.A. All rights reserved.
1
# Copyright 2011-2014 GRNET S.A. All rights reserved.
2 2
#
3 3
# Redistribution and use in source and binary forms, with or without
4 4
# modification, are permitted provided that the following conditions
......
39 39
import subprocess
40 40
from optparse import make_option
41 41
from django.core.management.base import BaseCommand
42
from synnefo.management.common import get_backend
42
from synnefo.management.common import get_resource
43 43
from synnefo.logic import reconciliation
44 44
from snf_django.management.utils import parse_bool
45 45

  
......
87 87
    def handle(self, **options):
88 88
        backend_id = options['backend-id']
89 89
        if backend_id:
90
            backends = [get_backend(backend_id)]
90
            backends = [get_resource("backend", backend_id)]
91 91
        else:
92 92
            backends = reconciliation.get_online_backends()
93 93

  
b/snf-cyclades-app/synnefo/logic/management/commands/server-create.py
1
# Copyright 2012 GRNET S.A. All rights reserved.
1
# Copyright 2012-2014 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
......
108 108
        if not image_id:
109 109
            raise CommandError("image-id is mandatory")
110 110

  
111
        flavor = common.get_flavor(flavor_id)
111
        flavor = common.get_resource("flavor", flavor_id)
112 112
        image = common.get_image(image_id, user_id)
113 113
        if backend_id:
114
            backend = common.get_backend(backend_id)
114
            backend = common.get_resource("backend", backend_id)
115 115
        else:
116 116
            backend = None
117 117

  
......
147 147
                    val = {"port": port_id}
148 148
                elif con_kind == "floatingip":
149 149
                    fip_id = opt.split(":")[1]
150
                    fip = common.get_floating_ip_by_id(fip_id, for_update=True)
150
                    fip = common.get_resource("floating-ip", fip_id,
151
                                              for_update=True)
151 152
                    val = {"uuid": fip.network_id, "fixed_ip": fip.address}
152 153
                else:
153 154
                    raise CommandError("Unknown argument for option --port")
b/snf-cyclades-app/synnefo/logic/management/commands/server-import.py
129 129

  
130 130
def import_server(instance_name, backend_id, flavor_id, image_id, user_id,
131 131
                  new_public_nic, stream=sys.stdout):
132
    flavor = common.get_flavor(flavor_id)
133
    backend = common.get_backend(backend_id)
132
    flavor = common.get_resource("flavor", flavor_id)
133
    backend = common.get_resource("backend", backend_id)
134 134

  
135 135
    backend_client = backend.get_client()
136 136

  
b/snf-cyclades-app/synnefo/logic/management/commands/server-inspect.py
1
# Copyright 2012-2013 GRNET S.A. All rights reserved.
1
# Copyright 2012-2014 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
......
61 61
        if len(args) != 1:
62 62
            raise CommandError("Please provide a server ID")
63 63

  
64
        vm = common.get_vm(args[0], for_update=True)
64
        vm = common.get_resource("server", args[0], for_update=True)
65 65

  
66 66
        displayname = options['displayname']
67 67

  
b/snf-cyclades-app/synnefo/logic/management/commands/server-list.py
1
# Copyright 2012-2013 GRNET S.A. All rights reserved.
1
# Copyright 2012-2014 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
......
36 36

  
37 37
from snf_django.management.commands import ListCommand
38 38
from synnefo.db.models import VirtualMachine
39
from synnefo.management.common import get_backend
39
from synnefo.management.common import get_resource
40 40
from synnefo.api.util import get_image
41 41
from synnefo.settings import (CYCLADES_SERVICE_TOKEN as ASTAKOS_TOKEN,
42 42
                              ASTAKOS_AUTH_URL)
......
120 120
            self.filters["suspended"] = True
121 121

  
122 122
        if options["backend_id"]:
123
            backend = get_backend(options["backend_id"])
123
            backend = get_resource("backend", options["backend_id"])
124 124
            self.filters["backend"] = backend.id
125 125

  
126 126
        if options["build"]:
b/snf-cyclades-app/synnefo/logic/management/commands/server-modify.py
1
# Copyright 2013 GRNET S.A. All rights reserved.
1
# Copyright 2013-2014 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
......
35 35

  
36 36
from django.db import transaction
37 37
from django.core.management.base import BaseCommand, CommandError
38
from synnefo.management.common import (get_vm, get_flavor, convert_api_faults,
38
from synnefo.management.common import (get_resource, convert_api_faults,
39 39
                                       wait_server_task)
40 40
from snf_django.management.utils import parse_bool
41 41
from synnefo.logic import servers
......
93 93
        if len(args) != 1:
94 94
            raise CommandError("Please provide a server ID")
95 95

  
96
        server = get_vm(args[0], for_update=True)
96
        server = get_resource("server", args[0], for_update=True)
97 97

  
98 98
        new_name = options.get("name", None)
99 99
        if new_name is not None:
......
123 123
        wait = parse_bool(options["wait"])
124 124
        new_flavor_id = options.get("flavor")
125 125
        if new_flavor_id is not None:
126
            new_flavor = get_flavor(new_flavor_id)
126
            new_flavor = get_resource("flavor", new_flavor_id)
127 127
            old_flavor = server.flavor
128 128
            msg = "Resizing server '%s' from flavor '%s' to '%s'.\n"
129 129
            self.stdout.write(msg % (server, old_flavor, new_flavor))
b/snf-cyclades-app/synnefo/logic/management/commands/server-remove.py
1
# Copyright 2013 GRNET S.A. All rights reserved.
1
# Copyright 2013-2014 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
......
34 34
from optparse import make_option
35 35

  
36 36
from django.core.management.base import CommandError
37
from synnefo.management.common import (get_vm, convert_api_faults,
37
from synnefo.management.common import (get_resource, convert_api_faults,
38 38
                                       wait_server_task)
39 39
from synnefo.logic import servers
40 40
from snf_django.management.commands import RemoveCommand
......
68 68
        for server_id in args:
69 69
            self.stdout.write("\n")
70 70
            try:
71
                server = get_vm(server_id)
71
                server = get_resource("server", server_id, for_update=True)
72 72

  
73 73
                self.stdout.write("Trying to remove server '%s' from backend "
74 74
                                  "'%s' \n" % (server.backend_vm_id,
b/snf-cyclades-app/synnefo/logic/management/commands/server-show.py
1
# Copyright 2012 GRNET S.A. All rights reserved.
1
# Copyright 2012-2014 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 django.core.management.base import CommandError
35 35
from snf_django.management.commands import SynnefoCommand
36
from synnefo.management.common import (format_vm_state, get_vm,
36
from synnefo.management.common import (format_vm_state, get_resource,
37 37
                                       get_image)
38 38
from snf_django.lib.astakos import UserCache
39 39
from synnefo.settings import (CYCLADES_SERVICE_TOKEN as ASTAKOS_TOKEN,
......
49 49
        if len(args) != 1:
50 50
            raise CommandError("Please provide a server ID")
51 51

  
52
        server = get_vm(args[0])
52
        server = get_resource("server", args[0])
53 53

  
54 54
        flavor = '%s (%s)' % (server.flavor.id, server.flavor.name)
55 55
        userid = server.userid
b/snf-cyclades-app/synnefo/logic/management/commands/stats-cyclades.py
1
# Copyright 2013 GRNET S.A. All rights reserved.
1
# Copyright 2013-2014 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
......
31 31
# interpreted as representing official policies, either expressed
32 32
# or implied, of GRNET S.A.
33 33

  
34

  
35 34
import json
36 35
import string
37 36

  
......
40 39
from snf_django.management.utils import pprint_table, parse_bool
41 40

  
42 41
from snf_django.management.commands import SynnefoCommand, CommandError
43
from synnefo.management.common import get_backend
42
from synnefo.management.common import get_resource
44 43
from synnefo.admin import stats as statistics
45 44

  
46 45

  
......
87 86

  
88 87
    def handle(self, *args, **options):
89 88
        if options["backend"] is not None:
90
            backend = get_backend(options["backend"])
89
            backend = get_resource("backend", options["backend"])
91 90
        else:
92 91
            backend = None
93 92

  
b/snf-cyclades-app/synnefo/logic/management/commands/subnet-create.py
1
# Copyright 2013 GRNET S.A. All rights reserved.
1
# Copyright 2013-2014 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
......
39 39
from synnefo.management import pprint
40 40
from synnefo.logic import subnets
41 41

  
42
import ipaddr
43

  
44 42
HELP_MSG = """
45 43

  
46 44
Create a new subnet without authenticating the user. The limit of one
......
103 101
        if not cidr:
104 102
            raise CommandError("cidr is mandatory")
105 103

  
106
        user_id = common.get_network(network_id).userid
104
        user_id = common.get_resource("network", network_id).userid
107 105
        name = options["name"] or ""
108 106
        allocation_pools = options["allocation_pools"]
109 107
        ipversion = options["ipversion"] or 4
b/snf-cyclades-app/synnefo/logic/management/commands/subnet-inspect.py
31 31
# interpreted as representing official policies, either expressed
32 32
# or implied, of GRNET S.A.
33 33

  
34
from optparse import make_option
34
#from optparse import make_option
35 35

  
36 36
from django.core.management.base import BaseCommand, CommandError
37 37
from synnefo.management import pprint, common
......
46 46
        if len(args) != 1:
47 47
            raise CommandError("Please provide a subnet ID.")
48 48

  
49
        subnet = common.get_subnet(args[0])
49
        subnet = common.get_resource("subnet", args[0])
50 50

  
51 51
        pprint.pprint_subnet_in_db(subnet, stdout=self.stdout)
52 52
        self.stdout.write("\n\n")
b/snf-cyclades-app/synnefo/logic/management/commands/subnet-modify.py
1
# Copyright 2013 GRNET S.A. All rights reserved.
1
# Copyright 2013-2014 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
......
66 66
        if not name:
67 67
            raise CommandError("--name is mandatory")
68 68

  
69
        subnet = common.get_subnet(subnet_id)
70
        user_id = common.get_network(subnet.network.id).userid
69
        subnet = common.get_resource("subnet", subnet_id, for_update=True)
70
        user_id = common.get_resource("network", subnet.network.id).userid
71 71

  
72 72
        subnets.update_subnet(sub_id=subnet_id,
73 73
                              name=name,
b/snf-cyclades-app/synnefo/management/common.py
1
# Copyright 2012 GRNET S.A. All rights reserved.
1
# Copyright 2012-2014 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
......
35 35
from synnefo.db.models import (Backend, VirtualMachine, Network,
36 36
                               Flavor, IPAddress, Subnet,
37 37
                               BridgePoolTable, MacPrefixPoolTable,
38
                               NetworkInterface, IPAddressLog)
38
                               NetworkInterface)
39 39
from functools import wraps
40 40

  
41
from django.conf import settings
41 42
from snf_django.lib.api import faults
42 43
from synnefo.api import util
43 44
from synnefo.logic import backend as backend_mod
44 45
from synnefo.logic.rapi import GanetiApiError, GanetiRapiClient
45 46
from synnefo.logic.utils import (id_from_instance_name,
46
                                 id_from_network_name)
47

  
47
                                 id_from_network_name,
48
                                 id_from_nic_name)
49
from django.core.exceptions import ObjectDoesNotExist
48 50
import logging
49 51
log = logging.getLogger(__name__)
50 52

  
......
55 57
    else:
56 58
        return vm.operstate
57 59

  
60
RESOURCE_MAP = {
61
    "backend": Backend.objects,
62
    "flavor": Flavor.objects,
63
    "server": VirtualMachine.objects,
64
    "network": Network.objects,
65
    "subnet": Subnet.objects,
66
    "port": NetworkInterface.objects,
67
    "floating-ip": IPAddress.objects.filter(floating_ip=True)}
68

  
69

  
70
def get_resource(name, value, for_update=False):
71
    """Get object from DB based by it's ID
72

  
73
    Helper function for getting an object from DB by it's DB and raising
74
    appropriate command line errors if the object does not exist or the
75
    ID is invalid.
58 76

  
59
def get_backend(backend_id):
77
    """
78
    objects = RESOURCE_MAP[name]
79
    if name == "floating-ip":
80
        capital_name = "Floating IP"
81
    else:
82
        capital_name = name.capitalize()
83

  
84
    if name in ["server", "network", "port"]:
85
        try:
86
            if value.startswith(settings.BACKEND_PREFIX_ID):
87
                if name == "server":
88
                    value = id_from_instance_name(value)
89
                elif name == "network":
90
                    value = id_from_network_name(value)
91
                elif name == "port":
92
                    value = id_from_nic_name(value)
93
        except ValueError:
94
            raise CommandError("Invalid {} ID: {}".format(capital_name, value))
95

  
96
    if for_update:
97
        objects = objects.select_for_update()
60 98
    try:
61
        backend_id = int(backend_id)
62
        return Backend.objects.get(id=backend_id)
63
    except ValueError:
64
        raise CommandError("Invalid Backend ID: %s" % backend_id)
65
    except Backend.DoesNotExist:
66
        raise CommandError("Backend with ID %s not found in DB. "
67
                           " Use snf-manage backend-list to find"
68
                           " out available backend IDs." % backend_id)
99
        return objects.get(id=value)
100
    except ObjectDoesNotExist:
101
        msg = ("{0} with ID {1} does not exist. Use {2}-list to find out"
102
               " available {2} IDs.")
103
        raise CommandError(msg.format(capital_name, value, name))
104
    except (ValueError, TypeError):
105
        raise CommandError("Invalid {} ID: {}".format(capital_name, value))
69 106

  
70 107

  
71 108
def get_image(image_id, user_id):
......
80 117
        raise CommandError("image-id is mandatory")
81 118

  
82 119

  
83
def get_vm(server_id, for_update=False):
84
    """Get a VirtualMachine object by its ID.
85

  
86
    @type server_id: int or string
87
    @param server_id: The server's DB id or the Ganeti name
88

  
89
    """
90
    try:
91
        server_id = int(server_id)
92
    except (ValueError, TypeError):
93
        try:
94
            server_id = id_from_instance_name(server_id)
95
        except VirtualMachine.InvalidBackendIdError:
96
            raise CommandError("Invalid server ID: %s" % server_id)
97

  
98
    try:
99
        objs = VirtualMachine.objects
100
        if for_update:
101
            objs = objs.select_for_update()
102
        return objs.get(id=server_id)
103
    except VirtualMachine.DoesNotExist:
104
        raise CommandError("Server with ID %s not found in DB."
105
                           " Use snf-manage server-list to find out"
106
                           " available server IDs." % server_id)
107

  
108

  
109
def get_network(network_id, for_update=True):
110
    """Get a Network object by its ID.
111

  
112
    @type network_id: int or string
113
    @param network_id: The networks DB id or the Ganeti name
114

  
115
    """
116

  
117
    try:
118
        network_id = int(network_id)
119
    except (ValueError, TypeError):
120
        try:
121
            network_id = id_from_network_name(network_id)
122
        except Network.InvalidBackendIdError:
123
            raise CommandError("Invalid network ID: %s" % network_id)
124

  
125
    networks = Network.objects
126
    if for_update:
127
        networks = networks.select_for_update()
128
    try:
129
        return networks.get(id=network_id)
130
    except Network.DoesNotExist:
131
        raise CommandError("Network with ID %s not found in DB."
132
                           " Use snf-manage network-list to find out"
133
                           " available network IDs." % network_id)
134

  
135

  
136
def get_subnet(subnet_id, for_update=True):
137
    """Get a Subnet object by its ID."""
138
    try:
139
        subet_id = int(subnet_id)
140
    except (ValueError, TypeError):
141
        raise CommandError("Invalid subnet ID: %s" % subnet_id)
142

  
143
    try:
144
        subnets = Subnet.objects
145
        if for_update:
146
            subnets.select_for_update()
147
        return subnets.get(id=subnet_id)
148
    except Subnet.DoesNotExist:
149
        raise CommandError("Subnet with ID %s not found in DB."
150
                           " Use snf-manage subnet-list to find out"
151
                           " available subnet IDs" % subnet_id)
152

  
153

  
154
def get_port(port_id, for_update=True):
155
    """Get a port object by its ID."""
156
    try:
157
        port_id = int(port_id)
158
    except (ValueError, TypeError):
159
        raise CommandError("Invalid port ID: %s" % port_id)
160

  
161
    try:
162
        ports = NetworkInterface.objects
163
        if for_update:
164
            ports.select_for_update()
165
        return ports.get(id=port_id)
166
    except NetworkInterface.DoesNotExist:
167
        raise CommandError("Port with ID %s not found in DB."
168
                           " Use snf-manage port-list to find out"
169
                           " available port IDs" % port_id)
170

  
171

  
172
def get_flavor(flavor_id, for_update=False):
173
    try:
174
        flavor_id = int(flavor_id)
175
        objs = Flavor.objects
176
        if for_update:
177
            objs = objs.select_for_update()
178
        return objs.get(id=flavor_id)
179
    except ValueError:
180
        raise CommandError("Invalid flavor ID: %s", flavor_id)
181
    except Flavor.DoesNotExist:
182
        raise CommandError("Flavor with ID %s not found in DB."
183
                           " Use snf-manage flavor-list to find out"
184
                           " available flavor IDs." % flavor_id)
185

  
186

  
187
def get_floating_ip_by_address(address, for_update=False):
188
    try:
189
        objects = IPAddress.objects
190
        if for_update:
191
            objects = objects.select_for_update()
192
        return objects.get(floating_ip=True, address=address, deleted=False)
193
    except IPAddress.DoesNotExist:
194
        raise CommandError("Floating IP does not exist.")
195

  
196

  
197
def get_floating_ip_log_by_address(address):
198
    try:
199
        objects = IPAddressLog.objects
200
        return objects.filter(address=address).order_by("released_at")
201
    except IPAddressLog.DoesNotExist:
202
        raise CommandError("Floating IP does not exist or it hasn't be"
203
                           "attached to any server yet")
204

  
205

  
206
def get_floating_ip_by_id(floating_ip_id, for_update=False):
207
    try:
208
        floating_ip_id = int(floating_ip_id)
209
    except (ValueError, TypeError):
210
        raise CommandError("Invalid floating-ip ID: %s" % floating_ip_id)
211

  
212
    try:
213
        objects = IPAddress.objects
214
        if for_update:
215
            objects = objects.select_for_update()
216
        return objects.get(floating_ip=True, id=floating_ip_id, deleted=False)
217
    except IPAddress.DoesNotExist:
218
        raise CommandError("Floating IP %s does not exist." % floating_ip_id)
219

  
220

  
221 120
def check_backend_credentials(clustername, port, username, password):
222 121
    try:
223 122
        client = GanetiRapiClient(clustername, port, username, password)
b/snf-cyclades-app/synnefo/tools/add_unique_name_to_nics
29 29

  
30 30
from django.db import close_connection
31 31
from synnefo.db.models import Backend, pooled_rapi_client
32
from synnefo.management.common import get_backend
32
from synnefo.management.common import get_resource
33 33

  
34 34
import logging
35 35
logger = logging.getLogger("migrate_nics")
......
67 67
    options, args = parser.parse_args()
68 68

  
69 69
    if options.backend_id:
70
        backends = [get_backend(options.backend_id)]
70
        backends = [get_resource("backend", options.backend_id)]
71 71
    else:
72 72
        if Backend.objects.filter(offline=True).exists():
73 73
            msg = "Can not update intances. An 'offline' backend exists."

Also available in: Unified diff