Statistics
| Branch: | Tag: | Revision:

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

History | View | Annotate | Download (6.5 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
from optparse import make_option
31
from django.core.management.base import CommandError
32

    
33
from synnefo.db.models import Backend, Network
34
from django.db.utils import IntegrityError
35
from synnefo.logic import backend as backend_mod
36
from snf_django.management.commands import SynnefoCommand
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(SynnefoCommand):
45
    can_import_settings = True
46

    
47
    help = 'Create a new backend.'
48
    option_list = SynnefoCommand.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
        self.create_backend(clustername, port, username, password,
89
                            hypervisor=options["hypervisor"],
90
                            initialize=options["init"])
91

    
92
    def create_backend(self, clustername, port, username, password,
93
                       hypervisor=None, initialize=True):
94
            kw = {"clustername": clustername,
95
                  "port": port,
96
                  "username": username,
97
                  "password": password,
98
                  "drained": True}
99

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

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

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

    
112
            if not initialize:
113
                return
114

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

    
120
            table = [[str(resources[x]) for x in attr]]
121
            pprint_table(self.stdout, table, attr)
122

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

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

    
130
            self.stderr.write("Creating the following public:\n")
131
            headers = ("ID", "Name", 'IPv4 Subnet',
132
                       "IPv6 Subnet", 'Mac Prefix')
133
            table = []
134

    
135
            for net in networks:
136
                subnet4 = net.subnet4.cidr if net.subnet4 else None
137
                subnet6 = net.subnet6.cidr if net.subnet6 else None
138
                table.append((net.id, net.backend_id, subnet4,
139
                              subnet6, str(net.mac_prefix)))
140
            pprint_table(self.stdout, table, headers)
141

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