Statistics
| Branch: | Tag: | Revision:

root / snf-cyclades-app / synnefo / api / management / commands / server-import.py @ 8d5795b4

History | View | Annotate | Download (9.5 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 optparse import make_option
35

    
36
from django.core.management.base import BaseCommand, CommandError
37
from synnefo.management import common
38

    
39
from synnefo.db.models import VirtualMachine, Network, Flavor
40
from synnefo.logic.utils import id_from_network_name, id_from_instance_name
41
from synnefo.logic.backend import wait_for_job
42
from synnefo.logic.rapi import GanetiApiError
43
from synnefo.api.util import allocate_public_address
44
from synnefo import quotas
45

    
46
import sys
47

    
48

    
49
HELP_MSG = """
50

51
Import an existing Ganeti instance into Synnefo, with the attributes specified
52
by the command line options. In order to be imported, the instance will be
53
turned off, renamed and then turned on again.
54

55
Importing an instance will fail, if the instance has NICs that are connected to
56
a network not belonging to Synnefo. You can either manually modify the instance
57
or use --new-nics option, that will remove all old NICs, and create a new one
58
connected to a public network of Synnefo.
59

60
"""
61

    
62

    
63
class Command(BaseCommand):
64
    help = "Import an existing Ganeti VM into Synnefo." + HELP_MSG
65
    args = "<ganeti_instance_name>"
66
    output_transaction = True
67

    
68
    option_list = BaseCommand.option_list + (
69
        make_option(
70
            "--backend-id",
71
            dest="backend_id",
72
            help="Unique identifier of the Ganeti backend that"
73
                 " hosts the VM. Use snf-manage backend-list to"
74
                 " find out available backends."),
75
        make_option(
76
            "--user-id",
77
            dest="user_id",
78
            help="Unique identifier of the owner of the server"),
79
        make_option(
80
            "--image-id",
81
            dest="image_id",
82
            default=None,
83
            help="Unique identifier of the image."
84
                 " Use snf-manage image-list to find out"
85
                 " available images."),
86
        make_option(
87
            "--flavor-id",
88
            dest="flavor_id",
89
            help="Unique identifier of the flavor"
90
                 " Use snf-manage flavor-list to find out"
91
                 " available flavors."),
92
        make_option(
93
            "--new-nics",
94
            dest='new_nics',
95
            default=False,
96
            action="store_true",
97
            help="Remove old NICs of instance, and create"
98
                 " a new NIC connected to a public network of"
99
                 " Synnefo.")
100
    )
101

    
102
    REQUIRED = ("user-id", "backend-id", "image-id", "flavor-id")
103

    
104
    def handle(self, *args, **options):
105
        if len(args) < 1:
106
            raise CommandError("Please specify a Ganeti instance")
107

    
108
        instance_name = args[0]
109

    
110
        try:
111
            id_from_instance_name(instance_name)
112
            raise CommandError("%s is already a synnefo instance")
113
        except:
114
            pass
115

    
116
        user_id = options['user_id']
117
        backend_id = options['backend_id']
118
        image_id = options['image_id']
119
        flavor_id = options['flavor_id']
120
        new_public_nic = options['new_nics']
121

    
122
        for field in self.REQUIRED:
123
            if not locals()[field.replace("-", "_")]:
124
                raise CommandError(field + " is mandatory")
125

    
126
        import_server(instance_name, backend_id, flavor_id, image_id, user_id,
127
                      new_public_nic, self.stdout)
128

    
129

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

    
135
    backend_client = backend.get_client()
136

    
137
    try:
138
        instance = backend_client.GetInstance(instance_name)
139
    except GanetiApiError as e:
140
        if e.code == 404:
141
            raise CommandError("Instance %s does not exist in backend %s"
142
                               % (instance_name, backend))
143
        else:
144
            raise CommandError("Unexpected error" + str(e))
145

    
146
    if new_public_nic:
147
        remove_instance_nics(instance, backend_client,
148
                             stream=stream)
149
        try:
150
            (network, address) = allocate_public_address(backend)
151
        except Exception as e:
152
            raise CommandError(e)
153
        nic = {'ip': address, 'network': network.backend_id}
154
        add_public_nic(instance_name, nic, backend_client,
155
                       stream=stream)
156
    else:
157
        check_instance_nics(instance)
158

    
159
    shutdown_instance(instance, backend_client, stream=stream)
160

    
161
    # Create the VM in DB
162
    stream.write("Creating VM entry in DB\n")
163
    vm = VirtualMachine.objects.create(name=instance_name,
164
                                       backend=backend,
165
                                       userid=user_id,
166
                                       imageid=image_id,
167
                                       flavor=flavor)
168

    
169
    quotas.issue_and_accept_commission(vm)
170
    # Rename instance
171
    rename_instance(instance_name, vm.backend_vm_id, backend_client,
172
                    stream)
173
    # Startup instance
174
    startup_instance(vm.backend_vm_id, backend_client, stream=stream)
175

    
176
    backend.put_client(backend_client)
177
    return
178

    
179

    
180
def flavor_from_instance(instance, flavor, stream=sys.stdout):
181
    beparams = instance['beparams']
182
    disk_sizes = instance['disk.sizes']
183
    if len(disk_sizes) != 1:
184
        stream.write("Instance has more than one disk.\n")
185

    
186
    disk = disk_sizes[0]
187
    disk_template = instance['disk_template']
188
    cpu = beparams['vcpus']
189
    ram = beparams['memory']
190

    
191
    return Flavor.objects.get_or_create(disk=disk, disk_template=disk_template,
192
                                        cpu=cpu, ram=ram)
193

    
194

    
195
def check_instance_nics(instance):
196
    instance_name = instance['name']
197
    networks = instance['nic.networks']
198
    try:
199
        networks = map(id_from_network_name, networks)
200
    except Network.InvalidBackendIdError:
201
        raise CommandError("Instance %s has NICs that do not belong to a"
202
                           " network belonging to synnefo. Either manually"
203
                           " modify the instance NICs or specify --new-nics"
204
                           " to clear the old NICs and create a new NIC to"
205
                           " a public network of synnefo." % instance_name)
206

    
207

    
208
def remove_instance_nics(instance, backend_client, stream=sys.stdout):
209
    instance_name = instance['name']
210
    ips = instance['nic.ips']
211
    nic_indexes = xrange(0, len(ips))
212
    op = map(lambda x: ('remove', x, {}), nic_indexes)
213
    stream.write("Removing instance nics\n")
214
    op.reverse()
215
    jobid = backend_client.ModifyInstance(instance_name, nics=op)
216
    (status, error) = wait_for_job(backend_client, jobid)
217
    if status != 'success':
218
        raise CommandError("Cannot rename instance: %s" % error)
219

    
220

    
221
def add_public_nic(instance_name, nic, backend_client, stream=sys.stdout):
222
    stream.write("Adding public NIC %s\n" % nic)
223
    jobid = backend_client.ModifyInstance(instance_name, nics=[('add', nic)])
224
    (status, error) = wait_for_job(backend_client, jobid)
225
    if status != 'success':
226
        raise CommandError("Cannot rename instance: %s" % error)
227

    
228

    
229
def shutdown_instance(instance, backend_client, stream=sys.stdout):
230
    instance_name = instance['name']
231
    if instance['status'] != 'ADMIN_down':
232
        stream.write("Instance is not down. Shutting down"
233
                     " instance\n")
234
        jobid = backend_client.ShutdownInstance(instance_name)
235
        (status, error) = wait_for_job(backend_client, jobid)
236
        if status != 'success':
237
            raise CommandError("Cannot shutdown instance: %s" % error)
238

    
239

    
240
def rename_instance(old_name, new_name, backend_client, stream=sys.stdout):
241
    stream.write("Renaming instance to %s\n" % new_name)
242

    
243
    jobid = backend_client.RenameInstance(old_name, new_name,
244
                                          ip_check=False, name_check=False)
245
    (status, error) = wait_for_job(backend_client, jobid)
246
    if status != 'success':
247
        raise CommandError("Cannot rename instance: %s" % error)
248

    
249

    
250
def startup_instance(name, backend_client, stream=sys.stdout):
251
    stream.write("Starting instance %s\n" % name)
252
    jobid = backend_client.StartupInstance(name)
253
    (status, error) = wait_for_job(backend_client, jobid)
254
    if status != 'success':
255
        raise CommandError("Cannot rename instance: %s" % error)