Statistics
| Branch: | Tag: | Revision:

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

History | View | Annotate | Download (8.7 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
        subnets = Subnet.objects
137
        if for_update:
138
            subnets.select_for_update()
139
        return subnets.get(id=subnet_id)
140
    except Subnet.DoesNotExist:
141
        raise CommandError("Subnet with ID %s not found in DB."
142
                           " Use snf-manage subnet-list to find out"
143
                           " available subnet IDs" % subnet_id)
144

    
145

    
146
def get_port(port_id, for_update=True):
147
    """Get a port object by its ID."""
148
    try:
149
        ports = NetworkInterface.objects
150
        if for_update:
151
            ports.select_for_update()
152
        return ports.get(id=port_id)
153
    except NetworkInterface.DoesNotExist:
154
        raise CommandError("Port with ID %s not found in DB."
155
                           " Use snf-manage port-list to find out"
156
                           " available port IDs" % port_id)
157

    
158

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

    
170

    
171
def get_floating_ip_by_address(address, for_update=False):
172
    try:
173
        objects = IPAddress.objects
174
        if for_update:
175
            objects = objects.select_for_update()
176
        return objects.get(floating_ip=True, address=address, deleted=False)
177
    except IPAddress.DoesNotExist:
178
        raise CommandError("Floating IP does not exist.")
179

    
180

    
181
def get_floating_ip_log_by_address(address):
182
    try:
183
        objects = IPAddressLog.objects
184
        return objects.filter(address=address).order_by("released_at")
185
    except IPAddressLog.DoesNotExist:
186
        raise CommandError("Floating IP does not exist or it hasn't be"
187
                           "attached to any server yet")
188

    
189

    
190
def get_floating_ip_by_id(floating_ip_id, for_update=False):
191
    try:
192
        objects = IPAddress.objects
193
        if for_update:
194
            objects = objects.select_for_update()
195
        return objects.get(floating_ip=True, id=floating_ip_id, deleted=False)
196
    except IPAddress.DoesNotExist:
197
        raise CommandError("Floating IP does not exist.")
198

    
199

    
200
def check_backend_credentials(clustername, port, username, password):
201
    try:
202
        client = GanetiRapiClient(clustername, port, username, password)
203
        # This command will raise an exception if there is no
204
        # write-access
205
        client.ModifyCluster()
206
    except GanetiApiError as e:
207
        raise CommandError(e)
208

    
209
    info = client.GetInfo()
210
    info_name = info['name']
211
    if info_name != clustername:
212
        raise CommandError("Invalid clustername value. Please use the"
213
                           " Ganeti Cluster name: %s" % info_name)
214

    
215

    
216
def convert_api_faults(func):
217
    @wraps(func)
218
    def wrapper(*args, **kwargs):
219
        try:
220
            return func(*args, **kwargs)
221
        except faults.Fault as e:
222
            raise CommandError(e.message)
223
    return wrapper
224

    
225

    
226
class Omit(object):
227
    pass
228

    
229

    
230
def wait_server_task(server, wait, stdout):
231
    jobID = server.task_job_id
232
    if wait:
233
        msg = "Issued job '%s'. Waiting to complete...\n"
234
        stdout.write(msg % jobID)
235
        client = server.get_client()
236
        wait_ganeti_job(client, jobID, stdout)
237
    else:
238
        msg = "Issued job '%s'.\n"
239
        stdout.write(msg % jobID)
240

    
241

    
242
def wait_ganeti_job(client, jobID, stdout):
243
    status, error = backend_mod.wait_for_job(client, jobID)
244
    if status == "success":
245
        stdout.write("Job finished successfully.\n")
246
    else:
247
        raise CommandError("Job failed! Error: %s\n" % error)
248

    
249

    
250
def pool_table_from_type(type_):
251
    if type_ == "mac-prefix":
252
        return MacPrefixPoolTable
253
    elif type_ == "bridge":
254
        return BridgePoolTable
255
    # elif type == "ip":
256
    #     return IPPoolTable
257
    else:
258
        raise ValueError("Invalid pool type")