Statistics
| Branch: | Tag: | Revision:

root / snf-cyclades-app / synnefo / management / common.py @ 4a769fc0

History | View | Annotate | Download (9.2 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):
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
        return VirtualMachine.objects.get(id=server_id)
100
    except VirtualMachine.DoesNotExist:
101
        raise CommandError("Server with ID %s not found in DB."
102
                           " Use snf-manage server-list to find out"
103
                           " available server IDs." % server_id)
104

    
105

    
106
def get_network(network_id, for_update=True):
107
    """Get a Network object by its ID.
108

109
    @type network_id: int or string
110
    @param network_id: The networks DB id or the Ganeti name
111

112
    """
113

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

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

    
132

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

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

    
150

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

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

    
168

    
169
def get_flavor(flavor_id):
170
    try:
171
        flavor_id = int(flavor_id)
172
        return Flavor.objects.get(id=flavor_id)
173
    except ValueError:
174
        raise CommandError("Invalid flavor ID: %s", flavor_id)
175
    except Flavor.DoesNotExist:
176
        raise CommandError("Flavor with ID %s not found in DB."
177
                           " Use snf-manage flavor-list to find out"
178
                           " available flavor IDs." % flavor_id)
179

    
180

    
181
def get_floating_ip_by_address(address, for_update=False):
182
    try:
183
        objects = IPAddress.objects
184
        if for_update:
185
            objects = objects.select_for_update()
186
        return objects.get(floating_ip=True, address=address, deleted=False)
187
    except IPAddress.DoesNotExist:
188
        raise CommandError("Floating IP does not exist.")
189

    
190

    
191
def get_floating_ip_log_by_address(address):
192
    try:
193
        objects = IPAddressLog.objects
194
        return objects.filter(address=address).order_by("released_at")
195
    except IPAddressLog.DoesNotExist:
196
        raise CommandError("Floating IP does not exist or it hasn't be"
197
                           "attached to any server yet")
198

    
199

    
200
def get_floating_ip_by_id(floating_ip_id, for_update=False):
201
    try:
202
        floating_ip_id = int(floating_ip_id)
203
    except (ValueError, TypeError):
204
        raise CommandError("Invalid floating-ip ID: %s" % floating_ip_id)
205

    
206
    try:
207
        objects = IPAddress.objects
208
        if for_update:
209
            objects = objects.select_for_update()
210
        return objects.get(floating_ip=True, id=floating_ip_id, deleted=False)
211
    except IPAddress.DoesNotExist:
212
        raise CommandError("Floating IP %s does not exist." % floating_ip_id)
213

    
214

    
215
def check_backend_credentials(clustername, port, username, password):
216
    try:
217
        client = GanetiRapiClient(clustername, port, username, password)
218
        # This command will raise an exception if there is no
219
        # write-access
220
        client.ModifyCluster()
221
    except GanetiApiError as e:
222
        raise CommandError(e)
223

    
224
    info = client.GetInfo()
225
    info_name = info['name']
226
    if info_name != clustername:
227
        raise CommandError("Invalid clustername value. Please use the"
228
                           " Ganeti Cluster name: %s" % info_name)
229

    
230

    
231
def convert_api_faults(func):
232
    @wraps(func)
233
    def wrapper(*args, **kwargs):
234
        try:
235
            return func(*args, **kwargs)
236
        except faults.Fault as e:
237
            raise CommandError(e.message)
238
    return wrapper
239

    
240

    
241
class Omit(object):
242
    pass
243

    
244

    
245
def wait_server_task(server, wait, stdout):
246
    jobID = server.task_job_id
247
    if wait:
248
        msg = "Issued job '%s'. Waiting to complete...\n"
249
        stdout.write(msg % jobID)
250
        client = server.get_client()
251
        wait_ganeti_job(client, jobID, stdout)
252
    else:
253
        msg = "Issued job '%s'.\n"
254
        stdout.write(msg % jobID)
255

    
256

    
257
def wait_ganeti_job(client, jobID, stdout):
258
    status, error = backend_mod.wait_for_job(client, jobID)
259
    if status == "success":
260
        stdout.write("Job finished successfully.\n")
261
    else:
262
        raise CommandError("Job failed! Error: %s\n" % error)
263

    
264

    
265
def pool_table_from_type(type_):
266
    if type_ == "mac-prefix":
267
        return MacPrefixPoolTable
268
    elif type_ == "bridge":
269
        return BridgePoolTable
270
    # elif type == "ip":
271
    #     return IPPoolTable
272
    else:
273
        raise ValueError("Invalid pool type")