Statistics
| Branch: | Tag: | Revision:

root / snf-cyclades-app / synnefo / logic / management / commands / backend-add.py @ 1da50fe3

History | View | Annotate | Download (6.1 kB)

1
# Copyright 2011-2013 GRNET S.A. All rights reserved.
2
#
3
# Redistribution and use in source and binary forms, with or without
4
# modification, are permitted provided that the following conditions
5
# are met:
6
#
7
#   1. Redistributions of source code must retain the above copyright
8
#      notice, this list of conditions and the following disclaimer.
9
#
10
#  2. Redistributions in binary form must reproduce the above copyright
11
#     notice, this list of conditions and the following disclaimer in the
12
#     documentation and/or other materials provided with the distribution.
13
#
14
# THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND
15
# ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
16
# IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
17
# ARE DISCLAIMED.  IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE
18
# FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
19
# DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
20
# OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
21
# HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
22
# LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
23
# OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
24
# SUCH DAMAGE.
25
#
26
# The views and conclusions contained in the software and documentation are
27
# those of the authors and should not be interpreted as representing official
28
# policies, either expressed or implied, of GRNET S.A.
29
#
30
import sys
31
from optparse import make_option
32
from django.core.management.base import BaseCommand, CommandError
33

    
34
from synnefo.db.models import Backend, Network
35
from django.db.utils import IntegrityError
36
from synnefo.logic import backend as backend_mod
37
from synnefo.management.common import check_backend_credentials
38
from snf_django.management.utils import pprint_table
39

    
40

    
41
HYPERVISORS = [h[0] for h in Backend.HYPERVISORS]
42

    
43

    
44
class Command(BaseCommand):
45
    can_import_settings = True
46

    
47
    help = 'Create a new backend.'
48
    option_list = BaseCommand.option_list + (
49
        make_option('--clustername', dest='clustername'),
50
        make_option('--port', dest='port', default=5080),
51
        make_option('--user', dest='username'),
52
        make_option('--pass', dest='password'),
53
        make_option(
54
            '--no-check',
55
            action='store_false',
56
            dest='check',
57
            default=True,
58
            help="Do not perform credentials check and resources update"),
59
        make_option(
60
            '--hypervisor',
61
            dest='hypervisor',
62
            default=None,
63
            choices=HYPERVISORS,
64
            metavar="|".join(HYPERVISORS),
65
            help="The hypervisor that the Ganeti backend uses"),
66
        make_option(
67
            '--no-init', action='store_false',
68
            dest='init', default=True,
69
            help="Do not perform initialization of the Backend Model")
70
    )
71

    
72
    def handle(self, *args, **options):
73
        if len(args) > 0:
74
            raise CommandError("Command takes no arguments")
75

    
76
        clustername = options['clustername']
77
        port = options['port']
78
        username = options['username']
79
        password = options['password']
80

    
81
        if not (clustername and username and password):
82
            raise CommandError("Clustername, user and pass must be supplied")
83

    
84
        # Ensure correctness of credentials
85
        if options['check']:
86
            check_backend_credentials(clustername, port, username, password)
87

    
88
        create_backend(clustername, port, username, password,
89
                       hypervisor=options["hypervisor"],
90
                       initialize=options["init"])
91

    
92

    
93
def create_backend(clustername, port, username, password, hypervisor=None,
94
                   initialize=True, stream=sys.stdout):
95
        kw = {"clustername": clustername,
96
              "port": port,
97
              "username": username,
98
              "password": password,
99
              "drained": True}
100

    
101
        if hypervisor:
102
            kw["hypervisor"] = hypervisor
103

    
104
        # Create the new backend in database
105
        try:
106
            backend = Backend.objects.create(**kw)
107
        except IntegrityError as e:
108
            raise CommandError("Cannot create backend: %s\n" % e)
109

    
110
        stream.write("Successfully created backend with id %d\n" % backend.id)
111

    
112
        if not initialize:
113
            return
114

    
115
        stream.write("Retrieving backend resources:\n")
116
        resources = backend_mod.get_physical_resources(backend)
117
        attr = ['mfree', 'mtotal', 'dfree', 'dtotal', 'pinst_cnt', 'ctotal']
118

    
119
        table = [[str(resources[x]) for x in attr]]
120
        pprint_table(stream, table, attr)
121

    
122
        backend_mod.update_backend_resources(backend, resources)
123
        backend_mod.update_backend_disk_templates(backend)
124

    
125
        networks = Network.objects.filter(deleted=False, floating_ip_pool=True)
126
        if not networks:
127
            return
128

    
129
        stream.write("Creating the follow networks:\n")
130
        headers = ('Name', 'Subnet', 'Gateway', 'Mac Prefix', 'Public')
131
        table = []
132

    
133
        for net in networks:
134
            table.append((net.backend_id, str(net.subnet), str(net.gateway),
135
                         str(net.mac_prefix), str(net.public)))
136
        pprint_table(stream, table, headers)
137

    
138
        for net in networks:
139
            net.create_backend_network(backend)
140
            result = backend_mod.create_network_synced(net, backend)
141
            if result[0] != "success":
142
                stream.write('\nError Creating Network %s: %s\n' %
143
                             (net.backend_id, result[1]))
144
            else:
145
                stream.write('Successfully created Network: %s\n' %
146
                             net.backend_id)
147
            result = backend_mod.connect_network_synced(network=net,
148
                                                        backend=backend)
149
            if result[0] != "success":
150
                stream.write('\nError Connecting Network %s: %s\n' %
151
                             (net.backend_id, result[1]))
152
            else:
153
                stream.write('Successfully connected Network: %s\n' %
154
                             net.backend_id)