Skip to content

clabe.aind.watchdog

UploadGroup

Bases: BaseModel

One upload job of a session, written as its own watchdog manifest.

A session's modalities can be split into groups that are uploaded independently, e.g. to make the behavior data available hours before its videos are compressed. All groups write to the same folder and asset: the group with creates_record creates the asset's metadata record and the others append to it, so the job types must be set up for that in the data transfer service.

The job_type, schedule_time, delete_modalities_source_after_success and upload_tasks fields of the watchdog section are the shorthand for a single group with every modality.

WatchdogSettings

Bases: ServiceSettings

Settings for the WatchdogDataTransferService.

Configures data transfer operations including destination paths, scheduling, and integration with the AIND watchdog service.

resolved_upload_groups

resolved_upload_groups() -> list[UploadGroup]

The session's upload groups, the group that creates the record first.

Without upload_groups, a single group with every modality, from the deprecated single-job fields. It is built on each call, so changes made to those fields after the settings are created apply. With upload_groups, those fields are ignored, with a warning if any of them was set.

Source code in src/clabe/aind/watchdog.py
def resolved_upload_groups(self) -> list[UploadGroup]:
    """The session's upload groups, the group that creates the record first.

    Without ``upload_groups``, a single group with every modality, from the deprecated single-job fields. It is
    built on each call, so changes made to those fields after the settings are created apply. With
    ``upload_groups``, those fields are ignored, with a warning if any of them was set.
    """
    if self.upload_groups is not None:
        ignored = sorted(_SINGLE_JOB_FIELDS & self.model_fields_set)
        if ignored:
            logger.warning(
                "WatchdogSettings %s are ignored because upload_groups is set: set them on the groups instead.",
                ignored,
            )
    groups = self.upload_groups or [
        UploadGroup(
            name=DEFAULT_UPLOAD_GROUP_NAME,
            job_type=self.job_type,
            modalities="*",
            creates_record=True,
            schedule_time=self.schedule_time,
            delete_modalities_source_after_success=self.delete_modalities_source_after_success,
            upload_tasks=self.upload_tasks,
        )
    ]
    return sorted(groups, key=lambda g: not g.creates_record)

settings_customise_sources classmethod

settings_customise_sources(
    settings_cls: type[BaseSettings],
    init_settings: PydanticBaseSettingsSource,
    env_settings: PydanticBaseSettingsSource,
    dotenv_settings: PydanticBaseSettingsSource,
    file_secret_settings: PydanticBaseSettingsSource,
) -> tuple[PydanticBaseSettingsSource, ...]

Customizes the settings sources to include the safe YAML settings source.

Parameters:

Name Type Description Default
settings_cls type[BaseSettings]

The settings class

required
init_settings PydanticBaseSettingsSource

The initial settings source

required
env_settings PydanticBaseSettingsSource

The environment settings source

required
dotenv_settings PydanticBaseSettingsSource

The dotenv settings source

required
file_secret_settings PydanticBaseSettingsSource

The file secret settings source

required

Returns:

Type Description
tuple[PydanticBaseSettingsSource, ...]

Tuple[PydanticBaseSettingsSource, ...]: A tuple of settings sources

Source code in src/clabe/settings.py
@classmethod
def settings_customise_sources(
    cls,
    settings_cls: type[ps.BaseSettings],
    init_settings: ps.PydanticBaseSettingsSource,
    env_settings: ps.PydanticBaseSettingsSource,
    dotenv_settings: ps.PydanticBaseSettingsSource,
    file_secret_settings: ps.PydanticBaseSettingsSource,
) -> tuple[ps.PydanticBaseSettingsSource, ...]:
    """
    Customizes the settings sources to include the safe YAML settings source.

    Args:
        settings_cls: The settings class
        init_settings: The initial settings source
        env_settings: The environment settings source
        dotenv_settings: The dotenv settings source
        file_secret_settings: The file secret settings source

    Returns:
        Tuple[PydanticBaseSettingsSource, ...]: A tuple of settings sources
    """
    yaml_sources = [
        _SafeYamlSettingsSource(settings_cls, yaml_file=p, yaml_config_section=cls.__yml_section__)
        for p in KNOWN_CONFIG_FILES
    ]
    # The in-memory document (--clabe-yml) ranks above every file
    return (
        init_settings,
        _InMemorySettingsSource(settings_cls, config_section=cls.__yml_section__),
        *yaml_sources,
        env_settings,
        dotenv_settings,
        file_secret_settings,
    )

PlannedManifest dataclass

PlannedManifest(
    group: str,
    creates_record: bool,
    filename: str,
    manifest: ManifestConfig,
)

A manifest to write to the watchdog's flag directory.

Attributes:

Name Type Description
group str

Name of the upload group.

creates_record bool

Whether the group creates the metadata record.

filename str

The manifest's file name in the watchdog's flag directory.

manifest ManifestConfig

The manifest.

WatchdogDataTransferService

WatchdogDataTransferService(
    source: PathLike | None | Sequence[PathLike | None],
    settings: WatchdogSettings,
    session: Session,
    *,
    validate: bool = False,
    email_from_experimenter_builder: Callable[[str], str]
    | None = _default_email_from_experimenter,
)

Bases: DataTransfer[WatchdogSettings]

A data transfer service that uses the aind-watchdog-service to monitor and transfer data.

Integrates with the AIND data transfer infrastructure to automatically monitor directories for new data and transfer it to specified destinations with proper metadata handling and validation.

A session is written as one manifest per upload group (see WatchdogSettings.upload_groups).

Methods:

Name Description
transfer

Writes the session's manifests and starts the watchdog service

plan

Builds the session's manifests without writing them

validate

Validates the Watchdog service and its configuration

is_valid_project_name

Checks if the project name is valid

is_running

Checks if the Watchdog service is currently running

force_restart

Attempts to restart the Watchdog application

dump_manifest_config

Dumps the manifest configuration to a YAML file

Initializes the WatchdogDataTransferService.

Parameters:

Name Type Description Default
source PathLike | None | Sequence[PathLike | None]

The session folder(s) to transfer, e.g. launcher.session_directories (this machine's and every other machine's of the run). Folders on other machines are given through their share. None entries are skipped (e.g. a machine an optional step did not use).

required
settings WatchdogSettings

Configuration for the watchdog service

required
session Session

The session data from aind-behavior-services

required
validate bool

Whether to validate the project name

False
email_from_experimenter_builder Callable[[str], str] | None

Function to build email from experimenter name. Defaults to looking up the email via Active Directory, raising ValueError if it cannot be determined.

_default_email_from_experimenter
Source code in src/clabe/aind/watchdog.py
def __init__(
    self,
    source: PathLike | None | Sequence[PathLike | None],
    settings: WatchdogSettings,
    session: Session,
    *,
    validate: bool = False,
    email_from_experimenter_builder: Callable[[str], str] | None = _default_email_from_experimenter,
) -> None:
    """
    Initializes the WatchdogDataTransferService.

    Args:
        source: The session folder(s) to transfer, e.g. ``launcher.session_directories`` (this machine's and
            every other machine's of the run). Folders on other machines are given through their share. ``None``
            entries are skipped (e.g. a machine an optional step did not use).
        settings: Configuration for the watchdog service
        session: The session data from aind-behavior-services
        validate: Whether to validate the project name
        email_from_experimenter_builder: Function to build email from experimenter name. Defaults to
            looking up the email via Active Directory, raising ``ValueError`` if it cannot be
            determined.
    """
    self._settings = settings
    given = list(source) if isinstance(source, Sequence) and not isinstance(source, (str, bytes)) else [source]
    self._sources = [s for s in given if s is not None]
    if not self._sources:
        raise ValueError("No folder to transfer: every source is None.")

    self._session = session

    _default_exe = os.environ.get("WATCHDOG_EXE", None)
    _default_config = os.environ.get("WATCHDOG_CONFIG", None)

    if _default_exe is None or _default_config is None:
        raise ValueError("WATCHDOG_EXE and WATCHDOG_CONFIG environment variables must be defined.")

    self.executable_path = Path(_default_exe)
    self.config_path = Path(_default_config)

    self._watch_config: WatchConfig | None = None
    self._manifest_config: ManifestConfig | None = None

    self._validate_project_name = validate

    if validate:
        self.validate()

    self._watch_config = WatchConfig.model_validate(self._read_yaml(self.config_path))

    self._email_from_experimenter_builder = email_from_experimenter_builder

settings property

settings: TSettings

Returns the settings for the data transfer service.

Returns:

Name Type Description
TSettings TSettings

The service settings

transfer

transfer() -> None

Writes the session's watchdog manifests, one per upload group, then starts the watchdog if needed.

The manifest of the group that creates the metadata record is written first, and nothing else is written if it fails. The manifests are written even if the service is not running, since it processes existing manifests when it starts; the service is then started if needed. Failing to start it is logged, never raised, since the manifests are already queued.

Source code in src/clabe/aind/watchdog.py
@runnable(name="Transfer (watchdog)", notify="Transferring data (watchdog)…")
def transfer(self) -> None:
    """
    Writes the session's watchdog manifests, one per upload group, then starts the watchdog if needed.

    The manifest of the group that creates the metadata record is written first, and nothing else is written if
    it fails. The manifests are written even if the service is not running, since it processes existing
    manifests when it starts; the service is then started if needed. Failing to start it is logged, never
    raised, since the manifests are already queued.
    """
    try:
        logger.debug("Creating watchdog manifest config(s).")

        if self._watch_config is None:
            raise ValueError("Watchdog config is not set.")

        planned = self.plan()
        self._manifest_config = planned[0].manifest
        written: list[Path] = []
        for item in planned:
            written.append(
                self.dump_manifest_config(
                    path=Path(self._watch_config.flag_dir) / item.filename, manifest=item.manifest
                )
            )
            logger.info("Watchdog manifest for '%s' created successfully at %s.", item.group, written[-1])

    except (OSError, pydantic.ValidationError, ValueError) as e:
        logger.error("Failed to create watchdog manifest config. %s", e)
        raise

    try:
        if self.is_running():
            return
        logger.warning("Watchdog service is not running. Attempting to start it.")
        self.force_restart(kill_if_running=False)
        started = self.is_running()
    except Exception as e:  # noqa: BLE001 -- the manifest is queued, so a failed start must not fail the transfer
        logger.error("Failed to start watchdog service: %s", e)
        started = False
    if started:
        logger.info("Watchdog service restarted successfully.")
    else:
        logger.error(
            "Watchdog service is not running. The manifest(s) %s are written and will be transferred "
            "once the watchdog service runs.",
            ", ".join(str(p) for p in written),
        )

plan

plan(
    session: Session | None = None,
) -> list[PlannedManifest]

Builds the session's manifests, one per upload group, without writing them.

Each source is searched for folders named after a modality and for *.json metadata files. Each modality goes to the group that claims it, or to the '*' group. Groups that find none of their modalities are skipped.

Parameters:

Name Type Description Default
session Session | None

The session. Defaults to the service's.

None

Returns:

Type Description
list[PlannedManifest]

The manifests, the one of the group that creates the record first.

Raises:

Type Description
FileNotFoundError

If a source cannot be reached.

ValueError

If a modality is claimed by no group, the group that creates the record finds none of its modalities, or a group that appends is submitted before it.

Source code in src/clabe/aind/watchdog.py
def plan(self, session: Session | None = None) -> list[PlannedManifest]:
    """
    Builds the session's manifests, one per upload group, without writing them.

    Each source is searched for folders named after a modality and for ``*.json`` metadata files. Each modality
    goes to the group that claims it, or to the ``'*'`` group. Groups that find none of their modalities are
    skipped.

    Args:
        session: The session. Defaults to the service's.

    Returns:
        The manifests, the one of the group that creates the record first.

    Raises:
        FileNotFoundError: If a source cannot be reached.
        ValueError: If a modality is claimed by no group, the group that creates the record finds none of its
            modalities, or a group that appends is submitted before it.
    """
    session = session or self._session

    if (len(session.experimenter) > 0) and self._email_from_experimenter_builder is not None:
        user_email = self._email_from_experimenter_builder(session.experimenter[-1])
    else:
        user_email = None

    destination = Path(self._settings.destination).resolve()

    sources = {Path(s).resolve() for s in self._sources}
    # Sources may be network shares on other machines, so report every unreachable one up front
    missing = sorted(str(s) for s in sources if not s.is_dir())
    if missing:
        raise FileNotFoundError(f"Watchdog source directories not found or not reachable: {', '.join(missing)}")

    if self._validate_project_name and self._settings.project_name is not None:
        project_names = self._get_project_names()
        if self._settings.project_name not in project_names:
            raise ValueError(f"Project name {self._settings.project_name} not found in {project_names}")

    found, schemas = self._discover(sources)

    groups = self._settings.resolved_upload_groups()
    claimed = {m for g in groups if g.modalities != "*" for m in g.modalities}
    unclaimed = [m for m in found if m not in claimed]  # in the order found, as in the manifest
    if unclaimed and not any(g.modalities == "*" for g in groups):
        raise ValueError(f"Modalities {unclaimed} are claimed by no upload group. Add them to one, or add '*'.")
    self._check_schedule_order(groups)

    planned: list[PlannedManifest] = []
    for group in groups:
        names = unclaimed if group.modalities == "*" else group.modalities
        modalities = {m: found[m] for m in names if m in found}
        if not modalities:
            if group.creates_record:
                raise ValueError(
                    f"Upload group '{group.name}' creates the record but found none of its modalities."
                )
            logger.warning("Upload group '%s' found none of its modalities %s. Skipping it.", group.name, names)
            continue
        not_found = [m for m in names if m not in found]
        if not_found:
            logger.info("Upload group '%s' did not find modalities %s.", group.name, not_found)
        planned.append(
            self._plan_group(
                session,
                group,
                modalities,
                schemas if group.creates_record else [],
                destination=destination,
                user_email=user_email,
            )
        )
    return planned

validate

validate() -> bool

Validates the Watchdog service and its configuration.

Checks for required executables, configuration files, service status, and project name validity.

Returns:

Type Description
bool

True if the service is valid, False otherwise

Raises:

Type Description
FileNotFoundError

If required files are missing

HTTPError

If the project name validation fails

Source code in src/clabe/aind/watchdog.py
def validate(self) -> bool:
    """
    Validates the Watchdog service and its configuration.

    Checks for required executables, configuration files, service status,
    and project name validity.

    Returns:
        True if the service is valid, False otherwise

    Raises:
        FileNotFoundError: If required files are missing
        HTTPError: If the project name validation fails
    """
    logger.debug("Attempting to validate Watchdog service.")
    if not self.executable_path.exists():
        raise FileNotFoundError(f"Executable not found at {self.executable_path}")
    if not self.config_path.exists():
        raise FileNotFoundError(f"Config file not found at {self.config_path}")

    if not self.is_running():
        logger.warning(
            "Watchdog service is not running. \
                            After the session is over, \
                            the launcher will attempt to forcefully restart it"
        )
        return False

    if self.settings.project_name is None:
        logger.warning("Watchdog project name is not set. Skipping validation.")
    else:
        try:
            _valid_proj = self.is_valid_project_name()
            if not _valid_proj:
                logger.warning("Watchdog project name is not valid.")
        except HTTPError as e:
            logger.error("Failed to fetch project names from endpoint. %s", e)
            raise
        return _valid_proj

    return True

is_valid_project_name

is_valid_project_name() -> bool

Checks if the project name is valid by querying the metadata service.

Returns:

Type Description
bool

True if the project name is valid, False otherwise

Source code in src/clabe/aind/watchdog.py
def is_valid_project_name(self) -> bool:
    """
    Checks if the project name is valid by querying the metadata service.

    Returns:
        True if the project name is valid, False otherwise
    """
    project_names = self._get_project_names()
    return self._settings.project_name in project_names

add_data_description_tags

add_data_description_tags(*tags: str) -> None

Registers tags to be added to the data description.

The tags are stored in the settings and written to the manifest of the group that creates the record when it is built (i.e. on transfer). Duplicates are dropped when written.

Parameters:

Name Type Description Default
*tags str

The tags to add

()
Source code in src/clabe/aind/watchdog.py
def add_data_description_tags(self, *tags: str) -> None:
    """
    Registers tags to be added to the data description.

    The tags are stored in the settings and written to the manifest of the group that creates the record when
    it is built (i.e. on `transfer`). Duplicates are dropped when written.

    Args:
        *tags: The tags to add
    """
    self._settings.data_description_tags = [*(self._settings.data_description_tags or []), *tags]

is_running

is_running() -> bool

Checks if the Watchdog service is currently running.

Returns:

Type Description
bool

True if the service is running, False otherwise

Source code in src/clabe/aind/watchdog.py
def is_running(self) -> bool:
    """
    Checks if the Watchdog service is currently running.

    Returns:
        True if the service is running, False otherwise
    """
    output = subprocess.check_output(
        ["tasklist", "/FI", f"IMAGENAME eq {self.executable_path.name}"], shell=True, encoding="utf-8"
    )
    processes = [line.split()[0] for line in output.splitlines()[2:]]
    return len(processes) > 0

force_restart

force_restart(kill_if_running: bool = True) -> Popen[bytes]

Attempts to restart the Watchdog application.

Parameters:

Name Type Description Default
kill_if_running bool

Whether to terminate the service if it's already running

True

Returns:

Type Description
Popen[bytes]

A subprocess.Popen object representing the restarted service

Source code in src/clabe/aind/watchdog.py
def force_restart(self, kill_if_running: bool = True) -> subprocess.Popen[bytes]:
    """
    Attempts to restart the Watchdog application.

    Args:
        kill_if_running: Whether to terminate the service if it's already running

    Returns:
        A subprocess.Popen object representing the restarted service
    """
    if kill_if_running is True:
        while self.is_running():
            subprocess.run(["taskkill", "/IM", self.executable_path.name, "/F"], shell=True, check=True)

    cmd_factory = f"{self.executable_path} -c {self.config_path}"

    return subprocess.Popen(cmd_factory, start_new_session=True, shell=True)

dump_manifest_config

dump_manifest_config(
    path: PathLike | None = None,
    make_dir: bool = True,
    manifest: ManifestConfig | None = None,
) -> Path

Dumps a manifest configuration to a YAML file.

Parameters:

Name Type Description Default
path PathLike | None

The file path to save the manifest

None
make_dir bool

Whether to create the directory if it doesn't exist

True
manifest ManifestConfig | None

The manifest to dump. Defaults to the last one built by transfer.

None

Returns:

Type Description
Path

The path to the saved manifest file

Raises:

Type Description
ValueError

If the manifest or watch configuration is not set

Source code in src/clabe/aind/watchdog.py
def dump_manifest_config(
    self, path: os.PathLike | None = None, make_dir: bool = True, manifest: ManifestConfig | None = None
) -> Path:
    """
    Dumps a manifest configuration to a YAML file.

    Args:
        path: The file path to save the manifest
        make_dir: Whether to create the directory if it doesn't exist
        manifest: The manifest to dump. Defaults to the last one built by `transfer`.

    Returns:
        The path to the saved manifest file

    Raises:
        ValueError: If the manifest or watch configuration is not set
    """
    manifest_config = manifest or self._manifest_config
    watch_config = self._watch_config

    if manifest_config is None or watch_config is None:
        raise ValueError("ManifestConfig or WatchConfig config is not set.")

    path = (Path(path) if path else Path(watch_config.flag_dir) / f"manifest_{manifest_config.name}.yaml").resolve()

    if path.suffix not in [".yml", ".yaml"]:
        path = path.with_suffix(".yaml")

    if not path.name.startswith("manifest_"):
        logger.debug("Prefix manifest_ not found in file name. Appending it.")
        path = path.with_name(f"manifest_{path.stem}{path.suffix}")

    if make_dir and not path.parent.exists():
        path.parent.mkdir(parents=True, exist_ok=True)

    manifest_config.destination = str(Path(manifest_config.destination))
    manifest_config.schemas = [str(Path(schema)) for schema in manifest_config.schemas]
    for modality in manifest_config.modalities:
        manifest_config.modalities[modality] = [str(Path(_path)) for _path in manifest_config.modalities[modality]]

    self._write_yaml(manifest_config, path)
    return path