Statistics
| Branch: | Tag: | Revision:

root / snf-cyclades-app / synnefo / logic / management / commands / reconcile.py @ cc3f266e

History | View | Annotate | Download (12.4 kB)

1
# Copyright 2011-2012 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
"""Reconciliation management command
31

32
Management command to reconcile the contents of the Synnefo DB with
33
the state of the Ganeti backend. See docstring on top of
34
logic/reconciliation.py for a description of reconciliation rules.
35

36
"""
37
import sys
38
import datetime
39
import subprocess
40

    
41
from optparse import make_option
42

    
43
from django.core.management.base import BaseCommand, CommandError
44

    
45
from synnefo.db.models import VirtualMachine, Network
46
from synnefo.logic import reconciliation, backend, utils
47

    
48

    
49
class Command(BaseCommand):
50
    can_import_settings = True
51

    
52
    help = 'Reconcile contents of Synnefo DB with state of Ganeti backend'
53
    output_transaction = True  # The management command runs inside
54
                               # an SQL transaction
55
    option_list = BaseCommand.option_list + (
56
        make_option('--detect-stale', action='store_true', dest='detect_stale',
57
                    default=False, help='Detect stale VM entries in DB'),
58
        make_option('--detect-orphans', action='store_true',
59
                    dest='detect_orphans',
60
                    default=False, help='Detect orphan instances in Ganeti'),
61
        make_option('--detect-unsynced', action='store_true',
62
                    dest='detect_unsynced',
63
                    default=False, help='Detect unsynced operstate between ' +
64
                                        'DB and Ganeti'),
65
        make_option('--detect-build-errors', action='store_true',
66
                    dest='detect_build_errors', default=False,
67
                    help='Detect instances with build error'),
68
        make_option('--detect-unsynced-nics', action='store_true',
69
                    dest='detect_unsynced_nics', default=False,
70
                    help='Detect unsynced nics between DB and Ganeti'),
71
        make_option('--detect-all', action='store_true',
72
                    dest='detect_all',
73
                    default=False, help='Enable all --detect-* arguments'),
74
        make_option('--fix-stale', action='store_true', dest='fix_stale',
75
                    default=False, help='Fix (remove) stale DB entries in DB'),
76
        make_option('--fix-orphans', action='store_true', dest='fix_orphans',
77
                    default=False, help='Fix (remove) orphan Ganeti VMs'),
78
        make_option('--fix-unsynced', action='store_true', dest='fix_unsynced',
79
                    default=False, help='Fix server operstate in DB, set ' +
80
                                        'from Ganeti'),
81
        make_option('--fix-build-errors', action='store_true',
82
                    dest='fix_build_errors', default=False,
83
                    help='Fix (remove) instances with build errors'),
84
         make_option('--fix-unsynced-nics', action='store_true',
85
                    dest='fix_unsynced_nics', default=False,
86
                    help='Fix unsynced nics between DB and Ganeti'),
87
        make_option('--fix-all', action='store_true', dest='fix_all',
88
                    default=False, help='Enable all --fix-* arguments'))
89

    
90
    def _process_args(self, options):
91
        keys_detect = [k for k in options.keys() if k.startswith('detect_')]
92
        keys_fix = [k for k in options.keys() if k.startswith('fix_')]
93

    
94
        if options['detect_all']:
95
            for kd in keys_detect:
96
                options[kd] = True
97
        if options['fix_all']:
98
            for kf in keys_fix:
99
                options[kf] = True
100

    
101
        if not reduce(lambda x, y: x or y,
102
                      map(lambda x: options[x], keys_detect)):
103
            raise CommandError("At least one of --detect-* must be specified")
104

    
105
        for kf in keys_fix:
106
            kd = kf.replace('fix_', 'detect_', 1)
107
            if (options[kf] and not options[kd]):
108
                raise CommandError("Cannot use --%s without corresponding "
109
                                   "--%s argument" % (kf, kd))
110

    
111
    def handle(self, **options):
112
        verbosity = int(options['verbosity'])
113
        self._process_args(options)
114

    
115
        D = reconciliation.get_servers_from_db()
116
        G = reconciliation.get_instances_from_ganeti()
117

    
118
        DBNics = reconciliation.get_nics_from_db()
119
        GNics = reconciliation.get_nics_from_ganeti()
120
        #
121
        # Detect problems
122
        #
123
        if options['detect_stale']:
124
            stale = reconciliation.stale_servers_in_db(D, G)
125
            if len(stale) > 0:
126
                print >> sys.stderr, "Found the following stale server IDs: "
127
                print "    " + "\n    ".join(
128
                    [str(x) for x in stale])
129
            elif verbosity == 2:
130
                print >> sys.stderr, "Found no stale server IDs in DB."
131

    
132
        if options['detect_orphans']:
133
            orphans = reconciliation.orphan_instances_in_ganeti(D, G)
134
            if len(orphans) > 0:
135
                print >> sys.stderr, "Found orphan Ganeti instances with IDs: "
136
                print "    " + "\n    ".join(
137
                    [str(x) for x in orphans])
138
            elif verbosity == 2:
139
                print >> sys.stderr, "Found no orphan Ganeti instances."
140

    
141
        if options['detect_unsynced']:
142
            unsynced = reconciliation.unsynced_operstate(D, G)
143
            if len(unsynced) > 0:
144
                print >> sys.stderr, "The operstate of the following server" \
145
                                     " IDs is out-of-sync:"
146
                print "    " + "\n    ".join(
147
                    ["%d is %s in DB, %s in Ganeti" %
148
                     (x[0], x[1], ('UP' if x[2] else 'DOWN'))
149
                     for x in unsynced])
150
            elif verbosity == 2:
151
                print >> sys.stderr, "The operstate of all servers is in sync."
152

    
153
        if options['detect_build_errors']:
154
            build_errors = reconciliation.instances_with_build_errors(D, G)
155
            if len(build_errors) > 0:
156
                print >> sys.stderr, "The os for the following server IDs was "\
157
                                     "not build successfully:"
158
                print "    " + "\n    ".join(
159
                    ["%d" % x for x in build_errors])
160
            elif verbosity == 2:
161
                print >> sys.stderr, "Found no instances with build errors."
162

    
163
        if options['detect_unsynced_nics']:
164
            def pretty_print_nics(nics):
165
                if not nics:
166
                    print ''.ljust(18) + 'None'
167
                for index, info in nics.items():
168
                    print ''.ljust(18) + 'nic/' + str(index) + ': MAC: %s, IP: %s, Network: %s' % \
169
                      (info['mac'], info['ipv4'], info['network'])
170

    
171
            unsynced_nics = reconciliation.unsynced_nics(DBNics, GNics)
172
            if len(unsynced_nics) > 0:
173
                print >> sys.stderr, "The nics of servers with the folloing ID's "\
174
                                     "are unsynced:"
175
                for id, nics in unsynced_nics.items():
176
                    print ''.ljust(2) + '%6d:' % id
177
                    print ''.ljust(8) + '%8s:' % 'DB'
178
                    pretty_print_nics(nics[0])
179
                    print ''.ljust(8) + '%8s:' % 'Ganeti'
180
                    pretty_print_nics(nics[1])
181
            elif verbosity == 2:
182
                print >> sys.stderr, "All instance nics are synced."
183

    
184
        #
185
        # Then fix them
186
        #
187
        if options['fix_stale'] and len(stale) > 0:
188
            print >> sys.stderr, \
189
                "Simulating successful Ganeti removal for %d " \
190
                "servers in the DB:" % len(stale)
191
            for vm in VirtualMachine.objects.filter(pk__in=stale):
192
                event_time = datetime.datetime.now()
193
                backend.process_op_status(vm=vm, etime=event_time, jobid=-0,
194
                    opcode='OP_INSTANCE_REMOVE', status='success',
195
                    logmsg='Reconciliation: simulated Ganeti event')
196
            print >> sys.stderr, "    ...done"
197

    
198
        if options['fix_orphans'] and len(orphans) > 0:
199
            print >> sys.stderr, \
200
                "Issuing OP_INSTANCE_REMOVE for %d Ganeti instances:" % \
201
                len(orphans)
202
            for id in orphans:
203
                vm = VirtualMachine.objects.get(pk=id)
204
                vm.client.DeleteInstance(utils.id_to_instance_name(id))
205
            print >> sys.stderr, "    ...done"
206

    
207
        if options['fix_unsynced'] and len(unsynced) > 0:
208
            print >> sys.stderr, "Setting the state of %d out-of-sync VMs:" % \
209
                len(unsynced)
210
            for id, db_state, ganeti_up in unsynced:
211
                vm = VirtualMachine.objects.get(pk=id)
212
                opcode = "OP_INSTANCE_REBOOT" if ganeti_up \
213
                         else "OP_INSTANCE_SHUTDOWN"
214
                event_time = datetime.datetime.now()
215
                backend.process_op_status(vm=vm, etime=event_time, jobid=-0,
216
                    opcode=opcode, status='success',
217
                    logmsg='Reconciliation: simulated Ganeti event')
218
            print >> sys.stderr, "    ...done"
219

    
220
        if options['fix_build_errors'] and len(build_errors) > 0:
221
            print >> sys.stderr, "Setting the state of %d build-errors VMs:" % \
222
                len(build_errors)
223
            for id in build_errors:
224
                vm = VirtualMachine.objects.get(pk=id)
225
                event_time = datetime.datetime.now()
226
                backend.process_op_status(vm=vm, etime=event_time, jobid=-0,
227
                    opcode="OP_INSTANCE_CREATE", status='error',
228
                    logmsg='Reconciliation: simulated Ganeti event')
229
            print >> sys.stderr, "    ...done"
230

    
231
        if options['fix_unsynced_nics'] and len(unsynced_nics) > 0:
232
            print >> sys.stderr, "Setting the nics of %d out-of-sync VMs:" % \
233
                                  len(unsynced_nics)
234
            for id, nics in unsynced_nics.items():
235
                vm = VirtualMachine.objects.get(pk=id)
236
                nics = nics[1]  # Ganeti nics
237
                if nics == {}:  # No nics
238
                    vm.nics.all.delete()
239
                    continue
240
                for index, nic in nics.items():
241
                    net_id = utils.id_from_network_name(nic['network'])
242
                    subnet6 = Network.objects.get(id=net_id).subnet6
243
                    # Produce ipv6
244
                    ipv6 = subnet6 and mac2eui64(nic['mac'], subnet6) or None
245
                    nic['ipv6'] = ipv6
246
                    # Rename ipv4 to ip
247
                    nic['ip'] = nic['ipv4']
248
                # Dict to sorted list
249
                final_nics = []
250
                nics_keys = nics.keys()
251
                nics_keys.sort()
252
                for i in nics_keys:
253
                    if nics[i]['network']:
254
                        final_nics.append(nics[i])
255
                    else:
256
                        print 'Network of nic %d of vm %s is None. ' \
257
                              'Can not reconcile' % (i, vm.backend_vm_id)
258
                event_time = datetime.datetime.now()
259
                backend.process_net_status(vm=vm, etime=event_time, nics=final_nics)
260
            print >> sys.stderr, "    ...done"
261

    
262

    
263
def mac2eui64(mac, prefixstr):
264
    process = subprocess.Popen(["mac2eui64", mac, prefixstr],
265
                                stdout=subprocess.PIPE)
266
    return process.stdout.read().rstrip()