diff --git a/README.md b/README.md index 2c93bc9..59ec1d4 100644 --- a/README.md +++ b/README.md @@ -4,10 +4,10 @@ Holds views and test data to fire up a dev instance of StatusDB (CouchDB). This The [databases](/DATABASES.md) documentation attempts to give an overview of each database and explain its purpose. # Views -The first part of this repository is the code for the CouchDB views used for the NGI Stockholm StatusDB. The views are organised in the directory StatusDB_views and listed in the views_config.yaml. +The first part of this repository is the code for the CouchDB views used for the NGI Stockholm StatusDB. The views are organised in the `StatusDB_views` directory and listed in `views_config.yaml`. ## History -StatusDB_views was kept private since it could contain some project details or other details that was not supposed to be public. However this decision was changed in 2026 since there is no real reason to keep sensitive information in this repository. The content of the repository was moved to StatusDB_NGI since the git history might still hide details which are not supposed to be made public. Here are the contributors of the old repository: +StatusDB_views was kept private since it could contain some project details or other details that were not supposed to be public. This decision was changed in 2026, since there is no real reason to keep sensitive information in this repository. The content was moved to StatusDB_NGI without its git history, which might still contain details that were not supposed to be public. Here are the contributors of the old repository: ## Contributors of historic StatusDB_Views repository - @aanil @@ -35,21 +35,21 @@ They need to follow the naming pattern `.map.js` and `.red Each database, design document and view is listed in the config file `views_config.yaml`. -## Checking and updating the views_config.yaml -To try to keep the views_config.yaml file up to date with the content of the repository, the script script/validate_views_config.py can be used: +## Checking and updating views_config.yaml +To check that `views_config.yaml` is in sync with the repository content, use `scripts/validate_views_config.py`: ``` -> python scripts/validate_views_config.py --config views_config.yaml --views-dir StatusDB_views --check +> python3 scripts/validate_views_config.py --config views_config.yaml --views-dir StatusDB_views --check ✅ Config is up to date with directory structure ``` -And to update the config (default is that a new view will not be included in dev): +To update the config from the directory structure (new views default to `scenarios: [stage]`): ``` -> python scripts/validate_views_config.py --config views_config.yaml --views-dir StatusDB_views --update +> python3 scripts/validate_views_config.py --config views_config.yaml --views-dir StatusDB_views --update ``` # Seed Data -The second part of this repository is the seed data, which is mock data that can be used for testing and demoing a range of internal services that use StatusDB as its backend. The data is located in the seed_data directory and is used to populate the database when building the docker image. +The second part of this repository is the seed data, which is mock data for testing and demoing the internal services that use StatusDB as their backend. The data lives in the `seed_data` directory, is copied into the Docker image, and is loaded into CouchDB on first startup. ## Seed Data Structure @@ -64,39 +64,42 @@ seed_data/ └── doc2.json ``` +JSON files placed directly in `seed_data/` (legacy layout) are loaded into a `statusdb` database. + ### Document Format Each JSON file should contain a single CouchDB document. If the document has an `_id` field, it will be used as the document ID. Otherwise, CouchDB will auto-generate an ID. -Example document (`seed_data/example_project.json`): +Example document (abridged from `seed_data/projects/P12345.json`): ```json { - "_id": "project_001", - "type": "project", - "name": "Example Genomics Project", + "_id": "P12345", "project_id": "P12345", + "project_name": "Test RNA-seq Project", + "application": "RNA-seq", + "status": "ongoing", ... } ``` # Docker Image -The docker image is most commonly used in the docker-compose setup for genomics status, see [Using with Genomics Status](#using-with-genomics-status) In that case, the docker is built automatically as part of the setup. However, in case the docker image should be used standalone, it needs to be built using: +The Docker image is most commonly used in the docker-compose setup for genomics-status (see [Using with Genomics Status](#using-with-genomics-status)), where it is built automatically as part of the setup. To use the image standalone, build it with: ``` -cd Statusdb_NGI -docker build . +cd StatusDB_NGI +docker build -t statusdb_ngi . ``` -And starting a container using +and start a container with ```bash docker run -d \ -p 5984:5984 \ -e COUCHDB_USER=admin \ -e COUCHDB_PASSWORD=admin \ - ghcr.io/scilifelab/StatusDB_NGI:latest + statusdb_ngi ``` After this, CouchDB will be available at: @@ -105,7 +108,17 @@ After this, CouchDB will be available at: - Fauxton UI: - Credentials: `admin` / `admin` -The seed data is automatically loaded on first startup along with all views in the Statusdb_Views directory. It's prepared to use different scenarios where only a subset of views and data could be loaded, but currently there is only one `stage` scenario where all views and data is loaded. +On first startup, the seed data and the design documents from `StatusDB_views` are loaded into CouchDB. What is loaded is controlled by *scenarios*, selected with the `SCENARIO` environment variable (default: `stage`). + +A scenario decides which databases and views are created: + +- A database can list the scenarios it belongs to with a `scenarios` key in `views_config.yaml`. A database without a `scenarios` key is included in all scenarios. +- Inside an included database, a view is only deployed if the scenario is also in the view's own `scenarios` list. +- Seed data follows the database: if a database is not included in the scenario, the database is not created and its seed documents are not loaded. + +Initialization is tracked per scenario, so it only runs on the first startup for a given scenario. Changing `SCENARIO` triggers a new initialization on the next startup; loading is idempotent, so documents that already exist are overwritten. + +Currently the only scenario in use is `stage`, where all databases, views and seed data are loaded. ### Persisting Data @@ -129,8 +142,8 @@ docker run -p 5984:5984 -e COUCHDB_USER=admin -e COUCHDB_PASSWORD=admin StatusDB ``` ## Container registry -There is a github workflow file written to facilitate automatic build and publishing of the seed data container, but it is not yet in use. +A GitHub workflow (`.github/workflows/docker-publish.yml`) for building and publishing the image to ghcr.io is in place, but the publish job is currently disabled. ## Using with Genomics Status -The [genomics-status](https://github.com/SciLifeLab/genomics-status) repository is configured to use this image in its docker compose setup. When starting docker compose, it will automatically build the image and populate it with the seed data, using the stage scenario. +The [genomics-status](https://github.com/SciLifeLab/genomics-status) repository is configured to use this image in its docker compose setup. When starting docker compose, the image is built automatically and the seed data is loaded on startup, using the `stage` scenario. diff --git a/scripts/init-seed-data.sh b/scripts/init-seed-data.sh index f0821fd..985dda5 100644 --- a/scripts/init-seed-data.sh +++ b/scripts/init-seed-data.sh @@ -8,13 +8,17 @@ COUCHDB_USER="${COUCHDB_USER:-admin}" COUCHDB_PASSWORD="${COUCHDB_PASSWORD:-admin}" SEED_DIR="${SEED_DIR:-/opt/couchdb/seed_data}" DESIGN_DOCS_DIR="${DESIGN_DOCS_DIR:-/opt/couchdb/design_docs_build}" -INIT_MARKER="/opt/couchdb/data/.seed_initialized" +# Marker file recording which scenario has been initialized (its content is the scenario name) +INIT_MARKER="${INIT_MARKER:-/opt/couchdb/data/.seed_initialized}" SCENARIO="${SCENARIO:-stage}" VIEWS_CONFIG="${VIEWS_CONFIG:-/opt/couchdb/views_config.yaml}" VIEWS_DIR="${VIEWS_DIR:-/opt/couchdb/StatusDB_views}" COUCHDB_URL="http://${COUCHDB_USER}:${COUCHDB_PASSWORD}@${COUCHDB_HOST}:${COUCHDB_PORT}" +# Databases created for the current scenario (one per line) +CREATED_DATABASES="" + # Wait for CouchDB to be ready wait_for_couchdb() { echo "Waiting for CouchDB to be ready..." @@ -47,38 +51,144 @@ create_system_databases() { create_database() { local db_name="$1" echo "Creating database: ${db_name}" - local response=$(curl -s -w "\n%{http_code}" -X PUT "${COUCHDB_URL}/${db_name}") - local http_code=$(echo "$response" | tail -n1) + local response http_code body + response=$(curl -s -w $'\n%{http_code}' -X PUT "${COUCHDB_URL}/${db_name}") || { + echo "ERROR: Could not reach CouchDB while creating '${db_name}'" >&2 + return 1 + } + http_code="${response##*$'\n'}" + body="${response%$'\n'*}" if [ "$http_code" = "201" ]; then echo " Database '${db_name}' created successfully" elif [ "$http_code" = "412" ]; then echo " Database '${db_name}' already exists" else - echo " Warning: Unexpected response creating '${db_name}': $http_code" + echo "ERROR: Unexpected response creating '${db_name}': ${http_code} ${body}" >&2 + return 1 fi } -# Load a single JSON document into a database +# Perform a CouchDB request, storing the HTTP status in HTTP_CODE and the +# response body in HTTP_BODY. Returns non-zero on transport errors. +couch_request() { + local method="$1" + local url="$2" + local data_file="$3" + local response + + response=$(curl -s -w $'\n%{http_code}' -X "$method" "$url" \ + -H "Content-Type: application/json" \ + -d @"$data_file") || return 1 + + HTTP_CODE="${response##*$'\n'}" + HTTP_BODY="${response%$'\n'*}" +} + +# Load a single JSON document into a database. +# Returns non-zero if the document could not be loaded, so that +# initialization is never marked as complete on partial failure. load_document() { local db_name="$1" local json_file="$2" - - local doc_id=$(jq -r '._id // empty' "$json_file" 2>/dev/null) + local doc_id rev tmp_payload + doc_id=$(jq -r '._id // empty' "$json_file" 2>/dev/null) || doc_id="" if [ -n "$doc_id" ]; then - # Document has an _id, use PUT + # Document has an _id, use PUT (upsert if it already exists) echo " Loading document '${doc_id}' into '${db_name}'..." - curl -s -X PUT "${COUCHDB_URL}/${db_name}/${doc_id}" \ - -H "Content-Type: application/json" \ - -d @"$json_file" > /dev/null + local url="${COUCHDB_URL}/${db_name}/${doc_id}" + + if ! couch_request PUT "$url" "$json_file"; then + echo "ERROR: Could not reach CouchDB while loading '${doc_id}' into '${db_name}'" >&2 + return 1 + fi + + if [ "$HTTP_CODE" = "409" ]; then + # Document already exists: fetch its current revision and overwrite it + rev=$(curl -s "$url" | jq -r '._rev // empty') + if [ -z "$rev" ]; then + echo "ERROR: Document '${doc_id}' exists in '${db_name}' but its revision could not be retrieved" >&2 + return 1 + fi + tmp_payload=$(mktemp) + if ! jq --arg rev "$rev" '._rev = $rev' "$json_file" > "$tmp_payload"; then + rm -f "$tmp_payload" + echo "ERROR: Could not update revision of '${doc_id}': invalid JSON in '$json_file'" >&2 + return 1 + fi + if ! couch_request PUT "$url" "$tmp_payload"; then + rm -f "$tmp_payload" + echo "ERROR: Could not reach CouchDB while updating '${doc_id}' in '${db_name}'" >&2 + return 1 + fi + rm -f "$tmp_payload" + fi + + if [ "$HTTP_CODE" != "201" ]; then + echo "ERROR: Failed to load document '${doc_id}' into '${db_name}': ${HTTP_CODE} ${HTTP_BODY}" >&2 + return 1 + fi else # No _id, use POST to auto-generate echo " Loading document from '$(basename "$json_file")' into '${db_name}'..." - curl -s -X POST "${COUCHDB_URL}/${db_name}" \ - -H "Content-Type: application/json" \ - -d @"$json_file" > /dev/null + if ! couch_request POST "${COUCHDB_URL}/${db_name}" "$json_file"; then + echo "ERROR: Could not reach CouchDB while loading '$(basename "$json_file")' into '${db_name}'" >&2 + return 1 + fi + if [ "$HTTP_CODE" != "201" ]; then + echo "ERROR: Failed to load document from '$(basename "$json_file")' into '${db_name}': ${HTTP_CODE} ${HTTP_BODY}" >&2 + return 1 + fi + fi +} + +# Compute the databases to create for this scenario: +# every database that belongs to the scenario according to views_config.yaml +# (both seed data databases and databases with design documents), plus the +# legacy 'statusdb' if top-level JSON files exist. +databases_to_create() { + local allowed_dbs db_dir json_file + + # --list-databases returns all databases included in the scenario, so no + # design docs need to be built before the databases can be created + if allowed_dbs=$(python3 /opt/couchdb/scripts/validate_views_config.py \ + --list-databases \ + --scenario "$SCENARIO" \ + --config "$VIEWS_CONFIG" \ + --seed-dir "$SEED_DIR" 2>/dev/null); then + echo "$allowed_dbs" + else + echo "WARNING: Could not determine databases for scenario '${SCENARIO}', including all seed data databases" >&2 + for db_dir in "$SEED_DIR"/*/; do + [ -d "$db_dir" ] && basename "$db_dir" + done + fi + + # Legacy top-level JSON files are loaded into a 'statusdb' database + for json_file in "$SEED_DIR"/*.json; do + if [ -f "$json_file" ]; then + echo "statusdb" + break + fi + done +} + +# Create all databases belonging to this scenario (seed data and design doc databases) +create_databases() { + echo "Creating databases for scenario: ${SCENARIO}..." + CREATED_DATABASES=$(databases_to_create | sort -u) + + if [ -z "$CREATED_DATABASES" ]; then + echo "No databases to create for scenario '${SCENARIO}'" + return 0 fi + + echo "Databases to create: $(echo "$CREATED_DATABASES" | tr '\n' ' ')" + local db_name + while IFS= read -r db_name; do + create_database "$db_name" + done <<< "$CREATED_DATABASES" } # Load all seed data @@ -96,8 +206,11 @@ load_seed_data() { for db_dir in "$SEED_DIR"/*/; do if [ -d "$db_dir" ]; then local db_name=$(basename "$db_dir") + if ! grep -qxF "$db_name" <<< "$CREATED_DATABASES"; then + echo "Skipping database: ${db_name} (not created for scenario '${SCENARIO}')" + continue + fi echo "Processing database: ${db_name}" - create_database "$db_name" # Load all JSON files in the database directory for json_file in "$db_dir"/*.json; do @@ -109,14 +222,8 @@ load_seed_data() { done # Also load any top-level JSON files into a 'statusdb' database (legacy support) - echo "Processing top-level JSON files for 'statusdb'..." - local has_toplevel_json=false for json_file in "$SEED_DIR"/*.json; do if [ -f "$json_file" ]; then - if [ "$has_toplevel_json" = false ]; then - create_database "statusdb" - has_toplevel_json=true - fi load_document "statusdb" "$json_file" fi done @@ -124,9 +231,11 @@ load_seed_data() { echo "Seed data loading complete!" } -# Deploy design documents based on scenario +# Build design documents based on scenario. +# This only generates JSON files in DESIGN_DOCS_DIR, it does not write +# anything to CouchDB (that happens in deploy_design_docs). create_design_docs() { - echo "Deploying design documents for scenario: ${SCENARIO}..." + echo "Building design documents for scenario: ${SCENARIO}..." if [ ! -f "$VIEWS_CONFIG" ]; then echo "Views config not found: ${VIEWS_CONFIG}" @@ -138,16 +247,20 @@ create_design_docs() { return 0 fi - python3 /opt/couchdb/scripts/validate_views_config.py \ + if ! python3 /opt/couchdb/scripts/validate_views_config.py \ --build \ --scenario "$SCENARIO" \ --config "$VIEWS_CONFIG" \ --views-dir "$VIEWS_DIR" \ - --design_docs_dir "$DESIGN_DOCS_DIR" + --design_docs_dir "$DESIGN_DOCS_DIR"; then + echo "WARNING: Failed to build design documents for scenario '${SCENARIO}', continuing without them" + return 0 + fi - echo "Design documents deployment complete!" + echo "Design documents build complete!" } +# Load the built design documents into their databases (which already exist) deploy_design_docs() { echo "Deploying design documents from ${DESIGN_DOCS_DIR}..." @@ -159,8 +272,11 @@ deploy_design_docs() { for db_dir in "$DESIGN_DOCS_DIR"/*/; do if [ -d "$db_dir" ]; then local db_name=$(basename "$db_dir") + if ! grep -qxF "$db_name" <<< "$CREATED_DATABASES"; then + echo "Skipping design docs for database: ${db_name} (not created for scenario '${SCENARIO}')" + continue + fi echo "Processing design docs for database: ${db_name}" - create_database "$db_name" for json_file in "$db_dir"/*.json; do if [ -f "$json_file" ]; then @@ -175,20 +291,27 @@ deploy_design_docs() { # Main execution main() { - # Check if we've already initialized + # Check if we've already initialized this scenario if [ -f "$INIT_MARKER" ]; then - echo "Seed data already initialized, skipping..." - exit 0 + local previous_scenario + previous_scenario=$(cat "$INIT_MARKER" 2>/dev/null) + if [ "$previous_scenario" = "$SCENARIO" ]; then + echo "Seed data already initialized for scenario '${SCENARIO}', skipping..." + exit 0 + fi + echo "Marker found for scenario '${previous_scenario:-unknown}', current scenario is '${SCENARIO}'; re-initializing..." fi wait_for_couchdb create_system_databases - create_design_docs + create_databases load_seed_data + create_design_docs deploy_design_docs - # Create marker file to indicate initialization is complete - touch "$INIT_MARKER" + # Record the initialized scenario so the next boot can skip initialization + mkdir -p "$(dirname "$INIT_MARKER")" + echo "$SCENARIO" > "$INIT_MARKER" echo "Initialization complete!" } diff --git a/scripts/validate_views_config.py b/scripts/validate_views_config.py index 3a377c1..439f086 100644 --- a/scripts/validate_views_config.py +++ b/scripts/validate_views_config.py @@ -77,8 +77,10 @@ def compare_and_report(scanned_config, loaded_config): for db_name in loaded_dbs: if db_name not in scanned_dbs: - print(f"⚠️ Database '{db_name}' is in config but missing from directory") - all_ok = False + # Seed-only databases (no design docs) are allowed to be missing from the directory + if loaded_dbs[db_name].get("design_docs"): + print(f"⚠️ Database '{db_name}' is in config but missing from directory") + all_ok = False continue for doc_name in loaded_dbs[db_name].get("design_docs", {}): if doc_name not in scanned_dbs[db_name].get("design_docs", {}): @@ -98,34 +100,75 @@ def update_config(scanned_config, loaded_config): """Update the loaded config to match the scanned structure, preserving scenarios.""" updated_config = {"databases": {}} for db_name, db_data in scanned_config.get("databases", {}).items(): - updated_config["databases"][db_name] = {"design_docs": {}} + loaded_db = loaded_config.get("databases", {}).get(db_name, {}) or {} + updated_db = {} + # Preserve database-level scenarios + if "scenarios" in loaded_db: + updated_db["scenarios"] = loaded_db["scenarios"] + updated_db["design_docs"] = {} for doc_name, doc_data in db_data.get("design_docs", {}).items(): - updated_config["databases"][db_name]["design_docs"][doc_name] = {"views": {}} + updated_db["design_docs"][doc_name] = {"views": {}} for view_name, view_config in doc_data.get("views", {}).items(): # Get existing scenarios list, default to ["stage"] - scenarios = loaded_config.get("databases", {}).get(db_name, {}).get("design_docs", {}).get(doc_name, {}).get("views", {}).get(view_name, {}).get("scenarios", ["stage"]) - updated_config["databases"][db_name]["design_docs"][doc_name]["views"][view_name] = { + scenarios = loaded_db.get("design_docs", {}).get(doc_name, {}).get("views", {}).get(view_name, {}).get("scenarios", ["stage"]) + updated_db["design_docs"][doc_name]["views"][view_name] = { "reduce": view_config["reduce"], "scenarios": scenarios } + updated_config["databases"][db_name] = updated_db + # Preserve seed-only databases (in config but without design docs) + for db_name, db_data in loaded_config.get("databases", {}).items(): + if db_name not in updated_config["databases"]: + updated_db = {"design_docs": {}} + if isinstance(db_data, dict) and "scenarios" in db_data: + updated_db["scenarios"] = db_data["scenarios"] + updated_config["databases"][db_name] = updated_db return updated_config +def db_in_scenario(db_data, scenario): + """Check if a database is included in the scenario. No scenarios key means all scenarios.""" + scenarios = (db_data or {}).get("scenarios") + if not scenarios: + return True + return scenario in scenarios + def filter_views_by_scenario(config, scenario): - """Filter views that include the specified scenario.""" + """Filter databases and views that include the specified scenario.""" filtered = {"databases": {}} for db_name, db_data in config.get("databases", {}).items(): - filtered["databases"][db_name] = {"design_docs": {}} + if not db_in_scenario(db_data, scenario): + continue + design_docs = {} for doc_name, doc_data in db_data.get("design_docs", {}).items(): views = {} for view_name, view_config in doc_data.get("views", {}).items(): if scenario in view_config.get("scenarios", []): views[view_name] = view_config if views: - filtered["databases"][db_name]["design_docs"][doc_name] = {"views": views} - if not filtered["databases"][db_name]["design_docs"]: - del filtered["databases"][db_name] + design_docs[doc_name] = {"views": views} + if design_docs: + filtered["databases"][db_name] = {"design_docs": design_docs} return filtered +def databases_for_scenario(config, scenario, seed_dir=None): + """List databases included in the scenario. + + Includes config databases whose scenarios allow the scenario, plus + seed-only databases (in seed_dir but not in config) which default to all scenarios. + """ + config_dbs = config.get("databases", {}) or {} + included = set() + for db_name, db_data in config_dbs.items(): + if db_in_scenario(db_data, scenario): + included.add(db_name) + if seed_dir is not None: + seed_dir = Path(seed_dir) + if seed_dir.exists(): + for item in seed_dir.iterdir(): + if item.is_dir() and item.name not in config_dbs: + included.add(item.name) + return sorted(included) + def build_design_doc(db_name, doc_name, views_config, views_dir): """Build a CouchDB design document from view files.""" design_doc = { @@ -181,26 +224,32 @@ def main(): parser.add_argument("--check", action="store_true", help="Check if config is up to date") parser.add_argument("--update", action="store_true", help="Update config to match directory structure") parser.add_argument("--build", action="store_true", help="Build design documents for deployment") + parser.add_argument("--list-databases", action="store_true", help="List databases included in the scenario (one per line)") parser.add_argument("--scenario", default="stage", help="Scenario to deploy (default: stage)") parser.add_argument("--design_docs_dir", default="design_docs_build", help="Directory to build design docs for deployment") + parser.add_argument("--seed-dir", default="seed_data", help="Path to seed data directory (for --list-databases)") args = parser.parse_args() views_dir = Path(args.views_dir) config_path = Path(args.config) - scanned_config = scan_views_directory(views_dir) loaded_config = load_config(config_path) - if args.build: - filtered_config = filter_views_by_scenario(loaded_config, args.scenario) - print(f"Building design documents for scenario: {args.scenario}") - build_design_docs(filtered_config, views_dir, args.design_docs_dir) - elif args.update: - updated_config = update_config(scanned_config, loaded_config) - save_config(updated_config, config_path) - print(f"✅ Config updated to match directory structure. File saved to {config_path}") - compare_and_report(scanned_config, loaded_config) + if args.list_databases: + for db_name in databases_for_scenario(loaded_config, args.scenario, args.seed_dir): + print(db_name) else: - compare_and_report(scanned_config, loaded_config) + scanned_config = scan_views_directory(views_dir) + if args.build: + filtered_config = filter_views_by_scenario(loaded_config, args.scenario) + print(f"Building design documents for scenario: {args.scenario}") + build_design_docs(filtered_config, views_dir, args.design_docs_dir) + elif args.update: + updated_config = update_config(scanned_config, loaded_config) + save_config(updated_config, config_path) + print(f"✅ Config updated to match directory structure. File saved to {config_path}") + compare_and_report(scanned_config, loaded_config) + else: + compare_and_report(scanned_config, loaded_config) if __name__ == "__main__": main() \ No newline at end of file