filesystem_sync.py 11.9 KB
"""Two-phase enumeration and bounded, per-path publication to SQLite and recall."""
from datetime import datetime
from hashlib import sha1
from io import BytesIO
import logging
import os
import stat
import threading
import time

import cv2

from filesystem_files import (IGNORE_DIRS, IGNORE_FILES, IMAGE_FORMATS, VIDEO_FORMATS,
                              FilePaths, extract_video, file_metadata, linked, marker_identity,
                              open_checked, read_image_bytes, staged_video)

logger = logging.getLogger(__name__)


class ScanInventory:
    def __init__(self, paths, video_enabled, held_paths):
        self.files = {}
        self.markers = {}
        self.failures = 0
        self.stat_failures = 0
        self.paths = paths
        self._enumerate(video_enabled, held_paths)

    def _error(self, error):
        self.failures += 1
        logger.warning('Incomplete filesystem scan: %s', error)

    def _stat(self, path):
        try:
            return os.lstat(path)
        except OSError as error:
            self.stat_failures += 1
            self._error(error)
            return None

    def _enumerate(self, video_enabled, held_paths):
        formats = IMAGE_FORMATS | VIDEO_FORMATS if video_enabled else IMAGE_FORMATS
        occupied = {self.paths.root_for(path) for path in held_paths}
        for root, name in self.paths.roots.items():
            try:
                self.markers[root] = marker_identity(root, name)
            except (OSError, UnicodeError) as error:
                self._error(f'{root}: {error}')
                continue
            start_count = len(self.files)
            for directory, dirs, files in os.walk(root, followlinks=False, onerror=self._error):
                allowed = []
                for subdir in dirs:
                    if subdir.casefold() not in IGNORE_DIRS:
                        info = self._stat(os.path.join(directory, subdir))
                        if info is not None and stat.S_ISDIR(info.st_mode) and not linked(info):
                            allowed.append(subdir)
                dirs[:] = allowed
                for name in files:
                    if (name.casefold() in IGNORE_FILES or name.startswith(('._', '~$', '.~'))
                            or os.path.splitext(name)[1].lower() not in formats):
                        continue
                    path = os.path.join(directory, name)
                    info = self._stat(path)
                    if info is not None and stat.S_ISREG(info.st_mode) and not linked(info):
                        self.files[path] = file_metadata(info)
            if root in occupied and len(self.files) == start_count:
                self._error(f'{root}: no eligible files in occupied root')

    def verify_markers(self):
        for root, name in self.paths.roots.items():
            if root not in self.markers:
                continue
            try:
                if marker_identity(root, name) != self.markers[root]:
                    raise OSError('Root identity changed')
            except (OSError, UnicodeError) as error:
                self._error(f'{root}: {error}')


def positive_int(value, label, minimum=1):
    if type(value) is not int or value < minimum:
        raise ValueError(f'{label} must be an integer >= {minimum}')
    return value


class FileSystemSync:
    def __init__(self, config, index, db_manager, extractor):
        settings = config['filesystem']
        self.paths = FilePaths(settings['roots'], settings['unc_prefixes'])
        self.index = index
        self.db = db_manager
        self.extractor = extractor
        self.interval = positive_int(settings.get('interval_seconds', 14400), 'interval_seconds')
        self.batch_size = positive_int(settings.get('batch_size', 32), 'batch_size')
        window = settings.get('night_window')
        if window is not None:
            if (len(window) != 2 or any(type(hour) is not int or not 0 <= hour < 24 for hour in window)
                    or window[0] == window[1]):
                raise ValueError('night_window requires distinct start/end hours in 0..23')
        self.night_window = window
        self.video_enabled = config.get('video', {}).get('enabled', False)
        if type(self.video_enabled) is not bool:
            raise ValueError('video.enabled requires a boolean')
        self.frame_cap = positive_int(config.get('video', {}).get('frame_cap', 8), 'frame_cap')
        self.version = self.db.max_feat_version()
        self.pending = set()
        self.mutex = threading.Lock()
        self.stop_event = threading.Event()
        self._status = {'last_scan_at': None, 'complete': None, 'pending_delete': 0,
                        'deletion_skipped': False, 'index_full': 0, 'failures': 0}

    @property
    def status(self):
        return dict(self._status)

    def _active_path(self, path):
        return self.video_enabled or os.path.splitext(path)[1].lower() not in VIDEO_FORMATS

    def _replace(self, path, metadata, digest, frames):
        # Normalize and serialize the entire group before making it durable.
        prepared = []
        for frame_ms, features in frames:
            if not features or features.get('cnn_vector') is None:
                raise ValueError('Feature extraction failed')
            vector = self.index.normalized(features['cnn_vector'])
            prepared.append((frame_ms, vector, self.db.feature_blobs(features)))
        with self.index.lock:
            entries = []
            with self.db.get_connection() as conn:
                old_ids = [r['id'] for r in conn.execute('SELECT id FROM images WHERE path=?', (path,))]
                if not self.index.can_replace_group(old_ids, len(prepared)):
                    return False
                conn.execute('DELETE FROM images WHERE path=?', (path,))
                for version, (frame_ms, vector, blobs) in enumerate(prepared, start=self.version + 1):
                    image_id = self.db.insert_file(conn, path, self.paths.unc(path), *metadata,
                                                   digest, frame_ms, blobs, version)
                    entries.append((image_id, 2, vector, version))
                conn.execute('DELETE FROM damaged_files WHERE path=?', (path,))
            self.index.replace_group(old_ids, entries)
            self.version += len(entries)
        return True

    def _refresh(self, path, root, metadata, old, counts):
        suffix = os.path.splitext(path)[1].lower()
        if suffix in VIDEO_FORMATS:
            hasher = sha1()
            with open_checked(path, root, metadata) as src, staged_video(src, suffix, hasher) as staged:
                counts['read_bytes'] += metadata[1]
                digest = hasher.hexdigest()
                if old and old['sha1'] == digest:
                    frames = None
                else:
                    try:
                        frames = extract_video(staged, self.frame_cap, self.extractor)
                    except (ValueError, cv2.error):
                        frames = []
        else:
            content, digest = read_image_bytes(path, root, metadata)
            counts['read_bytes'] += len(content)
            frames = (None if old and old['sha1'] == digest else
                      [(-1, self.extractor.extract_all_features(BytesIO(content)))])
        if frames is None:
            with self.db.get_connection() as conn:
                conn.execute('UPDATE images SET mtime=?, size=? WHERE path=?', (*metadata, path))
                conn.execute('DELETE FROM damaged_files WHERE path=?', (path,))
            return
        try:
            if frames:
                if not self._replace(path, metadata, digest, frames):
                    counts['index_full'] += 1
                    logger.error('index_full: deferred %s', path)
                return
        except ValueError:
            pass
        counts['failures'] += 1
        with self.db.get_connection() as conn:
            self.db.record_damage(conn, path, *metadata, digest, 'feature_extraction')

    def _delete(self, inventory, missing):
        inventory.verify_markers()
        if inventory.failures:
            self.pending.clear()
            return
        expired = self.pending & missing
        with self.index.lock:
            with self.db.get_connection() as conn:
                ids = []
                for path in expired:
                    ids.extend(r['id'] for r in conn.execute('SELECT id FROM images WHERE path=?', (path,)))
                    conn.execute('DELETE FROM images WHERE path=?', (path,))
                    conn.execute('DELETE FROM damaged_files WHERE path=?', (path,))
                if expired:
                    inventory.verify_markers()
                    if inventory.failures:
                        conn.rollback()
                        self.pending.clear()
                        return
            self.index.replace_group(ids, [])
        self.pending = missing - expired

    def scan_once(self, stop_event=None):
        stop_event = self.stop_event if stop_event is None else stop_event
        with self.mutex:
            try:
                return self._scan(stop_event)
            except Exception:
                self.pending.clear()
                self._status = dict(self.status, last_scan_at=datetime.now().isoformat(), complete=False,
                                    deletion_skipped=True, pending_delete=0, failures=1)
                raise

    def _scan(self, stop_event):
        started = time.monotonic()
        known = self.db.file_metadata()
        damaged = self.db.damaged_metadata()
        held = {path for path in known.keys() | damaged.keys() if self._active_path(path)}
        inventory = ScanInventory(self.paths, self.video_enabled, held & known.keys())
        counts = {'failures': 0, 'read_bytes': 0, 'index_full': 0}
        batch = []

        def process(items):
            for path, metadata in items:
                if stop_event.is_set():
                    return
                try:
                    self._refresh(path, self.paths.root_for(path), metadata, known.get(path), counts)
                except OSError as error:
                    inventory._error(error)

        for path, metadata in inventory.files.items():
            if stop_event.is_set():
                break
            old = known.get(path)
            if (old and (old['mtime'], old['size']) == metadata) or damaged.get(path) == metadata:
                continue
            batch.append((path, metadata))
            if len(batch) == self.batch_size:
                process(batch)
                batch.clear()
        process(batch)
        if stop_event.is_set():
            self.pending.clear()
            return self.status
        missing = {path for path in held - inventory.files.keys() if self.paths.root_for(path) is not None}
        self._delete(inventory, missing)
        counts['failures'] += inventory.failures
        self._status = dict(counts, last_scan_at=datetime.now().isoformat(), complete=not inventory.failures,
                            deletion_skipped=bool(inventory.failures), pending_delete=len(self.pending),
                            eligible_files=len(inventory.files), stat_failures=inventory.stat_failures,
                            duration_seconds=round(time.monotonic() - started, 3))
        logger.info('Filesystem scan: %s', self._status)
        return self.status

    def _in_night_window(self):
        if self.night_window is None:
            return True
        start, end = self.night_window
        hour = datetime.now().hour
        return start <= hour < end if start < end else hour >= start or hour < end

    def run_forever(self, stop_event=None):
        stop_event = self.stop_event if stop_event is None else stop_event
        while not stop_event.is_set():
            if not self._in_night_window():
                stop_event.wait(60)
                continue
            try:
                self.scan_once(stop_event)
            except Exception:
                logger.exception('Filesystem scan failed')
            stop_event.wait(self.interval)