Statistics
| Branch: | Tag: | Revision:

root / snf-cyclades-app / synnefo / api / management / commands / server-create.py @ 77fccdd4

History | View | Annotate | Download (5.6 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

    
38
from synnefo.db.models import VirtualMachine, Backend, Flavor
39
from synnefo.logic.backend import create_instance
40
from synnefo.logic.backend_allocator import BackendAllocator
41
from synnefo.api.util import get_image, allocate_public_address
42
from synnefo.api.faults import ItemNotFound
43

    
44

    
45
class Command(BaseCommand):
46
    help = "Create a new VM."
47

    
48
    output_transaction = True
49

    
50
    option_list = BaseCommand.option_list + (
51
            make_option("--backend-id", dest="backend_id",
52
                        help="ID of the Ganeti backend"),
53
            make_option("--name", dest="name",
54
                        help="Name of the server."),
55
            make_option("--user-id", dest="user_id",
56
                        help="ID of the Owner of the server."),
57
            make_option("--image-id", dest="image_id",
58
                        help="ID of the image."),
59
            make_option("--flavor-id", dest="flavor_id",
60
                        help="ID of the flavor"),
61
            make_option("--password", dest="password",
62
                        help="Password for the new server")
63
        )
64

    
65
    def handle(self, *args, **options):
66
        if args:
67
            raise CommandError("Command doesn't accept any arguments")
68

    
69
        name = options['name']
70
        user_id = options['user_id']
71
        backend_id = options['backend_id']
72
        image_id = options['image_id']
73
        flavor_id = options['flavor_id']
74
        password = options['password']
75

    
76
        if not name:
77
            raise CommandError("name is mandatory")
78
        if not user_id:
79
            raise CommandError("user-id is mandatory")
80
        if not password:
81
            raise CommandError("password is mandatory")
82

    
83
        # Get Flavor
84
        if flavor_id:
85
            try:
86
                flavor_id = int(flavor_id)
87
                flavor = Flavor.objects.get(id=flavor_id)
88
            except ValueError:
89
                raise CommandError("Invalid flavor-id")
90
            except Flavor.DoesNotExist:
91
                raise CommandError("Flavor not found")
92
        else:
93
            raise CommandError("flavor-id is mandatory")
94

    
95
        # Get Image
96
        if image_id:
97
            try:
98
                img = get_image(image_id, user_id)
99
            except ItemNotFound:
100
                raise CommandError("Image not found")
101

    
102
            properties = img.get('properties', {})
103
            image = {}
104
            image['backend_id'] = img['location']
105
            image['format'] = img['disk_format']
106
            image['metadata'] = dict((key.upper(), val) \
107
                                     for key, val in properties.items())
108
        else:
109
            raise CommandError("image-id is mandatory")
110

    
111
        # Get Backend
112
        if backend_id:
113
            try:
114
                backend_id = int(backend_id)
115
                backend = Backend.objects.get(id=backend_id)
116
            except (ValueError, Backend.DoesNotExist):
117
                raise CommandError("Invalid Backend ID")
118
        else:
119
            ballocator = BackendAllocator()
120
            backend = ballocator.allocate(user_id, flavor)
121
            if not backend:
122
                raise CommandError("Can not allocate VM")
123

    
124
        # Get Public address
125
        (network, address) = allocate_public_address(backend)
126
        if address is None:
127
            raise CommandError("Can not allocate a public address."\
128
                               " No available public network.")
129
        nic = {'ip': address, 'network': network.backend_id}
130

    
131
        # Create the VM in DB
132
        vm = VirtualMachine.objects.create(name=name,
133
                                           backend=backend,
134
                                           userid=user_id,
135
                                           imageid=image_id,
136
                                           flavor=flavor)
137

    
138
        # Create the instance in Backend
139
        jobID = create_instance(vm, nic, flavor, image, password, [])
140

    
141
        self.stdout.write("Creating VM %s with IP %s in Backend %s. JobID: %s\n" % \
142
                          (vm, address, backend, jobID))