Statistics
| Branch: | Tag: | Revision:

root / snf-cyclades-app / synnefo / management / common.py @ 1bf69a52

History | View | Annotate | Download (9.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 django.core.management import CommandError
35
from synnefo.db.models import (Backend, VirtualMachine, Network,
36
                               Flavor, IPAddress, Subnet,
37
                               BridgePoolTable, MacPrefixPoolTable,
38
                               NetworkInterface, IPAddressLog)
39
from functools import wraps
40

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

    
48
import logging
49
log = logging.getLogger(__name__)
50

    
51

    
52
def format_vm_state(vm):
53
    if vm.operstate == "BUILD":
54
        return "BUILD(" + str(vm.buildpercentage) + "%)"
55
    else:
56
        return vm.operstate
57

    
58

    
59
def get_backend(backend_id):
60
    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)
69

    
70

    
71
def get_image(image_id, user_id):
72
    if image_id:
73
        try:
74
            return util.get_image_dict(image_id, user_id)
75
        except faults.ItemNotFound:
76
            raise CommandError("Image with ID %s not found."
77
                               " Use snf-manage image-list to find"
78
                               " out available image IDs." % image_id)
79
    else:
80
        raise CommandError("image-id is mandatory")
81

    
82

    
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
def check_backend_credentials(clustername, port, username, password):
222
    try:
223
        client = GanetiRapiClient(clustername, port, username, password)
224
        # This command will raise an exception if there is no
225
        # write-access
226
        client.ModifyCluster()
227
    except GanetiApiError as e:
228
        raise CommandError(e)
229

    
230
    info = client.GetInfo()
231
    info_name = info['name']
232
    if info_name != clustername:
233
        raise CommandError("Invalid clustername value. Please use the"
234
                           " Ganeti Cluster name: %s" % info_name)
235

    
236

    
237
def convert_api_faults(func):
238
    @wraps(func)
239
    def wrapper(*args, **kwargs):
240
        try:
241
            return func(*args, **kwargs)
242
        except faults.Fault as e:
243
            raise CommandError(e.message)
244
    return wrapper
245

    
246

    
247
class Omit(object):
248
    pass
249

    
250

    
251
def wait_server_task(server, wait, stdout):
252
    jobID = server.task_job_id
253
    if wait:
254
        msg = "Issued job '%s'. Waiting to complete...\n"
255
        stdout.write(msg % jobID)
256
        client = server.get_client()
257
        wait_ganeti_job(client, jobID, stdout)
258
    else:
259
        msg = "Issued job '%s'.\n"
260
        stdout.write(msg % jobID)
261

    
262

    
263
def wait_ganeti_job(client, jobID, stdout):
264
    status, error = backend_mod.wait_for_job(client, jobID)
265
    if status == "success":
266
        stdout.write("Job finished successfully.\n")
267
    else:
268
        raise CommandError("Job failed! Error: %s\n" % error)
269

    
270

    
271
def pool_table_from_type(type_):
272
    if type_ == "mac-prefix":
273
        return MacPrefixPoolTable
274
    elif type_ == "bridge":
275
        return BridgePoolTable
276
    # elif type == "ip":
277
    #     return IPPoolTable
278
    else:
279
        raise ValueError("Invalid pool type")