forked from elastic/detection-rules
-
Notifications
You must be signed in to change notification settings - Fork 0
/
__init__.py
80 lines (57 loc) · 2.08 KB
/
__init__.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
# Copyright Elasticsearch B.V. and/or licensed to Elasticsearch B.V. under one
# or more contributor license agreements. Licensed under the Elastic License
# 2.0; you may not use this file except in compliance with the Elastic License
# 2.0.
import eql
from . import ast
from .dsl import ToDsl
from .eql2kql import Eql2Kql
from .errors import KqlParseError, KqlCompileError
from .evaluator import FilterGenerator
from .kql2eql import KqlToEQL
from .parser import lark_parse, KqlParser
__version__ = '0.1.6'
__all__ = (
"ast",
"from_eql",
"get_evaluator",
"KqlParseError",
"KqlCompileError",
"lint",
"parse",
"to_dsl",
"to_eql",
)
def to_dsl(parsed, optimize=True, schema=None):
"""Convert KQL to Elasticsearch Query DSL."""
if not isinstance(parsed, ast.KqlNode):
parsed = parse(parsed, optimize, schema)
return ToDsl.convert(parsed)
def to_eql(text, optimize=True, schema=None):
if isinstance(text, bytes):
text = text.decode("utf-8")
lark_parsed = lark_parse(text)
converted = KqlToEQL(text, schema=schema).visit(lark_parsed)
return converted.optimize(recursive=True) if optimize else converted
def parse(text, optimize=True, schema=None):
if isinstance(text, bytes):
text = text.decode("utf-8")
lark_parsed = lark_parse(text)
converted = KqlParser(text, schema=schema).visit(lark_parsed)
return converted.optimize(recursive=True) if optimize else converted
def lint(text):
if isinstance(text, bytes):
text = text.decode("utf-8")
return parse(text, optimize=True).render()
def from_eql(tree, optimize=True):
if not isinstance(tree, eql.ast.EqlNode):
try:
tree = eql.parse_query(tree, implied_any=True)
except eql.EqlSemanticError:
tree = eql.parse_expression(tree)
converted = Eql2Kql().walk(tree)
return converted.optimize(recursive=True) if optimize else converted
def get_evaluator(tree, optimize=False):
if not isinstance(tree, ast.KqlNode):
tree = parse(tree, optimize=optimize)
return FilterGenerator().filter(tree)