Zum Inhalt

archivematica_parallel_ingest

Overview

The archivematica_parallel_ingest module submits zipped BagIt archives to Archivematica for ingest (transfer + processing into an AIP), tracking multiple articles' transfer and ingest status concurrently in batches. It submits a batch of N articles (default 4) to Archivematica, then polls all of their statuses in parallel rounds until every item in the batch reaches a terminal state (COMPLETE, FAILED, REJECTED, USER_INPUT, or UNKNOWN), before finalizing the batch and moving to the next one.

Because Archivematica ingest can take a long time and the flow itself might be interrupted mid-batch, this module also implements its own resumability logic: on each run, before adding an article to a new batch, it first checks whether a temp-archivematica_parallel_ingest_<date> folder from an earlier, incomplete run already exists for that article, and if so, either finalizes it (if the ingest actually completed since the last check) or resumes tracking it.

Module ordering: archivematica_parallel_ingest should run after create_bags, since it operates on the zipped bag file produced by that module.

The module contains two primary Python files:

  1. flow.py
  2. tasks.py

flow.py

This file defines the main flow for Archivematica batch ingest using the Prefect library, and uses prefect's get_run_logger (with log_prints=True) to log various stages along with the module context and previous module information. Articles are accumulated into a batch list per journal; once the batch is full (or the journal's articles are exhausted), the whole batch is submitted together and polled together.

archivematica_parallel_ingest()

  • Required Parameters:

  • name_of_config_file (str): Name of the configuration file. Default is "archivematica_parallel_ingest_test.json"

  • test_copy (bool): Flag to indicate a test run. Default is False
  • number_of_desired_parallel_ingests (int): Batch size. Default is 4
  • start_interval (int): Currently unused

  • Context for Use:

  • This function is the main entry point. For each journal, it scans article directories and calls tasks.add_article_directory_to_planned_ingest_list for each one, which decides whether the article should be newly queued, resumed from an incomplete prior run, or skipped. Once the batch reaches number_of_desired_parallel_ingests articles, it is submitted via tasks.ingest_files_in_processing_data_list_into_archivematica, polled to completion via tasks.check_if_transfer_and_ingest_of_all_files_from_processing_data_list_completed, and finalized via tasks.write_documentation_and_rename_temp_folders_after_ingests_complete. Any remaining partial batch at the end of a journal's articles is processed the same way. If the polling loop reports that not all articles finished (there is a 50-round cap in check_if_transfer_and_ingest_of_all_files_from_processing_data_list_completed), the flow raises RuntimeError and stops entirely.

  • Example Usage:

  • python archivematica_parallel_ingest('config.json', test_copy=False, number_of_desired_parallel_ingests=4)

  • Example Output:

  • INFO: Module name: archivematica_parallel_ingest INFO: Set base path to: /mnt/.../wdm-test INFO: Module context: [{'ISSN': '2948-2143', 'position': 6, 'previous_module': 'create_bags', ...}] INFO: Start ingests for ISSN: 2948-2143. INFO: Check new article directory to see if it should be ingested: /mnt/.../s42467-023-00015-y INFO: No temp folder present. Article .../create_bags_2025-01-17 will be processed for the first time. Added to list_of_directories_to_be_ingested. INFO: Processing data before ingest: [...] INFO: Started ingest of /mnt/.../temp-archivematica_parallel_ingest_2025-01-17 INFO: Starting round 1 of transfer/ingest checking, current state of data: [...] INFO: /mnt/.../temp-archivematica_parallel_ingest_2025-01-17 transferred in less than 12.3 s INFO: /mnt/.../temp-archivematica_parallel_ingest_2025-01-17 ingested in less than 340.1 s total, 327.8 s since transfer end was detected

    If the ingest doesn't complete within the polling cap:
    
    WARNING: Not all files could be ingested correctly. Script is stopped (raises RuntimeError)

tasks.py

This file contains the task definitions used in the Archivematica batch ingest flow. It handles submitting transfer packages to the Archivematica v2beta API, polling transfer and ingest status, resuming interrupted runs, and finalizing completed batches with documentation and folder renaming.

add_article_directory_to_planned_ingest_list()

  • Required Parameters:

  • item (os.DirEntry): A directory entry representing an article folder

  • module_name (str): Name of the current module
  • previous_module (str): Name of the previous module
  • list_of_directories_to_be_ingested (list): The batch list to append to (mutated in place)

  • Context for Use:

  • Decides whether the given article should be added to the current ingest batch. If the previous module hasn't been updated, returns "continue" (skip this article). If a temp-archivematica_parallel_ingest_<date> folder already exists from an earlier, incomplete run, it is inspected via check_if_archivematica_temp_folder_was_ingested_already: if that ingest had completed since the last check, this function finalizes it immediately (writes documentation, renames folders) and returns "continue"; if it's still incomplete and the previous module hasn't been marked processed yet, the stale temp folder is deleted and the article is re-queued (returns True); if the previous module was already marked processed despite an incomplete temp folder existing, this is treated as an inconsistent state and raises RuntimeError. If no temp folder exists at all, the article is queued for the first time (returns True).

  • Example Usage:

  • python result = add_article_directory_to_planned_ingest_list( item, 'archivematica_parallel_ingest', 'create_bags', list_of_directories_to_be_ingested )

  • Example Output:

  • Return value: True, "continue", or raises RuntimeError in the inconsistent-state case.

ingest_transfer_package()

  • Required Parameters:

  • module_dir_path (pathlib.Path): The article's temp module directory containing the zipped bag

  • Context for Use:

  • This is a Prefect @task that copies the zipped bag to the Archivematica storage-service NAS path, then submits a transfer request to the Archivematica v2beta /api/v2beta/package endpoint (path base64-encoded per the API's requirements). Retries up to 4 times with increasing backoff (5*i seconds) if the API doesn't respond with HTTP 202. Returns the transfer UUID on success, or None if all retries are exhausted.

ingest_files_in_processing_data_list_into_archivematica()

  • Required Parameters:

  • processing_data (list): Data points prepared by prepare_list_of_data_points_to_track_transfer_and_ingest_status

  • Context for Use:

  • Iterates the batch and calls ingest_transfer_package for each data point, recording the returned transfer ID and start time. Articles for which no transfer ID was obtained are logged and skipped. After each successful submission, the current processing state is written to the article's status file via write_archivematica_processing_steps_to_file.

check_if_transfer_and_ingest_of_all_files_from_processing_data_list_completed()

  • Required Parameters:

  • processing_data (list): The batch's data points, updated in place as polling progresses

  • Context for Use:

  • Polls the Archivematica API in rounds (sleeping 20 seconds between rounds, capped at 50 rounds) until every data point in the batch has both transfer_finished and ingest_finished set to True. A transfer/ingest is considered "finished" (for polling purposes) once it reaches any of FAILED, REJECTED, USER_INPUT, or COMPLETE — not just COMPLETE (so a failed or stalled-on-user-input item does not block the rest of the batch from being recognized as "checked.") Returns True if every item finished within the round cap, False if the cap (50 rounds) was reached with items still pending.

write_documentation_and_rename_temp_folders_after_ingests_complete()

  • Required Parameters:

  • processing_data (list): The batch's data points, each expected to have a final ingest_status

  • module_name (str): Name of the current module

  • Context for Use:

  • For each data point whose ingest_status is exactly "COMPLETE", this writes a resumption-archivematica_parallel_ingest.csv harvesting log entry (mapping the article to its AIP name), writes a history.csv entry, finalizes the module folder (rename, clear previous module contents, mark processed), and removes the transfer from the Archivematica dashboard via hide_transfer. For data points whose ingest did not complete (FAILED, USER_INPUT, PROCESSING, UNKNOWN), the temp folder is deliberately left in place so the ingest can be retried or investigated on the next run.


The lower-level helper functions in tasks.py are listed below.

check_transfer_success() / check_ingest_success()

  • Required Parameters:

  • transfer_id / sip_id (str): The UUID to query

  • Context for Use:

  • Query the Archivematica API's transfer/ingest status endpoints respectively. Both return a (status, response_json) tuple where status is one of 'FAILED', 'REJECTED', 'USER_INPUT', 'COMPLETE', 'PROCESSING', or False (a non-status API failure, e.g. no response or an HTTP 400). Despite the "success" in their names, both functions return the raw status string on non-success outcomes too (the actual pass/fail interpretation is left to the calling code).

check_if_archivematica_temp_folder_was_ingested_already()

  • Required Parameters:

  • temp_archivematica_module_dir_path: Path to a pre-existing temp folder from an earlier, possibly-interrupted run

  • Context for Use:

  • Reads the article's Archivematica processing-status JSON file. If it already records ingest_status: "COMPLETE", returns "COMPLETE" immediately. If there's no sip_id recorded yet (the transfer never got far enough to produce one), returns False. Otherwise, it actively queries the Archivematica API via check_ingest_success to check whether the ingest completed since the status file was last written — if so, it updates the local status file and returns "COMPLETE"; if not, returns False.

get_auth_header() / get_archivematica_base_url() / get_storage_location_uuid() / get_config_json()

  • Context for Use:

  • Read Archivematica connection details (ARCHIVEMATICA_USERNAME, ARCHIVEMATICA_API_KEY, ARCHIVEMATICA_BASE_URL, ARCHIVEMATICA_STORAGE_LOCATION_UUID) from the shared harvesting config JSON. get_auth_header() formats the username/API key into Archivematica's ApiKey <username>:<key> auth header format.

hide_transfer()

  • Required Parameters:

  • transfer_id (str): The transfer UUID to remove from the dashboard

  • Context for Use:

  • A Prefect @task that issues a DELETE request to remove a completed transfer from the Archivematica dashboard's transfer list.

prepare_list_of_data_points_to_track_transfer_and_ingest_status()

  • Required Parameters:

  • list_of_directories_to_be_ingested (list): The batch of previous-module directories to prepare

  • module_name (str): Name of the current module
  • processing_data (list): The output list to populate (mutated in place)

  • Context for Use:

  • For each article in the batch, creates the temp-archivematica_parallel_ingest_<date> folder (via copy_content_from_previous_module) and builds an initial tracking dict (transfer_id, transfer_finished, ingest_finished, sip_id, timing fields, all initialized to None/False), which is then written to the article's status file and appended to processing_data.

write_archivematica_processing_steps_to_file() / read_data_from_archivematica_status_processing_file_to_dictionary()

  • Required Parameters:

  • data_point / module_dir_path / path_to_archivematica_processing_status_file

  • Context for Use:

  • Serialize/deserialize a data point dict to/from the article's local JSON status file (constants.ARCHIVEMATICA_PROCESSING_STATUS_FILE), converting pathlib.Path objects to strings and Unix timestamps to formatted date strings (and back) since JSON can't natively represent either. This status file is what makes the module's resumability possible across interrupted runs.

remove_transfer_uuid_file() / remove_bag_archivematica_test() / write_transfer_id_to_file() / create_transfer_status_file()

  • Context for Use:

  • Small Prefect @task helpers for managing auxiliary per-article files: writing/removing the transfer UUID file, removing a test-copied bag from the Archivematica storage-service NAS path, and writing the initial transfer status file.

_log_archivematica_response_debug()

  • Required Parameters:

  • logger, api_call_description (str), response (optional), error_message (optional)

  • Context for Use:

  • A shared debug-logging helper used throughout the module's API-calling functions. Logs the full request/response details (status code, reason, URL, and response body — parsed as JSON if possible, otherwise raw text) at DEBUG level, or a fatal-error message when no response was returned at all.