-
Notifications
You must be signed in to change notification settings - Fork 2
/
alert_response.py
executable file
·179 lines (145 loc) · 6.2 KB
/
alert_response.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
#!/usr/bin/env python
import sys, os
import datetime, pytz
import voeventparse
import logging
import subprocess
logging.basicConfig(level=logging.DEBUG)
logger = logging.getLogger(__name__)
from pysovo.local import contacts
from pysovo.visibility import get_ephem
from pysovo.triggers import swift
from pysovo.triggers import is_test_trigger
from pysovo.voevent import ivorn_base
import pysovo as ps
import amiobs
from jinja2 import Environment, PackageLoader
#-------------------------------------------------------------------------------
grb_contacts = contacts.grb_contacts
amiobs.email_address = contacts.test_contacts[0].email
notification_email_prefix = "[4 Pi Sky] "
default_archive_root = os.path.join(os.environ["HOME"],
"voevent-deploy","voe_archive")
active_sites = [amiobs.site]
env = Environment(loader=PackageLoader('pysovo', 'templates'),
trim_blocks=True,lstrip_blocks=True)
env.filters['datetime'] = ps.formatting.format_datetime
env.filters['rad_to_deg'] = ps.formatting.rad_to_deg
#-------------------------------------------------------------------------------
def main():
s = sys.stdin.read()
v = voeventparse.loads(s)
voevent_logic(v)
return 0
def voevent_logic(v):
#SWIFT BAT GRB alert:
if swift.filters.is_bat_grb_pkt(v):
swift_bat_grb_logic(v)
if is_test_trigger(v):
test_logic(v)
archive_voevent(v, rootdir=default_archive_root)
def swift_bat_grb_logic(v):
actions_taken=[]
alert = swift.BatGrb(v)
alert_rejection = alert.reject()
if alert_rejection is None:
ami_reject = ps.filters.ami.reject(alert.position)
if ami_reject is None:
try:
trigger_ami_swift_grb_alert(alert)
actions_taken.append('Observation requested from AMI.')
try:
send_initial_ami_alert_vo_notification(alert)
actions_taken.append('AMI request notified to VOEvent network.')
except subprocess.CalledProcessError as e:
emsg = '***Notification to VOEvent network failed.***'
logger.warn(emsg)
actions_taken.append(emsg)
except Exception as e:
emsg = 'Observation request failed.'
actions_taken.append(emsg)
logger.error(emsg)
raise
else:
actions_taken.append('Target rejected by ami: ' + ami_reject)
else:
actions_taken.append('Alert ignored: ' + alert_rejection)
send_alert_report(alert, actions_taken, grb_contacts)
def trigger_ami_swift_grb_alert(alert):
assert isinstance(alert, swift.BatGrb)
target_name = alert.id
comment = alert.id + " / " + alert.inferred_name
duration = datetime.timedelta(hours=2.)
ami_request = amiobs.request_email(
target_coords=alert.position,
target_name=target_name,
duration=duration,
timing='ASAP',
action='CHECK',
requester=amiobs.default_requester,
comment=comment)
ps.comms.email.send_email(recipient_addresses=amiobs.email_address,
subject=amiobs.request_email_subject,
body_text=ami_request)
def send_initial_ami_alert_vo_notification(alert):
notification_timestamp = datetime.datetime.utcnow()
request_status = {'sent_time':notification_timestamp,
'acknowledged':False,
}
stream_id = notification_timestamp.strftime(ps.formatting.datetime_format_short)
v = ps.voevent.create_ami_followup_notification(alert,
stream_id=stream_id,
request_status=request_status)
ps.comms.comet.send_voevent(v, contacts.local_vobroker.ipaddress,
contacts.local_vobroker.port)
def send_alert_report(alert, actions_taken, contacts):
notify_msg = generate_report_text(
alert,
active_sites,
actions_taken)
subject = alert.id
if alert.inferred_name is not None:
subject+= ' / ' + alert.inferred_name
ps.comms.email.send_email([p.email for p in contacts],
notification_email_prefix + subject,
notify_msg)
def test_logic(v):
now = datetime.datetime.now(pytz.utc)
stream_id = v.attrib['ivorn'].partition('#')[-1]
response = ps.voevent.create_4pisky_test_response_voevent(
stream_id=stream_id,
date=now)
ps.comms.comet.send_voevent(response, contacts.local_vobroker.ipaddress,
contacts.local_vobroker.port)
testresponse_template = env.get_template('test_response.j2')
msg_context = dict(now=now)
msg_context.update(ps.base_context())
msg = testresponse_template.render(msg_context)
ps.comms.email.send_email(
recipient_addresses=[c.email for c in contacts.test_contacts],
subject=notification_email_prefix + '[TEST] Test packet received',
body_text=msg)
archive_voevent(v, rootdir=default_archive_root)
def archive_voevent(v, rootdir):
relpath, filename = v.attrib['ivorn'].split('//')[1].split('#')
filename += ".xml"
fullpath = os.path.sep.join((rootdir, relpath, filename))
ps.utils.ensure_dir(fullpath)
with open(fullpath, 'w') as f:
voeventparse.dump(v, f)
def generate_report_text(alert, sites, actions_taken,
report_timestamp=None):
if report_timestamp is None:
report_timestamp = datetime.datetime.now(pytz.utc)
site_reports = [(site, get_ephem(alert.position, site, report_timestamp))
for site in sites]
notification_template = env.get_template('notify.j2')
msg_context=dict(alert=alert,
report_timestamp=report_timestamp,
site_reports=site_reports,
actions_taken=actions_taken,)
msg_context.update(ps.base_context())
msg = notification_template.render(msg_context)
return msg
if __name__ == '__main__':
sys.exit(main())