parsefabric 0.1.0__py3-none-any.whl
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- parsefabric/__init__.py +79 -0
- parsefabric/_json.py +247 -0
- parsefabric/_summary_review.py +315 -0
- parsefabric/aggregation/__init__.py +30 -0
- parsefabric/aggregation/base.py +265 -0
- parsefabric/aggregation/codec.py +77 -0
- parsefabric/aggregation/evidence.py +667 -0
- parsefabric/aggregation/routing.py +161 -0
- parsefabric/aggregation/statistical.py +153 -0
- parsefabric/builtins/__init__.py +22 -0
- parsefabric/builtins/application_log.py +121 -0
- parsefabric/builtins/cli_output.py +159 -0
- parsefabric/builtins/code_detection.py +228 -0
- parsefabric/builtins/json_parser.py +140 -0
- parsefabric/builtins/mixed_content.py +655 -0
- parsefabric/builtins/python_traceback.py +120 -0
- parsefabric/builtins/timestamped_log.py +135 -0
- parsefabric/capabilities.py +109 -0
- parsefabric/compression.py +118 -0
- parsefabric/engine.py +462 -0
- parsefabric/errors.py +150 -0
- parsefabric/execution/__init__.py +15 -0
- parsefabric/execution/_executor.py +102 -0
- parsefabric/execution/async_backend.py +69 -0
- parsefabric/execution/base.py +143 -0
- parsefabric/execution/process_backend.py +41 -0
- parsefabric/execution/thread_backend.py +36 -0
- parsefabric/models.py +506 -0
- parsefabric/observability.py +252 -0
- parsefabric/parser/__init__.py +10 -0
- parsefabric/parser/_text.py +34 -0
- parsefabric/parser/async_parser.py +53 -0
- parsefabric/parser/base.py +205 -0
- parsefabric/parser/deterministic.py +219 -0
- parsefabric/parser/semantic.py +15 -0
- parsefabric/partitioning.py +172 -0
- parsefabric/patterns/__init__.py +19 -0
- parsefabric/patterns/base.py +98 -0
- parsefabric/patterns/exact.py +61 -0
- parsefabric/patterns/match.py +22 -0
- parsefabric/patterns/predicate.py +62 -0
- parsefabric/patterns/regex.py +78 -0
- parsefabric/patterns/structured.py +59 -0
- parsefabric/py.typed +0 -0
- parsefabric/registry.py +174 -0
- parsefabric/serialization.py +67 -0
- parsefabric/summarization.py +563 -0
- parsefabric-0.1.0.dist-info/METADATA +208 -0
- parsefabric-0.1.0.dist-info/RECORD +51 -0
- parsefabric-0.1.0.dist-info/WHEEL +4 -0
- parsefabric-0.1.0.dist-info/licenses/LICENSE +201 -0
|
@@ -0,0 +1,161 @@
|
|
|
1
|
+
"""Delegate aggregation to the aggregators of the parsers that produced events."""
|
|
2
|
+
|
|
3
|
+
from __future__ import annotations
|
|
4
|
+
|
|
5
|
+
from collections.abc import AsyncIterable, Iterable, Mapping, Sequence
|
|
6
|
+
from typing import override
|
|
7
|
+
|
|
8
|
+
from parsefabric.aggregation.base import Aggregate, Aggregator
|
|
9
|
+
from parsefabric.errors import IntegrityError
|
|
10
|
+
from parsefabric.models import ParsedEvent
|
|
11
|
+
|
|
12
|
+
|
|
13
|
+
class RoutingAggregator(Aggregator):
|
|
14
|
+
"""Aggregate each event with the aggregator of the parser that produced it.
|
|
15
|
+
|
|
16
|
+
Composite parsers such as
|
|
17
|
+
`MixedContentParser` emit events from
|
|
18
|
+
several parsers. Events whose ``evidence.parser_name`` appears in
|
|
19
|
+
``routes`` are aggregated by that aggregator; all others by ``default``.
|
|
20
|
+
Each partition keeps its stream order, and outputs are ordered by first
|
|
21
|
+
appearance.
|
|
22
|
+
|
|
23
|
+
Args:
|
|
24
|
+
default: Aggregator for events of parsers without a route.
|
|
25
|
+
routes: Aggregator for each parser name.
|
|
26
|
+
|
|
27
|
+
Raises:
|
|
28
|
+
TypeError: If an aggregator or name has the wrong type.
|
|
29
|
+
"""
|
|
30
|
+
|
|
31
|
+
def __init__(
|
|
32
|
+
self, default: Aggregator, routes: Mapping[str, Aggregator] | None = None
|
|
33
|
+
) -> None:
|
|
34
|
+
if not isinstance(default, Aggregator):
|
|
35
|
+
raise TypeError("default must be an Aggregator")
|
|
36
|
+
self._default = default
|
|
37
|
+
self._routes = dict(routes or {})
|
|
38
|
+
if any(
|
|
39
|
+
not isinstance(name, str) or not isinstance(aggregator, Aggregator)
|
|
40
|
+
for name, aggregator in self._routes.items()
|
|
41
|
+
):
|
|
42
|
+
raise TypeError("routes must map parser names to Aggregator instances")
|
|
43
|
+
|
|
44
|
+
@property
|
|
45
|
+
def default(self) -> Aggregator:
|
|
46
|
+
"""Aggregator for events whose parser has no dedicated route."""
|
|
47
|
+
return self._default
|
|
48
|
+
|
|
49
|
+
@property
|
|
50
|
+
def routes(self) -> Mapping[str, Aggregator]:
|
|
51
|
+
"""Copy of the parser-name to aggregator routing table."""
|
|
52
|
+
return dict(self._routes)
|
|
53
|
+
|
|
54
|
+
def _key(self, parser_name: str | None) -> str | None:
|
|
55
|
+
return parser_name if parser_name in self._routes else None
|
|
56
|
+
|
|
57
|
+
def _aggregator(self, key: str | None) -> Aggregator:
|
|
58
|
+
return self._default if key is None else self._routes[key]
|
|
59
|
+
|
|
60
|
+
def _children(self) -> tuple[Aggregator, ...]:
|
|
61
|
+
return (self._default, *self._routes.values())
|
|
62
|
+
|
|
63
|
+
@property
|
|
64
|
+
@override
|
|
65
|
+
def lossless(self) -> bool:
|
|
66
|
+
return all(child.lossless for child in self._children())
|
|
67
|
+
|
|
68
|
+
@property
|
|
69
|
+
@override
|
|
70
|
+
def requires_source(self) -> bool:
|
|
71
|
+
return any(child.requires_source for child in self._children())
|
|
72
|
+
|
|
73
|
+
@override
|
|
74
|
+
async def aggregate(
|
|
75
|
+
self, events: Iterable[ParsedEvent] | AsyncIterable[ParsedEvent]
|
|
76
|
+
) -> tuple[Aggregate, ...]:
|
|
77
|
+
partitions: dict[str | None, list[ParsedEvent]] = {}
|
|
78
|
+
|
|
79
|
+
def add(event: ParsedEvent) -> None:
|
|
80
|
+
if not isinstance(event, ParsedEvent):
|
|
81
|
+
raise TypeError("events must be ParsedEvent instances")
|
|
82
|
+
key = self._key(event.evidence.parser_name)
|
|
83
|
+
partitions.setdefault(key, []).append(event)
|
|
84
|
+
|
|
85
|
+
if isinstance(events, AsyncIterable):
|
|
86
|
+
async for event in events:
|
|
87
|
+
add(event)
|
|
88
|
+
else:
|
|
89
|
+
for event in events:
|
|
90
|
+
add(event)
|
|
91
|
+
results: list[Aggregate] = []
|
|
92
|
+
for key, partition in partitions.items():
|
|
93
|
+
results.extend(await self._aggregator(key).aggregate(partition))
|
|
94
|
+
return tuple(results)
|
|
95
|
+
|
|
96
|
+
def _aggregate_key(self, aggregate: Aggregate) -> str | None:
|
|
97
|
+
parser_name = getattr(aggregate, "parser_name", None)
|
|
98
|
+
return self._key(parser_name if isinstance(parser_name, str) else None)
|
|
99
|
+
|
|
100
|
+
@override
|
|
101
|
+
async def materialize(
|
|
102
|
+
self,
|
|
103
|
+
aggregates: Sequence[Aggregate],
|
|
104
|
+
events: Sequence[ParsedEvent] | None = None,
|
|
105
|
+
) -> tuple[ParsedEvent, ...]:
|
|
106
|
+
"""Materialize each partition with its own aggregator, in source order."""
|
|
107
|
+
grouped: dict[str | None, list[Aggregate]] = {}
|
|
108
|
+
for aggregate in aggregates:
|
|
109
|
+
grouped.setdefault(self._aggregate_key(aggregate), []).append(aggregate)
|
|
110
|
+
given: dict[str | None, list[ParsedEvent]] = {}
|
|
111
|
+
for event in events or ():
|
|
112
|
+
given.setdefault(self._key(event.evidence.parser_name), []).append(event)
|
|
113
|
+
partitions: list[tuple[ParsedEvent, ...]] = []
|
|
114
|
+
from_source = True
|
|
115
|
+
for key in dict.fromkeys((*grouped, *given)):
|
|
116
|
+
aggregator = self._aggregator(key)
|
|
117
|
+
if aggregator.requires_source and events is None:
|
|
118
|
+
raise IntegrityError(
|
|
119
|
+
"a routed aggregator requires the events of a fresh re-parse"
|
|
120
|
+
)
|
|
121
|
+
partitions.append(
|
|
122
|
+
await aggregator.materialize(
|
|
123
|
+
grouped.get(key, ()),
|
|
124
|
+
given.get(key, []) if aggregator.requires_source else None,
|
|
125
|
+
)
|
|
126
|
+
)
|
|
127
|
+
from_source = from_source and aggregator.requires_source
|
|
128
|
+
if events is not None and from_source:
|
|
129
|
+
return tuple(events)
|
|
130
|
+
rebuilt = [event for partition in partitions for event in partition]
|
|
131
|
+
if len(partitions) <= 1:
|
|
132
|
+
return tuple(rebuilt)
|
|
133
|
+
if any(event.evidence.line_number is None for event in rebuilt):
|
|
134
|
+
raise IntegrityError(
|
|
135
|
+
"events from several parsers need line numbers to restore order"
|
|
136
|
+
)
|
|
137
|
+
return tuple(
|
|
138
|
+
sorted(
|
|
139
|
+
rebuilt,
|
|
140
|
+
key=lambda event: (
|
|
141
|
+
event.evidence.line_number,
|
|
142
|
+
event.evidence.start_offset or 0,
|
|
143
|
+
),
|
|
144
|
+
)
|
|
145
|
+
)
|
|
146
|
+
|
|
147
|
+
@override
|
|
148
|
+
async def merge(
|
|
149
|
+
self, partials: Iterable[Aggregate] | AsyncIterable[Aggregate]
|
|
150
|
+
) -> tuple[Aggregate, ...]:
|
|
151
|
+
grouped: dict[str | None, list[Aggregate]] = {}
|
|
152
|
+
if isinstance(partials, AsyncIterable):
|
|
153
|
+
async for item in partials:
|
|
154
|
+
grouped.setdefault(self._aggregate_key(item), []).append(item)
|
|
155
|
+
else:
|
|
156
|
+
for item in partials:
|
|
157
|
+
grouped.setdefault(self._aggregate_key(item), []).append(item)
|
|
158
|
+
results: list[Aggregate] = []
|
|
159
|
+
for key, items in grouped.items():
|
|
160
|
+
results.extend(await self._aggregator(key).merge(items))
|
|
161
|
+
return tuple(results)
|
|
@@ -0,0 +1,153 @@
|
|
|
1
|
+
"""Lossy statistical aggregation: counts and time ranges per group."""
|
|
2
|
+
|
|
3
|
+
from __future__ import annotations
|
|
4
|
+
|
|
5
|
+
from collections.abc import AsyncIterable, Iterable, Sequence
|
|
6
|
+
from typing import override
|
|
7
|
+
|
|
8
|
+
from parsefabric._json import dumps
|
|
9
|
+
from parsefabric.aggregation.base import Aggregate, Aggregator, CountAggregate
|
|
10
|
+
from parsefabric.models import JSONValue, ParsedEvent
|
|
11
|
+
|
|
12
|
+
|
|
13
|
+
def _group_identity(
|
|
14
|
+
event_type: str, attributes: dict[str, JSONValue]
|
|
15
|
+
) -> tuple[str, str]:
|
|
16
|
+
# Sorted JSON keeps booleans distinct from the numbers 0 and 1.
|
|
17
|
+
return event_type, dumps(attributes, sort_keys=True)
|
|
18
|
+
|
|
19
|
+
|
|
20
|
+
class EventAccumulator:
|
|
21
|
+
"""Incremental state for counting a large event stream in bounded memory.
|
|
22
|
+
|
|
23
|
+
Only one `CountAggregate` per distinct
|
|
24
|
+
group is kept. Create it with `EventAggregator.accumulator`.
|
|
25
|
+
|
|
26
|
+
Args:
|
|
27
|
+
aggregator: The aggregator whose grouping this state follows.
|
|
28
|
+
"""
|
|
29
|
+
|
|
30
|
+
def __init__(self, aggregator: EventAggregator) -> None:
|
|
31
|
+
self._aggregator = aggregator
|
|
32
|
+
self._groups: dict[tuple[str, str], CountAggregate] = {}
|
|
33
|
+
|
|
34
|
+
def _add(self, partial: CountAggregate) -> None:
|
|
35
|
+
key = _group_identity(partial.event_type, partial.key_attributes)
|
|
36
|
+
current = self._groups.get(key)
|
|
37
|
+
self._groups[key] = partial if current is None else current.merge(partial)
|
|
38
|
+
|
|
39
|
+
def add(self, events: Iterable[ParsedEvent]) -> None:
|
|
40
|
+
"""Count events into their groups.
|
|
41
|
+
|
|
42
|
+
Args:
|
|
43
|
+
events: Events to count.
|
|
44
|
+
"""
|
|
45
|
+
for event in events:
|
|
46
|
+
self._add(
|
|
47
|
+
CountAggregate(
|
|
48
|
+
event_type=event.event_type,
|
|
49
|
+
count=1,
|
|
50
|
+
first_seen=event.timestamp,
|
|
51
|
+
last_seen=event.timestamp,
|
|
52
|
+
key_attributes={
|
|
53
|
+
key: event.attributes.get(key)
|
|
54
|
+
for key in self._aggregator.group_by
|
|
55
|
+
},
|
|
56
|
+
)
|
|
57
|
+
)
|
|
58
|
+
|
|
59
|
+
def merge(self, partials: Iterable[Aggregate]) -> None:
|
|
60
|
+
"""Merge partial summaries into the accumulated groups.
|
|
61
|
+
|
|
62
|
+
Args:
|
|
63
|
+
partials: Count aggregates produced with the same grouping.
|
|
64
|
+
|
|
65
|
+
Raises:
|
|
66
|
+
TypeError: If a partial is not a ``CountAggregate``.
|
|
67
|
+
"""
|
|
68
|
+
for partial in partials:
|
|
69
|
+
if not isinstance(partial, CountAggregate):
|
|
70
|
+
raise TypeError("partials must be CountAggregate instances")
|
|
71
|
+
self._add(partial)
|
|
72
|
+
|
|
73
|
+
def result(self) -> tuple[CountAggregate, ...]:
|
|
74
|
+
"""Return the accumulated summaries in a deterministic order."""
|
|
75
|
+
return tuple(self._groups[key] for key in sorted(self._groups))
|
|
76
|
+
|
|
77
|
+
|
|
78
|
+
class EventAggregator(Aggregator):
|
|
79
|
+
"""Count events by event type and selected attribute values.
|
|
80
|
+
|
|
81
|
+
A statistical, lossy aggregator: it keeps counts and time ranges only, so
|
|
82
|
+
it cannot materialize events. Merging partial results is associative and
|
|
83
|
+
commutative, which suits partitioned or distributed counting. Parsers use
|
|
84
|
+
the lossless `EvidenceAggregator`; use
|
|
85
|
+
this aggregator directly for metrics.
|
|
86
|
+
|
|
87
|
+
Args:
|
|
88
|
+
group_by: Attribute names whose values, with the event type, identify
|
|
89
|
+
a group. A missing attribute groups as ``None``.
|
|
90
|
+
|
|
91
|
+
Raises:
|
|
92
|
+
ValueError: If a name is empty, not a string, or repeated.
|
|
93
|
+
"""
|
|
94
|
+
|
|
95
|
+
def __init__(self, *, group_by: Sequence[str] = ()) -> None:
|
|
96
|
+
names = tuple(group_by)
|
|
97
|
+
if any(not isinstance(name, str) or not name for name in names) or len(
|
|
98
|
+
set(names)
|
|
99
|
+
) != len(names):
|
|
100
|
+
raise ValueError("group_by names must be unique non-empty strings")
|
|
101
|
+
self._group_by = names
|
|
102
|
+
|
|
103
|
+
@property
|
|
104
|
+
def group_by(self) -> tuple[str, ...]:
|
|
105
|
+
"""Attribute names that identify a group."""
|
|
106
|
+
return self._group_by
|
|
107
|
+
|
|
108
|
+
def accumulator(self) -> EventAccumulator:
|
|
109
|
+
"""Create independent incremental state that uses this grouping."""
|
|
110
|
+
return EventAccumulator(self)
|
|
111
|
+
|
|
112
|
+
@override
|
|
113
|
+
async def aggregate(
|
|
114
|
+
self, events: Iterable[ParsedEvent] | AsyncIterable[ParsedEvent]
|
|
115
|
+
) -> tuple[CountAggregate, ...]:
|
|
116
|
+
"""Count events into one ``CountAggregate`` per group.
|
|
117
|
+
|
|
118
|
+
Args:
|
|
119
|
+
events: Events in any order.
|
|
120
|
+
|
|
121
|
+
Returns:
|
|
122
|
+
Summaries in a deterministic order.
|
|
123
|
+
"""
|
|
124
|
+
accumulator = self.accumulator()
|
|
125
|
+
if isinstance(events, AsyncIterable):
|
|
126
|
+
async for event in events:
|
|
127
|
+
accumulator.add((event,))
|
|
128
|
+
else:
|
|
129
|
+
accumulator.add(events)
|
|
130
|
+
return accumulator.result()
|
|
131
|
+
|
|
132
|
+
@override
|
|
133
|
+
async def merge(
|
|
134
|
+
self, partials: Iterable[Aggregate] | AsyncIterable[Aggregate]
|
|
135
|
+
) -> tuple[CountAggregate, ...]:
|
|
136
|
+
"""Merge partial summaries, as produced for separate chunks of events.
|
|
137
|
+
|
|
138
|
+
Args:
|
|
139
|
+
partials: Count aggregates produced with the same grouping.
|
|
140
|
+
|
|
141
|
+
Returns:
|
|
142
|
+
Summaries equal to aggregating all the events at once.
|
|
143
|
+
|
|
144
|
+
Raises:
|
|
145
|
+
TypeError: If a partial is not a ``CountAggregate``.
|
|
146
|
+
"""
|
|
147
|
+
accumulator = self.accumulator()
|
|
148
|
+
if isinstance(partials, AsyncIterable):
|
|
149
|
+
async for partial in partials:
|
|
150
|
+
accumulator.merge((partial,))
|
|
151
|
+
else:
|
|
152
|
+
accumulator.merge(partials)
|
|
153
|
+
return accumulator.result()
|
|
@@ -0,0 +1,22 @@
|
|
|
1
|
+
"""Built-in parsers for logs, JSON, command output, tracebacks and mixed content."""
|
|
2
|
+
|
|
3
|
+
from __future__ import annotations
|
|
4
|
+
|
|
5
|
+
from parsefabric.builtins.application_log import ApplicationLogParser
|
|
6
|
+
from parsefabric.builtins.cli_output import CLIOutputParser
|
|
7
|
+
from parsefabric.builtins.code_detection import DEFAULT_CODE_LANGUAGES, CodeDetector
|
|
8
|
+
from parsefabric.builtins.json_parser import JSONParser
|
|
9
|
+
from parsefabric.builtins.mixed_content import MixedContentParser
|
|
10
|
+
from parsefabric.builtins.python_traceback import PythonTracebackParser
|
|
11
|
+
from parsefabric.builtins.timestamped_log import TimestampedLogParser
|
|
12
|
+
|
|
13
|
+
__all__ = [
|
|
14
|
+
"DEFAULT_CODE_LANGUAGES",
|
|
15
|
+
"ApplicationLogParser",
|
|
16
|
+
"CLIOutputParser",
|
|
17
|
+
"CodeDetector",
|
|
18
|
+
"JSONParser",
|
|
19
|
+
"MixedContentParser",
|
|
20
|
+
"PythonTracebackParser",
|
|
21
|
+
"TimestampedLogParser",
|
|
22
|
+
]
|
|
@@ -0,0 +1,121 @@
|
|
|
1
|
+
"""Application log pattern parser."""
|
|
2
|
+
|
|
3
|
+
from __future__ import annotations
|
|
4
|
+
|
|
5
|
+
import re
|
|
6
|
+
from collections.abc import Iterable
|
|
7
|
+
|
|
8
|
+
from parsefabric.parser import DeterministicParser
|
|
9
|
+
from parsefabric.patterns import Pattern, RegexPattern
|
|
10
|
+
|
|
11
|
+
__all__ = [
|
|
12
|
+
"ApplicationLogParser",
|
|
13
|
+
"default_patterns",
|
|
14
|
+
]
|
|
15
|
+
|
|
16
|
+
# Everything up to the last non-whitespace character. Unlike ``(.*?)\s*$``,
|
|
17
|
+
# this form never re-scans whitespace runs, so matching stays linear.
|
|
18
|
+
_MESSAGE = r"(?P<message>(?:\S|\s+\S)*)"
|
|
19
|
+
|
|
20
|
+
|
|
21
|
+
def _signal(alternatives: str) -> str:
|
|
22
|
+
"""Match a line containing any alternative; the whole line is its message."""
|
|
23
|
+
return rf"^(?=.*\b(?:{alternatives})\b){_MESSAGE}"
|
|
24
|
+
|
|
25
|
+
|
|
26
|
+
def default_patterns() -> tuple[RegexPattern, ...]:
|
|
27
|
+
"""Return the default application-log signal patterns.
|
|
28
|
+
|
|
29
|
+
Returns:
|
|
30
|
+
Fresh pattern instances, from the most to the least specific.
|
|
31
|
+
"""
|
|
32
|
+
return (
|
|
33
|
+
RegexPattern(
|
|
34
|
+
"service_down",
|
|
35
|
+
_signal(r"service down|service stopped|unavailable"),
|
|
36
|
+
flags=re.IGNORECASE,
|
|
37
|
+
priority=20,
|
|
38
|
+
severity="ERROR",
|
|
39
|
+
),
|
|
40
|
+
RegexPattern(
|
|
41
|
+
"connection_failure",
|
|
42
|
+
_signal(r"connection refused|connection reset|connect failed"),
|
|
43
|
+
flags=re.IGNORECASE,
|
|
44
|
+
priority=20,
|
|
45
|
+
severity="ERROR",
|
|
46
|
+
),
|
|
47
|
+
RegexPattern(
|
|
48
|
+
"authentication_failure",
|
|
49
|
+
_signal(r"authentication failed|invalid credentials|login failed"),
|
|
50
|
+
flags=re.IGNORECASE,
|
|
51
|
+
priority=20,
|
|
52
|
+
severity="ERROR",
|
|
53
|
+
),
|
|
54
|
+
RegexPattern(
|
|
55
|
+
"authorization_failure",
|
|
56
|
+
_signal(r"authorization failed|permission denied|forbidden"),
|
|
57
|
+
flags=re.IGNORECASE,
|
|
58
|
+
priority=20,
|
|
59
|
+
severity="ERROR",
|
|
60
|
+
),
|
|
61
|
+
RegexPattern(
|
|
62
|
+
"timeout",
|
|
63
|
+
_signal(r"timeout|timed out"),
|
|
64
|
+
flags=re.IGNORECASE,
|
|
65
|
+
priority=15,
|
|
66
|
+
severity="ERROR",
|
|
67
|
+
),
|
|
68
|
+
RegexPattern(
|
|
69
|
+
"oom",
|
|
70
|
+
_signal(r"OOM|out of memory"),
|
|
71
|
+
flags=re.IGNORECASE,
|
|
72
|
+
priority=15,
|
|
73
|
+
severity="CRITICAL",
|
|
74
|
+
),
|
|
75
|
+
RegexPattern(
|
|
76
|
+
"retry",
|
|
77
|
+
_signal(r"retry|retrying|attempt \d+"),
|
|
78
|
+
flags=re.IGNORECASE,
|
|
79
|
+
priority=10,
|
|
80
|
+
),
|
|
81
|
+
RegexPattern(
|
|
82
|
+
"stack_trace",
|
|
83
|
+
r"^\s*(?P<message>Traceback \(most recent call last\):)",
|
|
84
|
+
priority=10,
|
|
85
|
+
severity="ERROR",
|
|
86
|
+
),
|
|
87
|
+
RegexPattern(
|
|
88
|
+
"error",
|
|
89
|
+
r"\bERROR\b[: ]?\s*(?P<message>.*)",
|
|
90
|
+
flags=re.IGNORECASE,
|
|
91
|
+
priority=5,
|
|
92
|
+
severity="ERROR",
|
|
93
|
+
),
|
|
94
|
+
RegexPattern(
|
|
95
|
+
"warning",
|
|
96
|
+
r"\bWARN(?:ING)?\b[: ]?\s*(?P<message>.*)",
|
|
97
|
+
flags=re.IGNORECASE,
|
|
98
|
+
priority=5,
|
|
99
|
+
severity="WARNING",
|
|
100
|
+
),
|
|
101
|
+
)
|
|
102
|
+
|
|
103
|
+
|
|
104
|
+
class ApplicationLogParser(DeterministicParser):
|
|
105
|
+
"""Recognize common failure signals in free-form application logs.
|
|
106
|
+
|
|
107
|
+
Every line is checked against every pattern, so one line can produce
|
|
108
|
+
several events (for example ``timeout`` and ``error``). Signal patterns
|
|
109
|
+
record the line without trailing whitespace as ``message``; ``error`` and
|
|
110
|
+
``warning`` record the text after the level.
|
|
111
|
+
|
|
112
|
+
Args:
|
|
113
|
+
patterns: Patterns to use instead of `default_patterns`; an
|
|
114
|
+
empty sequence means no patterns.
|
|
115
|
+
"""
|
|
116
|
+
|
|
117
|
+
def __init__(self, patterns: Iterable[Pattern] | None = None) -> None:
|
|
118
|
+
super().__init__(
|
|
119
|
+
default_patterns() if patterns is None else patterns,
|
|
120
|
+
name="application-log",
|
|
121
|
+
)
|
|
@@ -0,0 +1,159 @@
|
|
|
1
|
+
"""Command-output parser: jc's command parsers or caller-provided patterns."""
|
|
2
|
+
|
|
3
|
+
from __future__ import annotations
|
|
4
|
+
|
|
5
|
+
from collections.abc import Sequence
|
|
6
|
+
from typing import override
|
|
7
|
+
|
|
8
|
+
import jc
|
|
9
|
+
|
|
10
|
+
from parsefabric._json import copy_json
|
|
11
|
+
from parsefabric.capabilities import ParserCapabilities
|
|
12
|
+
from parsefabric.errors import ConfigurationError, ParseError, ParseIssue
|
|
13
|
+
from parsefabric.models import (
|
|
14
|
+
JSONValue,
|
|
15
|
+
ParseContext,
|
|
16
|
+
ParsedEvent,
|
|
17
|
+
ParseResult,
|
|
18
|
+
PatternStatistic,
|
|
19
|
+
)
|
|
20
|
+
from parsefabric.parser import DeterministicParser
|
|
21
|
+
from parsefabric.patterns import Pattern
|
|
22
|
+
|
|
23
|
+
|
|
24
|
+
def _records(output: object, command: str) -> list[dict[str, JSONValue]]:
|
|
25
|
+
records = ([output] if output else []) if isinstance(output, dict) else output
|
|
26
|
+
if not isinstance(records, list) or not all(
|
|
27
|
+
isinstance(record, dict) for record in records
|
|
28
|
+
):
|
|
29
|
+
raise ParseError(f"jc {command!r} returned non-JSON records")
|
|
30
|
+
try:
|
|
31
|
+
return [copy_json(record, f"jc {command!r} record") for record in records]
|
|
32
|
+
except ValueError as error:
|
|
33
|
+
raise ParseError(str(error)) from error
|
|
34
|
+
|
|
35
|
+
|
|
36
|
+
class CLIOutputParser(DeterministicParser):
|
|
37
|
+
"""Parse command output with a jc command parser or line patterns.
|
|
38
|
+
|
|
39
|
+
With ``command`` (for example ``command="df"``), the output is parsed by
|
|
40
|
+
[jc](https://github.com/kellyjonbrazil/jc) as one document (tables need
|
|
41
|
+
their header row), so each jc record becomes one ``cli_record`` event
|
|
42
|
+
whose attributes are the record and whose evidence spans the output.
|
|
43
|
+
Output that jc cannot parse becomes one ``unparsed`` event plus a
|
|
44
|
+
`ParseIssue`; non-blank output in which jc finds no records produces a
|
|
45
|
+
warning. With ``patterns``, every line is
|
|
46
|
+
matched like a `DeterministicParser`.
|
|
47
|
+
|
|
48
|
+
Args:
|
|
49
|
+
patterns: Line patterns; mutually exclusive with ``command``.
|
|
50
|
+
command: Name of a jc parser, such as ``"df"`` or ``"kv"``; see
|
|
51
|
+
``jc.parser_mod_list()``. Streaming parsers (``*_s``) are rejected.
|
|
52
|
+
name: Parser name recorded in evidence.
|
|
53
|
+
|
|
54
|
+
Raises:
|
|
55
|
+
ValueError: If both or neither of ``patterns`` and ``command`` are
|
|
56
|
+
given, or the command is unknown or streaming.
|
|
57
|
+
"""
|
|
58
|
+
|
|
59
|
+
def __init__(
|
|
60
|
+
self,
|
|
61
|
+
patterns: Sequence[Pattern] | None = None,
|
|
62
|
+
*,
|
|
63
|
+
command: str | None = None,
|
|
64
|
+
name: str = "cli-output",
|
|
65
|
+
) -> None:
|
|
66
|
+
if (patterns is None) == (command is None):
|
|
67
|
+
raise ValueError("provide exactly one of patterns or command")
|
|
68
|
+
if command is not None:
|
|
69
|
+
if command not in jc.parser_mod_list():
|
|
70
|
+
raise ValueError(
|
|
71
|
+
f"unknown jc command parser {command!r}; see jc.parser_mod_list()"
|
|
72
|
+
)
|
|
73
|
+
if command.endswith("_s"):
|
|
74
|
+
raise ValueError(
|
|
75
|
+
f"{command!r} is a streaming jc parser; use {command[:-2]!r}"
|
|
76
|
+
)
|
|
77
|
+
self._command = command
|
|
78
|
+
super().__init__(
|
|
79
|
+
patterns or (),
|
|
80
|
+
name=name,
|
|
81
|
+
capabilities=(
|
|
82
|
+
None
|
|
83
|
+
if command is None
|
|
84
|
+
else ParserCapabilities(
|
|
85
|
+
deterministic=True, parallel_safe=True, aggregatable=True
|
|
86
|
+
)
|
|
87
|
+
),
|
|
88
|
+
)
|
|
89
|
+
|
|
90
|
+
@property
|
|
91
|
+
def command(self) -> str | None:
|
|
92
|
+
"""The jc parser name, or ``None`` when parsing with patterns."""
|
|
93
|
+
return self._command
|
|
94
|
+
|
|
95
|
+
@override
|
|
96
|
+
def register_pattern(self, pattern: Pattern, *, replace: bool = False) -> None:
|
|
97
|
+
if self._command is not None:
|
|
98
|
+
raise ConfigurationError("a jc command parser does not use patterns")
|
|
99
|
+
super().register_pattern(pattern, replace=replace)
|
|
100
|
+
|
|
101
|
+
@override
|
|
102
|
+
async def parse(
|
|
103
|
+
self,
|
|
104
|
+
source: object,
|
|
105
|
+
context: ParseContext | None = None,
|
|
106
|
+
) -> ParseResult:
|
|
107
|
+
command = self._command
|
|
108
|
+
if command is None:
|
|
109
|
+
return await super().parse(source, context)
|
|
110
|
+
if isinstance(source, bytes):
|
|
111
|
+
text = source.decode("utf-8", errors="strict")
|
|
112
|
+
elif isinstance(source, str):
|
|
113
|
+
text = source
|
|
114
|
+
else:
|
|
115
|
+
raise TypeError("command output parsers accept only str or bytes")
|
|
116
|
+
start = context.source_offset if context and context.source_offset else 0
|
|
117
|
+
end = start + len(text.encode("utf-8"))
|
|
118
|
+
try:
|
|
119
|
+
records = _records(jc.parse(command, text, quiet=True), command)
|
|
120
|
+
except Exception as error: # jc parsers raise arbitrary errors on bad input
|
|
121
|
+
event = self._with_parser_evidence(
|
|
122
|
+
ParsedEvent("unparsed", attributes={"text": text}),
|
|
123
|
+
context,
|
|
124
|
+
start_offset=start,
|
|
125
|
+
end_offset=end,
|
|
126
|
+
pattern_name=command,
|
|
127
|
+
)
|
|
128
|
+
return ParseResult(
|
|
129
|
+
events=(event,),
|
|
130
|
+
errors=(
|
|
131
|
+
ParseIssue.from_exception(
|
|
132
|
+
error, source_id=context.source_id if context else None
|
|
133
|
+
),
|
|
134
|
+
),
|
|
135
|
+
parser_name=self.name,
|
|
136
|
+
parser_version=self.version,
|
|
137
|
+
correlation_id=context.correlation_id if context else None,
|
|
138
|
+
)
|
|
139
|
+
return ParseResult(
|
|
140
|
+
events=tuple(
|
|
141
|
+
self._with_parser_evidence(
|
|
142
|
+
ParsedEvent("cli_record", attributes=record),
|
|
143
|
+
context,
|
|
144
|
+
start_offset=start,
|
|
145
|
+
end_offset=end,
|
|
146
|
+
pattern_name=command,
|
|
147
|
+
)
|
|
148
|
+
for record in records
|
|
149
|
+
),
|
|
150
|
+
warnings=(
|
|
151
|
+
(f"jc {command!r} found no records in non-blank output",)
|
|
152
|
+
if not records and text.strip()
|
|
153
|
+
else ()
|
|
154
|
+
),
|
|
155
|
+
pattern_statistics=(PatternStatistic(command, len(records)),),
|
|
156
|
+
parser_name=self.name,
|
|
157
|
+
parser_version=self.version,
|
|
158
|
+
correlation_id=context.correlation_id if context else None,
|
|
159
|
+
)
|