SOC AI Agent

Integration Guide — Sending Server Logs via API

  • api
  • bash
  • curl
  • ingest
  • integration
  • logs
  • python
  • siem
  • soc

How to send server logs to Dolutech SOC AI through POST /api/v1/ingest/json: authentication, request and response format, error handling, limits, ready-to-use examples (curl, bash, Python) and an acceptance checklist.

Dolutech SOC AI

Document version 1.6
Date 11/11/2026
Instance {SOC_URL} ← fill in with your instance URL
Audience Technical teams integrating servers, scripts or their own SIEM with Dolutech SOC AI

About {SOC_URL}: throughout this guide, https://{SOC_URL} stands for the URL of your Dolutech SOC AI instance: the same one shown in your panel's address bar and on the endpoint screen where the API key is generated. Each instance has its own. Never send logs or keys to a URL other than the one shown in your panel.


1. Overview

The ingestion API receives log lines from your servers, stores each one exactly as sent, and then analyzes the content for threats. Anything relevant becomes an alert or incident in the SOC panel.

 ┌───────────────────────────┐                        ┌──────────────────────────────────┐
 │ Your server / script /    │   HTTPS (TLS 1.2+)     │ Dolutech SOC AI ({SOC_URL})      │
 │ SIEM                      │   POST /api/v1/        │                                  │
 │                           │   ingest/json          │ 1. Authenticates the key         │
 │ logs ──► batch (≤100)     │ ─────────────────────► │ 2. Validates, stores raw log     │
 │      ──► gzip             │   X-API-Key: soc_...   │ 3. Responds 201 (stored)         │
 │      ──► local spool      │ ◄───────────────────── │ 4. Analyzes (asynchronous)       │
 │                           │   201 + status/item    │ 5. Alerts and incidents → Panel  │
 └───────────────────────────┘                        └──────────────────────────────────┘

Two ways to integrate:

Option When to use
Official Dolutech SOC Collector agent (recommended) Linux, Windows or macOS servers where you can install software. The agent already does everything this guide describes: batching, gzip, idempotency, on-disk buffer and retries. It automatically collects /var/log/auth.log, secure, syslog, messages, audit, kern, nginx and apache/httpd logs, among others.
Direct API integration (this guide) Appliances, your own SIEM, scripts, applications, or environments where the agent cannot be installed.

2. Prerequisites

Item Detail
Registered endpoint One endpoint created in the SOC panel for each server that will send logs.
API key Generated in the panel: Endpoint → API key (or regenerate key). Format: soc_ followed by 32 characters.
Instance URL The https://{SOC_URL} URL shown in your panel.
TLS HTTPS client supporting TLS 1.2 or 1.3. TLS 1.0 and 1.1 are refused.
Outbound network HTTPS access (port 443) from the source server to {SOC_URL}.
Synchronized clock NTP enabled (chrony, systemd-timesyncd, w32time). Timestamps outside the accepted window are replaced with the reception time (see section 4).

3. Authentication and key safekeeping

3.1 How to authenticate

Every request carries the key in a header:

X-API-Key: soc_xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx

Rules:

  • The server's identity comes only from the key. Identification fields in the body (host name, endpoint ID, etc.) do not change which endpoint the log belongs to.

  • The key is shown only once, when it is generated. Copy it straight to secure storage (section 3.2). If you lose it, regenerate it.

  • The key can have an optional validity of 30, 60, 90, 180 or 365 days. During the last 7 days of validity, responses carry these headers:

    Header Value
    X-API-Key-Expiring true
    X-API-Key-Expires-At Expiration date in ISO-8601

    Monitor these headers and raise an internal alert to rotate the key before it expires. An expired key gets 401 with code: api_key_expired.

3.2 Key safekeeping — mandatory practices

Do Don't
Store the key in a file with 600 permissions (e.g. /etc/dolutech-soc/api.key, owned by root) or in a secrets vault. Pass the key as a command-line argument: it becomes visible in ps and in the shell history.
Read the key from an environment variable or from the file, at run time. Store the key in a git repository, container image, ticket or chat.
Use one key per server/endpoint. Share the same key across several servers.
Rotate it periodically (regenerate in the panel) and whenever a leak is suspected. Write the key to your application's or proxies' logs.
Revoke/regenerate it in the panel when the server is decommissioned. Follow HTTP redirects carrying the key (see 3.3).

Creating the key file without the key going through the shell history:

sudo install -d -m 700 -o root -g root /etc/dolutech-soc
sudo sh -c 'umask 077; cat > /etc/dolutech-soc/api.key'
# Paste the key, press Enter and then Ctrl+D.
sudo chmod 600 /etc/dolutech-soc/api.key

3.3 Transport

  • Always use https://. http:// requests get a 301 redirect.
  • Do not configure the client to follow redirects. A client that follows the 301 has already sent the key in clear text in the first request. Configure the https:// URL directly and treat any 3xx as a configuration error.

4. Request specification

4.1 Request line and headers

POST /api/v1/ingest/json HTTP/1.1
Host: {SOC_URL}
X-API-Key: soc_xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx
Content-Type: application/json
Content-Encoding: gzip

Headers:

  • X-API-Key — Required: Yes. Value: The endpoint's key.
  • Content-Type — Required: Yes. Value: application/json
  • Content-Encoding — Required: No (recommended). Value: gzip. It is the only encoding accepted besides an uncompressed body. Any other value returns 415.

Always use the /api/v1/ingest/json path. There is a legacy route without the /json suffix; do not use it in new integrations.

4.2 Body

{
  "logs": [
    {
      "raw_log": "Dec  3 10:15:42 web01 sshd[2211]: Failed password for invalid user admin from 203.0.113.45 port 52114 ssh2",
      "source_ip": "203.0.113.45",
      "log_type": "auth",
      "log_timestamp": "2026-12-03T10:15:42-03:00",
      "source_event_id": "3b7d1c0e5a9f4b2d8c6e0a1f3b5d7c9e2a4c6e8f0b1d3f5a7c9e1b3d5f7a9c0e",
      "parsed_metadata": { "host": "web01", "file": "/var/log/auth.log" }
    }
  ]
}

The logs array must hold 1 to 100 items per request.

4.3 Item fields

Field Type Required
raw_log string Yes
source_ip string No
log_type string (≤ 50) No
severity string No
log_timestamp string (≤ 64) No
source_event_id string No, but strongly recommended
parsed_metadata object No

Rules for each field:

  • raw_log — The raw, complete log line. It is stored exactly as sent, with no summarizing or truncation. Limit: 65,535 UTF-8 bytes per item. The limit is in bytes, not characters: accented letters and emojis take 2 to 4 bytes. Split or truncate before sending. Multi-line events (e.g. a stack trace) can go in a single item, with \n inside the JSON string. Logs that are already JSON can be sent serialized as a string in this field.
  • source_ip — A valid IPv4 or IPv6 address associated with the event (e.g. the attacker's IP). If omitted, the SOC extracts the IP from the text itself.
  • log_type — Log type/source. Examples: auth, syslog, nginx_access, nginx_error, apache_access, apache_error, firewall. The xdr_ prefix is reserved for the XDR agent's telemetry: do not use it. Depending on the credential, an item with that prefix either makes the whole batch be refused with 422 (namespace_denied) or is stored as unverified telemetry, which never triggers an automatic response.
  • severity — info, low, medium, high or critical. If sent, it is honored. If omitted, the SOC classifies it. Recommendation: omit it and let the SOC classify (see 4.4).
  • log_timestamp — Event date/time in ISO-8601 with time zone (e.g. 2026-12-03T10:15:42-03:00 or 2026-12-03T13:15:42Z). Accepted when between now − 7 days and now + 5 minutes. Outside that window, in numeric format (epoch) or unreadable, the SOC uses the reception time and flags the adjustment on the record.
  • source_event_id — Exactly 64 hexadecimal characters (e.g. SHA-256). A stable event identifier. It guarantees idempotency: resending the same ID returns duplicate and does not duplicate the log. Without it, a resend after a timeout stores the log twice.
  • parsed_metadata — Free-form metadata (e.g. host, file, app). Limits: maximum depth 6, up to 256 keys per level, strings up to 4 KiB. Some keys are reserved by the SOC and are silently removed.

Any other field is ignored.

4.4 Severity: why to omit it

By default, the endpoint discards events with info severity. Those items come back as rejected with reason: severity_filtered. If you send severity: "info" for relevant events (e.g. a failed login), they will not be analyzed.

  • Recommended: omit severity and let the SOC classify each line.
  • If you must send it: never mark an event that should be analyzed as info.

4.5 How to generate source_event_id

The ID must be the same every time the same event is resent and different between distinct events, including between two lines with identical text. A reliable recipe:

source_event_id = SHA-256( host | file_path | inode | line_offset | line_content )

The offset (the line's byte position in the file) and the inode tell identical lines apart, such as two identical failed logins in the same second. The examples in sections 8.3 and 8.4 implement this recipe.


5. Response specification

5.1 Success: HTTP 201

Every accepted request returns HTTP 201, even if some items were marked duplicate or rejected:

{
  "status": "success",
  "data": {
    "message": "1 logs ingested",
    "count": 1,
    "ids": [123456],
    "accepted": 1,
    "duplicate": 0,
    "rejected": 0,
    "events": [
      {
        "index": 0,
        "source_event_id": "3b7d1c0e5a9f4b2d8c6e0a1f3b5d7c9e2a4c6e8f0b1d3f5a7c9e1b3d5f7a9c0e",
        "status": "accepted",
        "storage": "persisted",
        "reason": "stored",
        "retryable": false,
        "log_id": 123456
      }
    ]
  }
}

HTTP 201 means the batch was stored safely. Threat analysis happens right after, asynchronously. Alerts and incidents show up in the panel a few moments later. There is no need to wait for or poll anything after the 201.

Invariants your client can check:

  • accepted equals the number of elements in ids;
  • accepted + duplicate + rejected equals the number of items sent.

5.2 Per-item result (events[])

Each element of events corresponds to one item of the batch, at the position given by index.

  • accepted (reason: stored, storage: persisted): Log stored and forwarded for analysis. Client action: None.
  • duplicate (reason: already_received, storage: none): A log with the same source_event_id already existed. Nothing was duplicated. Client action: None. This is the expected result of a resend.
  • rejected (reason: severity_filtered, storage: filtered): Discarded by the endpoint's severity filter (e.g. info). Client action: Do not resend. Review your use of severity (section 4.4).
  • rejected (reason: log_filter, storage: filtered): Discarded by a log filter rule configured in the panel. Client action: Do not resend. Review the filter rules in the panel if the discard was not intended.

6. Error codes and retry policy

Error responses generated by the API follow this format:

{ "status": "error", "code": "payload_too_large", "message": "..." }

Not every error response carries code. Validation errors (422) carry message and errors. Errors coming from the edge layer may arrive as HTML. Always decide by the HTTP status code, never by the body format.

For each HTTP status code: the typical cause (with the code, when present), whether the batch was stored, and the recommended action.

  • 201 — Success
    • Batch stored: Yes
    • Recommended action: Remove the batch from the local buffer.
  • 3xx — http:// URL or wrong URL
    • Batch stored: No
    • Recommended action: Configuration error. Do not follow the redirect. Fix the URL to https://{SOC_URL}.
  • 400 — payload_invalid: corrupt gzip or unreadable body
    • Batch stored: No
    • Recommended action: Client defect. Fix how the body is built. Do not resend the same content.
  • 401 — Missing or invalid key; api_key_expired; tenant_suspended
    • Batch stored: No
    • Recommended action: Stop sending. Fix or rotate the key in the panel. Do not loop: at most one new attempt every 5 minutes.
  • 403 — ingest_format_mismatch, ingest_instance_inactive
    • Batch stored: No
    • Recommended action: Stop sending. Check that the key belongs to an active endpoint suited to this ingestion type.
  • 413 — payload_too_large
    • Batch stored: No
    • Recommended action: Split the batch into smaller batches and resend. If a single item is too large, truncate it (≤ 65,535 bytes) or discard it.
  • 415 — unsupported_content_encoding
    • Batch stored: No
    • Recommended action: Use only Content-Encoding: gzip or none.
  • 422 — Validation error (message + errors), including namespace_denied
    • Batch stored: No: the whole batch is refused
    • Recommended action: Do not resend it unchanged. Split the batch in half repeatedly to isolate the invalid item, resend the valid ones and discard or fix the invalid one.
  • 429 — Rate limit
    • Batch stored: No
    • Recommended action: Wait for the time in the Retry-After header (in seconds). If absent, wait 30 s. Resend the same batch.
  • 500, 502, 503, 504 — Temporary unavailability
    • Batch stored: Not confirmed
    • Recommended action: Resend the same batch with exponential backoff (e.g. 5 s, 10 s, 20 s, 40 s… up to 5 min). Honor Retry-After when present (a 503 may carry Retry-After: 5).
  • Timeout / network error — Connection refused, DNS, TLS, timeout
    • Batch stored: Not confirmed
    • Recommended action: Same handling as 5xx.

General rules:

  • Client timeout: 30 seconds per request.
  • Always resend the same batch, with the same source_event_id values. That way, if the first send was stored and only the response was lost, the resend comes back as duplicate and nothing is duplicated.
  • Keep a local (spool) buffer on disk. Write the batch to disk before sending and delete it only after the 201. That way no log is lost during network outages or unavailability.
  • Never resend items that came back as rejected inside a 201.

7. Limits

Limit Value Note
Items per request 1 to 100 Above 100: 422.
raw_log size 65,535 UTF-8 bytes per item Measured in bytes, not characters.
Compressed body (gzip) 5 MiB Above: 413 payload_too_large.
Decompressed body 10 MiB Above: 413 payload_too_large.
Rate per key 480 requests/min, burst of 60 every 10 s Above: 429.
Rate per source public IP 300 requests/min, burst of 200 Servers behind the same NAT share this limit.
Volume per endpoint 64 MiB compressed / 128 MiB decompressed per minute Above: 429.
log_timestamp window now − 7 days to now + 5 min Outside it: the reception time is used.
parsed_metadata Depth 6, 256 keys per level, 4 KiB strings —

The rate and volume limits above are the platform defaults and can be adjusted per instance. Your client must always obey the HTTP status code and the Retry-After it receives, not fixed numbers.

Practical recommendation: each server sends one batch every 15–30 seconds, with up to 100 items, compressed with gzip. This is the same pattern as the official agent (every 30 s, batches of up to 100, gzip). If the server produces more than 100 lines in the interval, send several batches in sequence, without aggressive parallelism.


8. Practical examples

All examples use https://{SOC_URL}. Replace it with your instance URL.

For the interactive examples (8.1 and 8.2), load the key into the session without it landing in the history:

read -r -s -p 'API key: ' SOC_API_KEY; echo
export SOC_API_KEY
export SOC_URL="https://{SOC_URL}"   # replace with the URL of your panel

The examples pass the key to curl through --config - (standard input). That way it does not appear in the process list, as it would with -H "X-API-Key: ...".

8.1 curl: simple send (one log)

printf 'header = "X-API-Key: %s"\n' "$SOC_API_KEY" |
curl --config - --silent --show-error \
     --proto '=https' --tlsv1.2 --max-time 30 \
     --request POST "$SOC_URL/api/v1/ingest/json" \
     --header 'Content-Type: application/json' \
     --write-out '\nHTTP %{http_code}\n' \
     --data-binary '{
  "logs": [
    {
      "raw_log": "Dec  3 10:15:42 web01 sshd[2211]: Failed password for invalid user admin from 203.0.113.45 port 52114 ssh2",
      "log_type": "auth",
      "source_ip": "203.0.113.45",
      "source_event_id": "3b7d1c0e5a9f4b2d8c6e0a1f3b5d7c9e2a4c6e8f0b1d3f5a7c9e1b3d5f7a9c0e"
    }
  ]
}'

Expected output (formatted):

{"status":"success","data":{"message":"1 logs ingested","count":1,"ids":[123456],"accepted":1,"duplicate":0,"rejected":0,"events":[{"index":0,"source_event_id":"3b7d1c0e...","status":"accepted","storage":"persisted","reason":"stored","retryable":false,"log_id":123456}]}}
HTTP 201

Run the same command again: the response will be 201 with "accepted":0,"duplicate":1. That proves idempotency.

log_timestamp was left out on purpose: a fixed time in this document would soon fall outside the 7-day window. Example 8.2 generates the time at send time.

8.2 curl: gzip-compressed batch from a JSON file

Build the batch.json file (generated here with jq, with the time and IDs computed on the spot):

NOW="$(date -Iseconds)"
id() { printf '%s' "$1" | sha256sum | cut -d' ' -f1; }

jq -n --arg ts "$NOW" \
      --arg id1 "$(id "web01|acceptance|$NOW|1")" \
      --arg id2 "$(id "web01|acceptance|$NOW|2")" '
{
  logs: [
    {
      raw_log: "Dec  3 10:15:42 web01 sshd[2211]: Failed password for root from 203.0.113.45 port 52114 ssh2",
      log_type: "auth",
      log_timestamp: $ts,
      source_event_id: $id1,
      parsed_metadata: { host: "web01", file: "/var/log/auth.log" }
    },
    {
      raw_log: "203.0.113.45 - - [03/Dec/2026:10:15:43 -0300] \"GET /wp-login.php HTTP/1.1\" 404 153 \"-\" \"curl/8.5.0\"",
      log_type: "nginx_access",
      log_timestamp: $ts,
      source_event_id: $id2,
      parsed_metadata: { host: "web01", file: "/var/log/nginx/access.log" }
    }
  ]
}' > batch.json

Compress and send:

gzip -c batch.json > batch.json.gz

printf 'header = "X-API-Key: %s"\n' "$SOC_API_KEY" |
curl --config - --silent --show-error \
     --proto '=https' --tlsv1.2 --max-time 30 \
     --request POST "$SOC_URL/api/v1/ingest/json" \
     --header 'Content-Type: application/json' \
     --header 'Content-Encoding: gzip' \
     --data-binary @batch.json.gz \
     --dump-header headers.txt \
     --output response.json \
     --write-out 'HTTP %{http_code}\n'

jq '.data | {accepted, duplicate, rejected}' response.json
grep -i '^x-api-key-expir' headers.txt || true   # key expiration warnings

Use --data-binary, never --data or -d: those alter the file's bytes and corrupt the gzip.

8.3 bash script: continuous sending of /var/log/auth.log in batches

This script reads only the new lines of the file, generates a stable source_event_id per line, writes the batches to a local spool on disk and sends them with gzip. On a temporary failure, it keeps the batches in the spool and resends them later, with backoff. The key is read from the protected file and never appears in process arguments or in the output.

Requirements: bash 4+, curl 7.55+, jq, gzip, coreutils (GNU dd, stat, split, sha256sum), iconv, flock. Run as root (or a user that can read the log and the key).

Save it as /usr/local/sbin/dolutech-soc-auth-sender.sh and apply chmod 700:

#!/usr/bin/env bash
# Sends new lines of a log file to Dolutech SOC AI.
# Run it periodically (every 15-30 s), for example through a systemd timer.
set -euo pipefail
umask 077
export LC_ALL=C   # ${#var} now counts bytes

# ── Configuration ───────────────────────────────────────────────────────────
SOC_URL="https://{SOC_URL}"             # URL shown in the panel of YOUR instance
KEY_FILE="/etc/dolutech-soc/api.key"    # the key only (soc_...), mode 600
LOG_FILE="/var/log/auth.log"            # RHEL/Rocky/Alma: /var/log/secure
LOG_TYPE="auth"
STATE_DIR="/var/lib/dolutech-soc-sender"
BATCH_SIZE=100
MAX_RAW_BYTES=65535
MAX_BACKOFF=300
# ────────────────────────────────────────────────────────────────────────────

ENDPOINT="${SOC_URL%/}/api/v1/ingest/json"
SPOOL_DIR="$STATE_DIR/spool"
QUARANTINE_DIR="$STATE_DIR/quarantine"
STATE_FILE="$STATE_DIR/position"   # "<inode> <offset>"
RETRY_FILE="$STATE_DIR/retry"      # "<not_before_epoch> <next_delay>"
HOST_ID="$(hostname -f 2>/dev/null || hostname)"

log() { printf '%s dolutech-soc-sender: %s\n' "$(date -Is)" "$*" >&2; }

[[ "$SOC_URL" == https://* && "$SOC_URL" != *'{'* ]] \
  || { log "set SOC_URL to the https URL of your instance"; exit 1; }
[[ -r "$KEY_FILE" ]] || { log "key file not readable: $KEY_FILE"; exit 1; }
[[ -r "$LOG_FILE" ]] || { log "log file not readable: $LOG_FILE"; exit 1; }

mkdir -p "$SPOOL_DIR" "$QUARANTINE_DIR"
exec 9>"$STATE_DIR/lock"
flock -n 9 || exit 0   # another run is still in progress

WORK="$(mktemp -d "$STATE_DIR/work.XXXXXX")"
trap 'rm -rf "$WORK"' EXIT

# Valid UTF-8 with at most MAX_RAW_BYTES bytes.
sanitize() {
  local s
  s=$(printf '%s' "$1" | iconv -c -f UTF-8 -t UTF-8 2>/dev/null) || true
  if (( ${#s} > MAX_RAW_BYTES )); then
    s=$(printf '%s' "${s:0:MAX_RAW_BYTES}" | iconv -c -f UTF-8 -t UTF-8 2>/dev/null) || true
  fi
  printf '%s' "$s"
}

# Reads the new lines and writes .json.gz batches to the spool.
collect() {
  local inode size prev_inode offset pos line_pos line raw id part dest
  inode=$(stat -c %i "$LOG_FILE")
  size=$(stat -c %s "$LOG_FILE")

  if [[ ! -s "$STATE_FILE" ]]; then
    printf '%s %s\n' "$inode" "$size" > "$STATE_FILE"   # first run: new lines only
    return 0
  fi
  read -r prev_inode offset < "$STATE_FILE"
  if [[ "$inode" != "$prev_inode" ]] || (( size < offset )); then
    offset=0   # file rotated or truncated: start over from the beginning of the new file
  fi
  (( size > offset )) || return 0

  dd if="$LOG_FILE" of="$WORK/chunk" bs=1M iflag=skip_bytes,count_bytes \
     skip="$offset" count="$((size - offset))" status=none

  : > "$WORK/items.ndjson"
  pos=$offset
  # A final line without "\n" (still being written) does not enter the loop and waits for the next run.
  while IFS= read -r line; do
    line_pos=$pos
    pos=$(( pos + ${#line} + 1 ))
    [[ -n "$line" ]] || continue
    raw=$(sanitize "$line")
    [[ -n "$raw" ]] || continue
    id=$(printf '%s|%s|%s|%s|%s' "$HOST_ID" "$LOG_FILE" "$inode" "$line_pos" "$line" \
         | sha256sum | cut -d' ' -f1)
    jq -cn --arg raw "$raw" --arg id "$id" --arg type "$LOG_TYPE" \
           --arg host "$HOST_ID" --arg file "$LOG_FILE" \
       '{raw_log: $raw, log_type: $type, source_event_id: $id,
         parsed_metadata: {host: $host, file: $file}}' >> "$WORK/items.ndjson"
  done < "$WORK/chunk"

  if [[ -s "$WORK/items.ndjson" ]]; then
    split -l "$BATCH_SIZE" -d -a 6 "$WORK/items.ndjson" "$WORK/part."
    for part in "$WORK"/part.*; do
      dest="$SPOOL_DIR/$(date +%s%N)-$$-${part##*.}.json.gz"
      jq -cs '{logs: .}' "$part" | gzip -c > "$dest.tmp"
      mv "$dest.tmp" "$dest"
    done
  fi
  # The position only moves forward once the batches are in the spool.
  printf '%s %s\n' "$inode" "$pos" > "$STATE_FILE.tmp"
  mv "$STATE_FILE.tmp" "$STATE_FILE"
}

# Sends one batch; prints the HTTP code (000 = network failure/timeout).
send_file() {
  local code
  rm -f "$WORK/headers" "$WORK/body"
  code=$(printf 'header = "X-API-Key: %s"\n' "$(tr -d '[:space:]' < "$KEY_FILE")" |
    curl --config - --silent --show-error \
         --proto '=https' --tlsv1.2 --max-time 30 \
         --request POST "$ENDPOINT" \
         --header 'Content-Type: application/json' \
         --header 'Content-Encoding: gzip' \
         --data-binary @"$1" \
         --dump-header "$WORK/headers" --output "$WORK/body" \
         --write-out '%{http_code}') || code=000
  printf '%s' "$code"
}

retry_after() {   # Retry-After in seconds, if present
  local v
  v=$(awk 'tolower($1) == "retry-after:" { gsub(/\r/, "", $2); print $2 }' \
        "$WORK/headers" 2>/dev/null | tail -n 1) || true
  if [[ "$v" =~ ^[0-9]+$ ]]; then printf '%s' "$v"; fi
}

backoff() {   # $1 = wait in seconds (empty = exponential backoff)
  local _nb delay=5 wait next
  if [[ -s "$RETRY_FILE" ]]; then read -r _nb delay < "$RETRY_FILE"; fi
  wait=${1:-$delay}
  next=$(( delay * 2 > MAX_BACKOFF ? MAX_BACKOFF : delay * 2 ))
  printf '%s %s\n' "$(( $(date +%s) + wait ))" "$next" > "$RETRY_FILE"
  log "sending postponed by ${wait}s"
}

flush() {
  local f code ra nb _d summary
  if [[ -s "$RETRY_FILE" ]]; then
    read -r nb _d < "$RETRY_FILE"
    (( $(date +%s) >= nb )) || return 0
  fi
  for f in "$SPOOL_DIR"/*.json.gz; do
    [[ -e "$f" ]] || break
    code=$(send_file "$f")
    case "$code" in
      201)
        summary=$(jq -r '.data | "accepted=\(.accepted) duplicate=\(.duplicate) rejected=\(.rejected)"' \
                  "$WORK/body" 2>/dev/null) || summary="response not parsed"
        log "batch $(basename "$f") stored: $summary"
        if grep -qi '^x-api-key-expiring: *true' "$WORK/headers" 2>/dev/null; then
          log "WARNING: the API key expires soon; rotate it in the panel"
        fi
        rm -f "$f" "$RETRY_FILE"
        ;;
      429)
        ra=$(retry_after); backoff "${ra:-30}"; return 0 ;;
      500|502|503|504|000)
        backoff "$(retry_after)"; return 0 ;;
      401|403)
        log "HTTP $code ($(jq -r '.code // .message // empty' "$WORK/body" 2>/dev/null)): check or rotate the key in the panel"
        backoff 300; return 0 ;;
      400|413|415|422)
        log "HTTP $code: batch refused; moved to $QUARANTINE_DIR for review"
        mv "$f" "$QUARANTINE_DIR/" ;;
      *)
        log "unexpected HTTP $code (redirect? check SOC_URL); sending suspended for 5 min"
        backoff 300; return 0 ;;
    esac
  done
}

collect
flush

Schedule it with systemd (every 30 s):

# /etc/systemd/system/dolutech-soc-sender.service
[Unit]
Description=Log shipping to Dolutech SOC AI
After=network-online.target
Wants=network-online.target

[Service]
Type=oneshot
ExecStart=/usr/local/sbin/dolutech-soc-auth-sender.sh
# /etc/systemd/system/dolutech-soc-sender.timer
[Unit]
Description=Periodic log shipping to Dolutech SOC AI

[Timer]
OnBootSec=30s
OnUnitActiveSec=30s
AccuracySec=1s

[Install]
WantedBy=timers.target
sudo systemctl daemon-reload
sudo systemctl enable --now dolutech-soc-sender.timer
journalctl -u dolutech-soc-sender.service -f   # follow the sends

Notes on the script:

  • First run: it records the current position and only sends lines written from then on. To send the history, delete /var/lib/dolutech-soc-sender/position and write <inode> 0 (get the inode with stat -c %i /var/log/auth.log).
  • Log rotation: when it detects a new inode, the script starts over from the beginning of the new file. Lines written to the old file after the last read and before the rotation are not sent. The official agent handles this case.
  • Crash during a run: if the script stops between writing the spool and updating the position, the same lines are read again with the same IDs, and the SOC returns them as duplicate. Nothing is duplicated.
  • Quarantine: batches refused with 400/413/415/422 go to quarantine/ for manual review, since bash is not well suited to splitting batches. The Python example (8.4) splits them automatically.
  • Volume: the script runs a few processes per line. It handles auth.log and moderate-volume logs well. For high-volume logs, use the official agent or adapt the Python example.
  • Spool: monitor the size of spool/. It grows while the SOC is unreachable and empties when the connection comes back.

8.4 Python 3 (requests): batching, gzip, idempotency and retries

Sends every complete line of a log file in batches of 100, with gzip and a stable source_event_id. Handles 201, 429 and 5xx with Retry-After and exponential backoff. Automatically splits batches refused with 413/422. Does not follow redirects. Running the same file twice results in duplicate the second time, which is useful for acceptance testing.

Requirements: Python 3.8+ and requests (pip install requests).

#!/usr/bin/env python3
"""Sends a log file to Dolutech SOC AI (batches of 100, gzip, idempotent).

Usage:
    SOC_URL=https://soc.yourcompany.com python3 send_logs.py /var/log/auth.log auth

The key is read from SOC_API_KEY_FILE (default: /etc/dolutech-soc/api.key, mode 600).
"""
import gzip
import hashlib
import json
import os
import socket
import sys
import time

import requests

SOC_URL = os.environ.get("SOC_URL", "").rstrip("/")
KEY_FILE = os.environ.get("SOC_API_KEY_FILE", "/etc/dolutech-soc/api.key")
MAX_ITEMS = 100
MAX_RAW_BYTES = 65535
TIMEOUT = 30
MAX_BACKOFF = 300
HOST_ID = socket.getfqdn()


class FatalError(Exception):
    """An error that resending does not fix: it needs human action."""


def load_key() -> str:
    if os.stat(KEY_FILE).st_mode & 0o077:
        raise FatalError(f"{KEY_FILE} must have 600 permissions")
    with open(KEY_FILE, encoding="utf-8") as fh:
        key = fh.read().strip()
    if not key.startswith("soc_"):
        raise FatalError("unexpected content in the key file")
    return key


def truncate_utf8(text: str) -> str:
    """Ensures at most MAX_RAW_BYTES bytes without cutting a character in half."""
    data = text.encode("utf-8")
    if len(data) <= MAX_RAW_BYTES:
        return text
    return data[:MAX_RAW_BYTES].decode("utf-8", errors="ignore")


def read_items(path: str, log_type: str):
    """Yields one item per complete line, with a source_event_id stable across runs."""
    inode = os.stat(path).st_ino
    offset = 0
    with open(path, "rb") as fh:
        for raw in fh:
            line_offset = offset
            offset += len(raw)
            if not raw.endswith(b"\n"):
                break  # last line still being written
            text = raw.rstrip(b"\r\n").decode("utf-8", errors="replace")
            if not text.strip():
                continue
            seed = f"{HOST_ID}|{path}|{inode}|{line_offset}|".encode("utf-8") + raw
            yield {
                "raw_log": truncate_utf8(text),
                "log_type": log_type,
                "source_event_id": hashlib.sha256(seed).hexdigest(),
                "parsed_metadata": {"host": HOST_ID, "file": path},
            }


def batches(items, size):
    batch = []
    for item in items:
        batch.append(item)
        if len(batch) == size:
            yield batch
            batch = []
    if batch:
        yield batch


def retry_after(resp, default: int) -> int:
    try:
        return max(1, int(resp.headers.get("Retry-After", "")))
    except ValueError:
        return default


def error_code(resp) -> str:
    try:
        body = resp.json()
    except ValueError:  # non-JSON body (e.g. HTML from the edge layer)
        return f"HTTP {resp.status_code}"
    if isinstance(body, dict):
        return body.get("code") or body.get("message") or f"HTTP {resp.status_code}"
    return f"HTTP {resp.status_code}"


def post(session, key, items):
    body = gzip.compress(json.dumps({"logs": items}, ensure_ascii=False).encode("utf-8"))
    return session.post(
        f"{SOC_URL}/api/v1/ingest/json",
        data=body,
        headers={
            "X-API-Key": key,
            "Content-Type": "application/json",
            "Content-Encoding": "gzip",
        },
        timeout=TIMEOUT,
        allow_redirects=False,  # never follow a redirect carrying the key
    )


def send(session, key, items, totals):
    """Sends one batch. Resends the SAME batch on 429/5xx/network; splits on 413/422."""
    delay = 5
    while True:
        try:
            resp = post(session, key, items)
        except requests.RequestException as exc:
            wait, reason = delay, f"network error ({type(exc).__name__})"
        else:
            status = resp.status_code
            if status == 201:
                data = resp.json()["data"]
                if data["accepted"] + data["duplicate"] + data["rejected"] != len(items):
                    raise FatalError("response inconsistent with the batch sent")
                for ev in data.get("events", []):
                    if ev.get("status") == "rejected":
                        # Do not resend: discarded by a filter configured on the endpoint.
                        print(f"item {ev.get('index')} rejected: {ev.get('reason')}",
                              file=sys.stderr)
                if resp.headers.get("X-API-Key-Expiring") == "true":
                    print("WARNING: the key expires on "
                          f"{resp.headers.get('X-API-Key-Expires-At')}; rotate it in the panel",
                          file=sys.stderr)
                for k in ("accepted", "duplicate", "rejected"):
                    totals[k] += data[k]
                return
            if status in (413, 422):
                if len(items) > 1:
                    half = len(items) // 2
                    send(session, key, items[:half], totals)
                    send(session, key, items[half:], totals)
                    return
                print(f"item discarded ({error_code(resp)}): "
                      f"source_event_id={items[0]['source_event_id']}", file=sys.stderr)
                totals["discarded"] += 1
                return
            if status == 429:
                wait, reason = retry_after(resp, 30), "HTTP 429 (rate limit)"
            elif status in (500, 502, 503, 504):
                wait, reason = retry_after(resp, delay), f"HTTP {status}"
            elif status in (401, 403):
                raise FatalError(f"HTTP {status} ({error_code(resp)}): "
                                 "check or rotate the key in the panel")
            elif 300 <= status < 400:
                raise FatalError("redirect received: set SOC_URL "
                                 "to the direct https URL of your instance")
            else:
                raise FatalError(f"HTTP {status} ({error_code(resp)}): fix the client")
        print(f"{reason}; resending the same batch in {wait}s", file=sys.stderr)
        time.sleep(wait)
        delay = min(delay * 2, MAX_BACKOFF)


def main():
    if len(sys.argv) != 3:
        sys.exit(f"usage: {sys.argv[0]} <log_file> <log_type>")
    if not SOC_URL.startswith("https://") or "{" in SOC_URL:
        sys.exit("set SOC_URL to the https URL of your instance")
    path, log_type = sys.argv[1], sys.argv[2]
    totals = {"accepted": 0, "duplicate": 0, "rejected": 0, "discarded": 0}
    try:
        key = load_key()
        with requests.Session() as session:
            for batch in batches(read_items(path, log_type), MAX_ITEMS):
                send(session, key, batch, totals)
                time.sleep(0.2)  # keeps the rate well below the per-key limit
    except FatalError as exc:
        sys.exit(f"ERROR: {exc}")
    print(json.dumps(totals))


if __name__ == "__main__":
    main()

Run and expected output:

SOC_URL="https://{SOC_URL}" python3 send_logs.py /var/log/auth.log auth
# {"accepted": 842, "duplicate": 0, "rejected": 0, "discarded": 0}

# Second run with the same file: nothing is duplicated
SOC_URL="https://{SOC_URL}" python3 send_logs.py /var/log/auth.log auth
# {"accepted": 0, "duplicate": 842, "rejected": 0, "discarded": 0}

This example keeps the batches in memory while it waits for the SOC to recover. In a continuous production integration, write each batch to disk before sending and delete it only after the 201 (as in the spool of example 8.3). That way a process restart does not lose logs.


9. Best practices

  • Official agent — Whenever you can install software on the server, prefer the Dolutech SOC Collector. It already implements all the practices below.
  • Batching — Group up to 100 lines per request and send every 15–30 s per server. Avoid one request per line.
  • Compression — Use Content-Encoding: gzip. Logs compress very well, which reduces bandwidth and latency.
  • Idempotency — Always send source_event_id (SHA-256 of host + file + inode/offset + line). Whenever delivery is in doubt, resend the same batch.
  • On-disk spool — Write the batch to disk before sending and delete it only after the 201. Cap the spool size and monitor its growth.
  • Retries — Resend only on 429, 5xx and network errors, with exponential backoff of up to 5 min and honoring Retry-After. Never resend on 401/403 without fixing the key. Never resend rejected items.
  • Time — Keep NTP enabled and send log_timestamp in ISO-8601 with time zone. Do not use a numeric epoch.
  • Severity — Omit severity and let the SOC classify. If you send it, do not mark relevant events as info.
  • Size — Keep raw_log ≤ 65,535 bytes (not characters). Truncate without cutting UTF-8 characters in half.
  • Content — Send the raw log, without reformatting it. Do not include unnecessary data: passwords, tokens, card numbers or personal data with no detection value. If the application logs such data, mask it at the source.
  • One key per server — Makes it easier to trace the source, revoke a compromised server and respect the per-key limits.
  • Shared NAT — Several servers behind the same public IP share the per-IP limit. Spread the send times (e.g. a random offset of a few seconds per server).
  • Monitoring — Alert internally on: 401/403, a growing spool, the X-API-Key-Expiring: true header, and an unexpected growth of rejected.

10. Frequently asked questions

Is the log sent complete and raw? Yes. The content of raw_log is stored exactly as sent, with no summarizing or truncation, up to 65,535 bytes per item. Longer lines must be split or truncated by the client before sending.

Can I send JSON logs? Yes. Serialize the original JSON event as a string in the raw_log field, for example "raw_log": "{\"event\":\"login_failed\",\"user\":\"admin\",\"ip\":\"203.0.113.45\"}". Optionally, put context metadata in parsed_metadata.

How do I know the log arrived? From the 201 response: accepted tells how many items were stored, and events[] gives each item's result, with log_id. Then check the endpoint's Logs screen in the SOC panel.

What if the internet goes down? Keep the batches in the local spool on disk and resend with backoff when the connection comes back. With source_event_id, resending a batch that had already been stored creates no duplicates. The official agent does this automatically.

Why does my log show up as rejected? The item was discarded by an endpoint filter. reason: severity_filtered means the severity filter (e.g. info events; review the severity field). reason: log_filter means a log filter rule configured in the panel. In both cases, do not resend: the result will be the same.

I got a 201. Do the alerts show up right away? The 201 confirms storage. Threat analysis happens right after, asynchronously. Alerts and incidents show up in the panel a few moments later.

Can I use a single key for several servers? Technically it works, but it is not recommended. All logs would be attributed to the same endpoint and share the same rate limit. Revoking the key would also cut off every server at once.


11. Acceptance checklist

Run the tests below before putting the integration into production.

  1. ☐ TLS connectivity
    • How to run it: curl -sS -o /dev/null -w '%{http_code}\n' --tlsv1.2 https://{SOC_URL}/
    • Expected result: Connection established, with no TLS or certificate error.
  2. ☐ Sending 1 test log
    • How to run it: Example 8.1
    • Expected result: HTTP 201, accepted: 1, events[0].status: "accepted".
  3. ☐ Log visible in the panel
    • How to run it: Panel → endpoint → Logs
    • Expected result: The line sent appears with its full content.
  4. ☐ Idempotency
    • How to run it: Resend example 8.1 with the same source_event_id
    • Expected result: HTTP 201, accepted: 0, duplicate: 1, reason: "already_received".
  5. ☐ gzip batch
    • How to run it: Example 8.2
    • Expected result: HTTP 201, accepted equal to the number of items.
  6. ☐ Wrong key
    • How to run it: Repeat example 8.1 with an invalid key
    • Expected result: HTTP 401. The client stops and does not loop.
  7. ☐ No redirect
    • How to run it: Use http://{SOC_URL} in the client
    • Expected result: The client treats the 301 as an error and does not follow it.
  8. ☐ Network outage
    • How to run it: Block outbound traffic to {SOC_URL} for a few minutes, then allow it again
    • Expected result: Batches pile up in the spool and are sent once restored; no loss and no duplication.
  9. ☐ Time
    • How to run it: Check NTP (timedatectl / chronyc tracking) and the log times in the panel
    • Expected result: Correct event time, with no adjustment flag.
  10. ☐ Protected key
    • How to run it: stat -c '%a %U' /etc/dolutech-soc/api.key; ps -eo args | grep -c '[s]oc_' during a send
    • Expected result: 600 root; the grep returns 0 (the key does not appear in the process list).

With every item checked, the integration is ready for production. If you have questions, contact Dolutech SOC AI support and provide your instance URL, the time of the test and the HTTP code received. Never send your API key to support.