Statistics
| Branch: | Tag: | Revision:

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

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, connect_to_network
42
from synnefo.logic.rapi import GanetiApiError
43
from synnefo.logic import servers
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 not new_public_nic:
147
        check_instance_nics(instance)
148

    
149
    shutdown_instance(instance, backend_client, stream=stream)
150

    
151
    # Create the VM in DB
152
    stream.write("Creating VM entry in DB\n")
153
    vm = VirtualMachine.objects.create(name=instance_name,
154
                                       backend=backend,
155
                                       userid=user_id,
156
                                       imageid=image_id,
157
                                       flavor=flavor)
158

    
159
    quotas.issue_and_accept_commission(vm)
160

    
161
    if new_public_nic:
162
        remove_instance_nics(instance, backend_client,
163
                             stream=stream)
164

    
165
    # Rename instance
166
    rename_instance(instance_name, vm.backend_vm_id, backend_client,
167
                    stream)
168

    
169
    if new_public_nic:
170
        ports = servers.create_instance_ports(user_id)
171
        stream.write("Adding new NICs to server")
172
        [servers.associate_port_with_machine(port, vm)
173
         for port in ports]
174
        [connect_to_network(vm, port) for port in ports]
175

    
176
    # Startup instance
177
    startup_instance(vm.backend_vm_id, backend_client, stream=stream)
178

    
179
    backend.put_client(backend_client)
180
    return
181

    
182

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

    
189
    disk = disk_sizes[0]
190
    disk_template = instance['disk_template']
191
    cpu = beparams['vcpus']
192
    ram = beparams['memory']
193

    
194
    return Flavor.objects.get_or_create(disk=disk, disk_template=disk_template,
195
                                        cpu=cpu, ram=ram)
196

    
197

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

    
211

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

    
224

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

    
232

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

    
242

    
243
def rename_instance(old_name, new_name, backend_client, stream=sys.stdout):
244
    stream.write("Renaming instance to %s\n" % new_name)
245

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

    
252

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