Skip to content

Schemas [Code]

Schemas are the typed message objects used to transmit data between components (Parser → Detector). Each schema class wraps a Protobuf message and provides a small, convenient Python API for creation, inspection, (de)serialization and validation.

This document summarizes the available schema classes, the BaseSchema API and common usage patterns.

Design goals

  • Strongly-typed contracts between components.
  • Lightweight wrapper over generated Protobuf types.
  • Simple API for tests and runtime wiring.
  • Safe (de)serialization for transport and persistence.

Architecture

Schemas are used to transfer data between components. Each schema implements the methods defined in BaseSchema. This class acts as a wrapper around the underlying Protobuf classes (op.SchemaT).

UML

All concrete schema classes extend BaseSchema. Connectors let you read and write schema data in databases for downstream tasks such as monitoring and data analysis.

The diagram shows how the Service sends bytes to the Library. The Library deserializes those bytes into a Protobuf-backed schema that a CoreComponent can process through its dictionary-like interface. After processing, the Library can serialize the schema and return it to the Service. With a connector configured, a script can also retrieve a stored record by initializing a schema that uses the same connector.

Schema

Key utility methods:

Schema methods
class BaseSchema:
    def __contains__(self, idx: str) -> bool:
        """Return if a variable is in the schema"""

    def as_dict(self) -> dict[str, Any]:
        """Return the schema variables as a dictionary."""

    def get_schema(self) -> op.SchemaT:
        """Retrieve the current schema instance."""

    def set_schema(self, schema: op.SchemaT) -> None:
        """Set the schema instance and update attributes."""

    def init_schema(self, kwargs: dict[str, Any] | None) -> None:
        """Initialize the schema instance and set attributes."""

    def is_field_list(self, field_name: str) -> bool:
        """Check if a field is a list."""

    def copy(self) -> "BaseSchema":
        """Create a deep copy of the schema instance."""

    def serialize(self) -> bytes:
        """Serialize the schema instance to bytes."""

    def deserialize(self, message: bytes) -> None:
        """Deserialize bytes to populate the schema instance.

        Raises NotSupportedSchema if the bytes cannot be parsed.
        """

    def check_is_same(self, other: Self) -> None:
        """Check if another schema instance is of the same schema type.

        Raises IncorrectSchema if it is not.
        """

    def __eq__(self, other: object) -> bool:
        """Check equality between two schema instances."""

    def store(self) -> Self:
        """Store the schema in the connector framework."""

    def restore(self) -> Self:
        """Restore the schema from the connector framework."""

    @classmethod
    def from_id(cls, id_: str) -> Self:
        """Initialize a schema from the connector framework by its ID."""

The exceptions these methods raise can be imported from detectmatelibrary.schemas:

Schema exceptions
from detectmatelibrary.schemas import IncorrectSchema, NotSupportedSchema

Schema Classes

Below are the primary schema classes and their main fields. All fields are optional at the Protobuf level; components should document which fields they require.

LogSchema

Represents a raw log message.

Fields:

Field Type Notes
logID string Unique identifier for the raw log.
log string Raw log text.
logSource string Source of the log (file, topic, etc.).
hostname string Hostname where the log originated.

ParserSchema

Output of a Parser. Contains parsed fields and template information.

Fields:

Field Type Notes
parserType string Parser type.
parserID string Parser instance identifier.
eventID int32 Template/event identifier.
template string Event template text.
variables repeated string Parameters extracted from the template.
parsedLogID string ID assigned after parsing (optional).
logID string Original raw log ID (link to LogSchema).
log string Raw log text.
headerVariables map Key/value pairs from format extraction.
receivedTimestamp int64 Timestamp when the log was received.
parsedTimestamp int64 Timestamp when parsing completed.

DetectorSchema

Output from Detectors (alerts / findings).

Fields:

Field Type Notes
detectorID string Detector instance identifier.
detectorType string Type/name of detector.
alertID string Unique alert identifier.
detectedTimestamp int64 When the alert was produced.
logIDs repeated string IDs of logs related to the alert.
score float Confidence/score (if applicable).
logTimestamps repeated int64 Timestamps extracted from logs.
description string Human-readable description of the alert.
receivedTimestamp int64 When the detector received the input.
alertDetails map Additional alert metadata.

AggregateSchema

Output from Alert Aggregations (alerts / findings).

Fields:

Field Type Notes
detectorIDs repeated string List of detector instance identifiers.
detectorTypes repeated string List of type/name of detectors.
alertIDs repeated string List of unique alert identifiers.
aggregatedTimestamp int64 When the aggregation was produced.
logIDs repeated string IDs of logs related to the alerts.
logTimestamps repeated int64 Timestamps extracted from logs.
description string Human-readable description of the alert aggregation.
alertDetails map Additional alert metadata from the alert aggregation.

Examples

Short examples of working with the schemas.

Initialize a schema

Initialize schema
from detectmatelibrary import schemas


log_dict = {"log": "Test log"}

log_schema = schemas.LogSchema(log_dict)
print(log_schema.log == "Test log")  # True

Assign values

Assign values to schema
log_schema = schemas.LogSchema()
log_schema.log = "Test log"
print(log_schema["log"] == log_schema.log)  # True

log_schema2 = schemas.LogSchema()
print(log_schema == log_schema2)  # False

log_schema2.log = "Test log"
print(log_schema == log_schema2)  # True

Serialization

Serialize schema
log_schema = schemas.LogSchema()
log_schema.log = "Test log"
serialized = log_schema.serialize()
print(isinstance(serialized, bytes))  # True

new_log_schema = schemas.LogSchema()
new_log_schema.deserialize(serialized)
print(new_log_schema == log_schema)  # True

Connectors

The schemas can be linked to external frameworks, making it easy to read from and write to schemas across different servers or scripts.

Available frameworks:

Connector Type Name URL example Dependencies
Default Does nothing (default) Default None None
Verification Uses an internal dict for testing Verification None None
Mongo Uses MongoDB Mongo mongodb://root:example@localhost:27017/TestDataset/ParsedSchema mongo
Redis Uses Redis Redis http://localhost:6379:0 redis
URL formats
URL example IP Port Database Collection
mongodb://localhost:27017/TestDataset/ParsedSchema localhost 27017 TestDataset ParsedSchema
http://localhost:6379:0 localhost 6379 0 None

To install the optional dependencies, follow the installation instructions. You can configure the connector for all schemas like this:

Connect Schema with MongoDB
from detectmatelibrary.schemas import set_connector

set_connector(
    connector="Mongo",  # Connector name, e.g. "Mongo" or "Redis"
    url="mongodb://root:example@localhost:27017/TestDataset/test",  # Connector URL
)

parsed_schema = schemas.ParserSchema({"parsedLogID": "ciao"}).store()
parsed_schema2 = schemas.ParserSchema.from_id(parsed_schema["parsedLogID"])

print(parsed_schema == parsed_schema2)  # True

Optionally, you can configure the connector separately for each schema. Keep in mind that a schema-specific configuration will override the general setup for that particular schema.

Connect Schema with MongoDB
set_connector(
    connector="Default",  # Global connector: stores nothing
    url="None",  # Global URL
)

# This schema overrides the global setup and uses the Mongo connector
parsed_schema = schemas.ParserSchema(
    {"parsedLogID": "ciao"},
    connector="Mongo",  # Override name
    url="mongodb://root:example@localhost:27017/TestDataset/test",  # Override URL
).store()

# from_id() uses the global (default) connector, which stored nothing
parsed_schema2 = schemas.ParserSchema.from_id(parsed_schema["parsedLogID"])
print(parsed_schema == parsed_schema2)  # False

# A schema with the same override reads back what was stored
parsed_schema3 = schemas.ParserSchema(
    {"parsedLogID": "ciao"},
    connector="Mongo",
    url="mongodb://root:example@localhost:27017/TestDataset/test",
).restore()
print(parsed_schema == parsed_schema3)  # True