Statistics
| Branch: | Tag: | Revision:

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

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 BaseCommand, 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 synnefo.management.common import check_backend_credentials
37
from snf_django.management.utils import pprint_table
38

    
39

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

    
42

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

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

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

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

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

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

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

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

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

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

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

    
111
            if not initialize:
112
                return
113

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

    
119
            table = [[str(resources[x]) for x in attr]]
120
            pprint_table(self.stdout, 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, public=True)
126
            if not networks:
127
                return
128

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

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

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