### Setup development environment Source: https://github.com/ait-detectmate/detectmatelibrary/blob/main/docs/installation.md Install development dependencies and pre-commit hooks for linting and formatting. ```bash uv sync --dev ``` ```bash uv run --dev prek install ``` -------------------------------- ### Install DetectMateLibrary as a library Source: https://github.com/ait-detectmate/detectmatelibrary/blob/main/docs/installation.md Install the package into a specific virtual environment. ```bash uv pip install --no-cache-dir ``` -------------------------------- ### Install Python dependencies Source: https://github.com/ait-detectmate/detectmatelibrary/blob/main/README.md Set up the development environment and install pre-commit hooks. ```bash uv sync --dev uv run prek install ``` -------------------------------- ### Auto-configuration Setup Source: https://github.com/ait-detectmate/detectmatelibrary/blob/main/docs/detectors.md Example of enabling auto-configuration for a detector by setting auto_config to True. ```yaml detectors: NewValueDetector: method_type: new_value_detector auto_config: True # enable auto-configuration params: {} # no "events" block needed — it will be generated automatically ``` -------------------------------- ### Install and use Protobuf compiler Source: https://github.com/ait-detectmate/detectmatelibrary/blob/main/docs/installation.md Install the system compiler and generate Python modules from proto definitions. ```bash sudo apt-get update sudo apt-get install -y protobuf-compiler protoc --version ``` ```bash protoc \ --proto_path=src/detectmatelibrary/schemas/ \ --python_out=src/detectmatelibrary/schemas/ \ src/detectmatelibrary/schemas/schemas.proto ``` -------------------------------- ### Install LogBatcher Package Source: https://github.com/ait-detectmate/detectmatelibrary/blob/main/src/detectmatelibrary/parsers/logbatcher/engine/README.md Alternative methods to install the LogBatcher package via PyPI or from source. ```bash pip install logbatcher ``` ```bash pip install -e . ``` -------------------------------- ### Install and use Protobuf compiler Source: https://github.com/ait-detectmate/detectmatelibrary/blob/main/README.md Install system-level protobuf dependencies and compile schema files when modifications are made. ```bash sudo apt install -y protobuf-compiler protoc --version ``` ```bash protoc --proto_path=src/detectmatelibrary/schemas/ --python_out=src/detectmatelibrary/schemas/ src/detectmatelibrary/schemas/schemas.proto ``` -------------------------------- ### Install LogBatcherParser dependencies Source: https://github.com/ait-detectmate/detectmatelibrary/blob/main/docs/parsers/logbatcher_parser.md Install the required dependencies using pip or uv. ```bash pip install "detectmatelibrary[llm]" # or with uv uv sync --extra llm ``` -------------------------------- ### Install DetectMateLibrary in editable mode Source: https://github.com/ait-detectmate/detectmatelibrary/blob/main/docs/installation.md Use this command to install the package into the active Python environment with immediate reflection of source changes. ```bash uv sync ``` -------------------------------- ### Run LogBatcher Parsing Example Source: https://github.com/ait-detectmate/detectmatelibrary/blob/main/src/detectmatelibrary/parsers/logbatcher/engine/README.md Demonstrates how to initialize the parser, load log data, and execute the parsing process. ```python import json from logbatcher.parsing_base import single_dataset_paring from logbatcher.parser import Parser from logbatcher.util import data_loader # load api key, dataset format and parser model, dataset, folder_name ='gpt-3.5-turbo-0125', 'Apache', 'test' config = json.load(open('config.json', 'r')) parser = Parser(model, folder_name, config) # load contents from raw log file, structured log file or content list contents = data_loader( file_name=f"datasets/loghub-2k/{dataset}/{dataset}_2k.log", dataset_format= config['datasets_format'][dataset], file_format ='raw' ) # parse logs single_dataset_paring( dataset=dataset, contents=contents, output_dir= f'outputs/parser/{folder_name}/', parser=parser, debug=False ) ``` -------------------------------- ### Example workspace generation command Source: https://github.com/ait-detectmate/detectmatelibrary/blob/main/docs/create_components.md A concrete example of generating a parser workspace named custom_parser. ```bash mate create --type parser --name custom_parser --dir ./workspaces/custom_parser ``` -------------------------------- ### Development and Maintenance Commands Source: https://github.com/ait-detectmate/detectmatelibrary/blob/main/AGENTS.md Standard commands for environment setup, testing, linting, and Protobuf compilation. ```bash # Install dependencies and pre-commit hooks uv sync --dev uv run prek install # Run tests uv run pytest -q uv run pytest -s # verbose with stdout uv run pytest --cov=. --cov-report=term-missing # with coverage uv run pytest tests/test_foo.py # single test file # Run linting/formatting (all pre-commit hooks) uv run prek run -a # Recompile Protobuf (only if schemas.proto is modified) protoc --proto_path=src/detectmatelibrary/schemas/ \ --python_out=src/detectmatelibrary/schemas/ \ src/detectmatelibrary/schemas/schemas.proto # Scaffold a new component workspace mate create --type --name --dir ``` -------------------------------- ### Clone and Install LogBatcher Source: https://github.com/ait-detectmate/detectmatelibrary/blob/main/src/detectmatelibrary/parsers/logbatcher/engine/README.md Commands to clone the repository and install dependencies in a Python 3.9 environment. ```bash git clone https://github.com/LogIntelligence/LogBatcher.git && cd LogBatcher ``` ```bash conda create -n logbatcher python==3.9 conda activate logbatcher pip install -r requirements.txt ``` -------------------------------- ### Synchronize development environment Source: https://github.com/ait-detectmate/detectmatelibrary/blob/main/docs/development.md Installs all optional dependencies for the development environment using uv. ```bash uv sync --dev ``` -------------------------------- ### JSON log format example Source: https://github.com/ait-detectmate/detectmatelibrary/blob/main/docs/basic_usage.md Example structure of the input logs saved in logs.json. ```json { "0": { "log": "type=USER_ACCT msg=audit(1642723741.072:375): pid=10125 uid=0 auid=4294967295 ses=4294967295 msg='op=PAM:accounting acct=\"root\" exe=\"/usr/sbin/cron\" hostname=? addr=? terminal=cron res=success'", "__version__": "1.0.0", "hostname": "", "logSource": "", "logID": "0" }, ... } ``` -------------------------------- ### Install optional dependencies Source: https://github.com/ait-detectmate/detectmatelibrary/blob/main/docs/installation.md Manage optional feature sets using uv or standard pip commands. ```bash uv sync --extra dataframes ``` ```bash uv pip install "detectmatelibrary[dataframes]" # or pip install "detectmatelibrary[dataframes]" ``` ```bash uv sync --extra dataframes --extra polars-rtcompat ``` ```bash uv sync --extra full # or uv pip install "detectmatelibrary[full]" ``` -------------------------------- ### Example log output Source: https://github.com/ait-detectmate/detectmatelibrary/blob/main/docs/basic_idea.md The resulting string output produced by the Python logging example. ```text hello I am a log about DetectMate getting started and about what is a log ``` -------------------------------- ### Implementing a Custom Parser Source: https://github.com/ait-detectmate/detectmatelibrary/blob/main/docs/parsers.md Example of creating a parser by subclassing CoreParser and CoreParserConfig, implementing the parse() logic to populate the output schema. ```python # filepath: src/detectmatelibrary/parsers/my_parser.py from detectmatelibrary.common.parser import CoreParser, CoreParserConfig from detectmatelibrary import schemas from typing import Any class MyParserConfig(CoreParserConfig): method_type: str = "my_parser" # add parser-specific settings here pattern: str | None = None class MyParser(CoreParser): def __init__(self, name: str = "MyParser", config: MyParserConfig | dict[str, Any] = MyParserConfig()): if isinstance(config, dict): config = MyParserConfig.from_dict(config, name) super().__init__(name=name, config=config) def parse(self, input_: schemas.LogSchema, output_: schemas.ParserSchema) -> bool: text = input_.log or "" # simple example: split on whitespace and treat as variables tokens = text.split() output_["EventID"] = 1 output_["template"] = " ".join(["<*>"] * len(tokens)) output_["variables"].extend(tokens) output_["parsedTimestamp"] = int(time.time()) return True ``` -------------------------------- ### Install and run pre-commit hooks Source: https://github.com/ait-detectmate/detectmatelibrary/blob/main/docs/development.md Configures and executes pre-commit checks to ensure code quality before commits. ```bash uv run prek install ``` ```bash uv run prek run -a ``` -------------------------------- ### Variable Position Mapping Source: https://github.com/ait-detectmate/detectmatelibrary/blob/main/docs/detectors.md Example showing how to map variable positions in a log template. ```text pid=<*> uid=<*> auid=<*> ses=<*> msg='op=<*> acct=<*> exe=<*> hostname=<*> addr=<*> terminal=<*> res=<*>' ``` -------------------------------- ### Configure JSON Parser in YAML Source: https://github.com/ait-detectmate/detectmatelibrary/blob/main/docs/parsers/json_parser.md Example configuration showing the definition of a JsonParser and a sibling JsonMatcherParser. ```yaml parsers: JsonParser: method_type: json_parser params: timestamp_name: "time" content_name: "message" content_parser: JsonMatcherParser # optional — defaults to "JsonMatcherParser" JsonMatcherParser: method_type: matcher_parser params: path_templates: tests/test_data/test_templates.txt ``` -------------------------------- ### Windows CBS Setup Log Format Source: https://github.com/ait-detectmate/detectmatelibrary/blob/main/docs/other/log_formats.md Uses fixed-width columns with literal multiple spaces between fields. ```text 2016-09-28 04:30:22, Info CBS Loaded Servicing Stack v6.1.7601.23505 with Core: C:\Windows\winsxs\amd64_microsoft-windows-servicingstack_31bf3856ad364e35_6.1.7601.23505_none_681aa442f6fed7f0\cbscore.dll ``` -------------------------------- ### Configure EventSequenceDetector via YAML Source: https://github.com/ait-detectmate/detectmatelibrary/blob/main/docs/detectors/event_sequence.md Example configurations for the EventSequenceDetector using either a fixed window size or automatic configuration. ```yaml detectors: EventSequenceDetector: method_type: event_sequence_detector auto_config: False params: fixed_window_size: 3 ``` ```yaml detectors: EventSequenceDetector: method_type: event_sequence_detector auto_config: True data_use_configure: 500 params: min_window_size: 2 max_window_size: 10 ``` -------------------------------- ### Configure Stability Segmentation in YAML Source: https://github.com/ait-detectmate/detectmatelibrary/blob/main/docs/detectors.md Example configuration for a NewValueDetector using time-based stability segmentation. ```yaml detectors: NewValueDetector: method_type: new_value_detector auto_config: True params: stability_segmentation: time timestamp_variable: Time # a field name from the parser's log_format timestamp_format: "%y%m%d %H%M%S" # optional; omit to auto-detect ``` -------------------------------- ### Define Detector Configuration in YAML Source: https://github.com/ait-detectmate/detectmatelibrary/blob/main/AGENTS.md Example structure for configuring a detector, including persistence settings, event tracking, and variable selection. ```yaml detectors: MyDetector: method_type: new_value_detector auto_config: false # true = auto-discover variables from training data persist: # optional — omit to disable state saving path: ./state # base path; detector name is appended automatically interval_seconds: 300 # save every N seconds events_until_save: null # also save after N ingested events (null = disabled) auto_load: false # restore saved state on construction storage_options: {} # fsspec credentials (S3, Azure, GCS, etc.) events: login_failure: # named event ID (string) or integer EventID instance_label: # arbitrary instance name params: {} variables: - pos: pid # named wildcard label OR integer position in ParserSchema.variables[] name: pid header_variables: - pos: Type # key in ParserSchema.logFormatVariables{} params: {} global: # event-ID-independent instances (GLOBAL_EVENT_ID = "*") global_monitor: header_variables: - pos: Level params: {} ``` -------------------------------- ### Alerts JSON format Source: https://github.com/ait-detectmate/detectmatelibrary/blob/main/docs/basic_usage.md Example structure of the alerts saved in alerts.json. ```json { "0": { "extractedTimestamps": [ 1642723752 ], "receivedTimestamp": 1772032073, "score": 1.0, "detectionTimestamp": 1772032073, "alertID": "10", "detectorType": "random_detector", "detectorID": "RandomDetector", "description": "", "__version__": "1.0.0", "logIDs": [ "6" ], "alertsObtain": { "process": "1.0" } }, ... } ``` -------------------------------- ### Example JSON Save File Format Source: https://github.com/ait-detectmate/detectmatelibrary/blob/main/docs/helper/from_to.md Structure of a JSON file saved using the To.json method. ```json { "0": { "logID": "0", "hostname": "", "log": "pid=<*> uid=<*> auid=<*> ses=<*> msg='op=<*> acct=<*> exe=<*> hostname=<*> addr=<*> terminal=<*> res=<*>'", "logSource": "", "__version__": "1.0.0" }, "1": { "logID": "1", "hostname": "", "log": "pid=<*> uid=<*> auid=<*> ses=<*> msg='unit=<*> comm=<*> exe=<*> hostname=<*> addr=<*> terminal=<*> res=<*>'", "logSource": "", "__version__": "1.0.0" } } ``` -------------------------------- ### Example Output Data Source: https://github.com/ait-detectmate/detectmatelibrary/blob/main/docs/helper/from_to.md JSON structure representing the parsed output data after processing by the from-to helper. ```json { "0": { "template": "This is a dummy template", "parsedTimestamp": 1771336089, "EventID": 2, "logFormatVariables": { "Time": "0" }, "parserID": "DummyParser", "parserType": "dummy_parser", "log": "pid=<*> uid=<*> auid=<*> ses=<*> msg='op=<*> acct=<*> exe=<*> hostname=<*> addr=<*> terminal=<*> res=<*>'", "variables": [ "dummy_variable" ], "receivedTimestamp": 1771336089, "logID": "0", "__version__": "1.0.0", "parsedLogID": "10" }, "1": { "template": "This is a dummy template", "parsedTimestamp": 1771336089, "EventID": 2, "logFormatVariables": { "Time": "0" }, "parserID": "DummyParser", "parserType": "dummy_parser", "log": "pid=<*> uid=<*> auid=<*> ses=<*> msg='unit=<*> comm=<*> exe=<*> hostname=<*> addr=<*> terminal=<*> res=<*>'", "variables": [ "dummy_variable" ], "receivedTimestamp": 1771336089, "logID": "1", "__version__": "1.0.0", "parsedLogID": "11" } } ``` -------------------------------- ### Manual Detector Configuration Source: https://github.com/ait-detectmate/detectmatelibrary/blob/main/docs/detectors.md Example of configuring a detector manually when auto_config is set to False, requiring explicit event or global variable definitions. ```yaml detectors: NewValueDetector: method_type: new_value_detector auto_config: False data_use_configure: None # Data used for configuration data_use_training: 199 # Data used for training params: {} # global parameters events: # event-specific configuration 1: # event_id instance1: # name of instance (arbitrary) params: {} # additional params variables: - pos: 0 # location of an unnamed variable from the log message name: var1 # name of variable (arbitrary) header_variables: - pos: level # location of a named variable (defined in log_format of parser) global: # define global instance for new_value_detector similar to "events" global_instance1: # define instance name header_variables: # same logic as header_variables in "events" - pos: Status ``` -------------------------------- ### HealthApp Log Format Example Source: https://github.com/ait-detectmate/detectmatelibrary/blob/main/docs/other/log_formats.md Represents a single log entry from the step-counter mobile application using a pipe-delimited format. ```text 20170201-01:15:35:631|Step_StandCounter|4243|step counts since boot=76149; goal=6000; active=0; distance=45 ``` -------------------------------- ### Bootstrap a new component workspace Source: https://github.com/ait-detectmate/detectmatelibrary/blob/main/docs/create_components.md Use the mate create command to generate a new parser or detector workspace in a specified directory. ```bash mate create --type --name --dir ``` -------------------------------- ### Implement configure method Source: https://github.com/ait-detectmate/detectmatelibrary/blob/main/docs/detectors.md Ingest all available variables into the auto-configuration persistency instance. ```python def configure(self, input_): self.auto_conf_persistency.ingest_event( event_id=input_["EventID"], event_template=input_["template"], variables=input_["variables"], named_variables=input_["logFormatVariables"], ) ``` -------------------------------- ### Parsed log JSON format Source: https://github.com/ait-detectmate/detectmatelibrary/blob/main/docs/basic_usage.md Example structure of the output logs saved in parsed_log.json. ```json { "0": { "parserID": "MatcherParser", "parsedLogID": "10", "logID": "0", "parsedTimestamp": 1772027171, "logFormatVariables": { "Type": "USER_ACCT", "Serial": "375", "Time": "1642723741.072", "Content": "pid=10125 uid=0 auid=4294967295 ses=4294967295 msg='op=PAM:accounting acct=\"root\" exe=\"/usr/sbin/cron\" hostname=? addr=? terminal=cron res=success'" }, "__version__": "1.0.0", "receivedTimestamp": 1772027171, "variables": [ "10125", "0", "4294967295", "4294967295", "PAM:accounting", "\"root\"", "\"/usr/sbin/cron\"", "?", "?", "cron", "success" ], "log": "type=USER_ACCT msg=audit(1642723741.072:375): pid=10125 uid=0 auid=4294967295 ses=4294967295 msg='op=PAM:accounting acct=\"root\" exe=\"/usr/sbin/cron\" hostname=? addr=? terminal=cron res=success'", "parserType": "matcher_parser", "EventID": 0, "template": "pid=<*> uid=<*> auid=<*> ses=<*> msg='op=<*> acct=<*> exe=<*> hostname=<*> addr=<*> terminal=<*> res=<*>'" }, ... } ``` -------------------------------- ### Run unit tests Source: https://github.com/ait-detectmate/detectmatelibrary/blob/main/docs/installation.md Execute the test suite using the development environment configuration. ```bash uv run --dev pytest -s ``` ```bash uv run --dev pytest --cov=. --cov-report=term-missing ``` -------------------------------- ### Run LogBatcher with Docker Source: https://github.com/ait-detectmate/detectmatelibrary/blob/main/src/detectmatelibrary/parsers/logbatcher/engine/README.md Commands to load, build, and run the LogBatcher Docker container. ```bash docker load -i logbatcher.tar docker images docker run -it logbatcher ``` ```bash docker build -t logbatcher . docker images docker run -it logbatcher ``` -------------------------------- ### Initialize and process data with EventSequenceDetector Source: https://github.com/ait-detectmate/detectmatelibrary/blob/main/docs/detectors/event_sequence.md Demonstrates how to instantiate the detector with a specific configuration and process a log entry using ParserSchema. ```python from detectmatelibrary.detectors.event_sequence_detector import EventSequenceDetector, \ EventSequenceDetectorConfig import detectmatelibrary.schemas as schemas detector = EventSequenceDetector( name="EventSequenceTest", config=EventSequenceDetectorConfig(auto_config=False, fixed_window_size=3), ) parser_data = schemas.ParserSchema({ "parserType": "test", "EventID": 1, "template": "test template", "variables": ["var1"], "logID": "1", "parsedLogID": "1", "parserID": "test_parser", "log": "test log message", "logFormatVariables": {"timestamp": "123456"} }) alert = detector.process(parser_data) ``` -------------------------------- ### Configure API Keys Source: https://github.com/ait-detectmate/detectmatelibrary/blob/main/src/detectmatelibrary/parsers/logbatcher/engine/README.md JSON format for setting up API keys in the config.json file. ```json "api_key_from_openai": "", "api_key_from_together":"", ``` -------------------------------- ### Define Component and Configuration Classes Source: https://github.com/ait-detectmate/detectmatelibrary/blob/main/docs/overall_architecture.md Base structure for implementing custom components and their associated configuration classes in DetectMateLibrary. ```python class ConfigComponent(CoreConfig): """Contains all the arguments of the component""" class Component(CoreComponent): def run( self, input_: List[BaseSchema] | BaseSchema, output_: BaseSchema ) -> bool: """Run the component for a specific input""" def train( self, input_: List[BaseSchema] | BaseSchema, ) -> None: """Train the component with a specific input""" def update_state(self, state: StatesL) -> None: """ Update the current state by request of the user states: * keep_training: force to keep training * stop_training: force to stop training * keep_configuring: force to keep configuring * stop_configuring: force to stop configuring """ def get_state(self) -> str: """ Return the current state of the component states: * Configuring: the component is doing configurations * Training: the component is training * Default: the component is just processing data """ def process(self, data: BaseSchema | bytes) -> BaseSchema | bytes | None: """Process the data in a stream fashion (Defined in the CoreComponent)""" def get_config(self) -> Dict[str, Any]: """"Get the configuration of the component (Defined in the CoreComponent)""" def update_config(self, new_config: Dict[str, Any]) -> None: """"Update the configuration of the component (Defined in the CoreComponent)""" ``` -------------------------------- ### Configuring and Running PersistencySaver Source: https://github.com/ait-detectmate/detectmatelibrary/blob/main/docs/auxiliar/persistency.md Automates state persistence to disk using a background timer and event count thresholds. ```python saver = persistency.PersistencySaver( ep, persistency.PersistencySaverConfig( path="./state/my-detector", save_interval_seconds=300, events_until_save=10_000, # save after this many ingests, too auto_load=False, storage_options={}, # forwarded to fsspec ), ) saver.start() # ... detector runs ... saver.stop() # final flush, stops the background timer ``` -------------------------------- ### Implement set_configuration method Source: https://github.com/ait-detectmate/detectmatelibrary/blob/main/docs/detectors.md Query tracker results to select stable variables and generate the final detector configuration. ```python def set_configuration(self): variables = {} for event_id, tracker in self.auto_conf_persistency.get_events_data().items(): stable_vars = tracker.get_features_by_classification("STABLE") variables[event_id] = stable_vars config_dict = generate_detector_config( variable_selection=variables, detector_name=self.name, method_type=self.config.method_type, ) self.config = MyDetectorConfig.from_dict(config_dict, self.name) ``` -------------------------------- ### Generate workspace using CLI Source: https://github.com/ait-detectmate/detectmatelibrary/blob/main/README.md Bootstrap a new workspace for custom parsers or detectors. ```bash mate create --type --name --dir ``` ```bash mate create --type parser --name custom_parser --dir ./workspaces/custom_parser ``` -------------------------------- ### Run unit tests Source: https://github.com/ait-detectmate/detectmatelibrary/blob/main/README.md Execute the test suite with or without coverage reporting. ```bash uv run --dev pytest -q ``` ```bash uv run --dev pytest --cov=. --cov-report=term-missing ``` -------------------------------- ### Configure S3-compatible storage Source: https://github.com/ait-detectmate/detectmatelibrary/blob/main/docs/detectors.md Persistence to S3-compatible services like MinIO. ```yaml persist: path: s3://my-bucket/detector-state storage_options: endpoint_url: http://minio:9000 key: minioadmin secret: minioadmin ``` -------------------------------- ### Benchmark Argument Definitions Source: https://github.com/ait-detectmate/detectmatelibrary/blob/main/src/detectmatelibrary/parsers/logbatcher/engine/README.md Configuration options for the benchmark script arguments. ```bash --data_type Datasets type, Options: ['2k', 'full'], default: '2k'. --model the Large Lauguage model used in LogBatcher, default: 'gpt-3.5-turbo-0125'. --batch_size size of a batch query, default: 10. --chunk_size size of a log chunk, default: 2000. --clustering_method clustering method used in the partitioning stage, Options: ['dbscan', 'meanshift', 'hierarchical'], default: 'dbscan'. --sampling_method sampling method used in the batching stage, Options: ['dpp', 'similar', 'random'], default: 'dpp'. ``` -------------------------------- ### Configure local filesystem storage Source: https://github.com/ait-detectmate/detectmatelibrary/blob/main/docs/detectors.md Persistence to the local filesystem requires no additional storage options. ```yaml persist: path: ./state ``` -------------------------------- ### Initialize and use EventPersistency Source: https://github.com/ait-detectmate/detectmatelibrary/blob/main/docs/auxiliar/persistency.md Demonstrates how to instantiate the persistency handler and perform basic ingestion and retrieval operations. ```python from detectmatelibrary.utils import persistency ep = persistency.EventPersistency( event_data_class=persistency.EventStabilityTracker, ) ep.ingest_event( event_id="4624", event_template="An account was successfully logged on.", named_variables={"AccountName": "alice", "LogonType": "3"}, ) tracker = ep.get_event_data("4624") # or ep["4624"] ``` -------------------------------- ### From.log Source: https://github.com/ait-detectmate/detectmatelibrary/blob/main/docs/helper/from_to.md Loads log files and converts entries to LogSchema objects. ```APIDOC ## From.log ### Description Load logs as input schemas. ### Signature `From.log(component: CoreComponent, in_path: str, do_process: bool = True) -> Iterator[BaseSchema]` ``` -------------------------------- ### From.binary_file Source: https://github.com/ait-detectmate/detectmatelibrary/blob/main/docs/helper/from_to.md Loads binary files containing serialized schema objects. ```APIDOC ## From.binary_file ### Description Load binary files as input schemas. ### Signature `From.binary_file(component: CoreComponent, in_path: str, do_process: bool = True) -> Iterator[BaseSchema]` ``` -------------------------------- ### Generated workspace structure Source: https://github.com/ait-detectmate/detectmatelibrary/blob/main/docs/create_components.md The directory structure created by the mate create command. ```text workspaces/custom_parser/ # workspace root ├── custom_parser/ # Python package │ ├── __init__.py │ └── custom_parser.py # CoreParser-based template ├── tests/ │ └── test_custom_parser.py # generated from template to test custom_parser ├── data.json # example data to run the code ├── LICENSE.md # copied from main project ├── .gitignore # copied from main project ├── .pre-commit-config.yaml # copied from main project ├── pyproject.toml # minimal project + dev extras └── README.md # setup instructions ``` -------------------------------- ### Define a template file Source: https://github.com/ait-detectmate/detectmatelibrary/blob/main/docs/parsers/template_tree_matcher.md Templates are plain text files where the `<*>` token represents a wildcard slot for variable log content. ```text pid=<*> uid=<*> auid=<*> ses=<*> msg='op=PAM:<*> acct=<*> login success: user=<*> source=<*> ``` -------------------------------- ### From.yaml Source: https://github.com/ait-detectmate/detectmatelibrary/blob/main/docs/helper/from_to.md Loads schema objects from YAML files. ```APIDOC ## From.yaml ### Description Load YAML files as input schemas. ### Signature `From.yaml(component: CoreComponent, in_path: str, do_process: bool = True) -> Iterator[BaseSchema]` ``` -------------------------------- ### Expected Parsing Output Source: https://github.com/ait-detectmate/detectmatelibrary/blob/main/src/detectmatelibrary/parsers/logbatcher/engine/README.md Shows the console output after running the demo script. ```text python demo.py Parsing 2000 logs in dataset Apache... 100%|██████████████████████████████████| 2000/2000 [00:04<00:00, 420.55log/s] parsing time: 4.756490230560303 idetified templates: 6 ``` -------------------------------- ### Evaluate Benchmark Results Source: https://github.com/ait-detectmate/detectmatelibrary/blob/main/src/detectmatelibrary/parsers/logbatcher/engine/README.md Run the evaluation script to process benchmark outputs. ```bash cd evaluation && python logbatcher_eval.py --config logbatcher_2k ``` -------------------------------- ### Unit Testing a Parser Source: https://github.com/ait-detectmate/detectmatelibrary/blob/main/docs/parsers.md Demonstrates how to test the parse() method by passing a LogSchema object and asserting the expected values in the ParserSchema output. ```python def test_my_parser_parse(): from detectmatelibrary.parsers.my_parser import MyParser from detectmatelibrary import schemas parser = MyParser() raw = schemas.LogSchema({"log": "a b c", "logID": "1"}) out = schemas.ParserSchema() ok = parser.parse(raw, out) assert ok is True assert out["EventID"] == 1 assert out["variables"] == ["a", "b", "c"] ``` -------------------------------- ### Generate Detector Configuration Programmatically Source: https://github.com/ait-detectmate/detectmatelibrary/blob/main/AGENTS.md Use the helper function to build a detector configuration object in Python. ```python from detectmatelibrary.common._config import generate_detector_config config = generate_detector_config( variable_selection={1: ["var_0", "var_1"]}, detector_name="MyDetector", method_type="new_value_detector", ) ``` -------------------------------- ### Project Directory Structure Source: https://github.com/ait-detectmate/detectmatelibrary/blob/main/src/detectmatelibrary/parsers/logbatcher/engine/README.md Visual representation of the LogBatcher project file hierarchy. ```text 📦LogBatcher ┣ 📂datasets ┃ ┣ 📂loghub-2k ┃ ┃ ┣ 📂Android ┃ ┃ ┃ ┣ 📜Android_2k.log ┃ ┃ ┃ ┣ 📜Android_2k.log_structured.csv ┃ ┃ ┃ ┣ 📜Android_2k.log_templates.csv ┃ ┃ ┃ ┣ 📜Android_2k.log_structured_corrected.csv ┃ ┃ ┃ ┗ 📜Android_2k.log_templates_corrected.csv ┃ ┃ ┣ ... ┃ ┗ 📂loghub-2.0 ┣ 📂evaluation ┃ ┣ 📂utils ┃ ┣ 📜logbatcher_eval.py ┃ ┗ 📜settings.py ┣ 📂logbatcher ┃ ┣ 📜additional_cluster.py ┃ ┣ 📜cluster.py ┃ ┣ 📜parser.py ┃ ┣ 📜matching.py ┃ ┣ 📜parsing_base.py ┃ ┣ 📜postprocess.py ┃ ┣ 📜sample.py ┃ ┗ 📜util.py ┣ 📂outputs ┃ ┣ 📂figures ┃ ┗ 📂parser ┣ 📜README.md ┣ 📜benchmark.py ┣ 📜config.json ┣ 📜requirements.txt ┗ 📜demo.py ``` -------------------------------- ### Generate a log message in Python Source: https://github.com/ait-detectmate/detectmatelibrary/blob/main/docs/basic_idea.md Demonstrates the standard Python logging approach to create a log message containing variable data. ```python import logging var1 = "DetectMate getting started" var2 = "what is a log" logging.info(f"hello I am a log about {var1} and about {var2}") ``` -------------------------------- ### Configure systemd service for persistence Source: https://github.com/ait-detectmate/detectmatelibrary/blob/main/docs/detectors.md Use StateDirectory in a systemd unit file to manage state storage locations automatically. ```ini [Service] User=detectmate StateDirectory=detectmate # → state at /var/lib/detectmate// ``` -------------------------------- ### Standalone Export/Import Source: https://github.com/ait-detectmate/detectmatelibrary/blob/main/docs/auxiliar/persistency.md Functions for manual state snapshots and restoration. ```APIDOC ## Standalone Export/Import ### persistency.save(ep, [path]) Exports the state of an EventPersistency object. If a path is provided, it saves to that URI; otherwise, it returns the state as bytes. ### persistency.load(ep, source) Imports state into an EventPersistency object from a file URI or bytes. ``` -------------------------------- ### Review and squash commits Source: https://github.com/ait-detectmate/detectmatelibrary/blob/main/docs/contribution.md Inspect commit history and squash commits before pushing. ```bash git log ``` ```bash git rebase -i HEAD~n ``` -------------------------------- ### Create a feature branch Source: https://github.com/ait-detectmate/detectmatelibrary/blob/main/docs/contribution.md Create a new branch for your specific work package. ```bash cd DetectMateLibrary git checkout -b feature-some_important_work ``` -------------------------------- ### Configure LogBatcherParser via YAML Source: https://github.com/ait-detectmate/detectmatelibrary/blob/main/docs/parsers/logbatcher_parser.md Define the parser configuration in YAML format for either OpenAI or local Ollama instances. ```yaml parsers: LogBatcherParser: method_type: logbatcher_parser params: model: "gpt-4o-mini" api_key: "" batch_size: 10 ``` ```yaml parsers: LogBatcherParser: method_type: logbatcher_parser params: model: "llama3" api_key: "ollama" base_url: "http://localhost:11434/v1" batch_size: 10 ``` -------------------------------- ### Configure New Event Detector Source: https://github.com/ait-detectmate/detectmatelibrary/blob/main/docs/detectors/new_event.md YAML configuration for the New Event Detector, specifying the method type and parameters. ```yaml detectors: NewEventDetector: method_type: new_event_detector auto_config: False params: {} ``` -------------------------------- ### Manual State Export and Import Source: https://github.com/ait-detectmate/detectmatelibrary/blob/main/docs/auxiliar/persistency.md Standalone functions for one-shot state transfers or snapshots using file URIs or bytes. ```python from detectmatelibrary.utils import persistency # Export to a file URI persistency.save(ep, "./snapshots/trained-state") # Export to bytes (no disk I/O — useful when sending state over a network API) data: bytes = persistency.save(ep) # Import from a file URI persistency.load(ep, "./snapshots/trained-state") # Import from bytes persistency.load(ep, data) ``` -------------------------------- ### Execute test suite Source: https://github.com/ait-detectmate/detectmatelibrary/blob/main/docs/development.md Runs the project test suite using pytest with all optional dependencies included. ```bash uv run --dev pytest ``` -------------------------------- ### Run LogBatcher Benchmark Source: https://github.com/ait-detectmate/detectmatelibrary/blob/main/src/detectmatelibrary/parsers/logbatcher/engine/README.md Execute the benchmark script with specified data type, model, and batch parameters. ```bash python benchmark.py --data_type [DATATYPE] --model [MODEL] --batch_size [BATCHSIZE] --chunk_size [CHUNKSIZE] --sampling_method [SAMPLINGMETHOD] ``` -------------------------------- ### Restoring State with Auto-load Source: https://github.com/ait-detectmate/detectmatelibrary/blob/main/docs/auxiliar/persistency.md Initializes a PersistencySaver with auto-load enabled to pre-populate state from disk. ```python saver = persistency.PersistencySaver( ep, persistency.PersistencySaverConfig(path="./state/my-detector", auto_load=True), ) # ep is now pre-populated from disk ``` -------------------------------- ### Configure New Value Detector in YAML Source: https://github.com/ait-detectmate/detectmatelibrary/blob/main/docs/detectors/new_value.md Define the detector parameters and persistence settings within the configuration file. ```yaml detectors: NewValueDetector: method_type: new_value_detector auto_config: False params: {} persist: # optional — omit to disable saving path: ./state interval_seconds: 300 auto_load: false events: 1: test: params: {} variables: - pos: 0 name: var1 params: threshold: 0. header_variables: - pos: level params: {} ``` -------------------------------- ### From.json Source: https://github.com/ait-detectmate/detectmatelibrary/blob/main/docs/helper/from_to.md Loads schema objects from JSON files. ```APIDOC ## From.json ### Description Load JSON files as input schemas. ### Signature `From.json(component: CoreComponent, in_path: str, do_process: bool = True) -> Iterator[BaseSchema]` ``` -------------------------------- ### Configure Azure Blob Storage Source: https://github.com/ait-detectmate/detectmatelibrary/blob/main/docs/detectors.md Persistence to Azure Blob Storage using account credentials. ```yaml persist: path: az://my-container/detector-state storage_options: account_name: mystorageaccount account_key: base64encodedkey== ``` -------------------------------- ### Configure Deeplog Detector via YAML Source: https://github.com/ait-detectmate/detectmatelibrary/blob/main/docs/detectors/deeplog.md Define the detector parameters, model architecture, and training hyperparameters in the configuration file. ```yaml detectors: DeeplogDetector: method_type: deeplog_detector auto_config: False data_use_training: 10 window_size: 3 hyperparameters: Model: hidden_dim: 64 n_layers: 2 Train: seed: 0 batch_size: 2048 learning_rate: 0.01 epochs: 10 patience: 3 Finetune: - ["Model", "hidden_dim", [128, 256, 512]] - ["Model", "n_layers", [1, 2, 3]] - ["Train", "learning_rate", [0.01, 0.02, 0.03]] ``` -------------------------------- ### To Class Definition Source: https://github.com/ait-detectmate/detectmatelibrary/blob/main/docs/helper/from_to.md Static methods for saving schema objects to various file formats. ```python class To: @staticmethod def binary_file(out_: BaseSchema | bytes | None, out_path: str) -> bytes | None: """Save output schema to a binary file.""" @staticmethod def binary_file(out_: list[BaseSchema] | list[bytes], out_path: str) -> list[bytes]: """Save a list of output schemas to a binary file.""" @staticmethod def json(out_: BaseSchema | None, out_path: str) -> BaseSchema | None: """Save output schema to a JSON file.""" @staticmethod def json(out_: list[BaseSchema], out_path: str) -> list[BaseSchema]: """Save a list of output schemas to a JSON file.""" @staticmethod def yaml(out_: BaseSchema | None, out_path: str) -> BaseSchema | None: """Save output schema to a YAML file.""" @staticmethod def yaml(out_: list[BaseSchema], out_path: str) -> list[BaseSchema] | None: """Save a list of output schemas to a YAML file.""" ``` -------------------------------- ### Configure MatcherParser in YAML Source: https://github.com/ait-detectmate/detectmatelibrary/blob/main/docs/parsers/template_matcher.md Configuration for the MatcherParser, including template file path and preprocessing options like space and punctuation removal. ```yaml parsers: MatcherParser: method_type: matcher_parser auto_config: False params: remove_spaces: True remove_punctuation: True lowercase: True path_templates: path/to/templates.txt ``` -------------------------------- ### Initialize detector with auto-configuration persistency Source: https://github.com/ait-detectmate/detectmatelibrary/blob/main/docs/detectors.md Create a separate EventPersistency instance specifically for the auto-configuration phase. ```python class MyDetector(CoreDetector): def __init__(self, ...): super().__init__(...) # main persistency for training / detection self.persistency = EventPersistency( event_data_class=EventStabilityTracker, ) # separate persistency for auto-configuration self.auto_conf_persistency = EventPersistency( event_data_class=EventStabilityTracker, ) ``` -------------------------------- ### Detector lifecycle with auto-configuration Source: https://github.com/ait-detectmate/detectmatelibrary/blob/main/docs/detectors.md The sequence of method calls required when auto-configuration is enabled. ```text 1. configure(input_) # call for each event in the dataset 2. set_configuration() # finalize which variables to monitor 3. train(input_) # call for each event in the dataset 4. detect(input_, output_) # call for each event to detect anomalies ``` -------------------------------- ### Configure SCVS Detector in YAML Source: https://github.com/ait-detectmate/detectmatelibrary/blob/main/docs/detectors/scvs_detector.md Define the detector method type and window size within the configuration file. ```yaml detectors: SCVSDetector: method_type: scvs_detector window_size: 10 ``` -------------------------------- ### FromTo Conversion Methods Source: https://github.com/ait-detectmate/detectmatelibrary/blob/main/docs/helper/from_to.md Methods for converting between file formats (log, binary, json, yaml) and exporting Polars dataframes. ```APIDOC ## FromTo Class Methods ### Description The FromTo class provides static methods to load data from a source file or dataframe and save it to a destination format in a single operation. ### Methods - **log2binary_file**(component: CoreComponent, in_path: str, out_path: str) -> Iterator[BaseSchema] - **log2json**(component: CoreComponent, in_path: str, out_path: str) -> Iterator[BaseSchema] - **log2yaml**(component: CoreComponent, in_path: str, out_path: str) -> Iterator[BaseSchema] - **binary_file2binary_file**(component: CoreComponent, in_path: str, out_path: str) -> Iterator[BaseSchema] - **binary_file2json**(component: CoreComponent, in_path: str, out_path: str) -> Iterator[BaseSchema] - **binary_file2yaml**(component: CoreComponent, in_path: str, out_path: str) -> Iterator[BaseSchema] - **json2binary_file**(component: CoreComponent, in_path: str, out_path: str) -> Iterator[BaseSchema] - **json2json**(component: CoreComponent, in_path: str, out_path: str) -> Iterator[BaseSchema] - **json2yaml**(component: CoreComponent, in_path: str, out_path: str) -> Iterator[BaseSchema] - **yaml2binary_file**(component: CoreComponent, in_path: str, out_path: str) -> Iterator[BaseSchema] - **yaml2json**(component: CoreComponent, in_path: str, out_path: str) -> Iterator[BaseSchema] - **yaml2yaml**(component: CoreComponent, in_path: str, out_path: str) -> Iterator[BaseSchema] - **polars2binary_file**(component: CoreComponent, df: DataFrame | LazyFrame, out_path: str, renames: dict[str, str] | None = None) -> Iterator[BaseSchema] - **polars2json**(component: CoreComponent, df: DataFrame | LazyFrame, out_path: str, renames: dict[str, str] | None = None) -> Iterator[BaseSchema] - **polars2yaml**(component: CoreComponent, df: DataFrame | LazyFrame, out_path: str, renames: dict[str, str] | None = None) -> Iterator[BaseSchema] ### Parameters - **component** (CoreComponent) - Required - The component context. - **in_path** (str) - Required - Path to the input file. - **out_path** (str) - Required - Path to the output file. - **df** (DataFrame | LazyFrame) - Required (for polars methods) - The dataframe to export. - **renames** (dict[str, str]) - Optional - Dictionary for renaming columns during export. ``` -------------------------------- ### Configure NewValueComboDetector in YAML Source: https://github.com/ait-detectmate/detectmatelibrary/blob/main/docs/detectors/combo.md Define the detector parameters and event variables within the configuration file. ```yaml detectors: NewValueComboDetector: method_type: new_value_combo_detector auto_config: False params: max_combo_size: 3 events: 1: test: params: {} variables: - pos: 0 name: var1 header_variables: - pos: level ``` -------------------------------- ### Push changes to repository Source: https://github.com/ait-detectmate/detectmatelibrary/blob/main/docs/contribution.md Push your local commits to your GitHub repository. ```bash git push ``` -------------------------------- ### Configure a Generic Parser Source: https://github.com/ait-detectmate/detectmatelibrary/blob/main/docs/other/log_formats.md Use this YAML configuration to define a parser with a specific log format and optional template path. ```yaml parsers: MyParser: method_type: matcher_parser auto_config: false log_format: "