Statistics
| Branch: | Tag: | Revision:

root / logic / callbacks.py @ 960c15e0

History | View | Annotate | Download (8.1 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 socket
34
import traceback
35
import json
36
import sys
37

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

    
41
_logger = log.get_logger("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.exception("Unexpected error")
75

    
76

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

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

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

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

    
106

    
107
def send_email(message):
108
    """Process an email submission request"""
109

    
110
    try:
111
        msg = json.loads(message.body)
112

    
113
        sent = email_send.send(sender=msg['frm'], recipient = msg['to'],
114
                        body=msg['body'], subject=msg['subject'])
115

    
116
        if not sent:
117
            _logger.warn("Failed to send email to %s", msg['to'])
118
        else:
119
            message.channel.basic_ack(message.delivery_tag)
120
    except KeyError:
121
        _logger.error("Malformed incoming JSON, missing attributes: %s",
122
                      message.body)
123
    except socket.error as e:
124
        _logger.error("Cannot connect to SMTP server:%s\n", e)
125
    except Exception as e:
126
        _logger.exception("Unexpected error")
127
        raise
128

    
129

    
130
def update_credits(message):
131
    _logger.debug("Request to update credits")
132
    message.channel.basic_ack(message.delivery_tag)
133

    
134
def trigger_status_update(message):
135
    """
136
        Triggers a status update job for a specific VM id.
137
    """
138
    _logger.debug("Request to trigger status update: %s", message.body)
139

    
140
    try:
141
        msg = _parse_json(message.body)
142

    
143
        if msg["type"] != "reconcile":
144
             _logger.error("Message is of unknown type %s", msg["type"])
145
             return
146

    
147
        if msg["vmid"] == "":
148
            _logger.error("Reconciliate message does not specify a VM id")
149
            return
150

    
151
        vm = VirtualMachine.objects.get(id=msg["vmid"])
152
        backend.request_status_update(vm)
153

    
154
        message.channel.basic_ack(message.delivery_tag)
155
    except KeyError as k:
156
        _logger.error("Malformed incoming JSON, missing attributes: %s", k)
157
    except Exception as e:
158
        _logger.exception("Unexpected error")
159

    
160
def status_job_finished (message):
161
    """
162
        Updates VM status based on a previously sent status update request
163
    """
164
    try:
165
        msg = _parse_json(message.body)
166

    
167
        if msg["operation"] != 'OP_INSTANCE_QUERY_DATA':
168
            _logger.error("Message is of unknown type %s", msg["operation"])
169
            return
170

    
171
        if msg["status"] != "success":
172
            _logger.warn("Ignoring non-success status update from job %d on VM %s",
173
                          msg['jobId'], msg['instance'])
174
            message.channel.basic_ack(message.delivery_tag)
175
            return
176

    
177
        status = backend.get_job_status(msg['jobId'])
178

    
179
        _logger.debug("Node status job result: %s" % status)
180

    
181
        if status['summary'][0] != u'INSTANCE_QUERY_DATA':
182
             _logger.error("Status update is of unknown type %s", status['summary'])
183
             return
184

    
185
        conf_state = status['opresult'][0][msg['instance']]['config_state']
186
        run_state = status['opresult'][0][msg['instance']]['run_state']
187

    
188
        # XXX: The following assumes names like snf-12
189
        instid = msg['instance'].split('-')[1]
190

    
191
        vm = VirtualMachine.objects.get(id = instid)
192

    
193
        if run_state == "up":
194
            opcode = "OP_INSTANCE_REBOOT"
195
        else:
196
            opcode = "OP_INSTANCE_SHUTDOWN"
197

    
198
        backend.process_op_status(vm=vm, jobid=msg['jobId'],opcode=opcode,
199
                                  status="success",
200
                                  logmsg="Reconciliation: simulated event")
201

    
202
        message.channel.basic_ack(message.delivery_tag)
203
    except KeyError as k:
204
        _logger.error("Malformed incoming JSON, missing attributes: %s", k)
205
    except Exception as e:
206
        _logger.exception("Unexpected error")
207

    
208
def dummy_proc(message):
209
    try:
210
        _logger.debug("Msg: %s" %(message.body))
211
        message.channel.basic_ack(message.delivery_tag)
212
    except Exception as e:
213
        _logger.exception("Could not receive message")
214
        pass
215

    
216
def _parse_json(data):
217
    try:
218
        return json.loads(data)
219
    except Exception as e:
220
        _logger.error("Could not parse JSON file: %s", e)
221
        raise