Statistics
| Branch: | Tag: | Revision:

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

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

    
45
import sys
46

    
47

    
48
HELP_MSG = """
49

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

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

59
"""
60

    
61

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

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

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

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

    
107
        instance_name = args[0]
108

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

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

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

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

    
128

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

    
134
    backend_client = backend.get_client()
135

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

    
145
    if new_public_nic:
146
        remove_instance_nics(instance, backend_client,
147
                             stream=stream)
148
        (network, address) = allocate_public_address(backend)
149
        if address is None:
150
            raise CommandError("Can not allocate a public address."
151
                               " No available public network.")
152
        nic = {'ip': address, 'network': network.backend_id}
153
        add_public_nic(instance_name, nic, backend_client,
154
                       stream=stream)
155
    else:
156
        check_instance_nics(instance)
157

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

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

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

    
174
    backend.put_client(backend_client)
175
    return
176

    
177

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

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

    
189
    return Flavor.objects.get_or_create(disk=disk, disk_template=disk_template,
190
                                        cpu=cpu, ram=ram)
191

    
192

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

    
205

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

    
218

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

    
226

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

    
237

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

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

    
247

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