-
Notifications
You must be signed in to change notification settings - Fork 302
/
Copy pathelastalert.py
executable file
·1958 lines (1700 loc) · 88.9 KB
/
elastalert.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
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
# -*- coding: utf-8 -*-
import argparse
import copy
import datetime
import json
import logging
import os
import random
import re
import signal
import sys
import threading
import time
import timeit
import traceback
from email.mime.text import MIMEText
from smtplib import SMTP
from smtplib import SMTPException
from socket import error
import statsd
import pytz
from apscheduler.schedulers.background import BackgroundScheduler
from apscheduler.executors.pool import ThreadPoolExecutor
from croniter import croniter
from elasticsearch.exceptions import ConnectionError
from elasticsearch.exceptions import ElasticsearchException
from elasticsearch.exceptions import NotFoundError
from elasticsearch.exceptions import TransportError
from elastalert.alerters.debug import DebugAlerter
from elastalert.config import load_conf
from elastalert.enhancements import DropMatchException
from elastalert.kibana_discover import generate_kibana_discover_url
from elastalert.kibana_external_url_formatter import create_kibana_external_url_formatter
from elastalert.opensearch_discover import generate_opensearch_discover_url
from elastalert.opensearch_external_url_formatter import create_opensearch_external_url_formatter
from elastalert.prometheus_wrapper import PrometheusWrapper
from elastalert.ruletypes import FlatlineRule
from elastalert.ruletypes import RuleType
from elastalert.util import (add_keyword_postfix, cronite_datetime_to_timestamp, dt_to_ts, dt_to_unix, EAException,
elastalert_logger, elasticsearch_client, format_index, lookup_es_key, parse_deadline,
parse_duration, pretty_ts, replace_dots_in_field_names, seconds, set_es_key,
should_scrolling_continue, total_seconds, ts_add, ts_now, ts_to_dt, unix_to_dt,
ts_utc_to_tz)
class ElastAlerter(object):
""" The main ElastAlert runner. This class holds all state about active rules,
controls when queries are run, and passes information between rules and alerts.
:param args: An argparse arguments instance. Should contain debug and start"""
thread_data = threading.local()
def parse_args(self, args):
parser = argparse.ArgumentParser()
parser.add_argument(
'--config',
action='store',
dest='config',
default="config.yaml",
help='Global config file (default: config.yaml)')
parser.add_argument('--debug', action='store_true', dest='debug', help='Suppresses alerts and prints information instead. '
'Not compatible with `--verbose`')
parser.add_argument('--rule', dest='rule', help='Run only a specific rule (by filename, must still be in rules folder)')
parser.add_argument('--silence', dest='silence', help='Silence rule for a time period. Must be used with --rule. Usage: '
'--silence <units>=<number>, eg. --silence hours=2')
parser.add_argument(
"--silence_qk_value",
dest="silence_qk_value",
help="Silence the rule only for this specific query key value.",
)
parser.add_argument('--start', dest='start', help='YYYY-MM-DDTHH:MM:SS Start querying from this timestamp. '
'Use "NOW" to start from current time. (Default: present)')
parser.add_argument('--end', dest='end', help='YYYY-MM-DDTHH:MM:SS Query to this timestamp. (Default: present)')
parser.add_argument('--verbose', action='store_true', dest='verbose', help='Increase verbosity without suppressing alerts. '
'Not compatible with `--debug`')
parser.add_argument('--patience', action='store', dest='timeout',
type=parse_duration,
default=datetime.timedelta(),
help='Maximum time to wait for ElasticSearch to become responsive. Usage: '
'--patience <units>=<number>. e.g. --patience minutes=5')
parser.add_argument(
'--pin_rules',
action='store_true',
dest='pin_rules',
help='Stop ElastAlert from monitoring config file changes')
parser.add_argument('--es_debug', action='store_true', dest='es_debug', help='Enable verbose logging from Elasticsearch queries')
parser.add_argument(
'--es_debug_trace',
action='store',
dest='es_debug_trace',
help='Enable logging from Elasticsearch queries as curl command. Queries will be logged to file. Note that '
'this will incorrectly display localhost:9200 as the host/port')
parser.add_argument('--prometheus_port', type=int, dest='prometheus_port', help='Enables Prometheus metrics on specified port.')
self.args = parser.parse_args(args)
def __init__(self, args):
self.es_clients = {}
self.parse_args(args)
self.debug = self.args.debug
self.verbose = self.args.verbose
if self.verbose and self.debug:
elastalert_logger.info(
"Note: --debug and --verbose flags are set. --debug takes precedent."
)
if self.verbose or self.debug:
elastalert_logger.setLevel(logging.INFO)
if self.debug:
elastalert_logger.info(
"""Note: In debug mode, alerts will be logged to console but NOT actually sent.
To send them but remain verbose, use --verbose instead."""
)
if not self.args.es_debug:
logging.getLogger('elasticsearch').setLevel(logging.WARNING)
if self.args.es_debug_trace:
tracer = logging.getLogger('elasticsearch.trace')
tracer.setLevel(logging.INFO)
tracer.addHandler(logging.FileHandler(self.args.es_debug_trace))
self.conf = load_conf(self.args)
self.rules_loader = self.conf['rules_loader']
self.rules = self.rules_loader.load(self.conf, self.args)
elastalert_logger.info(f'{len(self.rules)} rules loaded')
self.max_query_size = self.conf['max_query_size']
self.scroll_keepalive = self.conf['scroll_keepalive']
self.writeback_index = self.conf['writeback_index']
self.run_every = self.conf['run_every']
self.alert_time_limit = self.conf['alert_time_limit']
self.old_query_limit = self.conf['old_query_limit']
self.disable_rules_on_error = self.conf['disable_rules_on_error']
self.notify_email = self.conf.get('notify_email', [])
self.notify_all_errors = self.conf.get('notify_all_errors', False)
self.notify_alert = self.conf.get('notify_alert', [])
alert_conf_obj = self.conf.copy()
alert_conf_obj['name'] = 'ElastAlert 2 System Error Notification'
alert_conf_obj['alert'] = self.notify_alert
alert_conf_obj['type'] = RuleType({})
self.notify_alerters = self.rules_loader.load_alerts(alert_conf_obj, self.notify_alert)
self.from_addr = self.conf.get('from_addr', 'ElastAlert')
self.smtp_host = self.conf.get('smtp_host', 'localhost')
self.max_aggregation = self.conf.get('max_aggregation', 10000)
self.buffer_time = self.conf['buffer_time']
self.silence_cache = {}
self.rule_hashes = self.rules_loader.get_hashes(self.conf, self.args.rule)
self.starttime = self.args.start
self.disabled_rules = []
self.replace_dots_in_field_names = self.conf.get('replace_dots_in_field_names', False)
self.thread_data.alerts_sent = 0
self.thread_data.num_hits = 0
self.thread_data.num_dupes = 0
executors = {
'default': ThreadPoolExecutor(max_workers=self.conf.get('max_threads', 10)),
}
job_defaults = {
'misfire_grace_time': self.conf.get('misfire_grace_time', 5),
'coalesce': True,
'max_instances': 1
}
self.scheduler = BackgroundScheduler(executors=executors, job_defaults=job_defaults)
self.string_multi_field_name = self.conf.get('string_multi_field_name', False)
self.statsd_instance_tag = self.conf.get('statsd_instance_tag', '')
self.statsd_host = self.conf.get('statsd_host', '')
if self.statsd_host and len(self.statsd_host) > 0:
self.statsd = statsd.StatsClient(host=self.statsd_host, port=8125)
else:
self.statsd = None
self.add_metadata_alert = self.conf.get('add_metadata_alert', False)
self.prometheus_port = self.args.prometheus_port
self.show_disabled_rules = self.conf.get('show_disabled_rules', True)
self.pretty_ts_format = self.conf.get('custom_pretty_ts_format')
self.writeback_es = elasticsearch_client(self.conf)
remove = []
for rule in self.rules:
if 'is_enabled' in rule and not rule['is_enabled']:
self.disabled_rules.append(rule)
remove.append(rule)
elif not self.init_rule(rule):
remove.append(rule)
list(map(self.rules.remove, remove))
if self.args.silence:
self.silence()
self.alert_lock = threading.Lock()
@staticmethod
def get_index(rule, starttime=None, endtime=None):
""" Gets the index for a rule. If strftime is set and starttime and endtime
are provided, it will return a comma seperated list of indices. If strftime
is set but starttime and endtime are not provided, it will replace all format
tokens with a wildcard. """
index = rule['index']
add_extra = rule.get('search_extra_index', False)
if rule.get('use_strftime_index'):
if starttime and endtime:
return format_index(index, starttime, endtime, add_extra)
else:
# Replace the substring containing format characters with a *
format_start = index.find('%')
format_end = index.rfind('%') + 2
return index[:format_start] + '*' + index[format_end:]
else:
return index
@staticmethod
def get_query(filters, starttime=None, endtime=None, sort=True, timestamp_field='@timestamp', to_ts_func=dt_to_ts, desc=False):
""" Returns a query dict that will apply a list of filters, filter by
start and end time, and sort results by timestamp.
:param filters: A list of Elasticsearch filters to use.
:param starttime: A timestamp to use as the start time of the query.
:param endtime: A timestamp to use as the end time of the query.
:param sort: If true, sort results by timestamp. (Default True)
:return: A query dictionary to pass to Elasticsearch.
"""
starttime = to_ts_func(starttime)
endtime = to_ts_func(endtime)
filters = copy.copy(filters)
# ElastAlert documentation still specifies an old way of writing filters
# This snippet of code converts it into the new standard
new_filters = []
for es_filter in filters:
if es_filter.get('query'):
new_filters.append(es_filter['query'])
else:
new_filters.append(es_filter)
es_filters = {'filter': {'bool': {'must': new_filters}}}
if starttime and endtime:
es_filters['filter']['bool']['must'].insert(0, {'range': {timestamp_field: {'gt': starttime,
'lte': endtime}}})
query = {'query': {'bool': es_filters}}
if sort:
query['sort'] = [{timestamp_field: {'order': 'desc' if desc else 'asc'}}]
return query
def get_terms_query(self, query, rule, size, field):
""" Takes a query generated by get_query and outputs a aggregation query """
query_element = query['query']
if 'sort' in query_element:
query_element.pop('sort')
aggs_query = query
aggs_query['aggs'] = {'counts': {'terms': {'field': field,
'size': size,
'min_doc_count': rule.get('min_doc_count', 1)}}}
return aggs_query
def get_aggregation_query(self, query, rule, query_key, terms_size, timestamp_field='@timestamp'):
""" Takes a query generated by get_query and outputs a aggregation query """
query_element = query['query']
if 'sort' in query_element:
query_element.pop('sort')
metric_agg_element = rule['aggregation_query_element']
bucket_interval_period = rule.get('bucket_interval_period')
if bucket_interval_period is not None:
aggs_element = {
'interval_aggs': {
'date_histogram': {
'field': timestamp_field,
'fixed_interval': bucket_interval_period},
'aggs': metric_agg_element
}
}
if rule.get('bucket_offset_delta'):
aggs_element['interval_aggs']['date_histogram']['offset'] = '+%ss' % (rule['bucket_offset_delta'])
else:
aggs_element = metric_agg_element
if query_key is not None:
for idx, key in reversed(list(enumerate(query_key.split(',')))):
aggs_element = {'bucket_aggs': {'terms': {'field': key, 'size': terms_size,
'min_doc_count': rule.get('min_doc_count', 1)},
'aggs': aggs_element}}
aggs_query = query
aggs_query['aggs'] = aggs_element
return aggs_query
def get_index_start(self, index, timestamp_field='@timestamp'):
""" Query for one result sorted by timestamp to find the beginning of the index.
:param index: The index of which to find the earliest event.
:return: Timestamp of the earliest event.
"""
query = {'sort': {timestamp_field: {'order': 'asc'}}}
try:
res = self.thread_data.current_es.search(index=index, size=1, body=query,
_source_includes=[timestamp_field], ignore_unavailable=True)
except ElasticsearchException as e:
self.handle_error("Elasticsearch query error: %s" % (e), {'index': index, 'query': query})
return '1969-12-30T00:00:00Z'
if len(res['hits']['hits']) == 0:
# Index is completely empty, return a date before the epoch
return '1969-12-30T00:00:00Z'
return res['hits']['hits'][0][timestamp_field]
@staticmethod
def process_hits(rule, hits):
""" Update the _source field for each hit received from ES based on the rule configuration.
This replaces timestamps with datetime objects,
folds important fields into _source and creates compound query_keys.
:return: A list of processed _source dictionaries.
"""
processed_hits = []
for hit in hits:
# Merge fields and _source
hit.setdefault('_source', {})
for key, value in list(hit.get('fields', {}).items()):
# Fields are returned as lists, assume any with length 1 are not arrays in _source
# Except sometimes they aren't lists. This is dependent on ES version
hit['_source'].setdefault(key, value[0] if type(value) is list and len(value) == 1 else value)
# Convert the timestamp to a datetime
ts = lookup_es_key(hit['_source'], rule['timestamp_field'])
if not ts and not rule["_source_enabled"]:
raise EAException(
"Error: No timestamp was found for hit. '_source_enabled' is set to false, check your mappings for stored fields"
)
set_es_key(hit['_source'], rule['timestamp_field'], rule['ts_to_dt'](ts))
set_es_key(hit, rule['timestamp_field'], lookup_es_key(hit['_source'], rule['timestamp_field']))
# Tack metadata fields into _source
for field in ['_id', '_index', '_type']:
if field in hit:
hit['_source'][field] = hit[field]
if rule.get('compound_query_key'):
values = [lookup_es_key(hit['_source'], key) for key in rule['compound_query_key']]
hit['_source'][rule['query_key']] = ', '.join([str(value) for value in values])
if rule.get('compound_aggregation_key'):
values = [lookup_es_key(hit['_source'], key) for key in rule['compound_aggregation_key']]
hit['_source'][rule['aggregation_key']] = ', '.join([str(value) for value in values])
processed_hits.append(hit['_source'])
return processed_hits
def get_hits(self, rule, starttime, endtime, index, scroll=False):
""" Query Elasticsearch for the given rule and return the results.
:param rule: The rule configuration.
:param starttime: The earliest time to query.
:param endtime: The latest time to query.
:return: A list of hits, bounded by rule['max_query_size'] (or self.max_query_size).
"""
query = self.get_query(
rule['filter'],
starttime,
endtime,
timestamp_field=rule['timestamp_field'],
to_ts_func=rule['dt_to_ts'],
)
extra_args = {'_source_includes': rule['include']}
scroll_keepalive = rule.get('scroll_keepalive', self.scroll_keepalive)
if not rule.get('_source_enabled'):
query['stored_fields'] = rule['include']
extra_args = {}
if rule.get('include_fields', None) is not None:
query['fields'] = rule['include_fields']
try:
if scroll:
res = self.thread_data.current_es.scroll(scroll_id=rule['scroll_id'], scroll=scroll_keepalive)
else:
res = self.thread_data.current_es.search(
scroll=scroll_keepalive,
index=index,
size=rule.get('max_query_size', self.max_query_size),
body=query,
ignore_unavailable=True,
**extra_args
)
if '_scroll_id' in res:
rule['scroll_id'] = res['_scroll_id']
self.thread_data.total_hits = int(res['hits']['total']['value'])
if len(res.get('_shards', {}).get('failures', [])) > 0:
try:
errs = [e['reason']['reason'] for e in res['_shards']['failures'] if 'Failed to parse' in e['reason']['reason']]
if len(errs):
raise ElasticsearchException(errs)
except (TypeError, KeyError):
# Different versions of ES have this formatted in different ways. Fallback to str-ing the whole thing
raise ElasticsearchException(str(res['_shards']['failures']))
elastalert_logger.debug(str(res))
except ElasticsearchException as e:
# Elasticsearch sometimes gives us GIGANTIC error messages
# (so big that they will fill the entire terminal buffer)
if len(str(e)) > 1024:
e = str(e)[:1024] + '... (%d characters removed)' % (len(str(e)) - 1024)
self.handle_error('Error running query: %s' % (e), {'rule': rule['name'], 'query': query})
return None
hits = res['hits']['hits']
self.thread_data.num_hits += len(hits)
lt = rule.get('use_local_time')
status_log = "Queried rule %s from %s to %s: %s / %s hits" % (
rule['name'],
pretty_ts(starttime, lt, self.pretty_ts_format),
pretty_ts(endtime, lt, self.pretty_ts_format),
self.thread_data.num_hits,
len(hits)
)
if self.thread_data.total_hits > rule.get('max_query_size', self.max_query_size):
elastalert_logger.info("%s (scrolling..)" % status_log)
else:
elastalert_logger.info(status_log)
hits = self.process_hits(rule, hits)
return hits
def get_hits_count(self, rule, starttime, endtime, index):
""" Query Elasticsearch for the count of results and returns a list of timestamps
equal to the endtime. This allows the results to be passed to rules which expect
an object for each hit.
:param rule: The rule configuration dictionary.
:param starttime: The earliest time to query.
:param endtime: The latest time to query.
:return: A dictionary mapping timestamps to number of hits for that time period.
"""
query = self.get_query(
rule['filter'],
starttime,
endtime,
timestamp_field=rule['timestamp_field'],
sort=False,
to_ts_func=rule['dt_to_ts'],
)
es_client = self.thread_data.current_es
try:
res = es_client.count(
index=index,
body=query,
ignore_unavailable=True
)
except ElasticsearchException as e:
# Elasticsearch sometimes gives us GIGANTIC error messages
# (so big that they will fill the entire terminal buffer)
if len(str(e)) > 1024:
e = str(e)[:1024] + '... (%d characters removed)' % (len(str(e)) - 1024)
self.handle_error('Error running count query: %s' % (e), {'rule': rule['name'], 'query': query})
return None
self.thread_data.num_hits += res['count']
lt = rule.get('use_local_time')
elastalert_logger.info(
"Queried rule %s from %s to %s: %s hits" % (rule['name'], pretty_ts(starttime, lt, self.pretty_ts_format),
pretty_ts(endtime, lt, self.pretty_ts_format), res['count'])
)
return {endtime: res['count']}
@staticmethod
def query_key_filters(rule: dict, qk_value_csv: str) -> dict:
if qk_value_csv is None:
return
# Split on comma followed by zero or more whitespace characters. It's
# expected to be commaspace separated. However 76ab593 suggests there
# are cases when it is only comma and not commaspace
qk_values = re.split(r',\s*',qk_value_csv)
end = '.keyword'
query_keys = []
try:
query_keys = rule['compound_query_key']
except KeyError:
query_key = rule.get('query_key')
if query_key is not None:
query_keys.append(query_key)
if len(qk_values) != len(query_keys):
msg = ( f"Received {len(qk_values)} value(s) for {len(query_keys)} key(s)."
f" Did '{qk_value_csv}' have a value with a comma?"
" See https://github.com/jertel/elastalert2/pull/1330#issuecomment-1849962106" )
elastalert_logger.warning( msg )
for key, value in zip(query_keys, qk_values):
if rule.get('raw_count_keys', True):
if not key.endswith(end):
key += end
yield {'term': {key: value}}
def get_hits_terms(self, rule, starttime, endtime, index, key, qk=None, size=None):
rule_filter = copy.copy(rule['filter'])
for filter in self.query_key_filters(rule=rule, qk_value_csv=qk):
rule_filter.append(filter)
base_query = self.get_query(
rule_filter,
starttime,
endtime,
timestamp_field=rule['timestamp_field'],
sort=False,
to_ts_func=rule['dt_to_ts'],
)
if size is None:
size = rule.get('terms_size', 50)
query = self.get_terms_query(base_query, rule, size, key)
try:
res = self.thread_data.current_es.search(index=index, body=query, size=0, ignore_unavailable=True)
except ElasticsearchException as e:
# Elasticsearch sometimes gives us GIGANTIC error messages
# (so big that they will fill the entire terminal buffer)
if len(str(e)) > 1024:
e = str(e)[:1024] + '... (%d characters removed)' % (len(str(e)) - 1024)
self.handle_error('Error running terms query: %s' % (e), {'rule': rule['name'], 'query': query})
return None
if 'aggregations' not in res:
return {}
buckets = res['aggregations']['counts']['buckets']
self.thread_data.num_hits += len(buckets)
lt = rule.get('use_local_time')
elastalert_logger.info(
'Queried rule %s from %s to %s: %s buckets' % (
rule['name'], pretty_ts(starttime, lt, self.pretty_ts_format),
pretty_ts(endtime, lt, self.pretty_ts_format), len(buckets))
)
return {endtime: buckets}
def get_hits_aggregation(self, rule, starttime, endtime, index, query_key, term_size=None):
rule_filter = copy.copy(rule['filter'])
base_query = self.get_query(
rule_filter,
starttime,
endtime,
timestamp_field=rule['timestamp_field'],
sort=False,
to_ts_func=rule['dt_to_ts'],
)
if term_size is None:
term_size = rule.get('terms_size', 50)
query = self.get_aggregation_query(base_query, rule, query_key, term_size, rule['timestamp_field'])
try:
res = self.thread_data.current_es.search(index=index, body=query, size=0, ignore_unavailable=True)
except ElasticsearchException as e:
if len(str(e)) > 1024:
e = str(e)[:1024] + '... (%d characters removed)' % (len(str(e)) - 1024)
self.handle_error('Error running query: %s' % (e), {'rule': rule['name']})
return None
if 'aggregations' not in res:
return {}
payload = res['aggregations']
self.thread_data.num_hits += res['hits']['total']['value']
return {endtime: payload}
def remove_duplicate_events(self, data, rule):
new_events = []
for event in data:
if event['_id'] in rule['processed_hits']:
continue
# Remember the new data's IDs
rule['processed_hits'][event['_id']] = lookup_es_key(event, rule['timestamp_field'])
new_events.append(event)
return new_events
def remove_old_events(self, rule):
# Anything older than the buffer time we can forget
now = ts_now()
remove = []
buffer_time = rule.get('buffer_time', self.buffer_time)
if rule.get('query_delay'):
try:
buffer_time += rule['query_delay']
except Exception as e:
self.handle_error("[remove_old_events]Error parsing query_delay send time format %s" % e)
for _id, timestamp in rule['processed_hits'].items():
if now - timestamp > buffer_time:
remove.append(_id)
list(map(rule['processed_hits'].pop, remove))
def run_query(self, rule, start=None, end=None, scroll=False):
""" Query for the rule and pass all of the results to the RuleType instance.
:param rule: The rule configuration.
:param start: The earliest time to query.
:param end: The latest time to query.
Returns True on success and False on failure.
"""
if start is None:
start = self.get_index_start(rule['index'])
if end is None:
end = ts_now()
if rule.get('query_timezone'):
elastalert_logger.info("Query start and end time converting UTC to query_timezone : {}".format(rule.get('query_timezone')))
start = ts_utc_to_tz(start, rule.get('query_timezone'))
end = ts_utc_to_tz(end, rule.get('query_timezone'))
# Reset hit counter and query
rule_inst = rule['type']
rule['scrolling_cycle'] = rule.get('scrolling_cycle', 0) + 1
index = self.get_index(rule, start, end)
if rule.get('use_count_query'):
data = self.get_hits_count(rule, start, end, index)
elif rule.get('use_terms_query'):
data = self.get_hits_terms(rule, start, end, index, rule['query_key'])
elif rule.get('aggregation_query_element'):
data = self.get_hits_aggregation(rule, start, end, index, rule.get('query_key', None))
else:
data = self.get_hits(rule, start, end, index, scroll)
if data:
old_len = len(data)
data = self.remove_duplicate_events(data, rule)
self.thread_data.num_dupes += old_len - len(data)
# There was an exception while querying
if data is None:
return False
elif data:
if rule.get('use_count_query'):
rule_inst.add_count_data(data)
elif rule.get('use_terms_query'):
rule_inst.add_terms_data(data)
elif rule.get('aggregation_query_element'):
rule_inst.add_aggregation_data(data)
else:
rule_inst.add_data(data)
try:
if rule.get('scroll_id') and self.thread_data.num_hits < self.thread_data.total_hits and should_scrolling_continue(rule):
if not self.run_query(rule, start, end, scroll=True):
return False
except RuntimeError:
# It's possible to scroll far enough to hit max recursive depth
pass
if 'scroll_id' in rule:
scroll_id = rule.pop('scroll_id')
try:
self.thread_data.current_es.clear_scroll(scroll_id=scroll_id)
except NotFoundError:
pass
return True
def get_starttime(self, rule):
""" Query ES for the last time we ran this rule.
:param rule: The rule configuration.
:return: A timestamp or None.
"""
sort = {'sort': {'@timestamp': {'order': 'desc'}}}
query = {'query': {'bool': {'filter': {'term': {'rule_name': '%s' % (rule['name'])}}}}}
query.update(sort)
try:
doc_type = 'elastalert_status'
index = self.writeback_es.resolve_writeback_index(self.writeback_index, doc_type)
res = self.writeback_es.search(index=index, size=1, body=query,
_source_includes=['endtime', 'rule_name'])
if res['hits']['hits']:
endtime = ts_to_dt(res['hits']['hits'][0]['_source']['endtime'])
if ts_now() - endtime < self.old_query_limit:
return endtime
else:
elastalert_logger.info("Found expired previous run for %s at %s" % (rule['name'], endtime))
return None
except (ElasticsearchException, KeyError) as e:
self.handle_error('Error querying for last run: %s' % (e), {'rule': rule['name']})
def set_starttime(self, rule, endtime):
""" Given a rule and an endtime, sets the appropriate starttime for it. """
# This means we are starting fresh
if 'starttime' not in rule:
if not rule.get('scan_entire_timeframe'):
# Try to get the last run from Elasticsearch
last_run_end = self.get_starttime(rule)
if last_run_end:
rule['starttime'] = last_run_end
self.adjust_start_time_for_overlapping_agg_query(rule)
self.adjust_start_time_for_interval_sync(rule, endtime)
rule['minimum_starttime'] = rule['starttime']
return None
# Use buffer for normal queries, or run_every increments otherwise
# or, if scan_entire_timeframe, use timeframe
if not rule.get('use_count_query') and not rule.get('use_terms_query'):
if not rule.get('scan_entire_timeframe'):
buffer_time = rule.get('buffer_time', self.buffer_time)
buffer_delta = endtime - buffer_time
else:
buffer_delta = endtime - rule['timeframe']
# If we started using a previous run, don't go past that
if 'minimum_starttime' in rule and rule['minimum_starttime'] > buffer_delta:
rule['starttime'] = rule['minimum_starttime']
# If buffer_time doesn't bring us past the previous endtime, use that instead
elif 'previous_endtime' in rule and rule['previous_endtime'] < buffer_delta:
rule['starttime'] = rule['previous_endtime']
self.adjust_start_time_for_overlapping_agg_query(rule)
else:
rule['starttime'] = buffer_delta
self.adjust_start_time_for_interval_sync(rule, endtime)
else:
if not rule.get('scan_entire_timeframe'):
# Query from the end of the last run, if it exists, otherwise a run_every sized window
rule['starttime'] = rule.get('previous_endtime', endtime - self.run_every)
else:
#Based on PR 3141 old Yelp/elastalert - rschirin
rule['starttime'] = endtime - rule['timeframe']
def adjust_start_time_for_overlapping_agg_query(self, rule):
if rule.get('aggregation_query_element'):
if rule.get('allow_buffer_time_overlap') and not rule.get('use_run_every_query_size') and (
rule['buffer_time'] > rule['run_every']):
rule['starttime'] = rule['starttime'] - (rule['buffer_time'] - rule['run_every'])
rule['original_starttime'] = rule['starttime']
def adjust_start_time_for_interval_sync(self, rule, endtime):
# If aggregation query adjust bucket offset
if rule.get('aggregation_query_element'):
if rule.get('bucket_interval'):
es_interval_delta = rule.get('bucket_interval_timedelta')
unix_starttime = dt_to_unix(rule['starttime'])
es_interval_delta_in_sec = total_seconds(es_interval_delta)
offset = int(unix_starttime % es_interval_delta_in_sec)
if rule.get('sync_bucket_interval'):
rule['starttime'] = unix_to_dt(unix_starttime - offset)
endtime = unix_to_dt(dt_to_unix(endtime) - offset)
else:
rule['bucket_offset_delta'] = offset
def get_segment_size(self, rule):
""" The segment size is either buffer_size for queries which can overlap or run_every for queries
which must be strictly separate. This mimicks the query size for when ElastAlert is running continuously. """
if not rule.get('use_count_query') and not rule.get('use_terms_query') and not rule.get('aggregation_query_element'):
return rule.get('buffer_time', self.buffer_time)
elif rule.get('aggregation_query_element'):
if rule.get('use_run_every_query_size'):
return self.run_every
else:
return rule.get('buffer_time', self.buffer_time)
else:
return self.run_every
def get_query_key_value(self, rule, match):
# get the value for the match's query_key (or none) to form the key used for the silence_cache.
# Flatline ruletype sets "key" instead of the actual query_key
if isinstance(rule['type'], FlatlineRule) and 'key' in match:
return str(match['key'])
return self.get_named_key_value(rule, match, 'query_key')
def get_aggregation_key_value(self, rule, match):
# get the value for the match's aggregation_key (or none) to form the key used for grouped aggregates.
return self.get_named_key_value(rule, match, 'aggregation_key')
def get_named_key_value(self, rule, match, key_name):
# search the match for the key specified in the rule to get the value
if key_name in rule:
try:
key_value = lookup_es_key(match, rule[key_name])
if key_value is not None:
# Only do the unicode conversion if we actually found something)
# otherwise we might transform None --> 'None'
key_value = str(key_value)
except KeyError:
# Some matches may not have the specified key
# use a special token for these
key_value = '_missing'
else:
key_value = None
return key_value
def enhance_filter(self, rule):
""" If there is a blacklist or whitelist in rule then we add it to the filter.
It adds it as a query_string. If there is already an query string its is appended
with blacklist or whitelist.
:param rule:
:return:
"""
if not rule.get('filter_by_list', True):
return
if 'blacklist' in rule:
listname = 'blacklist'
elif 'whitelist' in rule:
listname = 'whitelist'
else:
return
filters = rule['filter']
additional_terms = []
for term in rule[listname]:
if not term.startswith('/') or not term.endswith('/'):
additional_terms.append(rule['compare_key'] + ':"' + term + '"')
else:
# These are regular expressions and won't work if they are quoted
additional_terms.append(rule['compare_key'] + ':' + term)
if listname == 'whitelist':
query = "NOT " + " AND NOT ".join(additional_terms)
else:
query = " OR ".join(additional_terms)
query_str_filter = {'query_string': {'query': query}}
filters.append(query_str_filter)
elastalert_logger.debug("Enhanced filter with {} terms: {}".format(listname, str(query_str_filter)))
def get_elasticsearch_client(self, rule):
key = rule['name']
es_client = self.es_clients.get(key)
if es_client is None:
es_client = elasticsearch_client(rule)
self.es_clients[key] = es_client
return es_client
def run_rule(self, rule, endtime, starttime=None):
""" Run a rule for a given time period, including querying and alerting on results.
:param rule: The rule configuration.
:param starttime: The earliest timestamp to query.
:param endtime: The latest timestamp to query.
:return: The number of matches that the rule produced.
"""
run_start = time.time()
self.thread_data.current_es = self.get_elasticsearch_client(rule)
# If there are pending aggregate matches, try processing them
for x in range(len(rule['agg_matches'])):
match = rule['agg_matches'].pop()
self.add_aggregated_alert(match, rule)
# Start from provided time if it's given
if starttime:
rule['starttime'] = starttime
else:
self.set_starttime(rule, endtime)
rule['original_starttime'] = rule['starttime']
rule['scrolling_cycle'] = 0
self.thread_data.num_hits = 0
self.thread_data.num_dupes = 0
self.thread_data.cumulative_hits = 0
# Don't run if starttime was set to the future
if ts_now() <= rule['starttime']:
elastalert_logger.warning("Attempted to use query start time in the future (%s), sleeping instead" % (starttime))
return 0
# Run the rule. If querying over a large time period, split it up into segments
segment_size = self.get_segment_size(rule)
tmp_endtime = rule['starttime']
while endtime - rule['starttime'] > segment_size:
tmp_endtime = tmp_endtime + segment_size
if not self.run_query(rule, rule['starttime'], tmp_endtime):
return 0
self.thread_data.cumulative_hits += self.thread_data.num_hits
self.thread_data.num_hits = 0
rule['starttime'] = tmp_endtime
rule['type'].garbage_collect(tmp_endtime)
if rule.get('aggregation_query_element'):
if endtime - tmp_endtime == segment_size:
if not self.run_query(rule, tmp_endtime, endtime):
return 0
self.thread_data.cumulative_hits += self.thread_data.num_hits
elif total_seconds(rule['original_starttime'] - tmp_endtime) == 0:
rule['starttime'] = rule['original_starttime']
return 0
else:
endtime = tmp_endtime
else:
if not self.run_query(rule, rule['starttime'], endtime):
return 0
self.thread_data.cumulative_hits += self.thread_data.num_hits
rule['type'].garbage_collect(endtime)
# Process any new matches
num_matches = len(rule['type'].matches)
while rule['type'].matches:
match = rule['type'].matches.pop(0)
match['num_hits'] = self.thread_data.cumulative_hits
match['num_matches'] = num_matches
# If realert is set, silence the rule for that duration
# Silence is cached by query_key, if it exists
# Default realert time is 0 seconds
silence_cache_key = rule['realert_key']
query_key_value = self.get_query_key_value(rule, match)
if query_key_value is not None:
silence_cache_key += '.' + query_key_value
if self.is_silenced(rule['name'] + "._silence") or self.is_silenced(silence_cache_key):
elastalert_logger.info('Ignoring match for silenced rule %s' % (silence_cache_key,))
continue
if rule['realert']:
next_alert, exponent = self.next_alert_time(rule, silence_cache_key, ts_now())
self.set_realert(silence_cache_key, next_alert, exponent)
if rule.get('run_enhancements_first'):
try:
for enhancement in rule['match_enhancements']:
try:
enhancement.process(match)
except EAException as e:
self.handle_error("Error running match enhancement: %s" % (e), {'rule': rule['name']})
except DropMatchException:
continue
# If no aggregation, alert immediately
if not rule['aggregation']:
self.alert([match], rule)
continue
# Add it as an aggregated match
self.add_aggregated_alert(match, rule)
# Mark this endtime for next run's start
rule['previous_endtime'] = endtime
time_taken = time.time() - run_start
# Write to ES that we've run this rule against this time period
body = {'rule_name': rule['name'],
'endtime': endtime,
'starttime': rule['original_starttime'],
'matches': num_matches,
'hits': max(self.thread_data.num_hits, self.thread_data.cumulative_hits),
'@timestamp': ts_now(),
'time_taken': time_taken}
self.writeback('elastalert_status', body)
# Write metrics about the run to statsd
if self.statsd:
try:
self.statsd.gauge(
'rule.time_taken', time_taken,
tags={"elastalert_instance": self.statsd_instance_tag, "rule_name": rule['name']})
self.statsd.gauge(
'query.hits', self.thread_data.num_hits,
tags={"elastalert_instance": self.statsd_instance_tag, "rule_name": rule['name']})
self.statsd.gauge(
'already_seen.hits', self.thread_data.num_dupes,
tags={"elastalert_instance": self.statsd_instance_tag, "rule_name": rule['name']})
self.statsd.gauge(
'query.matches', num_matches,
tags={"elastalert_instance": self.statsd_instance_tag, "rule_name": rule['name']})
self.statsd.gauge(
'query.alerts_sent', self.thread_data.alerts_sent,
tags={"elastalert_instance": self.statsd_instance_tag, "rule_name": rule['name']})
except BaseException as e:
elastalert_logger.error("unable to send metrics:\n%s" % str(e))
return num_matches
def init_rule(self, new_rule, new=True):
''' Copies some necessary non-config state from an exiting rule to a new rule. '''
if not new and self.scheduler.get_job(job_id=new_rule['name']):
self.scheduler.remove_job(job_id=new_rule['name'])
self.enhance_filter(new_rule)
# Change top_count_keys to .raw
if 'top_count_keys' in new_rule and new_rule.get('raw_count_keys', True):
if self.string_multi_field_name:
string_multi_field_name = self.string_multi_field_name
else:
string_multi_field_name = '.keyword'
for i, key in enumerate(new_rule['top_count_keys']):
if not key.endswith(string_multi_field_name):
new_rule['top_count_keys'][i] += string_multi_field_name