Statistics
| Branch: | Tag: | Revision:

root / logic / dispatcher_callbacks.py @ 2f355fb5

History | View | Annotate | Download (7.5 kB)

1
# Copyright 2011 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
# Callback functions used by the dispatcher to process incoming notifications
31
# from AMQP queues.
32

    
33
import traceback
34
import json
35
import logging
36
import sys
37

    
38
from synnefo.db.models import VirtualMachine
39
from synnefo.logic import utils, backend
40

    
41
_logger = logging.getLogger("synnefo.dispatcher")
42

    
43
def update_db(message):
44
    """Process the status of a VM based on a ganeti status message"""
45
    _logger.debug("Processing ganeti-op-status msg: %s", message.body)
46
    try:
47
        msg = _parse_json(message.body)
48

    
49
        if msg["type"] != "ganeti-op-status":
50
            _logger.error("Message is of unknown type %s.", msg["type"])
51
            return
52

    
53
        if msg["operation"] == "OP_INSTANCE_QUERY_DATA":
54
            return status_job_finished(message)
55

    
56
        vmid = utils.id_from_instance_name(msg["instance"])
57
        vm = VirtualMachine.objects.get(id=vmid)
58

    
59
        backend.process_op_status(vm, msg["jobId"], msg["operation"],
60
                                  msg["status"], msg["logmsg"])
61
        _logger.debug("Done processing ganeti-op-status msg for vm %s.",
62
                      msg["instance"])
63
        message.channel.basic_ack(message.delivery_tag)
64
    except KeyError:
65
        _logger.error("Malformed incoming JSON, missing attributes: %s",
66
                      message.body)
67
    except VirtualMachine.InvalidBackendIdError:
68
        _logger.debug("Ignoring msg for unknown instance %s.",
69
                      msg["instance"])
70
    except VirtualMachine.DoesNotExist:
71
        _logger.error("VM for instance %s with id %d not found in DB.",
72
                      msg["instance"], vmid)
73
    except Exception as e:
74
        _logger.error("Unexpected error:\n%s" %
75
            "".join(traceback.format_exception(*sys.exc_info())))
76

    
77

    
78
def update_net(message):
79
    """Process a network status update notification from Ganeti"""
80
    _logger.debug("Processing ganeti-net-status msg: %s", message.body)
81
    try:
82
        msg = _parse_json(message.body)
83

    
84
        if msg["type"] != "ganeti-net-status":
85
            _logger.error("Message is of unknown type %s", msg["type"])
86
            return
87

    
88
        vmid = utils.id_from_instance_name(msg["instance"])
89
        vm = VirtualMachine.objects.get(id=vmid)
90

    
91
        backend.process_net_status(vm, msg["nics"])
92
        _logger.debug("Done processing ganeti-net-status msg for vm %s.",
93
                      msg["instance"])
94
        message.channel.basic_ack(message.delivery_tag)
95
    except KeyError:
96
        _logger.error("Malformed incoming JSON, missing attributes: %s",
97
                      message.body)
98
    except VirtualMachine.InvalidBackendIdError:
99
        _logger.debug("Ignoring msg for unknown instance %s.",
100
                      msg["instance"])
101
    except VirtualMachine.DoesNotExist:
102
        _logger.error("VM for instance %s with id %d not found in DB.",
103
                      msg["instance"], vmid)
104
    except Exception as e:
105
        _logger.error("Unexpected error:\n%s" %
106
            "".join(traceback.format_exception(*sys.exc_info())))
107

    
108

    
109
def send_email(message):
110
    _logger.debug("Request to send email message")
111
    message.channel.basic_ack(message.delivery_tag)
112

    
113

    
114
def update_credits(message):
115
    _logger.debug("Request to update credits")
116
    message.channel.basic_ack(message.delivery_tag)
117

    
118
def trigger_status_update(message):
119
    _logger.debug("Request to trigger status update: %s", message.body)
120

    
121
    try:
122
        msg = _parse_json(message.body)
123

    
124
        if msg["type"] != "reconcile" :
125
             _logger.error("Message is of unknown type %s", msg["type"])
126
             return
127

    
128
        if msg["vmid"] == "" :
129
            _logger.error("Reconciliate message does not specify a VM id")
130
            return
131

    
132
        vm = VirtualMachine.objects.get(id=msg["vmid"])
133
        backend.request_status_update(vm)
134

    
135
        message.channel.basic_ack(message.delivery_tag)
136
    except KeyError as k:
137
        _logger.error("Malformed incoming JSON, missing attributes: %s", k)
138
    except Exception as e:
139
        _logger.error("Unexpected error:%s", e)
140

    
141
def status_job_finished (message) :
142
    try:
143
        msg = _parse_json(message.body)
144

    
145
        if msg["operation"] != 'OP_INSTANCE_QUERY_DATA':
146
            _logger.error("Message is of unknown type %s", msg["operation"])
147
            return
148

    
149
        if msg["status"] != "success" :
150
            _logger.warn("Ignoring non-success status update from job %d on VM %s",
151
                          msg['jobId'], msg['instance'])
152
            message.channel.basic_ack(message.delivery_tag)
153
            return
154

    
155
        status = backend.get_job_status(msg['jobId'])
156

    
157
        _logger.debug("Node status job result: %s" % status)
158

    
159
        if status['summary'][0] != u'INSTANCE_QUERY_DATA' :
160
             _logger.error("Status update is of unknown type %s", status['summary'])
161
             return
162

    
163
        conf_state = status['opresult'][0][msg['instance']]['config_state']
164
        run_state = status['opresult'][0][msg['instance']]['run_state']
165

    
166
        # XXX: The following assumes names like snf-12
167
        instid = msg['instance'].split('-')[1]
168

    
169
        vm = VirtualMachine.objects.get(id = instid)
170

    
171
        if run_state == "up":
172
            opcode = "OP_INSTANCE_REBOOT"
173
        else :
174
            opcode = "OP_INSTANCE_SHUTDOWN"
175

    
176
        backend.process_op_status(vm=vm, jobid=msg['jobId'],opcode=opcode,
177
                                  status="success",
178
                                  logmsg="Reconciliation: simulated event")
179

    
180
        message.channel.basic_ack(message.delivery_tag)
181
    except KeyError as k:
182
        _logger.error("Malformed incoming JSON, missing attributes: %s", k)
183
    except Exception as e:
184
        _logger.error("Unexpected error:%s"%e)
185

    
186
def dummy_proc(message):
187
    try:
188
        msg = _logger.debug(message.body)
189
        _logger.debug("Msg (exchange:%s) ", msg)
190
        message.channel.basic_ack(message.delivery_tag)
191
    except Exception as e:
192
        _logger.error("Could not receive message %s" % e.message)
193
        pass
194

    
195
def _parse_json(data):
196
    try:
197
        return json.loads(data)
198
    except Exception as e:
199
        _logger.error("Could not parse JSON file: %s", e)
200
        raise