413 lines
14 KiB
Python
413 lines
14 KiB
Python
import json
|
|
import logging
|
|
import os
|
|
import shutil
|
|
from pathlib import Path
|
|
|
|
import fsspec
|
|
from datalad_core.runners import (
|
|
CommandError,
|
|
call_git_oneline,
|
|
)
|
|
from pydantic import ValidationError
|
|
|
|
from dump_things_service import Format
|
|
from dump_things_service.abstract_config import (
|
|
ConfigAuthSpec,
|
|
Configuration,
|
|
ForgejoAuthSpec,
|
|
PolicyInfo,
|
|
PolicyMapping,
|
|
RecordDirBackendConfig,
|
|
SQLiteBackendConfig,
|
|
)
|
|
from dump_things_service.audit.gitaudit import GitAuditBackend
|
|
from dump_things_service.auth.config import ConfigAuthenticationSource
|
|
from dump_things_service.auth.forgejo import ForgejoAuthenticationSource
|
|
from dump_things_service.backends.record_dir_index import index_file_name
|
|
from dump_things_service.converter import FormatConverter
|
|
from dump_things_service.exceptions import (
|
|
ConfigCollisionError,
|
|
ConfigError,
|
|
)
|
|
from dump_things_service.instance_state import (
|
|
InstanceState,
|
|
InstanceStateCollectionInfo,
|
|
get_record_dir_config,
|
|
get_schema_info,
|
|
record_dir_config_file_name,
|
|
)
|
|
from dump_things_service.utils import create_store
|
|
|
|
logger = logging.getLogger('dump_things_service')
|
|
|
|
|
|
def create_collection(
|
|
instance_state: InstanceState,
|
|
configuration: Configuration,
|
|
collection_name: str,
|
|
):
|
|
"""Create a collection instance as specified by `collection_configuration`
|
|
|
|
Reuse existing disk structures, if they are compatible. If they are not
|
|
compatible, raise an error.
|
|
|
|
:param instance_state:
|
|
:param configuration:
|
|
:param collection_name:
|
|
:return:
|
|
"""
|
|
|
|
collection_configuration = configuration.collections[collection_name]
|
|
curated_path = Path(instance_state.store_path / collection_configuration.curated)
|
|
incoming_path = (
|
|
None
|
|
if collection_configuration.incoming is None
|
|
else Path(instance_state.store_path / collection_configuration.incoming)
|
|
)
|
|
|
|
# Check for compatibility of all existing stores before creating any
|
|
# structures on disk.
|
|
if curated_path.exists():
|
|
check_store_compatibility(
|
|
curated_path,
|
|
collection_configuration.backend,
|
|
collection_configuration.schema_location,
|
|
)
|
|
|
|
for audit_backend in collection_configuration.audit_backends:
|
|
audit_path = Path(instance_state.store_path / audit_backend.path)
|
|
if audit_path.exists():
|
|
check_git_audit_compatibility(audit_path)
|
|
|
|
# We know now that all existing structures are compatible with the
|
|
# collection specification. We record what we create in order to delete
|
|
# it in case of an error.
|
|
created_directories = []
|
|
try:
|
|
if not curated_path.exists():
|
|
curated_path.mkdir(parents=True)
|
|
created_directories.append(curated_path)
|
|
|
|
if incoming_path and not incoming_path.exists():
|
|
incoming_path.mkdir(parents=True)
|
|
created_directories.append(incoming_path)
|
|
|
|
for audit_backend in collection_configuration.audit_backends:
|
|
audit_path = Path(instance_state.store_path / audit_backend.path)
|
|
if not audit_path.exists():
|
|
audit_path.mkdir(parents=True)
|
|
created_directories.append(audit_path)
|
|
|
|
except ConfigError:
|
|
# Delete all directories that were created in this
|
|
for directory in created_directories:
|
|
shutil.rmtree(directory)
|
|
raise
|
|
|
|
# Create the curated store
|
|
curated_store = create_store(
|
|
abstract_configuration=configuration,
|
|
instance_state=instance_state,
|
|
collection_name=collection_name,
|
|
)
|
|
|
|
instance_state.curated_stores[collection_name] = curated_store
|
|
|
|
# Incoming stores are created on demand when a token is authenticated
|
|
instance_state.incoming_stores[collection_name] = {}
|
|
|
|
# Create the schema modules, schema view, and conversion objects
|
|
schema_location = collection_configuration.schema_location
|
|
instance_state.schema_info[schema_location] = get_schema_info(schema_location)
|
|
|
|
# Determine the active classes based on the classes defined in the schema
|
|
# and the configuration of the collection
|
|
active_classes = set(instance_state.schema_info[schema_location].classes)
|
|
if collection_configuration.use_classes:
|
|
active_classes &= set(collection_configuration.use_classes)
|
|
if collection_configuration.ignore_classes:
|
|
active_classes -= set(collection_configuration.ignore_classes)
|
|
|
|
# If external policy information is specified, load it, otherwise use
|
|
# the policy information from the collection configuration.
|
|
if collection_configuration.policy_info_location:
|
|
default_policy, policy_mapping, policy_annotation_tag = load_policy_info(
|
|
configuration,
|
|
collection_name,
|
|
)
|
|
# If there is a local configuration, issue a warning
|
|
if (
|
|
collection_configuration.default_policy
|
|
or collection_configuration.policy_mapping
|
|
or collection_configuration.policy_annotation_tag
|
|
):
|
|
logger.warning(
|
|
"Collection '%s' specifies policy information in its "
|
|
'configuration (via `policy_annotation_tag`, `default_policy`, '
|
|
'and `policy_mapping`) as well as in an external source (via '
|
|
'`policy_info_location`). The policy information specified in '
|
|
'the configuration will be ignored and the externally sourced '
|
|
'policy information will be used.',
|
|
collection_name,
|
|
)
|
|
else:
|
|
default_policy = collection_configuration.default_policy
|
|
policy_mapping = collection_configuration.policy_mapping
|
|
policy_annotation_tag = collection_configuration.policy_annotation_tag
|
|
|
|
if not policy_annotation_tag and (default_policy or policy_mapping):
|
|
logger.warning(
|
|
"Collection '%s' specifies policy information in its configuration "
|
|
'(via `default_policy` and/or `policy_mapping`) but does not specify '
|
|
'a `policy_annotation_tag`. The policy information will be ignored '
|
|
'and no policy enforcement will be performed.',
|
|
collection_name,
|
|
)
|
|
|
|
instance_state.collections[collection_name] = InstanceStateCollectionInfo(
|
|
active_classes=active_classes,
|
|
tag_info={},
|
|
default_policy=default_policy,
|
|
policy_mapping=policy_mapping,
|
|
policy_annotation_tag=policy_annotation_tag,
|
|
)
|
|
|
|
# Create a validator for the collection
|
|
instance_state.validators[collection_name] = FormatConverter(
|
|
schema=collection_configuration.schema_location,
|
|
input_format=Format.json,
|
|
output_format=Format.ttl,
|
|
)
|
|
|
|
# Create the authentication sources
|
|
for authentication_spec in collection_configuration.auth_sources:
|
|
create_authentication_source(
|
|
configuration,
|
|
collection_name,
|
|
authentication_spec,
|
|
instance_state,
|
|
)
|
|
|
|
# Create the audit-backends
|
|
instance_state.audit_backends[collection_name] = []
|
|
for audit_backend_config in collection_configuration.audit_backends:
|
|
instance_state.audit_backends[collection_name].append(
|
|
GitAuditBackend(
|
|
path=Path(instance_state.store_path / audit_backend_config.path),
|
|
auto_flush_timeout=audit_backend_config.auto_flush_timeout,
|
|
),
|
|
)
|
|
|
|
|
|
def create_authentication_source(
|
|
abstract_configuration: Configuration,
|
|
collection_name: str,
|
|
authentication_spec: ConfigAuthSpec | ForgejoAuthSpec,
|
|
instance_state: InstanceState,
|
|
):
|
|
if collection_name not in instance_state.auth_sources:
|
|
instance_state.auth_sources[collection_name] = []
|
|
|
|
auth_sources = instance_state.auth_sources[collection_name]
|
|
if isinstance(authentication_spec, ConfigAuthSpec):
|
|
auth_source = ConfigAuthenticationSource(
|
|
abstract_configuration=abstract_configuration,
|
|
collection_name=collection_name,
|
|
)
|
|
elif isinstance(authentication_spec, ForgejoAuthSpec):
|
|
auth_source = ForgejoAuthenticationSource(
|
|
source_identifier=f'forgejo_{authentication_spec.instance_id}',
|
|
api_url=authentication_spec.url,
|
|
organization=authentication_spec.organization,
|
|
team=authentication_spec.team,
|
|
label_type=authentication_spec.label_type,
|
|
instance_id=authentication_spec.instance_id,
|
|
repository=authentication_spec.repository,
|
|
)
|
|
else:
|
|
msg = f"Unsupported authentication config type: '{type(authentication_spec)}'"
|
|
raise ConfigError(msg)
|
|
|
|
auth_sources.append(auth_source)
|
|
|
|
|
|
def write_record_dir_config(
|
|
path: Path,
|
|
backend_config: RecordDirBackendConfig,
|
|
schema: str,
|
|
):
|
|
if not isinstance(backend_config, RecordDirBackendConfig):
|
|
msg = 'backend_config is not an instance of RecordDirBackendConfig'
|
|
raise TypeError(msg)
|
|
|
|
record_dir_config_file_path = path / record_dir_config_file_name
|
|
if not record_dir_config_file_path.exists():
|
|
record_dir_config_file_path.write_text(
|
|
f"""# RecordDir Config
|
|
type: records
|
|
version: 1
|
|
schema: {schema}
|
|
format: yaml
|
|
idfx: {backend_config.mapping_method}
|
|
""",
|
|
)
|
|
|
|
|
|
def check_store_compatibility(
|
|
store_path: Path,
|
|
backend_config: RecordDirBackendConfig | SQLiteBackendConfig,
|
|
schema: str,
|
|
):
|
|
"""Check if an existing store is compatible with the specs in `backend_config`
|
|
|
|
:param store_path:
|
|
:param backend_config:
|
|
:param schema:
|
|
:return:
|
|
"""
|
|
if not store_path.exists():
|
|
return
|
|
if isinstance(backend_config, RecordDirBackendConfig):
|
|
check_record_dir_compatibility(store_path, backend_config, schema)
|
|
elif isinstance(backend_config, SQLiteBackendConfig):
|
|
check_sqlite_compatibility(store_path)
|
|
else:
|
|
msg = f"Unsupported backend config type: '{type(backend_config)}'"
|
|
raise ConfigError(msg)
|
|
return
|
|
|
|
|
|
def check_record_dir_compatibility(
|
|
store_path: Path,
|
|
backend_config: RecordDirBackendConfig,
|
|
schema: str,
|
|
):
|
|
# Non-existing or empty record_dir-directories are compatible
|
|
if not store_path.exists():
|
|
return
|
|
|
|
# A record_dir-directory is considered to be empty, if it contains no
|
|
# files or only an record_dir-index file
|
|
files_in_dir = tuple(dir_entry.name for dir_entry in os.scandir(store_path))
|
|
if files_in_dir in ((), (index_file_name,)):
|
|
return
|
|
|
|
record_dir_config = get_record_dir_config(store_path)
|
|
if record_dir_config.schema_location != schema:
|
|
msg = f"Existing backend uses a different schema: '{record_dir_config.schema_location}'"
|
|
raise ConfigCollisionError(msg)
|
|
|
|
stored_mapping_method = record_dir_config.idfx.value
|
|
if stored_mapping_method != backend_config.mapping_method:
|
|
msg = f"Configuration specifies mapping method '{backend_config.mapping_method}', existing backend uses mapping method: '{stored_mapping_method}'"
|
|
raise ConfigCollisionError(msg)
|
|
return
|
|
|
|
|
|
def check_sqlite_compatibility(
|
|
store_path: Path,
|
|
):
|
|
if not store_path.exists():
|
|
return
|
|
return
|
|
|
|
|
|
def check_git_audit_compatibility(
|
|
audit_path: Path,
|
|
):
|
|
"""Check if an existing audit path is compatible with a git audit store
|
|
|
|
:param audit_path:
|
|
:return:
|
|
"""
|
|
|
|
# Non-existing or empty directories are valid gitaudit-locations
|
|
if not audit_path.exists():
|
|
return
|
|
if not tuple(os.scandir(audit_path)):
|
|
return
|
|
|
|
# A non-empty directory should contain bare git repository
|
|
try:
|
|
result = call_git_oneline(
|
|
['rev-parse', '--is-bare-repository'],
|
|
cwd=audit_path,
|
|
force_c_locale=True,
|
|
)
|
|
except CommandError as ce:
|
|
msg = f'No git repository in gitaudit-path: {audit_path}'
|
|
raise ConfigError(msg) from ce
|
|
if result.strip().lower() != 'true':
|
|
msg = f'No bare git repository in gitaudit-path: {audit_path}'
|
|
raise ConfigError(msg)
|
|
return
|
|
|
|
|
|
def load_policy_info(
|
|
abstract_configuration: Configuration,
|
|
collection_name: str,
|
|
override_policy_info_location: str | None = None,
|
|
) -> tuple[str | None, list[PolicyMapping], str | None]:
|
|
policy_info_location = (
|
|
override_policy_info_location
|
|
or abstract_configuration.collections[collection_name].policy_info_location
|
|
)
|
|
|
|
if not policy_info_location:
|
|
return None, [], None
|
|
|
|
try:
|
|
with fsspec.open(policy_info_location) as source:
|
|
policy_info_json = json.load(source)
|
|
except Exception as e:
|
|
msg = f"Failed to load policy info from '{policy_info_location}': {e}"
|
|
raise ConfigError(msg) from e
|
|
|
|
try:
|
|
policy_info = PolicyInfo(**policy_info_json)
|
|
except ValidationError as e:
|
|
msg = f"Failed to load policy info from '{policy_info_location}': {e}"
|
|
raise ConfigError(msg) from e
|
|
|
|
return (
|
|
policy_info.default_policy,
|
|
policy_info.policy_mapping,
|
|
policy_info.policy_annotation_tag,
|
|
)
|
|
|
|
|
|
def reload_policy(
|
|
abstract_configuration: Configuration,
|
|
instance_state: InstanceState,
|
|
collection_name: str,
|
|
override_policy_info_location: str | None = None,
|
|
):
|
|
default_policy, policy_mapping, policy_annotation_tag = load_policy_info(
|
|
abstract_configuration,
|
|
collection_name,
|
|
override_policy_info_location,
|
|
)
|
|
instance_state.collections[collection_name].default_policy = default_policy
|
|
instance_state.collections[collection_name].policy_mapping = policy_mapping
|
|
instance_state.collections[
|
|
collection_name
|
|
].policy_annotation_tag = policy_annotation_tag
|
|
|
|
|
|
def check_recoverable_errors(
|
|
abstract_configuration: Configuration,
|
|
instance_state: InstanceState,
|
|
):
|
|
from dump_things_service.abstract_config import g_recoverable_error
|
|
from dump_things_service.manifest import manifest_configuration
|
|
|
|
if g_recoverable_error:
|
|
try:
|
|
manifest_configuration(
|
|
instance_state=instance_state,
|
|
configuration=abstract_configuration,
|
|
)
|
|
except Exception as e: # noqa: BLE001 -- we don't know which errors might occur during recovery, so we catch all exceptions
|
|
logger.info(f'Error recovery failed: {e}')
|
|
return (abstract_configuration, instance_state), {}
|