Statistics
| Branch: | Tag: | Revision:

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

History | View | Annotate | Download (8.9 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
        ports = NetworkInterface.objects
155
        if for_update:
156
            ports.select_for_update()
157
        return ports.get(id=port_id)
158
    except NetworkInterface.DoesNotExist:
159
        raise CommandError("Port with ID %s not found in DB."
160
                           " Use snf-manage port-list to find out"
161
                           " available port IDs" % port_id)
162

    
163

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

    
175

    
176
def get_floating_ip_by_address(address, for_update=False):
177
    try:
178
        objects = IPAddress.objects
179
        if for_update:
180
            objects = objects.select_for_update()
181
        return objects.get(floating_ip=True, address=address, deleted=False)
182
    except IPAddress.DoesNotExist:
183
        raise CommandError("Floating IP does not exist.")
184

    
185

    
186
def get_floating_ip_log_by_address(address):
187
    try:
188
        objects = IPAddressLog.objects
189
        return objects.filter(address=address).order_by("released_at")
190
    except IPAddressLog.DoesNotExist:
191
        raise CommandError("Floating IP does not exist or it hasn't be"
192
                           "attached to any server yet")
193

    
194

    
195
def get_floating_ip_by_id(floating_ip_id, for_update=False):
196
    try:
197
        objects = IPAddress.objects
198
        if for_update:
199
            objects = objects.select_for_update()
200
        return objects.get(floating_ip=True, id=floating_ip_id, deleted=False)
201
    except IPAddress.DoesNotExist:
202
        raise CommandError("Floating IP does not exist.")
203

    
204

    
205
def check_backend_credentials(clustername, port, username, password):
206
    try:
207
        client = GanetiRapiClient(clustername, port, username, password)
208
        # This command will raise an exception if there is no
209
        # write-access
210
        client.ModifyCluster()
211
    except GanetiApiError as e:
212
        raise CommandError(e)
213

    
214
    info = client.GetInfo()
215
    info_name = info['name']
216
    if info_name != clustername:
217
        raise CommandError("Invalid clustername value. Please use the"
218
                           " Ganeti Cluster name: %s" % info_name)
219

    
220

    
221
def convert_api_faults(func):
222
    @wraps(func)
223
    def wrapper(*args, **kwargs):
224
        try:
225
            return func(*args, **kwargs)
226
        except faults.Fault as e:
227
            raise CommandError(e.message)
228
    return wrapper
229

    
230

    
231
class Omit(object):
232
    pass
233

    
234

    
235
def wait_server_task(server, wait, stdout):
236
    jobID = server.task_job_id
237
    if wait:
238
        msg = "Issued job '%s'. Waiting to complete...\n"
239
        stdout.write(msg % jobID)
240
        client = server.get_client()
241
        wait_ganeti_job(client, jobID, stdout)
242
    else:
243
        msg = "Issued job '%s'.\n"
244
        stdout.write(msg % jobID)
245

    
246

    
247
def wait_ganeti_job(client, jobID, stdout):
248
    status, error = backend_mod.wait_for_job(client, jobID)
249
    if status == "success":
250
        stdout.write("Job finished successfully.\n")
251
    else:
252
        raise CommandError("Job failed! Error: %s\n" % error)
253

    
254

    
255
def pool_table_from_type(type_):
256
    if type_ == "mac-prefix":
257
        return MacPrefixPoolTable
258
    elif type_ == "bridge":
259
        return BridgePoolTable
260
    # elif type == "ip":
261
    #     return IPPoolTable
262
    else:
263
        raise ValueError("Invalid pool type")