process_alert.py 10.5 KB
Newer Older
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
"""
The MIT License (MIT)

Copyright (c) 2015 Zachary Seguin

Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:

The above copyright notice and this permission notice shall be included in
all copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
THE SOFTWARE.
"""

from sqlalchemy.sql.expression import false, true
from datetime import datetime
import requests
28
import pytz
29
import dateutil.parser
30
from celery.utils.log import get_task_logger
Zachary Seguin's avatar
Zachary Seguin committed
31
from lxml.etree import XMLSyntaxError
32
import re
33

34
from . import app, celery, db, redis
35
from ..xml import alert
36
from ..models import Alert, AlertCode, AlertReference
37 38 39
from ..models import Info, InfoCategory, InfoResponseType, InfoEventCode, InfoParameter
from ..models import Area, AreaPolygon, AreaCircle, AreaGeocode
from ..models import Resource
40

41 42
logger = get_task_logger(__name__)

43 44 45
def to_dictionary(objs):
   "Convert a valueName, value object set into a dictionary"
   kvps = {}
46

47 48
   for obj in objs:
      kvps[obj.valueName] = obj.value
49

50 51
   return kvps

52 53 54 55 56 57 58 59
def to_utc(value):
   "Converts a datetime object to UTC"

   if value == None:
      return None

   return value.astimezone(pytz.utc)

60 61 62 63 64 65 66 67 68 69 70 71 72
@celery.task(default_retry_delay=3600, ax_retries=1)
def cleanup_fetch_list():
   try:
      redis.delete('fetch_urls')
   except Exception, exc:
      cleanup_fetch_list.retry(exc=exc)

@celery.task(bind=True, default_retry_delay=120, max_retries=20)
def fetch_alert_from_url(self, url):
   "Fetch an alert from a URL"
   try:
      if redis.sadd('fetch_urls', url) == 1 or not self.request.retries == 0:
         logger.info('Requesting "{url}"'.format(url=url))
73

74 75 76
         # Execute the HTTP request
         xml = requests.get(url)
         xml.encoding = 'UTF-8'
77

78
         logger.info('Received status code {}'.format(xml.status_code))
Zachary Seguin's avatar
Zachary Seguin committed
79

80 81 82 83 84 85 86 87 88
         if xml.status_code == 200:
            process_alert.delay(xml.text)
         elif xml.status_code == 404:
            logger.warn('Alert not found upstream: {url}'.format(url = url))
         else:
            logger.warn('Received status code {status_code} for {url}'.format(status_code = xml.status_code, url = url))
            fetch_alert_from_url.retry(exc=Exception('Status Code: {status_code}'.format(status_code=xml.status_code)))
      else:
         logger.warn('Alert has already been queued: "{url}"'.format(url=url))
89

90 91
   except Exception, exc:
      fetch_alert_from_url.retry(exc=exc)
92

93 94 95

@celery.task(default_retry_delay=30, max_retries=None)
def fetch_alert_from_reference(reference):
96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111
   "Fetch an alert from reference"
   try:
      for capcp in app.config['NAAD_CAPCPS']:
         # Create the URL
         url = 'http://{hostname}:{port}/{sent_date}/{sent}I{identifier}.xml'.format(
            hostname = capcp[0],
            port = capcp[1],
            sent_date = reference[2][0:10],
            sent = reference[2].replace('-', '_').replace('+', 'P').replace(':', '_'),
            identifier = reference[1].replace('-', '_').replace('+', 'P').replace(':', '_')
         )

         if not redis.sismember('fetch_urls', url):
            fetch_alert_from_url.delay(url)
   except Exception, exc:
      fetch_alert_from_reference.retry(exc=exc)
112 113

@celery.task(default_retry_delay=10, max_retries=5)
114 115 116 117 118
def load_references(references):
   "Loads references if they are not already in the database"
   try:
      if not references:
         return
119

120
      references = references.split(' ')
121

122
      # Reference Format: sender,identifier,sent
123
      for reference in reversed(references):
124 125 126
         reference = reference.split(',')
         if len(reference) != 3:
            continue
127

128 129 130 131 132
         alert = db.session.query(Alert).filter(
            Alert.identifier == reference[1],
            Alert.sender == reference[0],
            Alert.sent == to_utc(dateutil.parser.parse(reference[2]))
         ).first()
133

134
         if not alert:
135
            fetch_alert_from_reference.delay(reference)
136 137 138 139 140 141
   except Exception, exc:
      load_references.retry(exc=exc)

@celery.task(default_retry_delay=10, max_retries=2)
def expire_alerts():
   try:
142
      alerts = db.session.query(Alert).filter(Alert.expired == false()).all()
Zachary Seguin's avatar
Zachary Seguin committed
143
      logger.info('Checking {count} alerts for expiry'.format(count=len(alerts)))
144

145 146
      for alert in alerts:
         all_expired = True
147

148
         for info in alert.infos:
149
            if info.expires:
150
               if info.expires > pytz.utc.localize(datetime.utcnow()):
151 152
                  all_expired = False
                  break;
153

Zachary Seguin's avatar
Zachary Seguin committed
154
         if all_expired:
Zachary Seguin's avatar
Zachary Seguin committed
155
            logger.info('Marking {id} as expired'.format(id=alert.id))
Zachary Seguin's avatar
Zachary Seguin committed
156
            alert.expired = True
Zachary Seguin's avatar
Zachary Seguin committed
157
         db.session.flush()
158

159 160 161 162 163 164 165
      db.session.commit()
   except Exception, exc:
      db.session.rollback()
      expire_alerts.retry(exc=exc)

@celery.task(default_retry_delay=10, max_retries=2)
def supersede_alerts():
166
   try:
167
      alerts = db.session.query(Alert).filter((Alert.superseded == false()) & (Alert.expired == false())).all()
Zachary Seguin's avatar
Zachary Seguin committed
168
      logger.info('Superseding references for {count} alerts'.format(count=len(alerts)))
169

170
      for alert in alerts:
171
         for reference in alert.references:
172 173
            if not reference:
               continue
174

175 176 177
            a = db.session.query(Alert).filter(
               Alert.identifier == reference.identifier,
               Alert.sender == reference.sender,
Zachary Seguin's avatar
Zachary Seguin committed
178 179
               Alert.sent == reference.sent,
               Alert.superseded == false()
180
            ).first()
181

182
            if a:
Zachary Seguin's avatar
Zachary Seguin committed
183
               logger.info('Marking {id}-{sender}-{sent} as superseded'.format(id=reference.identifier, sender=reference.sender, sent=reference.sent))
184
               a.superseded = True
185

Zachary Seguin's avatar
Zachary Seguin committed
186 187
            db.session.flush()

188 189 190 191 192
      db.session.commit()
   except Exception, exc:
      db.session.rollback()
      supersede_alerts.retry(exc=exc)

193
@celery.task(default_retry_delay=10, max_retries=5)
194
def process_heartbeat():
195 196 197 198 199
   try:
      # TODO:
      # Need to track when last heartbeat was received
      # and restart listenting if we haven't received
      # it in a while.
200
      None
201 202 203
   except Exception, exc:
      process_heartbeat.retry(exc=exc)

204
@celery.task(default_retry_delay=10, max_retries=None)
205 206
def process_alert(xml):
   try:
207
      xml = re.sub("encoding=['\"][^'\"]*['\"]", "", xml, flags=re.IGNORECASE)
208

209 210
      # Get the XML representation of the alert
      a = alert.parseString(xml)
211

212
      logger.info('Processing: {identifier}'.format(identifier=a.identifier))
213 214

      # Convert and insert into the database
215
      dba = Alert()
216
      dba.processed = pytz.utc.localize(datetime.utcnow())
217

218 219
      dba.identifier = a.identifier
      dba.sender = a.sender
220
      dba.sent = to_utc(a.sent)
221 222 223 224 225 226
      dba.status = a.status
      dba.msg_type = a.msgType
      dba.source = a.source
      dba.scope = a.scope
      dba.restriction = a.restriction
      dba.addresses = a.addresses
227 228
      dba.codes.extend(a.code)

229 230 231
      if a.references:
         for reference in a.references.split(' '):
             c = reference.split(',')
232

233 234
             if len(c) != 3:
                 continue
235

236 237 238 239 240
             dbar = AlertReference()
             dbar.sender = c[0]
             dbar.identifier = c[1]
             dbar.sent = to_utc(dateutil.parser.parse(c[2]))
             dbar.raw = reference
241

242
             dba.references.append(dbar)
243

244
      dba.incidents = a.incidents
245

246
      for i in a.info:
247 248
         dbi = Info()
         dbi.language = i.language
249 250
         dbi.categories.extend(i.category)

251
         dbi.event = i.event
252 253 254

         dbi.response_types.extend(i.responseType)

255 256 257 258
         dbi.urgency = i.urgency
         dbi.severity = i.severity
         dbi.certainty = i.certainty
         dbi.audience = i.audience
259 260
         dbi.event_codes.update(to_dictionary(i.eventCode))

261 262 263
         dbi.effective = to_utc(i.effective)
         dbi.onset = to_utc(i.onset)
         dbi.expires = to_utc(i.expires)
264 265 266 267 268 269
         dbi.sender_name = i.senderName
         dbi.headline = i.headline
         dbi.description = i.description
         dbi.instruction = i.instruction
         dbi.web = i.web
         dbi.contact = i.contact
270
         dbi.parameters.update(to_dictionary(i.parameter))
271

272
         dba.infos.append(dbi)
273

274
         for r in i.resource:
275 276 277 278 279 280 281
            dbr = Resource()
            dbr.description = r.resourceDesc
            dbr.mime_type = r.mimeType
            dbr.size = r.size
            dbr.uri = r.uri
            dbr.deref_uri = r.derefUri
            dbr.digest = r.digest
282

283
            dbi.resources.append(dbr)
284

285
         for ar in i.area:
286
            dbar = Area()
287 288 289
            dbar.description = ar.areaDesc
            dbar.polygons.extend(ar.polygon)
            dbar.circles.extend(ar.circle)
290

291
            dbar.geocodes.update(to_dictionary(ar.geocode))
292

293 294
            dbar.altitude = ar.altitude
            dbar.ceiling = ar.ceiling
295

296
            dbi.areas.append(dbar)
297 298


299 300
      # Save to the database and perform further processing
      if dba.status == 'System' and dba.sender == 'NAADS-Heartbeat':
Zachary Seguin's avatar
Zachary Seguin committed
301
         logger.info('Received heartbeat')
302 303 304

         # Queue Additional Processing
         load_references.delay(a.references)
305
         process_heartbeat.delay()
306
      else:
307 308 309 310 311 312 313
         if db.session.query(Alert).filter(
            Alert.identifier == a.identifier,
            Alert.sender == a.sender,
            Alert.sent == a.sent).first():
            logger.warning('Duplicate Alert: {identifier}'.format(identifier=a.identifier))
            return # Alert already exists

Zachary Seguin's avatar
Zachary Seguin committed
314
         logger.info('Saving alert "{identifier}" to database'.format(identifier=a.identifier))
315 316
         db.session.add(dba)
         db.session.commit()
Zachary Seguin's avatar
Zachary Seguin committed
317
         logger.info('Saved alert "{identifier}" to database'.format(identifier=a.identifier))
318 319 320 321 322

         # Queue Additional Processing
         load_references.delay(a.references)
         supersede_alerts.delay()

Zachary Seguin's avatar
Zachary Seguin committed
323 324
   except XMLSyntaxError:
      logger.warn('Syntax error in alert, discarding')
325
   except Exception, exc:
326
      process_alert.retry(exc=exc)