commit 98aa3f92fc20e7aa19b8d6d5e1355c077bcd6016 Author: livdebus Date: Thu Oct 1 23:33:06 2026 +0200 Initial Commit diff --git a/.env.example b/.env.example new file mode 100644 index 0000000..cc08a3a --- /dev/null +++ b/.env.example @@ -0,0 +1,72 @@ +# ───────────────────────────────────────────────────────────────────────────── +# AIDO SMB → Onyx sync connector +# Copy to .env and adjust. The connector runs as a sidecar next to Onyx. +# ───────────────────────────────────────────────────────────────────────────── + +# Onyx API base (in-compose service name; no trailing /api needed). +ONYX_API_URL=http://api_server:8080 + +# Auth — provide ONE of: +# (a) a pre-created API key (simplest), or +# (b) admin credentials so the connector creates + caches its own key on first boot. +ONYX_API_KEY= +# ONYX_ADMIN_EMAIL=admin@example.com +# ONYX_ADMIN_PASSWORD=change-me + +# How often to reconcile each share (seconds). +INGESTION_INTERVAL_SECONDS=300 + +# Prefix for the auto-created Onyx connector names (" - "). +ONYX_CONNECTOR_NAME_PREFIX=AIDO SMB +# HTTP timeout (s) for Onyx API calls — raise it for large files / slow embeddings. +ONYX_HTTP_TIMEOUT=60 + +# File selection. +INCLUDE_EXTENSIONS=pdf,docx,txt,md,csv,xlsx,html,htm,yaml,json,xml,ini,conf,cfg,sh,bash,ps1,py,sql,log,dockerfile,properties,toml,rst,mjs,patch,tsx +MAX_FILE_MB=50 +LOG_LEVEL=INFO + +# Codepage for recovering filenames whose bytes aren't valid UTF-8 (common on +# Windows/Latin-1 shares, e.g. 0xE4 = ä). cp1252 = Western European (default). +# The connector handles such names correctly regardless of the CIFS mount charset; +# you can additionally pass iocharset via SMB_SOURCE__MOUNT_OPTS (see below). +SMB_FILENAME_ENCODING=cp1252 + +# ── Sources: SMB mounted INSIDE the container (recommended) ────────────────── +# Give each share its SMB connection details and the connector mounts it itself +# (CIFS) — no host mount required. Uses the indexed style so each source can carry +# credentials. Requires the cap_add + apparmor lines in docker-compose.smb.yml. +# +# _MOUNT = where to mount it inside the container (any path) +# _UNC = //server/share (or set _SERVER + _SHARE) +# _LOGICAL = the path users recognise; shown in Onyx's citation view +# _USERNAME/_PASSWORD/_DOMAIN = CIFS credentials (omit user for guest) +# _VERS = SMB dialect, default 3.0 +# _CC_PAIR_ID (optional) = use a specific connector; auto-provisioned if omitted + +SMB_SOURCE_1_NAME=Finance +SMB_SOURCE_1_UNC=//nas.company.local/finance +SMB_SOURCE_1_MOUNT=/mnt/smb/finance +SMB_SOURCE_1_LOGICAL=\\company\finance +SMB_SOURCE_1_USERNAME=svc_onyx +SMB_SOURCE_1_PASSWORD=change-me +SMB_SOURCE_1_DOMAIN=COMPANY +# SMB_SOURCE_1_VERS=3.0 +# Extra raw CIFS mount options, appended verbatim to `mount -t cifs -o ...`. +# e.g. force the server's charset so filenames decode at mount time: +# SMB_SOURCE_1_MOUNT_OPTS=iocharset=utf8,nocase + +# SMB_SOURCE_2_NAME=Legal +# SMB_SOURCE_2_SERVER=nas.company.local +# SMB_SOURCE_2_SHARE=legal +# SMB_SOURCE_2_MOUNT=/mnt/smb/legal +# SMB_SOURCE_2_LOGICAL=\\company\legal +# SMB_SOURCE_2_USERNAME=svc_onyx +# SMB_SOURCE_2_PASSWORD=change-me +# SMB_SOURCE_2_DOMAIN=COMPANY + +# ── Legacy: host-mounted shares (still supported) ──────────────────────────── +# If you'd rather mount on the host and bind-mount into the container, OMIT the +# _UNC/_SERVER lines for that source (so it isn't CIFS-mounted here) and point +# _MOUNT at the bind-mounted path. You can also use the JSON form: +# SMB_SOURCES=[{"name":"Finance","mount":"/mnt/smb/finance","logical":"\\\\company\\finance"}] diff --git a/Dockerfile b/Dockerfile new file mode 100644 index 0000000..49f9687 --- /dev/null +++ b/Dockerfile @@ -0,0 +1,26 @@ +# AIDO SMB → Onyx sync connector +FROM python:3.12-slim + +ENV PYTHONUNBUFFERED=1 PYTHONDONTWRITEBYTECODE=1 + +# cifs-utils: mount SMB/CIFS shares inside the container (no host mount needed). +# gosu: drop from root (needed for mount) to the unprivileged app user at runtime. +RUN apt-get update \ + && apt-get install -y --no-install-recommends cifs-utils gosu \ + && rm -rf /var/lib/apt/lists/* + +WORKDIR /app +COPY requirements.txt ./ +RUN pip install --no-cache-dir -r requirements.txt + +COPY app/ ./app/ +COPY entrypoint.sh /entrypoint.sh +RUN chmod +x /entrypoint.sh + +# App runs as this unprivileged user (entrypoint mounts as root, then drops to it). +# State dir is a mounted volume so the manifest survives restarts. +RUN useradd -u 10001 -m runner && mkdir -p /app/state && chown -R runner /app/state +VOLUME ["/app/state"] + +# Root entrypoint mounts CIFS shares, then execs the app via gosu as `runner`. +ENTRYPOINT ["/entrypoint.sh"] diff --git a/README.md b/README.md new file mode 100644 index 0000000..49ec4cb --- /dev/null +++ b/README.md @@ -0,0 +1,147 @@ +# AIDO SMB → Onyx Connector + +Syncs files from one or more **SMB/CIFS shares** into Onyx via the public +**Ingestion API**: + +- **Update & delete sync** — changed files are re-indexed in place; files removed + from a share are deleted from Onyx (reconciled every cycle). +- **Self-provisioning** — creates/reuses the Onyx **API key** and one **File + connector (cc_pair)** per source automatically; idempotent across restarts. + Documents are pushed in as the `file` source, so they are searchable in Default + Chat and appear in the source filters like any other connector. +- **Multi-source via Docker config** — any number of shares, defined purely in env. +- **Logical path mapping** — each document is labelled with the path users + recognise (`\\company\share\…`), mapped from the local mount via config. +- **Per-source index document** — an optional table-of-contents document per share + so the assistant is aware of the full document set (see `SMB_WRITE_INDEX`). +- **Per-connector group access** — restrict a connector to Onyx user groups (see + `SMB_SOURCE__GROUPS`). + +It runs as its **own container** and touches **no Onyx source code** — only the +public ingestion + admin APIs — so it survives Onyx upgrades. + +> A small white-label UI overlay (`branding/smb/smb-ui.patch`) improves how these +> documents behave in the Onyx UI: the citation shows the short file name, and a +> click copies the full network path to the clipboard instead of opening a dead +> preview (SMB files have no browsable link). This applies to both the chat +> citation view and the licensed Search view. + +## How it works + +``` + SMB share ──(read-only mount)──▶ smb_connector ──ingestion API──▶ Onyx + │ + manifest.json (path → document_id + content hash) +``` + +Each cycle, per source: +1. Walk the share, hash each eligible file. +2. **new / changed** (hash differs) → `POST /onyx-api/ingestion` (upsert by stable id). +3. **gone** (in manifest, not on disk) → `DELETE /onyx-api/ingestion/{id}`. +4. Reconcile against Onyx's own doc list so deletes still happen if the manifest + is lost. + +Document ids are stable (`smb::::`), so re-indexing +a changed file **updates** it rather than duplicating. + +## Setup + +```bash +cd smb-connector +cp .env.example .env +# set ONYX_API_KEY (or ONYX_ADMIN_EMAIL/PASSWORD to auto-create one) +# define your shares in SMB_SOURCES (JSON) or SMB_SOURCE_1_* vars +``` + +Then bring it up. Two deployment modes: + +**A. Standalone (recommended) — its own Compose project next to Onyx.** +No `-f` injection, so a Compose management tool can handle it on its own. It +joins Onyx's network to reach the API by service name. + +```bash +cd smb-connector +docker compose -f docker-compose.standalone.yml up -d --build +docker compose -f docker-compose.standalone.yml logs -f +``` + +Onyx's compose has `name: onyx`, so its network is `onyx_default` (the default). +If your Onyx project uses another name, set `ONYX_NETWORK=_default`. + +**B. Injected into the Onyx compose (legacy).** Adds the service to the Onyx +project via a second compose file: + +```bash +docker compose -f docker-compose.yml -f smb-connector/docker-compose.smb.yml up -d --build smb_connector +docker compose logs -f smb_connector +``` + +### SMB mount — two modes + +**A. In-container mount (recommended, no host mount).** The connector mounts each +CIFS share itself; you just give it the share + credentials via env: + +``` +SMB_SOURCE_1_NAME=Finance +SMB_SOURCE_1_UNC=//nas.company.local/finance # or _SERVER + _SHARE +SMB_SOURCE_1_MOUNT=/mnt/smb/finance # where to mount it in the container +SMB_SOURCE_1_LOGICAL=\\company\finance # path shown in Onyx +SMB_SOURCE_1_USERNAME=svc_onyx +SMB_SOURCE_1_PASSWORD=… # kept in a 0600 creds file, never in the process list +SMB_SOURCE_1_DOMAIN=COMPANY # optional +# SMB_SOURCE_1_VERS=3.0 # SMB dialect, default 3.0 +``` + +This needs two Linux capabilities on the container (already set in +`docker-compose.smb.yml`): `cap_add: [SYS_ADMIN, DAC_READ_SEARCH]` + +`security_opt: [apparmor:unconfined]` (or `privileged: true` if your host is +stricter). The host kernel must have the `cifs` module (standard on Linux). The +share is mounted **read-only** and unmounted cleanly on container stop. + +**B. Host mount (legacy).** Mount the share on the host and bind-mount it into the +container, and **omit** the `_UNC`/`_SERVER` vars for that source so it isn't +CIFS-mounted a second time — `_MOUNT` then just points at the bind-mounted path. + +## Configuration + +| Var | Purpose | +|-----|---------| +| `ONYX_API_URL` | Onyx API base (e.g. `http://api_server:8080`) | +| `ONYX_API_KEY` | API key; if empty, auto-created from admin creds and cached | +| `ONYX_ADMIN_EMAIL` / `ONYX_ADMIN_PASSWORD` | Bootstrap creds to auto-create the key + connectors | +| `SMB_SOURCES` | JSON list of `{name, mount, logical, cc_pair_id?}` | +| `SMB_SOURCE__NAME/_MOUNT/_LOGICAL/_CC_PAIR_ID` | Indexed alternative to `SMB_SOURCES` | +| `SMB_SOURCE__UNC` (or `_SERVER`+`_SHARE`) | In-container CIFS mount: the share to mount at `_MOUNT` | +| `SMB_SOURCE__USERNAME/_PASSWORD/_DOMAIN/_VERS` | CIFS credentials + dialect (default `3.0`); omit user for guest | +| `INGESTION_INTERVAL_SECONDS` | Reconcile interval (default 300) | +| `INCLUDE_EXTENSIONS` | File types to ingest. Default covers office + web + many text/IT formats (pdf, docx, xlsx, csv, txt, md, html, plus yaml, json, xml, ini, conf, cfg, sh, bash, ps1, py, sql, log, dockerfile, properties, toml, rst, mjs, patch, tsx) | +| `MAX_FILE_MB` | Skip files larger than this (default 50) | +| `SMB_WRITE_INDEX` | Write a per-source index (table-of-contents) document listing every file, so the assistant is aware of the full set (default on; `0`/`false` to disable) | +| `SMB_SOURCE__GROUPS` | Onyx user-group ids (comma-separated) allowed to access this connector. Set → connector created **private** and restricted to those groups; empty → **public**. Applied only at connector creation. Needs the Onyx Business licence. In `SMB_SOURCES` JSON use `"groups": [id, …]`. | +| `SMB_DEFAULT_GROUP_IDS` | Fallback group ids for any source that has none set | +| `ONYX_NETWORK` | Standalone mode only: name of Onyx's Docker network (default `onyx_default`) | + +State (manifest + cached key/cc_pair) lives in the mounted `/app/state` volume. + +## Notes / scope + +- **Extraction** covers office, web, and common text/IT formats (see + `INCLUDE_EXTENSIONS`). Legacy `.doc`/`.xls` and scanned-image PDFs are skipped + (no OCR). Add or remove types via `INCLUDE_EXTENSIONS`. +- **Connector type**: documents are ingested as the `file` source (a first-class, + chat-searchable connector), so they appear in Default Chat and the source + filters. The connector is created once, then documents are pushed via the + Ingestion API (`from_ingestion_api`), not polled from a file location. +- **Auth for provisioning**: creating the API key/connectors needs one admin + credential the first time. At steady state only the cached API key is used. +- **API-key auto-creation requires `LICENSE_ENFORCEMENT_ENABLED=false`** on the Onyx + deployment: the `/admin/api-key` endpoint is EE-tier-gated and returns HTTP 402 + when enforcement is on (the default). CE/white-label deployments run with it off, + so this is fine — and if you'd rather not rely on it, just supply a pre-made + `ONYX_API_KEY`. Connector/cc_pair creation and the ingestion API itself are + **not** tier-gated and work on plain CE. +- **Document ids are URL-safe** (`smb__`), matching how Onyx stores/returns + them, so update and delete reconcile reliably (verified end-to-end). +- **`smb://` links** can't open from a browser; the full network path is stored in + the document metadata, and the UI overlay copies it to the clipboard on click + (see `branding/smb/smb-ui.patch`). diff --git a/app/__init__.py b/app/__init__.py new file mode 100644 index 0000000..e69de29 diff --git a/app/config.py b/app/config.py new file mode 100644 index 0000000..ae3fcdd --- /dev/null +++ b/app/config.py @@ -0,0 +1,194 @@ +"""Configuration loading for the AIDO SMB → Onyx sync connector. + +Multi-source is defined entirely via environment variables, so the number of SMB +shares scales without code changes. Two equivalent styles are supported: + +1) JSON list in ``SMB_SOURCES`` (preferred for many sources):: + + SMB_SOURCES='[ + {"name": "Finance", "mount": "/shares/finance", "logical": "\\\\company\\finance"}, + {"name": "Legal", "mount": "/shares/legal", "logical": "\\\\company\\legal"} + ]' + +2) Indexed vars ``SMB_SOURCE__*`` (readable for a handful of sources):: + + SMB_SOURCE_1_NAME=Finance + SMB_SOURCE_1_MOUNT=/shares/finance + SMB_SOURCE_1_LOGICAL=\\company\finance + SMB_SOURCE_1_CC_PAIR_ID=243 # optional; auto-provisioned if omitted + +Each source is mounted read-only into the container (typically a CIFS/SMB mount on +the host, bind-mounted here). ``logical`` is the human-facing path shown in Onyx's +citation view; it is mapped from the local ``mount`` at ingestion time. +""" + +from __future__ import annotations + +import json +import os +from dataclasses import dataclass, field + + +@dataclass +class SourceConfig: + name: str + mount: str + logical: str + # Optional explicit connector/credential pair id. When omitted the connector + # is auto-provisioned (idempotently) and the id cached in the state file. + cc_pair_id: int | None = None + # Onyx user-group ids that may access this connector. When set, the connector + # is created PRIVATE and restricted to these groups; empty means PUBLIC. + # Applied only when the connector is first provisioned (not on later runs). + # Group permissions need the Onyx Business licence. + group_ids: list[int] = field(default_factory=list) + + def normalized_logical(self) -> str: + # Trim trailing separators so path joins are clean. + return self.logical.rstrip("/\\") + + +@dataclass +class Config: + api_url: str + api_key: str | None + # Bootstrap admin credentials — only used to auto-create the API key and + # connectors when they are not supplied. Never required at steady state. + admin_email: str | None + admin_password: str | None + interval_seconds: int + state_path: str + include_ext: set[str] + max_file_mb: int + log_level: str + filename_encoding: str = "cp1252" + connector_name_prefix: str = "AIDO SMB" + http_timeout: int = 60 + # Write one table-of-contents (index) document per source, listing every + # file on the share so the assistant is aware of the full document set. + write_index: bool = True + sources: list[SourceConfig] = field(default_factory=list) + + +def _split_ext(value: str) -> set[str]: + return { + e.strip().lower().lstrip(".") + for e in value.split(",") + if e.strip() + } + + +def _parse_group_ids(value) -> list[int]: + """Accept a JSON list, a comma-separated string, or a single id.""" + if value is None or value == "": + return [] + if isinstance(value, (list, tuple)): + items = value + else: + items = str(value).split(",") + out: list[int] = [] + for item in items: + s = str(item).strip() + if not s: + continue + try: + out.append(int(s)) + except ValueError as exc: + raise SystemExit(f"Invalid Onyx group id '{s}': {exc}") from exc + return out + + +def _load_sources() -> list[SourceConfig]: + default_groups = _parse_group_ids(os.environ.get("SMB_DEFAULT_GROUP_IDS")) + raw = os.environ.get("SMB_SOURCES", "").strip() + if raw: + try: + data = json.loads(raw) + except json.JSONDecodeError as exc: + raise SystemExit(f"SMB_SOURCES is not valid JSON: {exc}") from exc + sources = [] + for i, item in enumerate(data, 1): + if not item.get("name") or not item.get("mount"): + raise SystemExit(f"SMB_SOURCES[{i - 1}] needs at least 'name' and 'mount'") + sources.append( + SourceConfig( + name=str(item["name"]), + mount=str(item["mount"]), + logical=str(item.get("logical") or item["mount"]), + cc_pair_id=(int(item["cc_pair_id"]) if item.get("cc_pair_id") else None), + group_ids=_parse_group_ids(item.get("groups")) or default_groups, + ) + ) + return sources + + # Indexed style: SMB_SOURCE_1_NAME, _MOUNT, _LOGICAL, _CC_PAIR_ID … + sources = [] + i = 1 + while os.environ.get(f"SMB_SOURCE_{i}_NAME"): + name = os.environ[f"SMB_SOURCE_{i}_NAME"] + mount = os.environ.get(f"SMB_SOURCE_{i}_MOUNT") + if not mount: + raise SystemExit(f"SMB_SOURCE_{i}_MOUNT is required for source '{name}'") + cc = os.environ.get(f"SMB_SOURCE_{i}_CC_PAIR_ID") + sources.append( + SourceConfig( + name=name, + mount=mount, + logical=os.environ.get(f"SMB_SOURCE_{i}_LOGICAL") or mount, + cc_pair_id=int(cc) if cc else None, + group_ids=_parse_group_ids(os.environ.get(f"SMB_SOURCE_{i}_GROUPS")) + or default_groups, + ) + ) + i += 1 + + # Backwards-compatible single-source fallback (matches the original POC). + if not sources and os.environ.get("DOCUMENT_SOURCE_PATH"): + sources.append( + SourceConfig( + name=os.environ.get("SMB_SOURCE_NAME", "SMB Share"), + mount=os.environ["DOCUMENT_SOURCE_PATH"], + logical=os.environ.get("SMB_LOGICAL_PATH", os.environ["DOCUMENT_SOURCE_PATH"]), + cc_pair_id=( + int(os.environ["CC_PAIR_ID"]) if os.environ.get("CC_PAIR_ID") else None + ), + group_ids=_parse_group_ids(os.environ.get("SMB_GROUPS")) or default_groups, + ) + ) + return sources + + +def load_config() -> Config: + api_url = os.environ.get("ONYX_API_URL", "http://api_server:8080").rstrip("/") + cfg = Config( + api_url=api_url, + api_key=os.environ.get("ONYX_API_KEY") or None, + admin_email=os.environ.get("ONYX_ADMIN_EMAIL") or None, + admin_password=os.environ.get("ONYX_ADMIN_PASSWORD") or None, + interval_seconds=int(os.environ.get("INGESTION_INTERVAL_SECONDS", "300")), + state_path=os.environ.get("STATE_PATH", "/app/state/manifest.json"), + include_ext=_split_ext( + os.environ.get( + "INCLUDE_EXTENSIONS", + "pdf,docx,doc,txt,md,csv,xlsx,xls,pptx,html,htm", + ) + ), + max_file_mb=int(os.environ.get("MAX_FILE_MB", "50")), + log_level=os.environ.get("LOG_LEVEL", "INFO").upper(), + # Codepage used to recover filenames whose bytes aren't valid UTF-8 (common + # on Windows/Latin-1 shares, e.g. 0xE4 = ä). cp1252 covers Western European. + filename_encoding=os.environ.get("SMB_FILENAME_ENCODING", "cp1252"), + # Prefix for the auto-created Onyx connector names (" - "). + connector_name_prefix=os.environ.get("ONYX_CONNECTOR_NAME_PREFIX", "AIDO SMB"), + # HTTP timeout for Onyx API calls; raise it for large embeddings/ingests. + http_timeout=int(os.environ.get("ONYX_HTTP_TIMEOUT", "60")), + # Write a per-source index (table-of-contents) document. Set to 0/false to disable. + write_index=os.environ.get("SMB_WRITE_INDEX", "1").strip().lower() + not in ("0", "false", "no", "off"), + sources=_load_sources(), + ) + if not cfg.sources: + raise SystemExit( + "No SMB sources configured. Set SMB_SOURCES (JSON) or SMB_SOURCE_1_NAME/_MOUNT." + ) + return cfg diff --git a/app/extract.py b/app/extract.py new file mode 100644 index 0000000..1acf021 --- /dev/null +++ b/app/extract.py @@ -0,0 +1,120 @@ +"""Text extraction for the file types typically found on an SMB share. + +Kept intentionally small and dependency-light (this is the "basic extraction" +scope of Phase 1). Unsupported/binary files return an empty string and are +skipped by the sync engine rather than ingested as noise. +""" + +from __future__ import annotations + +import csv +import io +import logging +import os + +logger = logging.getLogger("smb.extract") + + +def _txt(data: bytes) -> str: + for enc in ("utf-8", "utf-16", "latin-1"): + try: + return data.decode(enc) + except UnicodeDecodeError: + continue + return data.decode("utf-8", errors="replace") + + +def _pdf(data: bytes) -> str: + from pypdf import PdfReader # lazy import so a missing dep only breaks one type + + reader = PdfReader(io.BytesIO(data)) + return "\n\n".join((page.extract_text() or "") for page in reader.pages) + + +def _docx(data: bytes) -> str: + import docx # python-docx + + document = docx.Document(io.BytesIO(data)) + parts = [p.text for p in document.paragraphs] + for table in document.tables: + for row in table.rows: + parts.append("\t".join(cell.text for cell in row.cells)) + return "\n".join(parts) + + +def _xlsx(data: bytes) -> str: + from openpyxl import load_workbook + + wb = load_workbook(io.BytesIO(data), read_only=True, data_only=True) + out: list[str] = [] + for ws in wb.worksheets: + out.append(f"# {ws.title}") + for row in ws.iter_rows(values_only=True): + out.append("\t".join("" if c is None else str(c) for c in row)) + return "\n".join(out) + + +def _csv(data: bytes) -> str: + text = _txt(data) + rows = csv.reader(io.StringIO(text)) + return "\n".join("\t".join(r) for r in rows) + + +def _html(data: bytes) -> str: + import re + + text = _txt(data) + text = re.sub(r"(?is)<(script|style).*?", " ", text) + text = re.sub(r"(?s)<[^>]+>", " ", text) + return re.sub(r"\s+\n", "\n", text).strip() + + +_HANDLERS = { + "pdf": _pdf, + "docx": _docx, + "txt": _txt, + "md": _txt, + "csv": _csv, + "xlsx": _xlsx, + "html": _html, + "htm": _html, + # Text-based IT formats + "yaml": _txt, + "yml": _txt, + "json": _txt, + "xml": _txt, + "ini": _txt, + "conf": _txt, + "cfg": _txt, + "sh": _txt, + "bash": _txt, + "ps1": _txt, + "py": _txt, + "sql": _txt, + "log": _txt, + "dockerfile": _txt, + "properties": _txt, + "toml": _txt, + "rst": _txt, + "mjs": _txt, + "patch": _txt, + "tsx": _txt, +} + + +def supported_extensions() -> set[str]: + return set(_HANDLERS) + + +def extract_text(path: str, data: bytes) -> str: + ext = os.path.splitext(path)[1].lower().lstrip(".") + handler = _HANDLERS.get(ext) + if handler is None: + # .doc/.xls (legacy binary) and others aren't handled by the light deps. + logger.debug("No extractor for .%s (%s) — skipping", ext, path) + return "" + try: + return (handler(data) or "").strip() + except Exception as exc: # never let one bad file stop the whole sync + logger.warning("Extraction failed for %s: %s", path, exc) + return "" diff --git a/app/main.py b/app/main.py new file mode 100644 index 0000000..89ce284 --- /dev/null +++ b/app/main.py @@ -0,0 +1,84 @@ +"""Entry point: bootstrap auth, then run the sync loop on an interval.""" + +from __future__ import annotations + +import logging +import signal +import sys +import time + +from .config import load_config +from .onyx_client import OnyxClient, OnyxError +from .state import State +from .sync import sync_all + +_stop = False + + +def _handle_signal(signum, _frame): + global _stop + logging.getLogger("smb").info("Received signal %s — finishing current cycle then exiting", signum) + _stop = True + + +def bootstrap_api_key(client: OnyxClient, state: State) -> None: + """Ensure we have a usable API key. Preference order: + 1. ONYX_API_KEY (already on the client) 2. cached key in the state file + 3. create one via admin bootstrap credentials.""" + if client.api_key: + return + if state.api_key: + client.api_key = state.api_key + return + key = client.create_api_key("AIDO SMB Connector") + state.api_key = key + state.save() + logging.getLogger("smb").info("Created and cached a new Onyx API key") + + +def main() -> int: + cfg = load_config() + logging.basicConfig( + level=getattr(logging, cfg.log_level, logging.INFO), + format="%(asctime)s %(levelname)-7s %(name)s | %(message)s", + ) + log = logging.getLogger("smb") + + signal.signal(signal.SIGTERM, _handle_signal) + signal.signal(signal.SIGINT, _handle_signal) + + state = State.load(cfg.state_path) + client = OnyxClient(cfg.api_url, cfg.api_key, timeout=cfg.http_timeout) + client.set_admin_credentials(cfg.admin_email, cfg.admin_password) + + try: + bootstrap_api_key(client, state) + except OnyxError as exc: + log.error("Could not obtain an API key: %s", exc) + return 2 + + log.info( + "AIDO SMB connector started: %d source(s), every %ds → %s", + len(cfg.sources), cfg.interval_seconds, cfg.api_url, + ) + + while not _stop: + started = time.time() + try: + sync_all(client, cfg, state) + except Exception as exc: # never crash the loop + log.exception("Sync cycle error: %s", exc) + elapsed = time.time() - started + log.info("Cycle finished in %.1fs; next in %ds", elapsed, cfg.interval_seconds) + # Sleep in small slices so SIGTERM is responsive. + remaining = cfg.interval_seconds + while remaining > 0 and not _stop: + time.sleep(min(2, remaining)) + remaining -= 2 + + log.info("Shut down cleanly.") + return 0 + + +if __name__ == "__main__": + sys.exit(main()) diff --git a/app/onyx_client.py b/app/onyx_client.py new file mode 100644 index 0000000..4ba5b88 --- /dev/null +++ b/app/onyx_client.py @@ -0,0 +1,240 @@ +"""Thin, typed client for the Onyx public + admin APIs used by the connector. + +Endpoints (stable across Onyx v4.5–v4.8): + POST /onyx-api/ingestion upsert a document (by DocumentBase.id) + DELETE /onyx-api/ingestion/{document_id} remove a document entirely + GET /onyx-api/connector-docs/{cc_pair_id} list docs for a cc_pair (reconcile) + POST /admin/api-key create an API key (bootstrap only) + GET /manage/connector list connectors (idempotent provision) + POST /manage/admin/connector-with-mock-credential + create connector+credential+cc_pair + +Auth is a bearer token: ``Authorization: Bearer ``. +""" + +from __future__ import annotations + +import logging +import time +from typing import Any + +import requests + +logger = logging.getLogger("smb.onyx") + +_RETRYABLE = {429, 500, 502, 503, 504} + + +class OnyxError(RuntimeError): + pass + + +class OnyxClient: + def __init__(self, base_url: str, api_key: str | None, timeout: int = 60) -> None: + self.base_url = base_url.rstrip("/") + self.api_key = api_key + self.timeout = timeout + self._session = requests.Session() + + # -- low level ----------------------------------------------------------- + def _headers(self, extra: dict[str, str] | None = None) -> dict[str, str]: + headers = {"Content-Type": "application/json"} + if self.api_key: + headers["Authorization"] = f"Bearer {self.api_key}" + if extra: + headers.update(extra) + return headers + + def _request( + self, + method: str, + path: str, + *, + json: Any = None, + auth: tuple[str, str] | None = None, + retries: int = 4, + ) -> requests.Response: + url = f"{self.base_url}{path}" + last_exc: Exception | None = None + for attempt in range(1, retries + 1): + try: + resp = self._session.request( + method, + url, + json=json, + headers=self._headers(), + auth=auth, + timeout=self.timeout, + ) + if resp.status_code in _RETRYABLE: + raise OnyxError(f"{resp.status_code} from {method} {path}") + return resp + except (requests.RequestException, OnyxError) as exc: + last_exc = exc + if attempt == retries: + break + backoff = min(2 ** attempt, 30) + logger.warning( + "%s %s failed (attempt %d/%d): %s — retrying in %ds", + method, path, attempt, retries, exc, backoff, + ) + time.sleep(backoff) + raise OnyxError(f"{method} {path} failed after {retries} attempts: {last_exc}") + + # -- ingestion ----------------------------------------------------------- + def upsert_document(self, document: dict[str, Any], cc_pair_id: int) -> dict[str, Any]: + """Create or update a document. Onyx keys on ``document.id`` so re-posting + the same id updates in place — that's how change-sync works.""" + payload = {"document": document, "cc_pair_id": cc_pair_id} + resp = self._request("POST", "/onyx-api/ingestion", json=payload) + if resp.status_code >= 400: + raise OnyxError(f"ingestion upsert failed [{resp.status_code}]: {resp.text[:400]}") + return resp.json() + + def delete_document(self, document_id: str) -> bool: + resp = self._request("DELETE", f"/onyx-api/ingestion/{document_id}") + if resp.status_code in (200, 204): + return True + if resp.status_code == 404: + return False + raise OnyxError(f"delete failed [{resp.status_code}]: {resp.text[:300]}") + + def list_cc_pair_documents(self, cc_pair_id: int) -> list[dict[str, Any]]: + """Docs Onyx currently holds for a cc_pair — used to reconcile deletes + even if our local manifest is lost.""" + resp = self._request("GET", f"/onyx-api/connector-docs/{cc_pair_id}") + if resp.status_code >= 400: + raise OnyxError(f"list docs failed [{resp.status_code}]: {resp.text[:300]}") + return resp.json() + + # -- bootstrap: API key -------------------------------------------------- + def create_api_key(self, name: str) -> str: + """Create an admin-scoped API key via basic-auth admin login. Only used + once, when ONYX_API_KEY is not supplied.""" + if not self._admin_auth: + raise OnyxError( + "Cannot create an API key: provide ONYX_API_KEY, or " + "ONYX_ADMIN_EMAIL/ONYX_ADMIN_PASSWORD to bootstrap one." + ) + resp = self._request( + "POST", + "/admin/api-key", + json={"name": name, "role": "admin"}, + auth=self._admin_auth, + ) + if resp.status_code >= 400: + raise OnyxError(f"api-key create failed [{resp.status_code}]: {resp.text[:300]}") + key = resp.json().get("api_key") + if not key: + raise OnyxError(f"api-key response missing 'api_key': {resp.text[:300]}") + self.api_key = key + return key + + # -- idempotent connector provisioning ----------------------------------- + def find_cc_pair_id_by_name(self, name: str) -> int | None: + """Look up an existing connector/credential pair by name so provisioning is + idempotent even if the local state (cached id) was lost.""" + resp = self._request( + "POST", "/manage/admin/connector/indexing-status", + json={"secondary_index": False}, auth=self._admin_auth, + ) + if resp.status_code >= 400: + return None + body = resp.json() + # Response is a list grouped by source; each group nests the actual + # cc_pairs under "indexing_statuses": [{cc_pair_id, name, ...}]. + groups = body if isinstance(body, list) else [body] + for group in groups: + statuses = (group or {}).get("indexing_statuses") or [] + for row in statuses: + if isinstance(row, dict) and row.get("name") == name and row.get("cc_pair_id"): + return int(row["cc_pair_id"]) + return None + + def provision_cc_pair(self, name: str, group_ids: list[int] | None = None) -> int: + """Create a File connector + mock credential + cc_pair. Returns the + cc_pair id. Idempotent: reuses an existing one with the same name. + + The connector is a File connector (documents are pushed in via the + Ingestion API with from_ingestion_api=True). File is a first-class, + chat-searchable source, so the documents show up in Default Chat and + the source filters; the older ingestion_api source is hidden there. + + When ``group_ids`` is given, the connector is created PRIVATE and + restricted to those Onyx user groups (needs the Business licence). + Access is set only at creation; an existing connector is reused as-is.""" + existing = self.find_cc_pair_id_by_name(name) + if existing: + logger.info("Reusing existing connector '%s' (cc_pair_id=%s)", name, existing) + self.set_cc_pair_active(existing) + return existing + + groups = group_ids or [] + connector = { + "name": name, + "source": "file", + "input_type": "load_state", + "connector_specific_config": { + "file_locations": [] + }, + "refresh_freq": None, + "prune_freq": None, + "indexing_start": None, + "access_type": "private" if groups else "public", + "groups": groups, + } + if groups: + logger.info("Creating connector '%s' private, restricted to groups %s", name, groups) + resp = self._request( + "POST", "/manage/admin/connector-with-mock-credential", json=connector, + auth=self._admin_auth, + ) + if resp.status_code >= 400: + raise OnyxError( + f"connector provision failed [{resp.status_code}]: {resp.text[:400]}" + ) + body = resp.json() + # add_credential_to_connector returns StatusResponse[int] with data = cc_pair_id. + data = body.get("data") + cc = data if isinstance(data, int) else body.get("cc_pair_id") + if not cc: + # Fall back to a name lookup — the create call may return only a status. + cc = self.find_cc_pair_id_by_name(name) + if not cc: + raise OnyxError(f"could not determine cc_pair_id after provisioning: {body}") + logger.info("Provisioned connector '%s' → cc_pair_id=%s", name, cc) + self.set_cc_pair_active(int(cc)) + return int(cc) + + def set_cc_pair_active(self, cc_pair_id: int) -> None: + """Mark the cc_pair ACTIVE so the connector is enabled and its documents + are searchable. Documents are pushed via the Ingestion API rather than + polled from a file location. Best-effort.""" + try: + resp = self._request( + "PUT", + f"/manage/admin/cc-pair/{cc_pair_id}/status", + json={"status": "ACTIVE"}, + auth=self._admin_auth, + ) + if resp.status_code >= 400: + logger.warning( + "Could not set cc_pair %s ACTIVE [%s]: %s", + cc_pair_id, resp.status_code, resp.text[:200], + ) + except OnyxError as exc: + logger.warning("Could not set cc_pair %s ACTIVE: %s", cc_pair_id, exc) + + # -- helpers ------------------------------------------------------------- + _admin_email: str | None = None + _admin_password: str | None = None + + def set_admin_credentials(self, email: str | None, password: str | None) -> None: + self._admin_email = email + self._admin_password = password + + @property + def _admin_auth(self) -> tuple[str, str] | None: + if self._admin_email and self._admin_password: + return (self._admin_email, self._admin_password) + return None diff --git a/app/state.py b/app/state.py new file mode 100644 index 0000000..1b9106e --- /dev/null +++ b/app/state.py @@ -0,0 +1,93 @@ +"""Persistent sync state (the manifest). + +The manifest is what makes update/delete sync possible: it remembers, per source, +which files were ingested, their stable Onyx ``document_id`` and a content hash. +On each cycle the engine diffs the share against this manifest to decide what to +upsert (new/changed) and what to delete (gone from disk). + +It also caches the auto-provisioned ``cc_pair_id`` per source so provisioning is +idempotent across restarts. +""" + +from __future__ import annotations + +import json +import os +import tempfile +from dataclasses import dataclass, field + + +@dataclass +class FileRecord: + document_id: str + content_hash: str + logical_path: str + size: int + mtime: float + # Ingestion payload format this file was last sent with. Bumping + # DOC_FORMAT_VERSION in sync.py forces a one-time re-upsert of every file + # when the document shape changes (e.g. the semantic_identifier), even + # though the file bytes are unchanged. Defaults to 1 for manifests written + # before this field existed. + doc_format_version: int = 1 + + +@dataclass +class SourceState: + cc_pair_id: int | None = None + # relative-path -> FileRecord + files: dict[str, FileRecord] = field(default_factory=dict) + # Content hash of the last table-of-contents (index) document written for + # this source. Lets the engine re-upsert the index only when the file set + # changed. None until the first index is written. + index_hash: str | None = None + + +class State: + def __init__(self, path: str) -> None: + self.path = path + self.api_key: str | None = None + self.sources: dict[str, SourceState] = {} + + # -- load/save ----------------------------------------------------------- + @classmethod + def load(cls, path: str) -> "State": + state = cls(path) + if not os.path.exists(path): + return state + with open(path, "r", encoding="utf-8") as fh: + raw = json.load(fh) + state.api_key = raw.get("api_key") + for name, s in (raw.get("sources") or {}).items(): + ss = SourceState(cc_pair_id=s.get("cc_pair_id"), index_hash=s.get("index_hash")) + for rel, rec in (s.get("files") or {}).items(): + ss.files[rel] = FileRecord(**rec) + state.sources[name] = ss + return state + + def save(self) -> None: + os.makedirs(os.path.dirname(self.path) or ".", exist_ok=True) + data = { + "api_key": self.api_key, + "sources": { + name: { + "cc_pair_id": ss.cc_pair_id, + "index_hash": ss.index_hash, + "files": {rel: vars(rec) for rel, rec in ss.files.items()}, + } + for name, ss in self.sources.items() + }, + } + # Atomic write so a crash mid-write can't corrupt the manifest. + fd, tmp = tempfile.mkstemp(dir=os.path.dirname(self.path) or ".", suffix=".tmp") + try: + with os.fdopen(fd, "w", encoding="utf-8") as fh: + json.dump(data, fh, indent=2) + os.replace(tmp, self.path) + finally: + if os.path.exists(tmp): + os.remove(tmp) + + # -- accessors ----------------------------------------------------------- + def source(self, name: str) -> SourceState: + return self.sources.setdefault(name, SourceState()) diff --git a/app/sync.py b/app/sync.py new file mode 100644 index 0000000..036df8b --- /dev/null +++ b/app/sync.py @@ -0,0 +1,312 @@ +"""The reconciliation engine: the production functionality the POC was missing. + +For each source, one cycle: + 1. Walk the mounted share, hashing each eligible file's content. + 2. NEW / CHANGED (hash differs from the manifest) → upsert into Onyx. + 3. GONE (in the manifest but no longer on disk) → delete from Onyx. + 4. Reconcile against Onyx's own doc list so deletes still happen even if the + local manifest was lost (e.g. fresh volume). + +Document ids are stable (derived from source name + relative path), so re-ingesting +a changed file updates it in place instead of creating a duplicate. +""" + +from __future__ import annotations + +import hashlib +import logging +import os +import re +from datetime import datetime, timezone + +from .config import Config, SourceConfig +from .extract import extract_text +from .onyx_client import OnyxClient, OnyxError +from .state import FileRecord, State + +logger = logging.getLogger("smb.sync") + +# Bump this when the ingestion document shape changes (fields Onyx displays or +# indexes) so every already-synced file is re-upserted once, even though its +# bytes are unchanged. v2: semantic_identifier is the file name, not the path. +DOC_FORMAT_VERSION = 2 + + +def _source_slug(source_name: str) -> str: + return re.sub(r"[^a-zA-Z0-9]+", "-", source_name).strip("-").lower() or "src" + + +def _fs_safe(value: str, fallback_encoding: str) -> str: + """Return a UTF-8/JSON-safe version of a filesystem string. + + Filenames whose bytes are not valid UTF-8 arrive from os.walk as surrogate- + escaped strings (e.g. '\\udce4' for the Latin-1/CP1252 byte 0xE4 = 'ä'). + Encoding those to UTF-8 — for the id hash, the ingestion JSON, or the manifest + — raises UnicodeEncodeError and crashes the cycle. Recover the original bytes + and decode them with the share's codepage so the real character comes through. + """ + try: + value.encode("utf-8") + return value # already clean UTF-8 + except UnicodeEncodeError: + raw = os.fsencode(value) # reverse surrogateescape → original on-disk bytes + for enc in (fallback_encoding, "utf-8", "latin-1"): + try: + return raw.decode(enc) + except (UnicodeDecodeError, LookupError): + continue + return raw.decode("utf-8", "replace") + + +def _stable_document_id(source_name: str, rel_path: str) -> str: + # URL-safe id (no ':' etc.) so it is NOT re-encoded by Onyx — keeps the id we + # send, store and later delete/reconcile byte-for-byte identical. + digest = hashlib.sha256(f"{source_name}\x00{rel_path}".encode("utf-8")).hexdigest()[:20] + return f"smb_{_source_slug(source_name)}_{digest}" + + +def _source_id_prefix(source_name: str) -> str: + return f"smb_{_source_slug(source_name)}_" + + +def _logical_path(source: SourceConfig, rel_path: str) -> str: + # Present the Windows-style path the user recognises, mapped from the mount. + sep = "\\" if "\\" in source.normalized_logical() else "/" + joined = rel_path.replace("/", sep) + return f"{source.normalized_logical()}{sep}{joined}" + + +def _eligible(path: str, cfg: Config) -> bool: + ext = os.path.splitext(path)[1].lower().lstrip(".") + if cfg.include_ext and ext not in cfg.include_ext: + return False + try: + if os.path.getsize(path) > cfg.max_file_mb * 1024 * 1024: + logger.info("Skipping %s (> %d MB)", path, cfg.max_file_mb) + return False + except OSError: + return False + return not os.path.basename(path).startswith(".") + + +def _build_document( + source: SourceConfig, rel_path: str, doc_id: str, text: str, mtime: float +) -> dict: + logical = _logical_path(source, rel_path) + filename = os.path.basename(rel_path) + updated = datetime.fromtimestamp(mtime, tz=timezone.utc).isoformat() + return { + "id": doc_id, + "source": "file", + # semantic_identifier is the label Onyx shows in the citation view. Use the + # file name so the citation stays short; the full network path is still in + # `link` and metadata, and the UI overlay copies it on click. + "semantic_identifier": filename, + "title": filename, + # The full logical network path. smb://Z:\... won't open in a browser; the + # AIDO UI overlay copies this to the clipboard on click instead. + "link": f"file://{logical}", + "sections": [{"text": text, "link": None}], + "metadata": { + "smb_source": source.name, + "logical_path": logical, + "relative_path": rel_path, + }, + "doc_updated_at": updated, + "from_ingestion_api": True, + } + + +def _index_document_id(source_name: str) -> str: + # Shares the source prefix so it is recognised as this connector's document, + # but has a fixed suffix so it is never treated as a file. The reconcile pass + # must whitelist this id (see sync_source) or it would be deleted as an orphan. + return f"{_source_id_prefix(source_name)}index" + + +def _build_index_text(source: SourceConfig, files: dict[str, "FileRecord"]) -> str: + """A human/LLM-readable table of contents: every file grouped by folder.""" + by_folder: dict[str, list[str]] = {} + for rel, rec in files.items(): + folder = os.path.dirname(rec.logical_path) or source.normalized_logical() + by_folder.setdefault(folder, []).append(rec.logical_path) + + lines = [ + f"Index of all documents synced from {source.name}.", + f"Total files: {len(files)}.", + "", + "This document lists every file available on this share, grouped by folder,", + "so the assistant knows the full set of documents even when a search only", + "returns some of them.", + "", + ] + for folder in sorted(by_folder): + lines.append(f"{folder}") + for path in sorted(by_folder[folder]): + lines.append(f" - {os.path.basename(path)}\t{path}") + lines.append("") + return "\n".join(lines) + + +def _build_index_document(source: SourceConfig, files: dict[str, "FileRecord"]) -> dict: + text = _build_index_text(source, files) + label = f"{source.name} — Index ({len(files)} Dateien)" + return { + "id": _index_document_id(source.name), + "source": "file", + "semantic_identifier": label, + "title": label, + # No file:// link: the index is a generated document, not a file on the + # share, so clicking it should not try to copy a path. + "link": None, + "sections": [{"text": text, "link": None}], + "metadata": { + "smb_source": source.name, + "smb_index": "true", + }, + "doc_updated_at": datetime.now(tz=timezone.utc).isoformat(), + "from_ingestion_api": True, + } + + +def sync_source(client: OnyxClient, cfg: Config, source: SourceConfig, state: State) -> None: + if not os.path.isdir(source.mount): + logger.error("Source '%s': mount %s is not accessible — skipping", source.name, source.mount) + return + + ss = state.source(source.name) + cc_pair_id = source.cc_pair_id or ss.cc_pair_id + if not cc_pair_id: + cc_pair_id = client.provision_cc_pair( + f"{cfg.connector_name_prefix} - {source.name}", + group_ids=source.group_ids, + ) + ss.cc_pair_id = cc_pair_id + state.save() + + seen: set[str] = set() + upserts = deletes = unchanged = 0 + + for root, _dirs, files in os.walk(source.mount): + for fname in files: + abspath = os.path.join(root, fname) + if not _eligible(abspath, cfg): + continue + rel = os.path.relpath(abspath, source.mount).replace(os.sep, "/") + # Normalise non-UTF-8 filenames (surrogate-escaped) so the id hash, + # the ingestion payload and the manifest are all UTF-8/JSON-safe. + rel = _fs_safe(rel, cfg.filename_encoding) + seen.add(rel) + try: + data = open(abspath, "rb").read() + except OSError as exc: + logger.warning("Cannot read %s: %s", abspath, exc) + continue + + content_hash = hashlib.sha256(data).hexdigest() + prev = ss.files.get(rel) + if ( + prev + and prev.content_hash == content_hash + and prev.doc_format_version == DOC_FORMAT_VERSION + ): + unchanged += 1 + continue + + text = extract_text(abspath, data) + if not text.strip(): + # Nothing extractable — don't ingest an empty document. + continue + + doc_id = _stable_document_id(source.name, rel) + document = _build_document(source, rel, doc_id, text, os.path.getmtime(abspath)) + try: + result = client.upsert_document(document, cc_pair_id) + except OnyxError as exc: + logger.error("Upsert failed for %s: %s", rel, exc) + continue + + # Store the id Onyx actually persisted (it may normalise/encode the id), + # so later delete + reconcile match byte-for-byte. + canonical_id = result.get("document_id", doc_id) if isinstance(result, dict) else doc_id + ss.files[rel] = FileRecord( + document_id=canonical_id, + content_hash=content_hash, + logical_path=_logical_path(source, rel), + size=len(data), + mtime=os.path.getmtime(abspath), + doc_format_version=DOC_FORMAT_VERSION, + ) + upserts += 1 + logger.info("%s %s", "updated" if prev else "indexed", rel) + + # Deletes: files in the manifest but no longer on disk. + for rel in list(ss.files.keys()): + if rel in seen: + continue + rec = ss.files.pop(rel) + try: + client.delete_document(rec.document_id) + deletes += 1 + logger.info("deleted %s (removed from share)", rel) + except OnyxError as exc: + logger.error("Delete failed for %s: %s", rel, exc) + ss.files[rel] = rec # keep it; retry next cycle + + state.save() + + # Index (table-of-contents) document: one per source, re-upserted only when + # the file set changed. Written after deletes so it reflects the current set. + index_id = _index_document_id(source.name) + if cfg.write_index and ss.files: + index_doc = _build_index_document(source, ss.files) + index_hash = hashlib.sha256( + index_doc["sections"][0]["text"].encode("utf-8") + ).hexdigest() + if ss.index_hash != index_hash: + try: + client.upsert_document(index_doc, cc_pair_id) + ss.index_hash = index_hash + state.save() + logger.info("wrote index document (%d files)", len(ss.files)) + except OnyxError as exc: + logger.error("Index upsert failed for '%s': %s", source.name, exc) + elif not cfg.write_index and ss.index_hash is not None: + # Feature turned off after an index was written — remove it. + try: + client.delete_document(index_id) + ss.index_hash = None + state.save() + logger.info("removed index document (SMB_WRITE_INDEX disabled)") + except OnyxError as exc: + logger.warning("Index delete for '%s' skipped: %s", source.name, exc) + + # Manifest-independent reconcile: remove Onyx docs for this cc_pair that we + # no longer track (covers a lost manifest / externally-added docs). + try: + live_ids = {r.document_id for r in ss.files.values()} + # The index document shares the source prefix but is not a file, so it + # must be whitelisted here or the reconcile would delete it every cycle. + if cfg.write_index and ss.files: + live_ids.add(index_id) + for doc in client.list_cc_pair_documents(cc_pair_id): + did = doc.get("document_id") + if did and did.startswith(_source_id_prefix(source.name)) and did not in live_ids: + client.delete_document(did) + deletes += 1 + logger.info("reconciled orphan delete %s", did) + except OnyxError as exc: + logger.warning("Reconcile pass for '%s' skipped: %s", source.name, exc) + + logger.info( + "Source '%s' done: %d upserted, %d deleted, %d unchanged (cc_pair_id=%s)", + source.name, upserts, deletes, unchanged, cc_pair_id, + ) + + +def sync_all(client: OnyxClient, cfg: Config, state: State) -> None: + for source in cfg.sources: + try: + sync_source(client, cfg, source, state) + except Exception as exc: # isolate a failing source from the rest + logger.exception("Source '%s' failed this cycle: %s", source.name, exc) diff --git a/docker-compose.smb.yml b/docker-compose.smb.yml new file mode 100644 index 0000000..140897c --- /dev/null +++ b/docker-compose.smb.yml @@ -0,0 +1,46 @@ +# Add this service to your Onyx docker-compose (same `onyx-network`). +# +# docker compose -f docker-compose.yml -f smb-connector/docker-compose.smb.yml up -d smb_connector +# +# The connector mounts the SMB/CIFS shares INSIDE the container (default mode) — +# no host mount needed. Just give it the share + credentials via env (see +# smb-connector/.env.example). For that, the container needs the two capabilities +# and the unconfined apparmor profile below (required for mount.cifs in a +# container; the host also needs the `cifs` kernel module, which is standard). +services: + smb_connector: + build: ./smb-connector + image: livtec/aido-smb-connector:local + container_name: aido-smb-connector + restart: unless-stopped + networks: + - onyx-network + env_file: + - path: ./smb-connector/.env + required: false + depends_on: + api_server: + condition: service_healthy + + # --- required to mount SMB/CIFS shares inside the container --------------- + cap_add: + - SYS_ADMIN + - DAC_READ_SEARCH + security_opt: + - apparmor:unconfined + # If your host's Docker still refuses the mount, use privileged mode instead + # of the two cap_add lines above: + # privileged: true + + volumes: + # Persist the sync manifest + cached api-key/cc_pair (survives restarts). + - ./smb-connector/state:/app/state + # NOTE: no host bind-mounts of the shares are needed in in-container mode. + # (Legacy host-mount mode still works: bind-mount the share here and OMIT + # the SMB_SOURCE_*_SERVER/_UNC env for that source, e.g. + # - /mnt/smb/finance:/mnt/smb/finance:ro ) + logging: + driver: json-file + options: + max-size: "50m" + max-file: "6" diff --git a/docker-compose.standalone.yml b/docker-compose.standalone.yml new file mode 100644 index 0000000..b028796 --- /dev/null +++ b/docker-compose.standalone.yml @@ -0,0 +1,60 @@ +# Standalone SMB connector — its own Compose project, next to Onyx. +# +# Run it on its own (no `-f` injection into the Onyx compose): +# +# cd smb-connector +# docker compose -f docker-compose.standalone.yml up -d --build +# +# It reaches Onyx over Onyx's existing Docker network. Onyx's compose has +# `name: onyx` and no custom network, so its network is `onyx_default`. If your +# Onyx project uses a different name, set ONYX_NETWORK to _default. +# The connector talks to the API by service name (http://api_server:8080). +# +# In-container CIFS mounting works the same as before: give the share + +# credentials via env (see .env.example). The two capabilities and the +# unconfined apparmor profile below are required for mount.cifs in a container. +name: aido-smb-connector + +services: + smb_connector: + build: . + image: livtec/aido-smb-connector:local + container_name: aido-smb-connector + restart: unless-stopped + environment: + # Reach the Onyx API over the shared network (override if needed). + - ONYX_API_URL=${ONYX_API_URL:-http://api_server:8080} + env_file: + - path: .env + required: false + networks: + - onyx_net + + # --- required to mount SMB/CIFS shares inside the container --------------- + cap_add: + - SYS_ADMIN + - DAC_READ_SEARCH + security_opt: + - apparmor:unconfined + # If your host's Docker still refuses the mount, use privileged mode instead + # of the two cap_add lines above: + # privileged: true + + volumes: + # Persist the sync manifest + cached api-key/cc_pair (survives restarts). + - ./state:/app/state + # Legacy host-mount mode still works: bind-mount a share here and OMIT the + # SMB_SOURCE_*_SERVER/_UNC env for that source, e.g. + # - /mnt/smb/finance:/mnt/smb/finance:ro + logging: + driver: json-file + options: + max-size: "50m" + max-file: "6" + +# Onyx's network, created by the Onyx compose project. Joined as external so +# this stays a separate Compose project. Override the name with ONYX_NETWORK. +networks: + onyx_net: + external: true + name: ${ONYX_NETWORK:-onyx_default} diff --git a/entrypoint.sh b/entrypoint.sh new file mode 100644 index 0000000..cf6f706 --- /dev/null +++ b/entrypoint.sh @@ -0,0 +1,105 @@ +#!/bin/sh +# ───────────────────────────────────────────────────────────────────────────── +# AIDO SMB connector entrypoint. +# +# Mounts each configured SMB/CIFS share *inside the container* (no host mount +# needed), then drops privileges and runs the sync app. Mounting is opt-in per +# source: a source is CIFS-mounted only if it provides SMB connection details +# (SMB_SOURCE__UNC or _SERVER + _SHARE). Sources without them are assumed to +# be bind-mounted from the host at their _MOUNT path (the original Phase-1 mode), +# so both styles work side by side. +# +# Per-source env (indexed style): +# SMB_SOURCE__NAME label (also used by the app) +# SMB_SOURCE__MOUNT where to mount inside the container (e.g. /mnt/smb/finance) +# SMB_SOURCE__UNC //server/share (or use _SERVER + _SHARE) +# SMB_SOURCE__SERVER server host/ip \_ combined into //server/share +# SMB_SOURCE__SHARE share name / +# SMB_SOURCE__USERNAME CIFS username (omit for guest) +# SMB_SOURCE__PASSWORD CIFS password +# SMB_SOURCE__DOMAIN AD domain/workgroup (optional) +# SMB_SOURCE__VERS SMB dialect, default 3.0 +# SMB_SOURCE__MOUNT_OPTS extra raw mount -o options (optional) +# +# Requires the container to have CAP_SYS_ADMIN + DAC_READ_SEARCH and an +# unconfined apparmor profile (see docker-compose.smb.yml). +# ───────────────────────────────────────────────────────────────────────────── +set -eu + +APP_UID="${APP_UID:-10001}" +APP_GID="${APP_GID:-10001}" +MOUNTED="" + +log() { echo "$(date -u +%Y-%m-%dT%H:%M:%SZ) [entrypoint] $*"; } + +cleanup() { + # Unmount in reverse so the app's file handles are released cleanly on stop. + for m in $MOUNTED; do + umount "$m" 2>/dev/null && log "unmounted $m" || log "warn: could not unmount $m" + done +} +trap cleanup EXIT INT TERM + +mount_one() { + n="$1" + eval unc="\${SMB_SOURCE_${n}_UNC:-}" + eval server="\${SMB_SOURCE_${n}_SERVER:-}" + eval share="\${SMB_SOURCE_${n}_SHARE:-}" + eval mnt="\${SMB_SOURCE_${n}_MOUNT:-}" + eval user="\${SMB_SOURCE_${n}_USERNAME:-}" + eval pass="\${SMB_SOURCE_${n}_PASSWORD:-}" + eval domain="\${SMB_SOURCE_${n}_DOMAIN:-}" + eval vers="\${SMB_SOURCE_${n}_VERS:-3.0}" + eval extra="\${SMB_SOURCE_${n}_MOUNT_OPTS:-}" + + # No SMB connection details → host-bind-mount mode; nothing to do here. + if [ -z "$unc" ] && [ -z "$server" ]; then + return 0 + fi + [ -n "$unc" ] || unc="//${server}/${share}" + if [ -z "$mnt" ]; then + log "ERROR: SMB_SOURCE_${n}_MOUNT is required when mounting $unc inside the container" + exit 1 + fi + + mkdir -p "$mnt" + # Credentials via a 0600 file so the password never appears in the process list. + cred="/tmp/.smbcred_${n}" + { + [ -n "$user" ] && echo "username=$user" + [ -n "$pass" ] && echo "password=$pass" + [ -n "$domain" ] && echo "domain=$domain" + } > "$cred" + chmod 600 "$cred" + + opts="ro,vers=${vers},uid=${APP_UID},gid=${APP_GID},file_mode=0440,dir_mode=0550,nounix,serverino" + if [ -n "$user" ]; then + opts="${opts},credentials=${cred}" + else + opts="${opts},guest" + fi + [ -n "$extra" ] && opts="${opts},${extra}" + + log "mounting $unc -> $mnt (vers=${vers}${user:+, user=$user}${domain:+, domain=$domain})" + if mount -t cifs "$unc" "$mnt" -o "$opts"; then + MOUNTED="$mnt $MOUNTED" + rm -f "$cred" + else + rm -f "$cred" + log "ERROR: failed to mount $unc at $mnt — check credentials, host reachability, and that the container has CAP_SYS_ADMIN" + exit 1 + fi +} + +# Walk SMB_SOURCE_1.., mounting any that carry connection details. +i=1 +while :; do + eval name="\${SMB_SOURCE_${i}_NAME:-}" + [ -n "$name" ] || break + mount_one "$i" + i=$((i + 1)) +done + +# Hand off to the sync app as the unprivileged runner. +log "starting sync app as uid=${APP_UID}" +exec gosu "${APP_UID}:${APP_GID}" python -m app.main diff --git a/requirements.txt b/requirements.txt new file mode 100644 index 0000000..5ef43e7 --- /dev/null +++ b/requirements.txt @@ -0,0 +1,4 @@ +requests==2.32.3 +pypdf==5.1.0 +python-docx==1.1.2 +openpyxl==3.1.5