Blame view

src/alert_manager/tasks.py 8.7 KB
5b5566ab   haribo   added celery
1
2
3
from __future__ import absolute_import

from celery.task import Task
77816f10   haribo   Workflow implemen...
4
from common.RequestBuilder import RequestBuilder
d84050e6   haribo   Date: 20/07/2016
5
from alert_manager.StrategyBuilder import StrategyBuilder
5b5566ab   haribo   added celery
6

94336356   haribo   Added starting fi...
7
from django.conf import settings
5b5566ab   haribo   added celery
8
9
from django.templatetags.static import static
import socket
94336356   haribo   Added starting fi...
10
from pyrosapp.models import *
5b5566ab   haribo   added celery
11
12

import time
94336356   haribo   Added starting fi...
13
import voeventparse
5b5566ab   haribo   added celery
14

94336356   haribo   Added starting fi...
15
16
import os
from os.path import isfile, join
77816f10   haribo   Workflow implemen...
17
import observation_manager
bb45cd4a   haribo   Date: 25/05/2016
18
import majordome.TaskManager
7a79e25b   haribo   Date: 19/05/2016
19
from decimal import Decimal
7a79e25b   haribo   Date: 19/05/2016
20

d84050e6   haribo   Date: 20/07/2016
21

5b5566ab   haribo   added celery
22
23
24
IP = '127.0.0.1'
PORT = 31569

1b341a0f   haribo   Date: 19/07/2016
25
TIMESTAMP_JD = 2440587.500000
94336356   haribo   Added starting fi...
26
27
28
VOEVENTS_PATH = "alert_manager/events_received"


5b5566ab   haribo   added celery
29
30
31
32
class alert_listener(Task):
    '''
        Launched at server start
        Listens to VOEvents, and create appropriate request when an event is received
94336356   haribo   Added starting fi...
33
    '''
5b5566ab   haribo   added celery
34
35

    def run(self):
94336356   haribo   Added starting fi...
36
37
38
39
40
41
        '''
            Is called at the beginning of the task
            Calls the function to get the new events in the VOEVENTS_PATH directory
            For each event, calls a fonction to analyze it
        '''

2ceea892   haribo   Date: 19/07/2016
42
        print("alert listener started")
94336356   haribo   Added starting fi...
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
        if settings.SIMULATION == False:
            self.old_files = [
                f for f in os.listdir(VOEVENTS_PATH) if isfile(join(VOEVENTS_PATH, f))]
            while True:
                fresh_events = self.get_fresh_events()
                for event in fresh_events:
                    self.analyze_event(event)
                time.sleep(1)
        else:
            self.run_simulation()

    def get_fresh_events(self):
        '''
            Reads in the VOEVENTS_PATH directory to see if there are new events to analyze
            :returns : A list containing the new files to analyze
        '''

        fresh_events = []
        files = [
            f for f in os.listdir(VOEVENTS_PATH) if isfile(join(VOEVENTS_PATH, f))]

        diff = list(set(files).difference(set(self.old_files)))

        for event in diff:
7a79e25b   haribo   Date: 19/05/2016
67
            print("New file found : %s" % (event,))
94336356   haribo   Added starting fi...
68
69
70
71
            fresh_events.append(event)
        self.old_files = files
        return fresh_events

2ceea892   haribo   Date: 19/07/2016
72
    def analyze_event(self, event_file):
94336356   haribo   Added starting fi...
73
74
75
76
        '''
            Opens and parse the voevent file
            Will create the request & the alert object related
        '''
2ceea892   haribo   Date: 19/07/2016
77

2ceea892   haribo   Date: 19/07/2016
78
        with open(os.path.join(VOEVENTS_PATH, event_file), 'rb') as f:
94336356   haribo   Added starting fi...
79
            voevent = voeventparse.load(f)
d84050e6   haribo   Date: 20/07/2016
80
        self.create_related_request(voevent, event_file)
94336356   haribo   Added starting fi...
81

2ceea892   haribo   Date: 19/07/2016
82
    def create_related_request(self, voevent, event_file):
94336356   haribo   Added starting fi...
83
84
85
86
        '''
            Creates a request object related to the voevent received.
            For the moment, it doesn't take care of the voevent content, and hardcode the sequences etc

2ceea892   haribo   Date: 19/07/2016
87
            :param voevent: Object resulting of the VOEvent parsing with voeventparse library
94336356   haribo   Added starting fi...
88
89
90
            :returns : The request
        '''

94336356   haribo   Added starting fi...
91
92
        pyros_user = PyrosUser.objects.get(user__username="haribo")
        scientific_program = ScientificProgram.objects.get(name="GRB")
2ceea892   haribo   Date: 19/07/2016
93
94
95
96


        alert = self.get_alert_attributes(voevent, event_file)

d84050e6   haribo   Date: 20/07/2016
97
98
        if alert == None or StrategyObs.objects.filter(is_default=True).exists() == False:
            return
2ceea892   haribo   Date: 19/07/2016
99

d84050e6   haribo   Date: 20/07/2016
100
101
        alert.strat = StrategyObs.objects.filter(is_default=True)[0]
        name = "GRB - " + str(alert.trig_id)
2ceea892   haribo   Date: 19/07/2016
102

d84050e6   haribo   Date: 20/07/2016
103
104
105
106
107
108
109
110
111
        sb = StrategyBuilder()
        sb.create_request_from_strategy(alert.strat.xml_file, pyros_user, scientific_program, name)
        req = sb.validate()
        for seq in req.sequences.all():
            seq.ra = alert.burst_ra
            seq.dec = alert.burst_dec
            seq.save()
        alert.request = req
        alert.save()
2ceea892   haribo   Date: 19/07/2016
112
113


2ceea892   haribo   Date: 19/07/2016
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
    def get_alert_attributes(self, voevent, event_file):
        '''
            Parses the VOEvent to get all the required attributes
            Creates the alert object
            Handles errors (missing params, wrong params, ...)
            
            :param voevent: Object resulting of the VOEvent parsing with voeventparse library
            :returns : The alert object
        '''


        '''
            The parameters are a dictionnary with the "<What>" <Group>s as keys,
            and a dictionnary of their <Param> as values.
            The nested dictionnaries have the 'name' attribute as keys,
            and another dictionnary as values, containing {attribute : value} pairs
            The <Param>s without <Group> are in the dictionnary with 'None' as key
        '''
eecfb779   haribo   Date: 26/05/2016
132
        v_params = voeventparse.pull_params(voevent)
2ceea892   haribo   Date: 19/07/2016
133

2ceea892   haribo   Date: 19/07/2016
134
135
136
137
138
139
140
141
142
143
144
145
146
        alert = Alert(voevent_file=event_file)
        try:
            alert.trig_id = v_params[None]["TrigID"]["value"]
            alert.editor = v_params[None]["Packet_Type"]["value"]
            alert.soln_status = v_params[None]["Soln_Status"]["value"]
            alert.pkt_ser_num = v_params[None]["Pkt_Ser_Num"]["value"]

            tjd = Decimal(v_params[None]["Burst_TJD"]["value"])
            sod = Decimal(v_params[None]["Burst_SOD"]["value"])
            alert.burst_jd = tjd - 13370 - 1 + 2453371 + (sod / 86400)
            alert.defly_not_grb = int(alert.soln_status[0]) & 0xF0

            alert.author = voevent.Who.AuthorIVORN
1b341a0f   haribo   Date: 19/07/2016
147
148
            alert.jd_send = time.mktime(time.strptime(str(voevent.Who.Date), "%Y-%m-%dT%H:%M:%S")) / 86400 + TIMESTAMP_JD
            alert.jd_received = time.time() / 86400 + TIMESTAMP_JD
2ceea892   haribo   Date: 19/07/2016
149

d84050e6   haribo   Date: 20/07/2016
150
            alert.astro_coord_system = voevent.WhereWhen.ObsDataLocation.ObservationLocation.AstroCoordSystem
2ceea892   haribo   Date: 19/07/2016
151
152
153
154
            alert.burst_ra = voevent.WhereWhen.ObsDataLocation.ObservationLocation.AstroCoords.Position2D.Value2.C1
            alert.burst_dec = voevent.WhereWhen.ObsDataLocation.ObservationLocation.AstroCoords.Position2D.Value2.C2
            alert.error_radius = voevent.WhereWhen.ObsDataLocation.ObservationLocation.AstroCoords.Position2D.Error2Radius

2ceea892   haribo   Date: 19/07/2016
155
156
157
158
159
        except KeyError or AttributeError as e:
            print("Error while parsing VOEvent : ", e)
            return None

        return alert
94336356   haribo   Added starting fi...
160
161
162
163
164

    def run_simulation(self):
        '''
            Uses a socket to block until a message is received (simulation of a VOEvent reception)
        '''
5b5566ab   haribo   added celery
165
166
        print("run")
        self.server_socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
94336356   haribo   Added starting fi...
167
168
        self.server_socket.setsockopt(
            socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
5b5566ab   haribo   added celery
169
170
171
172
        self.server_socket.setblocking(True)
        self.server_socket.bind((IP, PORT))
        self.server_socket.listen(12)
        while True:
77816f10   haribo   Workflow implemen...
173
            print("Task en attente de signal")
5b5566ab   haribo   added celery
174
            self.server_socket.accept()
77816f10   haribo   Workflow implemen...
175
            print("signal reçu")
94336356   haribo   Added starting fi...
176
            self.alert_received_simulation()
5b5566ab   haribo   added celery
177

94336356   haribo   Added starting fi...
178
179
    def alert_received_simulation(self):
        '''
7a79e25b   haribo   Date: 19/05/2016
180
            IMPORTANT : To do simulation, settings.SIMULATION must be set True
94336356   haribo   Added starting fi...
181
182
183
            Simulates a VOEvent message by reading sequences into a file
            Creates a request with them
        '''
7a79e25b   haribo   Date: 19/05/2016
184

77816f10   haribo   Workflow implemen...
185
        # je supprime les sequences et requetes déjà existantes
9774228b   haribo   Date: 22/06/2016
186
        majordome.TaskManager.delete_pending_alert()
bb45cd4a   haribo   Date: 25/05/2016
187
188
        Plan.objects.all().delete()
        Album.objects.all().delete()
77816f10   haribo   Workflow implemen...
189
        Sequence.objects.all().delete()
bb45cd4a   haribo   Date: 25/05/2016
190
        Alert.objects.all().delete()
77816f10   haribo   Workflow implemen...
191
        Request.objects.all().delete()
bb45cd4a   haribo   Date: 25/05/2016
192
        ScheduleHasSequences.objects.all().delete()
77816f10   haribo   Workflow implemen...
193
194

        Log.objects.create(agent='Alert manager', message='Alert received')
94336356   haribo   Added starting fi...
195

77816f10   haribo   Workflow implemen...
196
197
        for file_name in os.listdir(observation_manager.tasks.IMAGES_FOLDER):
            if file_name != "empty":
94336356   haribo   Added starting fi...
198
199
                file_path = os.path.join(
                    observation_manager.tasks.IMAGES_FOLDER, file_name)
77816f10   haribo   Workflow implemen...
200
                os.unlink(file_path)
94336356   haribo   Added starting fi...
201

9774228b   haribo   Date: 22/06/2016
202
203
        print("All deleted")

7a79e25b   haribo   Date: 19/05/2016
204
        # j'ouvre le fichier des séquences de simulation, et je le lis ligne par ligne
5b5566ab   haribo   added celery
205
206
        with open("alert_manager/simulation_sequences", 'r') as sequences_file:
            sequences = sequences_file.readlines()
77816f10   haribo   Workflow implemen...
207

9774228b   haribo   Date: 22/06/2016
208
209
        print("File read")

94336356   haribo   Added starting fi...
210
211
        Log.objects.create(
            agent='Alert manager', message='Simulation sequences file read')
77816f10   haribo   Workflow implemen...
212

5b5566ab   haribo   added celery
213
        sequences = [sequence.strip('\n') for sequence in sequences]
77816f10   haribo   Workflow implemen...
214
        request_builder = RequestBuilder()
fd99569d   haribo   Date: 22/06/2016
215
        request_builder.start_new_request(PyrosUser.objects.all()[0], ScientificProgram.objects.all()[0], True, name="Simulation_request")
5b5566ab   haribo   added celery
216
        for sequence in sequences:
7a79e25b   haribo   Date: 19/05/2016
217
218
219
220
221
222
223
224
            sequence_array = sequence.split(" ")
            id_seq = sequence_array[0]
            priority = int(sequence_array[2])
            ''' transforms the duration (seconds) in days (86,400s in a day)'''
            duration = Decimal(float(sequence_array[4]) / 86400.0)
            jd1 = Decimal("%.8f" % float(sequence_array[5]))
            jd2 = Decimal("%.8f" % float(sequence_array[6]))

eecfb779   haribo   Date: 26/05/2016
225
            request_builder.add_sequence(priority, jd1, jd2, name="Simulation_" + id_seq, duration=duration)
7a79e25b   haribo   Date: 19/05/2016
226

9774228b   haribo   Date: 22/06/2016
227
        print("Parsé")
77816f10   haribo   Workflow implemen...
228
        request_builder.validate_request()
9774228b   haribo   Date: 22/06/2016
229
        print("Validé")
bb45cd4a   haribo   Date: 25/05/2016
230
        Alert.objects.create(request=request_builder.request, strategyobs=StrategyObs.objects.all()[0])
77816f10   haribo   Workflow implemen...
231
        Log.objects.create(agent='Alert manager', message='Request built')