Source code for cng_datasets.k8s.workflows

"""
Workflow generation utilities.

Functions for creating complete dataset processing workflows with
multiple coordinated Kubernetes jobs.
"""

from dataclasses import dataclass
from typing import Optional, Dict, Any, List, Union
from pathlib import Path
import json
import math
import re
import shlex
import yaml
from ..duckdb_memory import to_duckdb_memory_limit
from .jobs import K8sJobManager
from .armada import (
    convert_workflow_to_armada,
    resolve_armada_priority_class,
    DEFAULT_ARMADA_PRIORITY_CLASS,
)

# Keys that ClusterConfig accepts (used for profile validation)
_CONFIG_KEYS = {
    "s3_endpoint", "s3_public_endpoint", "s3_secret_name",
    "rclone_secret_name", "rclone_remote", "priority_class", "node_affinity",
    "namespace", "armada_queue", "armada_max_cpu", "armada_max_memory",
}


def _nodata_cli_value(nodata_value) -> Optional[str]:
    """Render a nodata spec as the value for a generated `--nodata` flag.

    Accepts None, a number, a list/tuple, or a comma-separated string and
    returns a clean comma-separated string ("-9999,-1111,32767") or None.
    Categorical products carry several fill codes that must all be excluded
    (issue #108). Kept dependency-free so YAML generation never imports GDAL.
    """
    if nodata_value is None:
        return None
    if isinstance(nodata_value, (list, tuple)):
        items = list(nodata_value)
    elif isinstance(nodata_value, str):
        items = [p.strip() for p in nodata_value.split(",") if p.strip()]
    else:
        items = [nodata_value]
    if not items:
        return None

    def _fmt(v):
        f = float(v)
        return str(int(f)) if f.is_integer() else repr(f)

    return ",".join(_fmt(v) for v in items)


def _primary_nodata_cli_value(nodata_value) -> Optional[str]:
    """The first nodata value as a CLI string, or None.

    Once the COG preprocess step has collapsed every fill code to the primary
    value, the hex job only needs to exclude that one — passing the full list
    would force each hex pod to redundantly re-remap the whole COG (issue #108).
    """
    full = _nodata_cli_value(nodata_value)
    return full.split(",")[0] if full else None


[docs] @dataclass class ClusterConfig: """Configuration for a target Kubernetes cluster and S3 backend. All values default to the NRP Nautilus cluster, preserving backwards compatibility. Override individual fields to target a different cluster. Can be constructed from a profile file via :func:`load_profile`. """ # S3 endpoints s3_endpoint: str = "rook-ceph-rgw-nautiluss3.rook" s3_public_endpoint: str = "s3-west.nrp-nautilus.io" # K8s secret names s3_secret_name: str = "aws" rclone_secret_name: str = "rclone-config" # Rclone remote name used in setup-bucket and pmtiles jobs rclone_remote: str = "nrp" # Kubernetes namespace the generated jobs run in. Also the default Armada # queue, since NRP maps queues one-to-one onto namespaces — but the two are # separate fields in a submitted job set, so `armada_queue` can differ. namespace: str = "geo-workflows" # Armada queue. None means "use the namespace", which is right on NRP and # was the only possible behaviour before this was configurable. armada_queue: Optional[str] = None # Largest pod Armada can place. Every Armada pod is controller-less, and # NRP's admission webhook refuses such a pod above 16 cores or 32Gi (its # message says "32 GB", but 34G is admitted and 32.1Gi is refused, measured # with server-side dry runs). Checked when converting to Armada, because a # pod past it fails at admission, job by job, after submission (#183). # Empty string = no limit, for a cluster without one. armada_max_cpu: str = "16" armada_max_memory: str = "32Gi" # Priority class (empty string = omit from spec, giving default priority 0). # # Default is now to omit it. On NRP `opportunistic` is priority # -2000000000, the lowest available, and preemption exposure scales with # pod runtime — so the class was applied to exactly the pods least able to # absorb it: multi-hour hex and COG pods with no checkpointing, which # restart from zero. Measured on a real LANDFIRE build (issue #201), six # identical res-10 slices at `opportunistic` spread 5x in runtime, from # ~7 h to a projected ~52 h, with every pod saturating its full CPU # request — so this is contention, not scheduler CPU starvation. The # counterfactual from an earlier build: raising priority while halving # parallelism *improved* per-pod runtime, 117 min against 3h32m for # identical work. # # Trade-off worth knowing: `opportunistic` lets a build exceed its # namespace quota, and default priority does not. A large fan-out that # relied on that will now hit the quota instead of running slowly — pass # `--priority-class opportunistic` to restore the old behaviour. priority_class: str = "" # Node affinity: "gpu-avoid" (default NRP rule) or "none" (disable) node_affinity: str = "gpu-avoid"
# Built-in profiles directory (ships with the package) _BUILTIN_PROFILES_DIR = Path(__file__).parent / "profiles" # User profile directory _USER_PROFILES_DIR = Path.home() / ".config" / "cng-datasets" / "profiles"
[docs] def load_profile(name_or_path: str) -> Dict[str, Any]: """Load a cluster profile and return its values as a dict. Resolution order: 1. Treat as a file path if it ends in ``.yaml`` / ``.yml`` or contains a path separator — resolved relative to the current working directory. 2. ``~/.config/cng-datasets/profiles/<name>.yaml`` 3. Built-in profiles shipped with the package (currently: ``nrp``). Args: name_or_path: Built-in profile name (e.g. ``"nrp"``) or path to a YAML file (e.g. ``"./my-cluster.yaml"``). Returns: Dict of config values from the profile. Unknown keys are ignored. Raises: FileNotFoundError: If no profile matching the name or path is found. ValueError: If the profile YAML is invalid. """ p = Path(name_or_path) # Explicit path: ends with .yaml/.yml or contains a separator candidates: List[Path] = [] if name_or_path.endswith((".yaml", ".yml")) or "/" in name_or_path or "\\" in name_or_path: candidates.append(p if p.is_absolute() else Path.cwd() / p) else: # Named profile: user dir first, then built-in candidates.append(_USER_PROFILES_DIR / f"{name_or_path}.yaml") candidates.append(_BUILTIN_PROFILES_DIR / f"{name_or_path}.yaml") for candidate in candidates: if candidate.exists(): with open(candidate) as f: data = yaml.safe_load(f) or {} # Strip the display-only 'name' key, keep only ClusterConfig fields return {k: v for k, v in data.items() if k in _CONFIG_KEYS} raise FileNotFoundError( f"Cluster profile {name_or_path!r} not found.\n" f"Searched:\n" + "\n".join(f" {c}" for c in candidates) + "\n" f"Built-in profiles: {[p.stem for p in _BUILTIN_PROFILES_DIR.glob('*.yaml')]}\n" f"To create a custom profile, write a YAML file to " f"{_USER_PROFILES_DIR}/<name>.yaml" )
[docs] def cluster_config_from_args( profile: Optional[str] = None, **cli_overrides, ) -> "ClusterConfig": """Build a ClusterConfig by merging a profile with explicit CLI overrides. Precedence (highest to lowest): 1. Values in ``cli_overrides`` that are not ``None`` 2. Values from the profile file (if ``profile`` is given) 3. ``ClusterConfig`` field defaults (NRP Nautilus values) Args: profile: Profile name or path, or ``None`` to use bare defaults. **cli_overrides: Keyword arguments matching ``ClusterConfig`` field names. Pass ``None`` for any flag the user did not explicitly set. Returns: A fully-populated :class:`ClusterConfig`. """ base: Dict[str, Any] = {} if profile is not None: base = load_profile(profile) # Apply non-None CLI overrides on top of profile values for key, value in cli_overrides.items(): if key in _CONFIG_KEYS and value is not None: base[key] = value return ClusterConfig(**base)
def _s3_env_vars(config: ClusterConfig) -> List[Dict[str, Any]]: """Build S3 environment variables for job specs from cluster config.""" return [ {"name": "AWS_ACCESS_KEY_ID", "valueFrom": {"secretKeyRef": {"name": config.s3_secret_name, "key": "AWS_ACCESS_KEY_ID"}}}, {"name": "AWS_SECRET_ACCESS_KEY", "valueFrom": {"secretKeyRef": {"name": config.s3_secret_name, "key": "AWS_SECRET_ACCESS_KEY"}}}, {"name": "AWS_S3_ENDPOINT", "value": config.s3_endpoint}, {"name": "AWS_PUBLIC_ENDPOINT", "value": config.s3_public_endpoint}, {"name": "AWS_HTTPS", "value": "false"}, {"name": "AWS_VIRTUAL_HOSTING", "value": "FALSE"}, ] def _node_affinity_spec(config: ClusterConfig) -> Optional[Dict[str, Any]]: """Return the affinity dict for pod specs, or None to omit affinity.""" if config.node_affinity == "none": return None # Default: avoid NVIDIA GPU nodes (NRP NFD label) return { "nodeAffinity": { "requiredDuringSchedulingIgnoredDuringExecution": { "nodeSelectorTerms": [{ "matchExpressions": [{ "key": "feature.node.kubernetes.io/pci-10de.present", "operator": "NotIn", "values": ["true"], }] }] } } } def _apply_scheduling(pod_spec: Dict[str, Any], config: ClusterConfig) -> None: """Mutate pod_spec in place: add priorityClassName and affinity from config.""" if config.priority_class: pod_spec["priorityClassName"] = config.priority_class affinity = _node_affinity_spec(config) if affinity is not None: pod_spec["affinity"] = affinity def _job_metadata(manager, job_name: str) -> Dict[str, Any]: """ Build a Job's ``metadata`` block, stamped with the workflow's namespace. Every step manifest is meant to be applicable on its own — the docs sanction `kubectl apply -f <dataset>-hex.yaml` for step-by-step control, and the orchestrator itself passes `-n <namespace>`. Without ``metadata.namespace`` a direct apply silently targets whatever namespace kubectl defaults to, which on a least-privilege cluster fails with an RBAC error naming "default" rather than the missing field (issue #190). ``generate_sync_job`` already stamps it; this is the same block for the generators, which built their metadata inline and left it out. """ return { "name": job_name, "namespace": manager.namespace, "labels": {"k8s-app": job_name}, } def _normalize_h0_subset(h0_subset: Optional[List[int]]) -> Optional[List[int]]: """ Validate and canonicalize an ``--h0-subset``, or return None when unset. Sorted and de-duplicated so the emitted ``H0S`` array is deterministic and the completion index maps to a stable h0 across regenerations. A subset covering all 122 positions is the default fan-out, so it collapses to None rather than emitting a redundant index mapping (issue #191). The range check below cannot tell a position from an H3 base cell number, because both numberings run 0-121 — so its wording carries the whole burden of not implying that a base-cell list has been validated (#218). """ if h0_subset is None: return None cells = sorted({int(h) for h in h0_subset}) if not cells: raise ValueError( "h0_subset was given but empty. Omit it to fan out over all 122 h0 " "cells, or pass the grid positions the source overlaps, e.g. " "--h0-subset \"12,14,20,50,71,78\" for CONUS. To give H3 base cell " "numbers instead, use --h0-cells \"9,19,20,21,34,36\"." ) out_of_range = [h for h in cells if not 0 <= h <= 121] if out_of_range: raise ValueError( f"h0_subset contains out-of-range h0 grid position(s) {out_of_range}. " "The h0 grid has 122 rows, so each position must be in 0-121. Note " "H3 base cell numbers also run 0-121 and are a different numbering " "— every base-cell list passes this check (#213); pass one to " "--h0-cells rather than --h0-subset." ) if len(cells) == 122: return None return cells def parse_years(spec: Union[str, List[int], None]) -> Optional[List[int]]: """Parse a ``--years`` list such as "1985,1990,2015-2025" (issue #172). Ranges are inclusive. The result is sorted and de-duplicated, so the completion index maps to the same year across regenerations. """ if spec is None: return None if isinstance(spec, str): years = set() for part in (p.strip() for p in spec.split(",")): if not part: continue lo, sep, hi = part.partition("-") try: lo_y, hi_y = int(lo), int(hi) if sep else int(lo) except ValueError: raise ValueError(f"--years: {part!r} is not a year or a range like 2015-2025") if hi_y < lo_y: raise ValueError(f"--years: range {part!r} runs backwards") years.update(range(lo_y, hi_y + 1)) else: years = {int(y) for y in spec} if not years: raise ValueError("--years was given but lists no years") return sorted(years) def _year_template(value: str) -> str: """*value* with its ``{year}`` placeholder in shell form, for a manifest that sets YEAR from the completion index (issue #172).""" return value.replace("{year}", "${YEAR}") def _year_preamble(years: List[int], per_year: int) -> str: """Bash that sets YEAR, and UNIT (the index within that year's block of *per_year* completions), from the completion index (issue #172). Indexes run year-major, so the years finish in order. The index is written as ``${JOB_COMPLETION_INDEX}`` so the Armada converter, which rewrites that spelling to a literal, still produces valid arithmetic. """ fail = (' echo "No year for completion index \'${JOB_COMPLETION_INDEX}\' in ' f'(${{YEARS[*]}}) x {per_year}" >&2\n exit 1\nfi\n') return ( f"# Completions run year by year, {per_year} per year (#172).\n" f"YEARS=({' '.join(str(y) for y in years)})\n" 'if [ -z "${JOB_COMPLETION_INDEX}" ]; then\n' + fail + f"YEAR=${{YEARS[$(( ${{JOB_COMPLETION_INDEX}} / {per_year} ))]}}\n" f"UNIT=$(( ${{JOB_COMPLETION_INDEX}} % {per_year} ))\n" 'if [ -z "$YEAR" ]; then\n' + fail + "\n" ) # Default cells per exact_extract call in the hex step; mirrors # cng_datasets.raster.cog's CNG_HEX_CHUNK_SIZE default. Generated manifests # pin it explicitly rather than inherit it, so a pod's peak memory is a # function of the manifest alone (issue #195). DEFAULT_HEX_CHUNK_SIZE = 100000 # CPU request/limit for a hex pod. Also the default worker count, since one # process per requested CPU is the point at which the pod stops oversubscribing # the cores it actually asked for. DEFAULT_HEX_CPU = "4" def _cpu_quantity_to_workers(cpu: str) -> int: """Whole CPUs in a Kubernetes CPU quantity ("4", "3500m"), floored at 1.""" text = str(cpu).strip() try: cores = float(text[:-1]) / 1000.0 if text.endswith("m") else float(text) except ValueError: raise ValueError( f"hex_cpu must be a Kubernetes CPU quantity such as '4' or '3500m', got {cpu!r}" ) from None if cores <= 0: raise ValueError(f"hex_cpu must be greater than zero, got {cpu!r}") return max(1, int(cores)) def _resolve_hex_workers(hex_workers: Optional[int], hex_cpu: str) -> int: """ Worker-process count for a hex pod: the request, else the pod's CPU request. Left unset in the pod, `cng-datasets raster` sizes its pool from the cgroup quota and falls back to the node's core count when that is unreadable — 64 workers on a 4-CPU pod, and a different number on a differently sized node (issue #195). Peak RSS is roughly workers x chunk size x bytes per cell, so an unpinned worker count makes peak memory a property of the scheduler rather than of the manifest. Resolving it here means every generated hex job carries an explicit number. """ if hex_workers is None: return _cpu_quantity_to_workers(hex_cpu) hex_workers = int(hex_workers) if hex_workers < 1: raise ValueError(f"hex_workers must be at least 1, got {hex_workers}") return hex_workers # Bytes of parent-process peak RSS per H3 cell enumerated in a hex chunk. # # Measured in issue #173 after boundary derivation moved into the workers: the # parent now carries 8 B/cell of ids, and ~121 B/cell of peak RSS once DuckDB's # own materialisation of the child list is counted. The constant is taken from # the res-9 run rather than a smaller one because peak RSS grows *sub*-linearly # in cell count (4.58x for 7x the cells), so extrapolating from a small run # over-predicts. It reproduces the three measured points: 282M cells -> ~32 GiB, # 40.4M -> 4.6 GiB, 5.8M -> 0.68 GiB. # # This models the parent's enumeration, which is the term that scales with chunk # size. Worker memory is already bounded by CNG_HEX_WORKERS x CNG_HEX_CHUNK_SIZE # and does not enter here, and the output-side accumulation is not modelled — so # treat the estimate as a floor, not a guarantee. HEX_BYTES_PER_CELL = 121 # Above this many chunks a build is past the namespace pod guideline and belongs # on an external queue rather than in one indexed Job (issue #173 lever D, #39). K8S_CHUNK_COUNT_GUIDELINE = 200 # Hard ceiling on the fan-out. Armada's regime is thousands of small jobs — the # reference build in #183 ran 4,270 — not hundreds of thousands, and each chunk # is a pod that schedules, pulls the image and reads its own window. The ceiling # also protects generation itself: enumerating the chunk list means materialising # one row per chunk, so an unguarded --chunk-resolution 10 would try to build a # 282-million-entry list here and hang before writing a single manifest. MAX_CHUNK_COUNT = 50000 def _parse_memory_to_bytes(quantity: str) -> int: """Bytes in a Kubernetes memory quantity ("32Gi", "512Mi", "1000000").""" text = str(quantity).strip() units = {"Ki": 2 ** 10, "Mi": 2 ** 20, "Gi": 2 ** 30, "Ti": 2 ** 40, "K": 10 ** 3, "M": 10 ** 6, "G": 10 ** 9, "T": 10 ** 12} for suffix, factor in sorted(units.items(), key=lambda kv: -len(kv[0])): if text.endswith(suffix): return int(float(text[:-len(suffix)]) * factor) return int(float(text)) def estimate_chunk_peak_bytes(h3_resolution: int, chunk_resolution: int) -> int: """Estimated parent peak RSS for one chunk, from the #173 measurements. Cells per chunk is 7 ** (h3_resolution - chunk_resolution): every level between the chunk and the native resolution multiplies the count by seven. Pentagons have six children rather than seven, so this over-counts slightly for the twelve pentagon lineages — the safe direction for a memory budget. """ if chunk_resolution > h3_resolution: raise ValueError( f"chunk_resolution {chunk_resolution} is finer than the target " f"h3_resolution {h3_resolution}; a chunk would contain no cells" ) return 7 ** (h3_resolution - chunk_resolution) * HEX_BYTES_PER_CELL def select_chunk_resolution(h3_resolution: int, budget: str) -> int: """Coarsest chunk resolution whose estimated peak fits the memory budget. Coarsest rather than finest because every extra level multiplies the pod count by seven, and pods are not free: each one schedules, pulls the image and reads its own window of the source. The aim is the smallest fan-out that fits, not the smallest possible chunk. """ budget_bytes = _parse_memory_to_bytes(budget) if budget_bytes <= 0: raise ValueError(f"max_hex_memory must be positive, got {budget!r}") for chunk_resolution in range(0, h3_resolution + 1): if estimate_chunk_peak_bytes(h3_resolution, chunk_resolution) <= budget_bytes: return chunk_resolution raise ValueError( f"No chunk resolution fits {budget} at h3_resolution {h3_resolution}: even a " f"single native cell per chunk needs about " f"{estimate_chunk_peak_bytes(h3_resolution, h3_resolution) / 2 ** 20:.1f} MiB. " f"Raise --max-hex-memory or lower --h3-resolution." ) # Retry budget for an indexed hex fan-out. # # The fan-out used to carry `backoffLimit: 0`, which is a *job-wide* budget: one # pod failure anywhere fails the whole Job. A `podFailurePolicy` already ignores # DisruptionTarget, so a preemption or a node drain is retried and does not count # — that half of the problem was covered. What was not covered is every other # transient failure on a multi-hour pod: an OOM, a truncated Ceph read, a node # going away without setting the condition. Any one of those killed the run with # no retry at all. # # backoffLimitPerIndex makes the budget per index, so one flaky slice retries # instead of taking 342 healthy ones with it, and maxFailedIndexes stops the job # once a failure looks systematic rather than burning hours on the rest. DEFAULT_HEX_RETRIES = 2 DEFAULT_MAX_FAILED_INDEXES = 1 def _indexed_retry_spec(retries: int, max_failed_indexes: int) -> Dict[str, Any]: """Job-spec fields giving an indexed fan-out a per-index retry budget. `backoffLimit` is deliberately omitted rather than set alongside these: the two express the same thing at different granularities, Kubernetes ignores the job-wide one once a per-index budget exists, and emitting both invites a reader to trust whichever they saw first. If the cluster is old enough to prune these fields, the Job falls back to the API default backoffLimit of 6 — a weaker budget than intended, but not the zero-retry behaviour this replaces (issue #201). """ if retries < 0: raise ValueError(f"hex_retries must be >= 0, got {retries}") if max_failed_indexes < 1: raise ValueError( f"max_failed_indexes must be at least 1, got {max_failed_indexes}: " "a fan-out that tolerates no failed index at all is the " "backoffLimit: 0 behaviour this replaces" ) return { "backoffLimitPerIndex": retries, "maxFailedIndexes": max_failed_indexes, } def _validate_hex_chunk_size(hex_chunk_size) -> int: """Cells per exact_extract call, as a positive int.""" hex_chunk_size = int(hex_chunk_size) if hex_chunk_size < 1: raise ValueError(f"hex_chunk_size must be at least 1, got {hex_chunk_size}") return hex_chunk_size def _validate_k8s_name(k8s_name: str, original: str) -> None: """Raise ValueError if k8s_name is not a valid Kubernetes resource name.""" pattern = re.compile(r'^[a-z0-9][a-z0-9\-]*[a-z0-9]$') if not pattern.match(k8s_name): raise ValueError( f"Dataset name {original!r} produces invalid Kubernetes name {k8s_name!r}.\n" "Kubernetes names must consist of lowercase alphanumeric characters and '-', " "and must start and end with an alphanumeric character.\n" "Common causes: dots ('.'), underscores left after substitution, or starting/ending with '-'.\n" f"Suggested fix: rename using only lowercase letters, digits, hyphens, and '/' as path separator." ) def _count_source_features(source_urls: Union[str, List[str]], layer: str = None) -> int: """ Count features in source file(s) (shapefile, geopackage, etc.) using GDAL with vsicurl. For .zip files, it downloads, extracts, and counts features in all shapefiles. Args: source_urls: HTTP(S) or S3 URL(s) to source vector file(s). Can be a single string or list. layer: Optional layer name for multi-layer sources (GDB, GPKG) Returns: Total number of features across all source file(s) """ # Normalize to list if isinstance(source_urls, str): source_urls = [source_urls] total_count = 0 for source_url in source_urls: total_count += _count_single_source(source_url, layer) return total_count def _resolve_feature_count( source_urls: List[str], layer: Optional[str], expect_features: Optional[int] ) -> int: """Feature count to size the hex job by, or a ValueError if there is none. Counts the source. If it can't be read, falls back to ``expect_features`` (``--expect-features``) when the caller gave one: that count is known independently and the convert step enforces it at runtime, so a job sized by it cannot quietly be wrong. Otherwise it raises. It used to fall back to a made-up ``max_completions * 1000`` features, exit 0 and write a complete 200-way fan-out for a source that 404s. For a small source that made each chunk up to 200x larger than a real count would, and the warning suggested a ``--chunk-size`` flag that ``workflow`` does not accept (issue #235). """ if len(source_urls) > 1: print(f"Counting features in {len(source_urls)} sources...") else: print(f"Counting features in {source_urls[0]}...") try: return _count_source_features(source_urls, layer=layer) except Exception as e: if expect_features is not None: print( f" Warning: could not count features ({e}); sizing the hex job " f"from --expect-features {int(expect_features):,} instead." ) return int(expect_features) sources = ", ".join(source_urls) raise ValueError( f"Could not count features in {sources} ({e}). The hex job is sized " f"from the feature count, so no workflow was written. Check that the " f"URL is correct and readable from here (a 404, a typo in the bucket " f"name or missing credentials all look like this). If the source is " f"right but can't be read from this machine, or isn't uploaded yet, " f"pass --expect-features N with its known feature count." ) from e def _count_single_source(source_url: str, layer: str = None) -> int: """ Count features in a single source file. Args: source_url: HTTP(S) or S3 URL to source vector file layer: Optional layer name for multi-layer sources (GDB, GPKG) Returns: Number of features in the source file """ import subprocess import tempfile import os import shutil import zipfile from urllib.request import urlretrieve # Check for zip file if source_url.lower().endswith('.zip'): try: print(" Detected zip file, downloading to temporary directory...") temp_dir = tempfile.mkdtemp() local_zip = os.path.join(temp_dir, "download.zip") # Handle S3 vs HTTP download_url = source_url if source_url.startswith('s3://'): if "nrp-nautilus.io" in source_url or "public-iucn" in source_url: path = source_url.replace("s3://", "") download_url = f"https://s3-west.nrp-nautilus.io/{path}" # Strip vsicurl if present (legacy compat) if download_url.startswith('/vsicurl/'): download_url = download_url.replace('/vsicurl/', '') if download_url.startswith('http://') or download_url.startswith('https://') or download_url.startswith('ftp://'): urlretrieve(download_url, local_zip) elif os.path.exists(download_url): shutil.copy(download_url, local_zip) else: # Try adding file:// scheme if it looks like an absolute path but failed above checks? # Or just let urlretrieve try if it has a scheme. urlretrieve(download_url, local_zip) with zipfile.ZipFile(local_zip, 'r') as zip_ref: zip_ref.extractall(temp_dir) # Find all shapefiles total_count = 0 shapefiles = [] for root, dirs, files in os.walk(temp_dir): for file in files: if file.lower().endswith(".shp"): shapefiles.append(os.path.join(root, file)) if not shapefiles: raise ValueError("No shapefiles found in zip archive") print(f" Found {len(shapefiles)} shapefiles, counting features...") for shp in shapefiles: result = subprocess.run( ['ogrinfo', '-so', '-al', shp], capture_output=True, text=True, check=True ) for line in result.stdout.split('\n'): if 'Feature Count:' in line: count = int(line.split(':')[1].strip()) total_count += count break return total_count finally: if 'temp_dir' in locals() and os.path.exists(temp_dir): shutil.rmtree(temp_dir) # Convert s3:// URLs to https:// for vsicurl if source_url.startswith('s3://'): path = source_url.replace('s3://', '') source_url = f"https://s3-west.nrp-nautilus.io/{path}" # Use vsicurl prefix for remote files if source_url.startswith('http://') or source_url.startswith('https://'): gdal_path = f"/vsicurl/{source_url}" else: gdal_path = source_url # Use ogrinfo to count features if layer: # Query specific layer for multi-layer sources (GDB, GPKG) result = subprocess.run( ['ogrinfo', '-so', gdal_path, layer], capture_output=True, text=True, check=True, timeout=30, ) else: # -al: all layers (for single-layer sources) result = subprocess.run( ['ogrinfo', '-so', '-al', gdal_path], capture_output=True, text=True, check=True, timeout=30, ) # Parse output to find "Feature Count: XXXXX" for line in result.stdout.split('\n'): if 'Feature Count:' in line: count_str = line.split(':')[1].strip() return int(count_str) raise ValueError("Could not find feature count in ogrinfo output") def _detect_geometry_type(source_urls: Union[str, List[str]], layer: str = None) -> str: """Detect the predominant geometry type from source file(s). Returns one of 'point', 'line', 'polygon', or 'unknown'. Uses the first source URL only (multi-source datasets are expected to share geometry type). """ import subprocess url = source_urls[0] if isinstance(source_urls, list) else source_urls # Convert s3:// to https:// for vsicurl if url.startswith('s3://'): path = url.replace('s3://', '') url = f"https://s3-west.nrp-nautilus.io/{path}" if url.startswith('http://') or url.startswith('https://'): gdal_path = f"/vsicurl/{url}" else: gdal_path = url try: cmd = ['ogrinfo', '-so', gdal_path] if layer: cmd.append(layer) else: cmd.append('-al') result = subprocess.run(cmd, capture_output=True, text=True, timeout=30) output = result.stdout.lower() if 'line string' in output or 'linestring' in output or 'multi line string' in output: return 'line' if 'point' in output or 'multi point' in output: return 'point' if 'polygon' in output or 'multi polygon' in output: return 'polygon' except Exception: pass return 'unknown' # Default H3 resolutions per geometry type _DEFAULT_H3_RESOLUTION = { 'point': 10, 'polygon': 10, 'line': 8, 'unknown': 10, } # Target number of features per hex chunk. chunk_size is floored at this value # so a small dataset is not shredded into ~max_completions tiny chunks (issue # #144): every k8s completion pulls the multi-GB image and claims a # namespace-quota slot, so over-provisioning a 6-chunk job to 200 pods is pure # waste (and blocks other jobs on a shared quota). Larger datasets still shrink # chunk_size above this floor to keep completions within max_completions. 1000 # matches the effective chunk_size the previous formula already produced at the # 200k-feature scale, so per-pod memory/time is unchanged for large builds. _DEFAULT_TARGET_CHUNK_SIZE = 1000 def _calculate_chunking( total_rows: int, max_completions: int = 200, max_parallelism: int = 50, target_chunk_size: int = _DEFAULT_TARGET_CHUNK_SIZE, ) -> tuple[int, int, int]: """ Calculate optimal chunk size, completions, and parallelism. chunk_size is the target (default 1000) unless the dataset is large enough that hitting it would need more than ``max_completions`` chunks, in which case chunk_size grows so completions caps at ``max_completions``. This right-sizes ``completions`` to the chunks that actually hold data instead of always provisioning up to ``max_completions`` pods (issue #144). Args: total_rows: Total number of rows/features in dataset max_completions: Maximum number of job completions (default: 200) max_parallelism: Maximum parallelism (default: 50) target_chunk_size: Preferred features per chunk / floor for chunk_size Returns: Tuple of (chunk_size, completions, parallelism) """ # Floor chunk_size at the target; grow it only when the dataset would # otherwise exceed max_completions chunks. chunk_size = max(target_chunk_size, math.ceil(total_rows / max_completions)) # Actual number of completions needed (at least 1, so the job is never # generated with completions=0 for an empty/near-empty count). completions = max(1, math.ceil(total_rows / chunk_size)) # Set parallelism to min of max_parallelism or completions parallelism = min(max_parallelism, completions) return chunk_size, completions, parallelism
[docs] def generate_dataset_workflow( dataset_name: str, source_urls: Union[str, List[str]] = None, bucket: str = None, output_dir: str = ".", namespace: Optional[str] = None, image: str = "ghcr.io/boettiger-lab/datasets:latest", git_repo: str = "https://github.com/boettiger-lab/datasets.git", h3_resolution: Optional[int] = None, resolution_by_area: Optional[str] = None, parent_resolutions: Optional[List[int]] = None, polyfill: str = "centre", id_column: Optional[str] = None, layer: Optional[str] = None, hex_memory: str = "8Gi", convert_memory: Optional[str] = None, hex_retries: int = DEFAULT_HEX_RETRIES, max_failed_indexes: int = DEFAULT_MAX_FAILED_INDEXES, max_parallelism: int = 50, max_completions: int = 200, chunk_size: Optional[int] = None, cells_per_chunk: Optional[float] = None, intermediate_chunk_size: int = 10, row_group_size: int = 100000, simplify_tolerance: Optional[float] = None, trim_strings: bool = False, lat_column: Optional[str] = None, lon_column: Optional[str] = None, expect_features: Optional[int] = None, spatial_order: bool = True, csv_sample_size: Optional[int] = None, pmtiles_max_zoom: Optional[int] = None, pmtiles_chunks: Optional[int] = None, pmtiles_split_zoom: Optional[int] = None, pmtiles_storage: str = "50Gi", backend: str = "k8s", armada_priority_class: Optional[str] = None, armada_queue: Optional[str] = None, hex_storage: str = "10Gi", repartition_storage: str = "50Gi", repartition_memory: str = "32Gi", # Cluster/storage configuration — all default to None so explicit values # can be distinguished from "not set" when merging with a profile. profile: Optional[str] = None, s3_endpoint: Optional[str] = None, s3_public_endpoint: Optional[str] = None, s3_secret_name: Optional[str] = None, rclone_secret_name: Optional[str] = None, rclone_remote: Optional[str] = None, priority_class: Optional[str] = None, node_affinity: Optional[str] = None, # Backwards compatibility: accept source_url (singular) source_url: Union[str, List[str]] = None, ): """ Generate complete workflow for a dataset. Creates all necessary Kubernetes job configurations for processing a geospatial dataset through the standard pipeline: 1. Convert to GeoParquet 2. Generate PMTiles 3. H3 hexagonal tiling 4. Repartition by h0 Args: dataset_name: Name of the dataset (e.g., "redlining") source_urls: URL(s) to source data file(s). Can be a single string or list. Multiple sources will be merged. bucket: S3 bucket for outputs output_dir: Directory to write YAML files namespace: Kubernetes namespace image: Container image to use git_repo: Git repository URL for package source h3_resolution: Target H3 resolution for tiling. Auto-detected if None (10 for polygons/points, 8 for lines). parent_resolutions: List of parent H3 resolutions to include (default: [9, 8, 0]) id_column: ID column name (auto-detected if not specified) hex_memory: Memory request/limit for hex job pods (default: "8Gi") convert_memory: Memory request/limit for the convert job pod (default: same as hex_memory, issue #275) hex_retries: Per-index retry budget for the hex fan-out (backoffLimitPerIndex, default 2). A preemption is already ignored by the pod failure policy; this covers everything else that can end a multi-hour pod — an OOM, a truncated read, a node going away (issue #201). max_failed_indexes: How many indexes may exhaust their retries before the Job stops (default 1). Keeps a systematic failure from burning hours on the remaining chunks. max_parallelism: Maximum parallelism for hex jobs (default: 50) max_completions: Maximum job completions - increase to reduce chunk size (default: 200) lat_column: Latitude column for a CSV point source, passed through to the convert step. Without it a CSV source cannot be used here at all (issue #188). lon_column: Longitude column for a CSV point source (issue #188). expect_features: Row count the convert step must produce, known independently by the caller. The step exits non-zero on a mismatch, so a silently truncated source fails the workflow rather than flowing into the hex and PMTiles steps (issue #186). Also sizes the hex job when the source can't be counted from here (issue #235). spatial_order: False passes ``--no-spatial-order`` to the convert step, which then keeps source row order instead of sorting along a Hilbert curve. The way out for a dataset whose sort does not fit the convert pod (issues #276, #311). csv_sample_size: Rows the convert step samples for CSV type inference (``--csv-sample-size``, issue #188). None leaves the convert default, the whole file. armada_priority_class: Armada priority class for the `armada` backend — a literal name ("armada-default") or a shorthand ("default", "preemptible", "high"). Defaults to non-preemptible, since a preempted Armada job is not rescheduled and the k8s Job-level retry settings do not survive conversion (issue #183). Ignored when backend is "k8s". chunk_size: Features per hex chunk (default 1000). Lower it for a dataset with few but very large features, whose peak memory is set by the cells of the largest features in a chunk rather than by the feature count (issue #237). Still raised if needed to keep the fan-out within ``max_completions``, and that is reported. Giving it turns off cells-per-chunk planning. cells_per_chunk: Estimated H3 cells per hex chunk (default ``DEFAULT_CELLS_PER_CHUNK``). Unless chunk_size is given, a plan step after convert cuts the GeoParquet into contiguous row ranges at this budget (never more than the fixed rule's features per chunk), and the workflow sizes the hex Job to the plan (#124). intermediate_chunk_size: Number of rows to process in pass 2 (unnesting arrays) - reduce if hitting OOM (default: 10) pmtiles_chunks: Build PMTiles in this many parallel parts plus a low-zoom overview, merged with tile-join, instead of in one pod (#83). None (the default) keeps the single pod. pmtiles_split_zoom: With pmtiles_chunks, the first zoom the parts build; the overview builds every zoom below it (default 7). pmtiles_storage: With pmtiles_chunks, ephemeral storage for each PMTiles pod (default 50Gi, the house norm). source_url: (Deprecated) Use source_urls instead. Kept for backwards compatibility. """ # Handle backwards compatibility for source_url parameter if source_url is not None and source_urls is None: source_urls = source_url elif source_urls is None: raise ValueError("Either source_urls or source_url must be provided") if bucket is None: raise ValueError("bucket parameter is required") config = cluster_config_from_args( profile=profile, s3_endpoint=s3_endpoint, s3_public_endpoint=s3_public_endpoint, s3_secret_name=s3_secret_name, rclone_secret_name=rclone_secret_name, rclone_remote=rclone_remote, priority_class=priority_class, node_affinity=node_affinity, armada_queue=armada_queue, ) # See the note in generate_raster_workflow: namespace comes from the profile # unless named, and the Armada queue follows it unless set separately. namespace = namespace or config.namespace armada_queue = config.armada_queue or namespace manager = K8sJobManager(namespace=namespace, image=image) output_path = Path(output_dir) # Sanitize dataset name for Kubernetes (replace underscores, slashes with hyphens) k8s_name = dataset_name.replace('_', '-').replace('/', '-').lower() _validate_k8s_name(k8s_name, dataset_name) # Normalize source_urls to list if isinstance(source_urls, str): source_urls = [source_urls] requested_chunk_size = chunk_size if requested_chunk_size is not None and int(requested_chunk_size) < 1: raise ValueError(f"chunk_size must be at least 1, got {requested_chunk_size}") if requested_chunk_size is not None and cells_per_chunk is not None: raise ValueError( "chunk_size and cells_per_chunk are alternatives: chunk_size fixes the " "features per chunk, cells_per_chunk sizes chunks by estimated cells. " "Give one.") if cells_per_chunk is not None and cells_per_chunk <= 0: raise ValueError(f"cells_per_chunk must be positive, got {cells_per_chunk}") planned = requested_chunk_size is None if planned and cells_per_chunk is None: from ..vector.chunk_plan import DEFAULT_CELLS_PER_CHUNK cells_per_chunk = DEFAULT_CELLS_PER_CHUNK # Count features to size the hex fan-out. This runs before any manifest is # written: when the source can't be read, the workflow must fail rather than # emit a plausible-looking fan-out sized for a made-up count (issue #235). total_rows = _resolve_feature_count(source_urls, layer, expect_features) chunk_size, completions, parallelism = _calculate_chunking( total_rows, max_completions=max_completions, max_parallelism=max_parallelism, target_chunk_size=(_DEFAULT_TARGET_CHUNK_SIZE if requested_chunk_size is None else int(requested_chunk_size)), ) print(f" Total features: {total_rows:,}") print(f" Chunk size: {chunk_size:,}") if requested_chunk_size is not None and chunk_size > requested_chunk_size: # A size asked for explicitly is a memory decision; overriding it # quietly would hand back the OOM it was chosen to avoid. print(f" ⚠ --chunk-size {requested_chunk_size:,} would need " f"{math.ceil(total_rows / requested_chunk_size):,} completions, so it was " f"raised to {chunk_size:,} to stay within --max-completions " f"{max_completions}. Raise --max-completions to keep the smaller chunks " f"(past ~200, use --backend armada).") if planned: # The plan decides the real chunk count after convert; the Job carries # an upper bound so it is valid as written, and the workflow patches # it down to the plan (#124). No more chunks than rows. completions = max(1, min(max_completions, total_rows)) parallelism = min(max_parallelism, completions) print(f" Hex chunks: planned after convert at ~{cells_per_chunk:,.0f} " f"estimated cells each (at most {chunk_size:,} features), up to " f"{completions} completions") print(f" Completions: {completions}{' (upper bound)' if planned else ''}") print(f" Parallelism: {parallelism}") output_path.mkdir(parents=True, exist_ok=True) # Variable-resolution mode (issue #98): the hex job receives the # --resolution-by-area spec instead of a single --h3-resolution. Derive the # finest bin resolution from the spec for messaging / column naming, and skip # geometry-type auto-detection (which only picks a single target resolution). if polyfill not in ("centre", "overlap"): raise ValueError(f"polyfill must be 'centre' or 'overlap', not {polyfill!r}") if resolution_by_area is not None: from ..vector.h3_tiling import parse_resolution_by_area bins = parse_resolution_by_area(resolution_by_area) h3_resolution = max(res for _, res in bins) print(f" Variable resolution by area: {resolution_by_area} (finest res {h3_resolution})") # Auto-detect geometry type and set H3 resolution default if not specified elif h3_resolution is None: geom_type = _detect_geometry_type(source_urls, layer=layer) h3_resolution = _DEFAULT_H3_RESOLUTION.get(geom_type, 10) print(f" Detected geometry type: {geom_type} — using H3 resolution {h3_resolution}") if geom_type == 'line': print(" Line geometries will be indexed by every H3 cell they pass through.") # Set defaults for parent resolutions if not provided if parent_resolutions is None: parent_resolutions = [9, 8, 0] # Generate bucket setup job (must run first) _generate_setup_bucket_job(manager, k8s_name, bucket, output_path, git_repo, config) # Generate conversion job _generate_convert_job(manager, k8s_name, source_urls, bucket, output_path, git_repo, layer, memory=convert_memory or hex_memory, row_group_size=row_group_size, s3_dataset=dataset_name, config=config, simplify_tolerance=simplify_tolerance, trim_strings=trim_strings, lat_column=lat_column, lon_column=lon_column, expect_features=expect_features, spatial_order=spatial_order, csv_sample_size=csv_sample_size) # Generate pmtiles job(s) (uses converted parquet, not source) if pmtiles_chunks is not None: if pmtiles_chunks > max_completions: raise ValueError( f"--pmtiles-chunks {pmtiles_chunks} is past --max-completions " f"{max_completions}, the per-Job completions guideline.") _generate_pmtiles_chunked_jobs( manager, k8s_name, bucket, output_path, chunks=pmtiles_chunks, parallelism=min(pmtiles_chunks, max_parallelism), memory=hex_memory, storage=pmtiles_storage, s3_dataset=dataset_name, config=config, h3_resolution=h3_resolution, max_zoom=pmtiles_max_zoom, split_zoom=pmtiles_split_zoom) else: if pmtiles_split_zoom is not None: raise ValueError("--pmtiles-split-zoom applies only with --pmtiles-chunks.") _generate_pmtiles_job(manager, k8s_name, None, bucket, output_path, git_repo, memory=hex_memory, s3_dataset=dataset_name, config=config, h3_resolution=h3_resolution, max_zoom=pmtiles_max_zoom) print(f" H3 resolution: {h3_resolution}") print(f" Parent resolutions: {parent_resolutions}") plan_url = None if planned: plan_url = _hex_plan_url(bucket, dataset_name) _generate_plan_job(manager, k8s_name, bucket, output_path, plan_url, h3_resolution, resolution_by_area, cells_per_chunk, max_chunks=completions, memory=hex_memory, s3_dataset=dataset_name, config=config) # Generate hex tiling job _generate_hex_job(manager, k8s_name, bucket, output_path, git_repo, chunk_size, completions, parallelism, h3_resolution, parent_resolutions, id_column, hex_memory, intermediate_chunk_size, s3_dataset=dataset_name, hex_storage=hex_storage, config=config, resolution_by_area=resolution_by_area, hex_retries=hex_retries, max_failed_indexes=max_failed_indexes, plan_url=plan_url, polyfill=polyfill) # Generate repartition job _generate_repartition_job(manager, k8s_name, bucket, output_path, git_repo, s3_dataset=dataset_name, repartition_storage=repartition_storage, repartition_memory=repartition_memory, config=config) # Sizes and checksums of the outputs, for their STAC assets (#340) _generate_checksums_job( manager, k8s_name, bucket, output_path, [f"s3://{bucket}/{dataset_name}.parquet", f"s3://{bucket}/{dataset_name}.pmtiles", f"s3://{bucket}/{dataset_name}/hex/"], s3_dataset=dataset_name, config=config) # Generate workflow RBAC (generic for all cng-datasets workflows) _generate_workflow_rbac(namespace, output_path) # Build generation command for documentation parent_res_str = ','.join(map(str, parent_resolutions)) # Format source URLs for command recreation source_urls_str = ' '.join([f'--source-url {shlex.quote(url)}' for url in source_urls]) res_flag = (f"--resolution-by-area \"{resolution_by_area}\"" if resolution_by_area is not None else f"--h3-resolution {h3_resolution}") gen_command = (f"cng-datasets workflow --dataset {dataset_name} " f"{source_urls_str} --bucket {bucket} " f"{res_flag} --parent-resolutions \"{parent_res_str}\"") if polyfill != "centre": gen_command += f" --polyfill {polyfill}" if requested_chunk_size is not None: gen_command += f" --chunk-size {requested_chunk_size}" else: gen_command += f" --cells-per-chunk {cells_per_chunk:.0f}" # Generate ConfigMap YAML from job files _generate_configmap(k8s_name, namespace, output_path, gen_command) # Generate Argo workflow with ConfigMap-based approach _generate_argo_workflow(k8s_name, namespace, output_path, output_dir, planned=planned, max_parallelism=max_parallelism, pmtiles_chunked=pmtiles_chunks is not None) if backend == "armada": armada_files = convert_workflow_to_armada( k8s_yaml_dir=str(output_path), dataset_name=k8s_name, queue=armada_queue, priority_class=armada_priority_class, max_cpu=config.armada_max_cpu, max_memory=config.armada_max_memory, ) effective_priority = ( resolve_armada_priority_class(armada_priority_class) or DEFAULT_ARMADA_PRIORITY_CLASS ) print(f"\n✓ Generated Armada workflow for {dataset_name}") print(f" Armada priority class: {effective_priority} " f"(override with --armada-priority-class)") print(f"\nArmada files created in {output_dir}:") for f in armada_files: print(f" - {Path(f).name}") print("\nTo run (submit each step in order):") steps = ["setup-bucket", "convert", "plan", "pmtiles", "pmtiles-parts", "pmtiles-overview", "hex", "repartition", "pmtiles-merge"] for step in steps: armada_file = output_path / f"armada-{k8s_name}-{step}.yaml" if armada_file.exists(): print(f" armadactl submit {output_dir}/armada-{k8s_name}-{step}.yaml") print("\nMonitor at: https://armada-lookout.nrp-nautilus.io") else: print(f"\n✓ Generated complete workflow for {dataset_name}") print(f"\nFiles created in {output_dir}:") print(f" - {k8s_name}-setup-bucket.yaml") print(f" - {k8s_name}-convert.yaml") if planned: print(f" - {k8s_name}-plan.yaml") if pmtiles_chunks is not None: print(f" - {k8s_name}-pmtiles-parts.yaml") print(f" - {k8s_name}-pmtiles-overview.yaml") print(f" - {k8s_name}-pmtiles-merge.yaml") else: print(f" - {k8s_name}-pmtiles.yaml") print(f" - {k8s_name}-hex.yaml" + (" (upper bound; the workflow sizes it to the plan)" if planned else "")) print(f" - {k8s_name}-repartition.yaml") print(" - workflow-rbac.yaml (generic, reusable)") print(" - configmap.yaml (job configs)") print(" - workflow.yaml (orchestrator)") print("\nTo run:") print(" # One-time RBAC setup") print(f" kubectl apply -f {output_dir}/workflow-rbac.yaml") print("") print(" # Apply all workflow files (safe to re-run)") print(f" kubectl apply -f {output_dir}/configmap.yaml") print(f" kubectl apply -f {output_dir}/workflow.yaml") print("") print(" # Monitor progress") print(f" kubectl logs -f job/{k8s_name}-workflow") print("") print(" # Clean up") print(f" kubectl delete -f {output_dir}/workflow.yaml") print(f" kubectl delete -f {output_dir}/configmap.yaml")
def _count_chunks(chunk_resolution: int, h0_subset: Optional[List[int]]) -> Optional[int]: """The number of chunks a fan-out has at *chunk_resolution*, or None at 0. Bounded before it is enumerated, and enumerated by the same function a pod indexes into, so the Job and the chunk list cannot disagree (issue #173). Shared by the raster and mdim generators (#181). """ if not chunk_resolution: return None # Bound the fan-out *before* enumerating it: 7 children per level is an # upper bound (pentagons have six), so this over-estimates in the safe # direction and costs nothing. upper_bound = (len(h0_subset) if h0_subset else 122) * 7 ** chunk_resolution if upper_bound > MAX_CHUNK_COUNT: raise ValueError( f"chunk-resolution {chunk_resolution} would fan out to as many as " f"{upper_bound:,} chunks, past the {MAX_CHUNK_COUNT:,} ceiling. Each " f"chunk is a pod that schedules, pulls the image and reads the source, " f"so this trades a memory problem for a scheduling one — and " f"enumerating a list that size would hang generation itself. Use a " f"coarser --chunk-resolution, or narrow the build with --h0-subset." ) from cng_datasets.raster.cog import enumerate_chunk_cells chunk_count = len(enumerate_chunk_cells(chunk_resolution, h0_subset=h0_subset)) if chunk_count == 0: raise ValueError( f"No chunks at chunk-resolution {chunk_resolution} for h0 subset " f"{h0_subset}. Check --h0-subset." ) return chunk_count
[docs] def generate_raster_workflow( dataset_name: str, source_urls: Union[str, List[str]], bucket: str, output_dir: str = ".", namespace: Optional[str] = None, image: str = "ghcr.io/boettiger-lab/datasets:latest", git_repo: str = "https://github.com/boettiger-lab/datasets.git", h3_resolution: int = 8, parent_resolutions: Optional[List[int]] = None, value_column: str = "value", nodata_value: Optional[float] = None, hex_resampling: str = "mean", hex_memory: str = "32Gi", max_parallelism: int = 61, h0_subset: Optional[List[int]] = None, hex_storage: str = "20Gi", hex_workers: Optional[int] = None, hex_chunk_size: int = DEFAULT_HEX_CHUNK_SIZE, hex_cpu: str = DEFAULT_HEX_CPU, chunk_resolution: int = 0, max_hex_memory: Optional[str] = None, hex_retries: int = DEFAULT_HEX_RETRIES, max_failed_indexes: int = DEFAULT_MAX_FAILED_INDEXES, merge_memory: str = "16Gi", merge_storage: str = "50Gi", cog_storage: str = "50Gi", target_extent: Optional[tuple] = None, target_resolution: Optional[float] = None, band: Optional[int] = None, output_cog_name: Optional[str] = None, years: Union[str, List[int], None] = None, cutline: Optional[str] = None, cutline_where: Optional[str] = None, value_units: Optional[str] = None, backend: str = "k8s", armada_priority_class: Optional[str] = None, armada_queue: Optional[str] = None, # Cluster/storage configuration — all default to None so explicit values # can be distinguished from "not set" when merging with a profile. profile: Optional[str] = None, s3_endpoint: Optional[str] = None, s3_public_endpoint: Optional[str] = None, s3_secret_name: Optional[str] = None, rclone_secret_name: Optional[str] = None, rclone_remote: Optional[str] = None, priority_class: Optional[str] = None, node_affinity: Optional[str] = None, # backwards compat source_url: Optional[str] = None, ): """ Generate complete workflow for a raster dataset. Creates all necessary Kubernetes job configurations: - Single COG source URL: setup-bucket → hex - Single non-COG source URL: setup-bucket → preprocess-cog → hex (auto-detected) - Multiple source URLs (or target_extent/band): setup-bucket → preprocess-cog → hex The preprocess-cog step mosaics/converts tiles (handling mixed CRS such as multiple UTM zones), optionally clips to target_extent, and writes a single WGS84 COG to S3 that the hex job then reads. Non-COG sources are automatically detected and converted because GDAL must scan the entire file per pod without COG block/overview structure, causing catastrophic slowdowns on large rasters. Args: dataset_name: Name of the dataset (e.g., "wyoming/rap-arte") source_urls: URL(s) to source raster tile(s). Repeat for multi-tile mosaics. bucket: S3 bucket for outputs output_dir: Directory to write YAML files namespace: Kubernetes namespace image: Container image to use h3_resolution: Target H3 resolution for tiling (default: 8) parent_resolutions: List of parent H3 resolutions (default: [0]) value_column: Name for raster value column (default: "value") nodata_value: NoData value(s) to exclude (optional). A single value, a list, or a comma-separated string ("-9999,-1111,32767") for categorical products with multiple fill codes — all are collapsed to the first in the COG step and excluded from hex tiling (issue #108). hex_resampling: Area-weighted reducer for H3 aggregation (default: "mean"). Use "sum" for counts/stocks (population, carbon), "mean" for intensities (NDVI, indices), "mode" for categorical (land cover) to preserve class codes — averaging yields meaningless non-canonical values. Use "fractions" for categorical area accounting: per-class coverage rows (value, frac) per cell so areas are exact, not mode-biased (#142). hex_memory: Memory per hex pod (default: "32Gi") max_parallelism: Max parallel hex pods (default: 61) h0_subset: Positions in the h0 grid's ordering that the source actually overlaps, e.g. [12, 14, 20, 50, 71, 78] for CONUS. The hex job then runs one completion per listed cell instead of all 122, and the completion index selects from the list. Omit for a global source (issue #191). These are **not** H3 base cell numbers — the CONUS set is base cells 9, 19, 20, 21, 34, 36 — and both numberings run 0-121, so the wrong one is always in range (issue #213); the CLI takes base cell numbers via --h0-cells. hex_workers: Worker processes per hex pod, emitted as CNG_HEX_WORKERS. Defaults to hex_cpu, i.e. one worker per requested core. This is the memory lever: peak RSS is roughly workers x hex_chunk_size x bytes per cell, and unlike hex_memory it stays schedulable — a larger memory request on an already-scarce large-RAM node turns a retryable OOM into an unschedulable pod (issue #195). hex_chunk_size: Cells per exact_extract call, emitted as CNG_HEX_CHUNK_SIZE (default 100000). The other half of the peak-RSS product; lower it when fewer workers alone is too coarse a step. hex_cpu: CPU request and limit per hex pod (default "4"). chunk_resolution: H3 resolution of one hex pod's unit of work. 0 (default) is one h0 base cell, as before. A higher value splits each h0 into its res-N descendants, cutting the largest chunk's cell count — and so the pod's peak memory — about sevenfold per level (issue #173). Sub-h0 builds gain a merge step that restores the published one-file-per-partition layout. max_hex_memory: Pick chunk_resolution automatically as the coarsest that fits this budget, e.g. "8Gi". Mutually exclusive with an explicit chunk_resolution. Coarsest rather than finest because each extra level multiplies the pod count sevenfold. merge_memory: Memory for the merge pod (default "16Gi"). It streams one partition at a time, so this does not track the dataset's size. merge_storage: Ephemeral storage for the merge pod (default "50Gi", the house limit — see the note on quota norms in _generate_raster_merge_job). The merge holds one partition at a time and deletes it after upload, so it does not scale with the dataset. hex_retries: Per-index retry budget for the hex fan-out (backoffLimitPerIndex, default 2). A preemption is already ignored by the pod failure policy; this covers everything else that can end a multi-hour pod — an OOM, a truncated read, a node going away (issue #201). max_failed_indexes: How many indexes may exhaust their retries before the Job stops (default 1). Keeps a systematic failure from burning hours on the remaining chunks. target_extent: Clip bbox (xmin, ymin, xmax, ymax) in EPSG:4326 for mosaic step cutline: Polygon layer (path or URL) the COG step clips to, e.g. a country boundary (#344). Adds the preprocess-cog step even for one source. Pixels outside become nodata; a source already in EPSG:4326 keeps its grid and its values. Excludes target_extent. cutline_where: Attribute filter on the cutline, e.g. "iso3 = 'PER'". value_units: Units of the source values, e.g. "Mg/ha" (#105). Required by hex_resampling="total"; a per-area unit is refused with "sum". target_resolution: Output pixel size in degrees for mosaic step band: Extract single band from multi-band sources (1-indexed) for mosaic step output_cog_name: S3 key for intermediate COG (default: "{dataset_name}-cog.tif", or "{dataset_name}-{year}-cog.tif" with years) years: Build one raster per year (issue #172): a list, or a spec like "1985,1990,2015-2025". Every source URL holding a ``{year}`` placeholder is read once per year. Each year gets its own COG, and the hex output is one collection partitioned by year, ``hex/year=<year>/h0=<cell>/data_0.parquet``, so a query filters on ``year`` and a cross-year change is a self-join on the cell. armada_priority_class: Armada priority class for the `armada` backend — a literal name ("armada-default") or a shorthand ("default", "preemptible", "high"). Defaults to non-preemptible (issue #183). Ignored when backend is "k8s". source_url: Deprecated alias for source_urls (single URL). """ # backwards compat if source_url is not None and source_urls is None: source_urls = source_url if isinstance(source_urls, str): source_urls = [source_urls] config = cluster_config_from_args( profile=profile, s3_endpoint=s3_endpoint, s3_public_endpoint=s3_public_endpoint, s3_secret_name=s3_secret_name, rclone_secret_name=rclone_secret_name, rclone_remote=rclone_remote, priority_class=priority_class, node_affinity=node_affinity, armada_queue=armada_queue, ) # Namespace comes from the profile unless the caller named one, so a site # changes it in one place. The Armada queue follows the namespace unless it # is set separately — they are 1:1 on NRP by convention, not by the format. namespace = namespace or config.namespace armada_queue = config.armada_queue or namespace manager = K8sJobManager(namespace=namespace, image=image) output_path = Path(output_dir) output_path.mkdir(parents=True, exist_ok=True) k8s_name = dataset_name.replace('_', '-').replace('/', '-').lower() _validate_k8s_name(k8s_name, dataset_name) # A categorical layer is usually built twice from one COG, once as `mode` # and once as `fractions`. The two tables have different schemas, so they # get their own hex tree, job names and checksums file; with shared ones, # the second build overwrote the first and its `kubectl apply` collided # with the first build's jobs (issue #343). The COG and its render are # the same for both (both resample it with `mode`), so those stay shared. hex_dir = hex_dir_name(hex_resampling) if hex_resampling == "fractions": k8s_name = f"{k8s_name}-fractions" checksums_stem = f"{dataset_name}-fractions" else: checksums_stem = dataset_name if parent_resolutions is None: parent_resolutions = [0] h0_subset = _normalize_h0_subset(h0_subset) # A multi-year build reads each year from its own source (issue #172). A # template without the placeholder would hex one raster N times over, and # a placeholder without --years would be read literally. years = parse_years(years) templated = [u for u in source_urls if "{year}" in u] if years and not templated: raise ValueError( "--years needs a {year} placeholder in --source-url, e.g. " "'s3://bucket/Annual_NLCD_LndCov_{year}_CU_C1V2.tif'; without one " "every year would read the same raster.") if templated and not years: raise ValueError( f"--source-url {templated[0]!r} has a {{year}} placeholder; pass " "--years to say which years to build.") if years and output_cog_name and "{year}" not in output_cog_name: raise ValueError( "--output-cog-name needs a {year} placeholder with --years, or every " "year would write the same COG.") # Resolve the hex pod's sizing before anything is written, so an unusable # knob fails the generation outright rather than leaving a partial workflow # on disk for the next kubectl apply to pick up (issue #195). hex_cpu = str(hex_cpu).strip() hex_workers = _resolve_hex_workers(hex_workers, hex_cpu) hex_chunk_size = _validate_hex_chunk_size(hex_chunk_size) if max_hex_memory is not None and chunk_resolution: raise ValueError( "max_hex_memory and chunk_resolution both given: the first picks the " "second. Pass one." ) auto_chunking = max_hex_memory is not None if auto_chunking: chunk_resolution = select_chunk_resolution(h3_resolution, max_hex_memory) if chunk_resolution < 0: raise ValueError(f"chunk_resolution must be >= 0, got {chunk_resolution}") if chunk_resolution > h3_resolution: raise ValueError( f"chunk_resolution {chunk_resolution} is finer than --h3-resolution " f"{h3_resolution}; a chunk would contain no cells" ) # The fan-out and the list a pod indexes into come from one enumeration, so # they cannot disagree — a Job narrower than the chunk list would drop whole # chunks with a clean exit (issue #173). chunk_count = _count_chunks(chunk_resolution, h0_subset) # A reducer that contradicts the declared units fails here, before # anything is written (#105). from cng_datasets.raster.cog import check_value_units check_value_units(hex_resampling, value_units) if hex_resampling == "sum" and not value_units: print(" ⚠ --hex-resampling sum adds the pixel values, which is right only for an " "amount per pixel (persons, tonnes). For a per-area density (Mg/ha, " "persons/km2) use total with --value-units, or mean. Pass --value-units " "to declare which this is.") if cutline_where and not cutline: raise ValueError("--cutline-where needs --cutline") if cutline and target_extent is not None: raise ValueError("--cutline and --target-extent both given; the cutline sets " "the extent. Pass one.") # Decide whether a preprocess-cog step is needed. A clip or a new # resolution always needs it, even for one source that is already a COG. needs_preprocess = (len(source_urls) > 1 or target_extent is not None or target_resolution is not None or band is not None or cutline is not None) # For single-source case, check if the source is already a COG. Non-COG rasters # force GDAL to scan the entire file for every hex pod, causing catastrophic slowdowns # (e.g. GHS-POP 10.9 GB stalled 32+ hours per pod vs 25 min after COG conversion). if not needs_preprocess: from cng_datasets.raster.cog import is_cog # One year stands for the series: opening every year's source would # make generation slow, and a series is one product in one format. if not is_cog(source_urls[0].replace("{year}", str(years[0]) if years else "")): print(" ⚠ Source raster is not a COG — adding preprocess-cog step to convert before hex tiling") needs_preprocess = True if needs_preprocess: cog_key = output_cog_name or ( f"{dataset_name}-{{year}}-cog.tif" if years else f"{dataset_name}-cog.tif") cog_s3_url = f"s3://{bucket}/{cog_key}" hex_input_url = cog_s3_url else: cog_key = None hex_input_url = source_urls[0] # Generate bucket setup job _generate_setup_bucket_job(manager, k8s_name, bucket, output_path, git_repo, config) # Generate preprocess-cog job when needed if needs_preprocess: _generate_cog_preprocess_job( manager, k8s_name, source_urls, cog_s3_url, output_path, target_extent=target_extent, target_resolution=target_resolution, band=band, nodata_value=nodata_value, hex_resampling=hex_resampling, cog_storage=cog_storage, cutline=cutline, cutline_where=cutline_where, config=config, years=years, max_parallelism=max_parallelism, max_failed_indexes=max_failed_indexes, ) # The hex job excludes nodata. When a preprocess-cog step runs it has # already collapsed every fill code to the primary value, so the hex job # only needs that one (issue #108) — handing it the full list would make # each hex pod redundantly re-remap the whole COG. Without preprocess the # source is untouched, so the full list is passed through. hex_nodata = _primary_nodata_cli_value(nodata_value) if needs_preprocess else nodata_value # Generate raster hex tiling job _generate_raster_hex_job( manager, k8s_name, hex_input_url, bucket, output_path, git_repo, h3_resolution, parent_resolutions, value_column, hex_nodata, hex_memory, max_parallelism, hex_storage=hex_storage, hex_resampling=hex_resampling, config=config, s3_dataset=dataset_name, h0_subset=h0_subset, hex_workers=hex_workers, hex_chunk_size=hex_chunk_size, hex_cpu=hex_cpu, chunk_resolution=chunk_resolution, chunk_count=chunk_count, hex_retries=hex_retries, max_failed_indexes=max_failed_indexes, years=years, hex_dir=hex_dir, value_units=value_units, ) per_year = chunk_count if chunk_resolution else (len(h0_subset) if h0_subset else 122) hex_completions = per_year * (len(years) if years else 1) if chunk_resolution: _generate_raster_merge_job( manager, k8s_name, bucket, output_path, s3_dataset=dataset_name, merge_memory=merge_memory, merge_storage=merge_storage, config=config, expect_chunks=chunk_count, years=years, hex_dir=hex_dir, usage_stem=checksums_stem, # What the measured use is valid for: a later build is the same # shape only if all of these match (#308). build_shape=dict( workflow="raster", source=source_urls, hex_input=hex_input_url, h3_resolution=h3_resolution, chunk_resolution=chunk_resolution, hex_resampling=hex_resampling, parent_resolutions=parent_resolutions, h0_subset=h0_subset, target_resolution=target_resolution, hex_workers=hex_workers, hex_chunk_size=hex_chunk_size, ), ) # Sizes and checksums of the outputs, for their STAC assets (#340). A # source that was already a COG is not an output, so only a COG this # workflow wrote is listed. checksum_targets = [] if cog_key: cogs = ([f"s3://{bucket}/{cog_key.replace('{year}', str(y))}" for y in years] if years else [f"s3://{bucket}/{cog_key}"]) checksum_targets += cogs # Default render and thumbnail of each COG this workflow wrote (#340). _generate_render_job(manager, k8s_name, bucket, output_path, cogs, s3_dataset=dataset_name, config=config) checksum_targets.append(f"s3://{bucket}/{dataset_name}/{hex_dir}/") _generate_checksums_job(manager, k8s_name, bucket, output_path, checksum_targets, s3_dataset=checksums_stem, config=config) # Generate workflow RBAC _generate_workflow_rbac(namespace, output_path) # Build generation command for documentation parent_res_str = ','.join(map(str, parent_resolutions)) source_flags = ' '.join(f'--source-url "{u}"' for u in source_urls) gen_command = (f"cng-datasets raster-workflow --dataset {dataset_name} " f"{source_flags} --bucket {bucket} " f"--h3-resolution {h3_resolution} --parent-resolutions \"{parent_res_str}\"") if years: gen_command += f" --years {','.join(str(y) for y in years)}" if cutline: gen_command += f" --cutline {shlex.quote(cutline)}" if cutline_where: gen_command += f" --cutline-where {shlex.quote(cutline_where)}" if value_units: gen_command += f" --value-units {shlex.quote(value_units)}" gen_command += f" --hex-resampling {hex_resampling}" # Generate ConfigMap and orchestrator workflow _generate_raster_configmap(k8s_name, namespace, output_path, gen_command, needs_preprocess, needs_merge=bool(chunk_resolution)) _generate_raster_argo_workflow(k8s_name, namespace, output_path, output_dir, needs_preprocess, needs_merge=bool(chunk_resolution), wait_scale=len(years) if years else 1) # The hex pod's memory profile, stated at generation time. Peak RSS tracks # workers × chunk size, and both are now pinned in the manifest; printing # the product is what makes an oversubscribed pod visible before it is # applied rather than after it OOMs (issue #195). hex_profile = ( f" Hex pod: cpu {hex_cpu}, memory {hex_memory}, " f"{hex_workers} workers × {hex_chunk_size} cells/chunk" ) hex_profile_hint = ( " Peak memory scales with that product — lower --hex-workers first " "(a bigger --hex-memory can make the pod unschedulable)" ) if chunk_resolution: est = estimate_chunk_peak_bytes(h3_resolution, chunk_resolution) chosen = (f" (chosen for --max-hex-memory {max_hex_memory})" if auto_chunking else "") hex_profile_hint += ( f"\n Chunking: res-{chunk_resolution} cells, {chunk_count} chunks{chosen}" f"\n Estimated peak per pod ≈ {est / 2 ** 30:.1f} GiB against a " f"{hex_memory} request. This models the cell enumeration, which is the " f"term that scales with chunk size — it is a floor, not a guarantee." f"\n Merge: {k8s_name}-merge consolidates {hex_dir}-chunks/ into " f"{hex_dir}/h0=*/data_0.parquet" ) # Fine chunking is what makes an external queue necessary: an indexed Job of # thousands of completions is past the namespace pod guideline, and small # uniform pods schedule on any node (issue #173 lever D, #39). # A multi-year build multiplies the fan-out by its year count (#172), so # the guideline is checked against the Job's completions, not the chunks. if backend == "auto": backend = "armada" if hex_completions > K8S_CHUNK_COUNT_GUIDELINE else "k8s" print(f" Backend: {backend} (--backend auto; {hex_completions} hex " f"completions vs the {K8S_CHUNK_COUNT_GUIDELINE}-pod k8s guideline)") elif backend == "k8s" and hex_completions > K8S_CHUNK_COUNT_GUIDELINE: print(f" ⚠ {hex_completions} hex completions exceeds the " f"~{K8S_CHUNK_COUNT_GUIDELINE}-pod namespace guideline for a single indexed Job.") print(" Consider --backend armada (or --backend auto), which has no pod cap.") if backend == "armada": armada_files = convert_workflow_to_armada( k8s_yaml_dir=str(output_path), dataset_name=k8s_name, queue=armada_queue, priority_class=armada_priority_class, max_cpu=config.armada_max_cpu, max_memory=config.armada_max_memory, ) effective_priority = ( resolve_armada_priority_class(armada_priority_class) or DEFAULT_ARMADA_PRIORITY_CLASS ) print(f"\n✓ Generated Armada raster workflow for {dataset_name}") print(f" Armada priority class: {effective_priority} " f"(override with --armada-priority-class)") print(hex_profile) print(hex_profile_hint) print(f"\nArmada files created in {output_dir}:") for f in armada_files: print(f" - {Path(f).name}") print("\nTo run (submit each step in order):") steps = ["setup-bucket"] if needs_preprocess: steps.append("preprocess-cog") steps.append("hex") if chunk_resolution: steps.append("merge") for step in steps: print(f" armadactl submit {output_dir}/armada-{k8s_name}-{step}.yaml") print("\nMonitor at: https://armada-lookout.nrp-nautilus.io") else: print(f"\n✓ Generated raster workflow for {dataset_name}") if chunk_resolution: print(f" Hex completions: {chunk_count} " f"(res-{chunk_resolution} chunks" + (f" under h0 grid positions {', '.join(str(h) for h in h0_subset)}" if h0_subset else "") + ")") elif h0_subset: print(f" Hex completions: {len(h0_subset)} " f"(h0 grid positions {', '.join(str(h) for h in h0_subset)})") else: print(" Hex completions: 122 (every h0 cell) — pass --h0-subset " "or --h0-cells to skip the ones the source does not cover") if years: print(f" Years: {len(years)} ({years[0]}–{years[-1]}), so {hex_completions} " f"hex completions in all, written to " f"s3://{bucket}/{dataset_name}/{hex_dir}/year=<year>/") elif hex_dir != "hex": print(f" Hex output: s3://{bucket}/{dataset_name}/{hex_dir}/") print(hex_profile) print(hex_profile_hint) print(f"\nFiles created in {output_dir}:") print(f" - {k8s_name}-setup-bucket.yaml") if needs_preprocess: print(f" - {k8s_name}-preprocess-cog.yaml (mosaic {len(source_urls)} tiles → {cog_key})") print(f" - {k8s_name}-hex.yaml") if chunk_resolution: print(f" - {k8s_name}-merge.yaml") print(" - workflow-rbac.yaml") print(" - configmap.yaml") print(" - workflow.yaml") print("\nTo run:") print(f" kubectl apply -f {output_dir}/workflow-rbac.yaml # one-time") print(f" kubectl apply -f {output_dir}/configmap.yaml -f {output_dir}/workflow.yaml")
def _generate_cog_preprocess_job( manager, dataset_name, source_urls, output_cog_url, output_path, target_extent=None, target_resolution=None, band=None, nodata_value=None, hex_resampling="mean", cog_storage="50Gi", config: ClusterConfig = None, years: Optional[List[int]] = None, max_parallelism: int = 61, max_failed_indexes: int = DEFAULT_MAX_FAILED_INDEXES, cutline: Optional[str] = None, cutline_where: Optional[str] = None, ): """Generate a k8s job that mosaics multiple raster tiles into a single COG on S3. With *years* (issue #172) it is an indexed Job, one year per completion, and the source URLs and output COG URL hold a ``{year}`` placeholder. """ if config is None: config = ClusterConfig() # Assemble all CLI flags as a list and join with " \\\n " so the line # continuations are always well-formed and the final flag carries no # trailing backslash (a missing/extra backslash silently breaks the # multi-line shell command). if years: source_urls = [_year_template(u) for u in source_urls] output_cog_url = _year_template(output_cog_url) flags = [f'--input "{u}"' for u in source_urls] flags.append(f'--output-cog "{output_cog_url}"') flags.append("--target-crs EPSG:4326") # Bilinear invents class codes at every boundary of a categorical source, # so those warp with nearest (issue #272). categorical = hex_resampling in ("mode", "fractions") flags.append(f"--resampling {'nearest' if categorical else 'bilinear'}") if target_extent is not None: xmin, ymin, xmax, ymax = target_extent flags.append(f'--target-extent "{xmin},{ymin},{xmax},{ymax}"') if target_resolution is not None: flags.append(f"--target-resolution {target_resolution}") if cutline is not None: flags.append(f"--cutline {shlex.quote(cutline)}") if cutline_where: flags.append(f"--cutline-where {shlex.quote(cutline_where)}") if band is not None: flags.append(f"--band {band}") nodata_cli = _nodata_cli_value(nodata_value) if nodata_cli is not None: flags.append(f'--nodata "{nodata_cli}"') # Carry the reducer into the COG step so a categorical source builds # mode (not average) overviews and collapses all fill codes (issue #108). flags.append(f"--hex-resampling {hex_resampling}") flag_block = " \\\n ".join(flags) # PROJ database selection is handled deterministically inside the CLI # (cog._configure_proj picks the highest-version proj.db, MINOR>=7). A bash # `find ... | head -1` here would be non-deterministic and could export a # stale PROJ_DATA — see issue #91. year_preamble = _year_preamble(years, 1) if years else "" command_str = f"""set -e {year_preamble}echo "Mosaicking {len(source_urls)} tiles → {output_cog_url}" cng-datasets raster \\ {flag_block} echo "✓ Preprocess COG complete: {output_cog_url}" """ pod_spec = { "restartPolicy": "Never", "volumes": [ {"name": "rclone-config", "secret": {"secretName": config.rclone_secret_name}} ], "containers": [{ "name": "preprocess-cog", "image": "ghcr.io/boettiger-lab/datasets:latest", "imagePullPolicy": "Always", "env": _s3_env_vars(config) + [ {"name": "GDAL_CACHEMAX", "value": "4096"}, {"name": "GDAL_HTTP_TIMEOUT", "value": "60"}, {"name": "GDAL_HTTP_MAX_RETRY", "value": "5"}, ], "volumeMounts": [ {"name": "rclone-config", "mountPath": "/root/.config/rclone", "readOnly": True} ], "command": ["bash", "-c", command_str], "resources": { "requests": {"cpu": "8", "memory": "32Gi", "ephemeral-storage": cog_storage}, "limits": {"cpu": "8", "memory": "32Gi", "ephemeral-storage": cog_storage}, }, }], } _apply_scheduling(pod_spec, config) if years: # One year per index, each with its own retry budget, so one year's # transient failure does not abort the others (#172, #201). run_spec = { "completions": len(years), "parallelism": min(max_parallelism, len(years)), "completionMode": "Indexed", **_indexed_retry_spec(1, max_failed_indexes), } else: run_spec = {"completions": 1, "parallelism": 1, "backoffLimit": 1} job_spec = { "apiVersion": "batch/v1", "kind": "Job", "metadata": _job_metadata(manager, f"{dataset_name}-preprocess-cog"), "spec": { **run_spec, "ttlSecondsAfterFinished": 86400, "template": { "metadata": {"labels": {"k8s-app": f"{dataset_name}-preprocess-cog"}}, "spec": pod_spec, }, }, } manager.save_job_yaml(job_spec, str(output_path / f"{dataset_name}-preprocess-cog.yaml")) def _time_units(t, time_agg: str, time_start: Optional[str], time_end: Optional[str], steps: int): """(starts, ends) as YYYY-MM-DD strings: consecutive runs of whole --time-agg keys, each about *steps* time steps, covering the requested window (#267). Cuts fall only between keys, so no month or year is split between units; the merge step concatenates units, which is correct only under that rule. """ import numpy as np from cng_datasets.mdim.processor import _date_key key = t.year.astype(np.int64) * 10000 + t.month * 100 + t.day mask = np.ones(len(key), dtype=bool) if time_start: mask &= key >= _date_key(time_start) if time_end: mask &= key <= _date_key(time_end) idx = np.nonzero(mask)[0] if len(idx) == 0: raise ValueError(f"no time steps between {time_start} and {time_end}") if time_agg == "year": group = t.year.astype(np.int64) elif time_agg == "month": group = t.year.astype(np.int64) * 12 + t.month else: group = np.arange(len(key)) steps = max(1, int(steps)) def fmt(i): return f"{int(t.year[i]):04d}-{int(t.month[i]):02d}-{int(t.day[i]):02d}" starts, ends = [], [] first, count = idx[0], 0 for n, i in enumerate(idx): count += 1 last = n == len(idx) - 1 if last or (count >= steps and group[idx[n + 1]] != group[i]): starts.append(fmt(first)) ends.append(fmt(i)) if not last: first, count = idx[n + 1], 0 return starts, ends
[docs] def generate_mdim_workflow( dataset_name: str, inputs: Union[str, List[str]], variables: Union[str, List[str]], bucket: str, output_dir: str = ".", namespace: Optional[str] = None, image: str = "ghcr.io/boettiger-lab/datasets:latest", h3_resolution: int = 6, parent_resolutions: Optional[List[int]] = None, hex_resampling: str = "mean", time_agg: str = "none", time_start: Optional[str] = None, time_end: Optional[str] = None, placement: str = "auto", hex_memory: str = "16Gi", hex_cpu: str = "4", hex_storage: str = "10Gi", max_parallelism: int = 50, h0_subset: Optional[List[int]] = None, chunk_resolution: int = 0, hex_retries: int = DEFAULT_HEX_RETRIES, max_failed_indexes: int = DEFAULT_MAX_FAILED_INDEXES, merge_memory: str = "16Gi", merge_storage: str = "50Gi", validate_source: bool = True, fan_out: str = "auto", time_unit_steps: int = 365, backend: str = "k8s", armada_priority_class: Optional[str] = None, armada_queue: Optional[str] = None, profile: Optional[str] = None, s3_endpoint: Optional[str] = None, s3_public_endpoint: Optional[str] = None, s3_secret_name: Optional[str] = None, rclone_secret_name: Optional[str] = None, rclone_remote: Optional[str] = None, priority_class: Optional[str] = None, node_affinity: Optional[str] = None, ): """Generate the fan-out for a (time, lat, lon) cube (issue #181). setup-bucket -> hex (one `cng-datasets mdim` pod per chunk) -> merge (when chunk_resolution > 0). The same chunk list, output layout, merge step and orchestrator as `raster-workflow`, so the two products are interchangeable downstream. fan_out picks the axis the hex Job splits over (#267). "space" gives one pod per spatial chunk over all time. "time" gives one pod per time unit over every h0 — a unit per input file, or a single input split at --time-agg key boundaries into units of about time_unit_steps steps — with a merge step that concatenates the per-h0 parts. "auto" picks time when one chunk of the source spans the whole grid, where a spatial fan-out would make every pod fetch every chunk. validate_source opens the *first* input at generation time, so a wrong variable, an unsupported calendar or an empty time window fails here rather than in every pod. Only the first: a NEX-GDDP series is 86 remote files, and opening each would make generation take minutes. """ import shlex if isinstance(inputs, str): inputs = [inputs] if isinstance(variables, str): variables = [variables] if not inputs or not variables: raise ValueError("at least one input and one variable are required") from cng_datasets.mdim.processor import ( VALID_PLACEMENTS, VALID_REDUCERS, VALID_TIME_AGG) if hex_resampling == "sum": raise ValueError("--hex-resampling sum is refused for mdim: placement is not " "area-weighted. Use a 2-D COG and raster-workflow instead.") if hex_resampling not in VALID_REDUCERS: raise ValueError(f"hex_resampling must be one of {VALID_REDUCERS}") if time_agg not in VALID_TIME_AGG: raise ValueError(f"time_agg must be one of {VALID_TIME_AGG}") if placement not in VALID_PLACEMENTS: raise ValueError(f"placement must be one of {VALID_PLACEMENTS}") if not 0 <= chunk_resolution <= h3_resolution: raise ValueError(f"chunk_resolution must be between 0 and {h3_resolution}") config = cluster_config_from_args( profile=profile, s3_endpoint=s3_endpoint, s3_public_endpoint=s3_public_endpoint, s3_secret_name=s3_secret_name, rclone_secret_name=rclone_secret_name, rclone_remote=rclone_remote, priority_class=priority_class, node_affinity=node_affinity, armada_queue=armada_queue, ) namespace = namespace or config.namespace armada_queue = config.armada_queue or namespace manager = K8sJobManager(namespace=namespace, image=image) output_path = Path(output_dir) output_path.mkdir(parents=True, exist_ok=True) k8s_name = dataset_name.replace('_', '-').replace('/', '-').lower() _validate_k8s_name(k8s_name, dataset_name) parent_resolutions = parent_resolutions if parent_resolutions is not None else [0] h0_subset = _normalize_h0_subset(h0_subset) src = None if validate_source: from cng_datasets.mdim.reader import CubeSource src = CubeSource(inputs[:1], variables) dy, dx = src.pixel_deg t = src.time print(f" Source: {len(src.lat)}x{len(src.lon)} grid, {dy:g}x{dx:g} deg pixels, " f"chunks {src.block}, calendar {t.calendar}, first file " f"{t.year[0]}-{t.month[0]:02d}-{t.day[0]:02d} to " f"{t.year[-1]}-{t.month[-1]:02d}-{t.day[-1]:02d}") if time_agg == "none" and t.dates is None: raise ValueError(f"calendar {t.calendar!r} needs --time-agg month or year") # Which axis to fan out over (#267). A spatial fan-out reads only the tiles # under each pod's window — unless one chunk spans the whole grid, when # every pod must fetch every chunk (NEX-GDDP: ~122x the transfer). if fan_out not in ("auto", "space", "time"): raise ValueError("fan_out must be 'auto', 'space' or 'time'") if fan_out == "auto": whole_grid = (src is not None and src.block[src.axis["lat"]] >= len(src.lat) and src.block[src.axis["lon"]] >= len(src.lon)) fan_out = "time" if whole_grid else "space" reason = ("each chunk spans the whole grid" if whole_grid else "chunks are spatial tiles" if src is not None else "source not inspected (--no-validate-source)") print(f" Fan-out: {fan_out} ({reason})") if fan_out == "time" and chunk_resolution: raise ValueError("--chunk-resolution applies to the spatial fan-out; drop it " "with --fan-out time, where each pod covers every h0") _generate_setup_bucket_job(manager, k8s_name, bucket, output_path, None, config) common = [f"--variable {shlex.quote(v)}" for v in variables] common += [f"--resolution {h3_resolution}", f"--parent-resolutions {','.join(map(str, parent_resolutions))}", f"--hex-resampling {hex_resampling}", f"--time-agg {time_agg}", f"--placement {placement}"] if fan_out == "space": chunk_count = _count_chunks(chunk_resolution, h0_subset) completions, preamble, selector, out_url = _hex_fanout( bucket, dataset_name, chunk_resolution, chunk_count, h0_subset) flags = [f"--input {shlex.quote(i)}" for i in inputs] + common flags += [f"--output-parquet {out_url}", selector] if time_start: flags.append(f"--time-start {time_start}") if time_end: flags.append(f"--time-end {time_end}") merge_chunks = chunk_count if chunk_resolution else None else: out_url = f"s3://{bucket}/{dataset_name}/hex-chunks/" guard = ('if [ -z "${JOB_COMPLETION_INDEX}" ] || [ -z "$UNIT" ]; then\n' ' echo "No time unit for completion index ${JOB_COMPLETION_INDEX}" >&2\n' ' exit 1\nfi\n\n') flags = [] if len(inputs) > 1: # One unit per input file: NEX-GDDP ships a file per year. completions = len(inputs) preamble = ("# One time unit per input file (#267).\n" f"INPUTS=({' '.join(shlex.quote(i) for i in inputs)})\n" 'UNIT="${INPUTS[$JOB_COMPLETION_INDEX]}"\n' + guard) flags.append('--input "$UNIT"') if time_start: flags.append(f"--time-start {time_start}") if time_end: flags.append(f"--time-end {time_end}") else: if src is None: raise ValueError("--fan-out time on a single input splits its time axis, " "which needs the source inspected; drop --no-validate-source") starts, ends = _time_units(src.time, time_agg, time_start, time_end, time_unit_steps) completions = len(starts) preamble = ("# Time units split at --time-agg key boundaries (#267).\n" f"STARTS=({' '.join(starts)})\nENDS=({' '.join(ends)})\n" 'UNIT="${STARTS[$JOB_COMPLETION_INDEX]}"\n' + guard) flags.append(f"--input {shlex.quote(inputs[0])}") flags += ['--time-start "$UNIT"', '--time-end "${ENDS[$JOB_COMPLETION_INDEX]}"'] flags += common flags += [f"--output-parquet {out_url}", "--fan-out time", "--unit-index ${JOB_COMPLETION_INDEX}"] if h0_subset: flags.append(f"--h0-subset \"{','.join(str(h) for h in h0_subset)}\"") chunk_count = completions merge_chunks = completions command_str = "set -e\n\n" + preamble + "cng-datasets mdim \\\n " + " \\\n ".join(flags) env = _s3_env_vars(config) + [ {"name": "GDAL_DATA", "value": "/usr/share/gdal"}, {"name": "BUCKET", "value": bucket}, # Bound DuckDB to the pod (#227, #255) and GDAL's block cache, which # holds decoded chunks between slab reads. {"name": "DUCKDB_MEMORY_LIMIT", "value": _duckdb_memory_limit(hex_memory)}, {"name": "GDAL_CACHEMAX", "value": "1024"}, {"name": "GDAL_HTTP_MAX_RETRY", "value": "5"}, {"name": "GDAL_HTTP_RETRY_DELAY", "value": "2"}, # The cpu request, for the usage each chunk records (#183). {"name": "CNG_POD_CPU", "value": str(hex_cpu)}, ] resources = { "requests": {"cpu": str(hex_cpu), "memory": hex_memory, "ephemeral-storage": hex_storage}, "limits": {"cpu": str(hex_cpu), "memory": hex_memory, "ephemeral-storage": hex_storage}, } job_spec = _indexed_hex_job_spec( manager, k8s_name, command_str, env, resources, completions, max_parallelism, hex_retries, max_failed_indexes, config) manager.save_job_yaml(job_spec, str(output_path / f"{k8s_name}-hex.yaml")) if merge_chunks: _generate_raster_merge_job( manager, k8s_name, bucket, output_path, s3_dataset=dataset_name, merge_memory=merge_memory, merge_storage=merge_storage, config=config, expect_chunks=merge_chunks, build_shape=dict( workflow="mdim", source=inputs, variables=variables, h3_resolution=h3_resolution, chunk_resolution=chunk_resolution, hex_resampling=hex_resampling, parent_resolutions=parent_resolutions, h0_subset=h0_subset, time_agg=time_agg, time_start=time_start, time_end=time_end, placement=placement, ), ) # Sizes and checksums of the hex output (#340). The orchestrator shared # with raster-workflow applies this step, so it must exist here too. _generate_checksums_job(manager, k8s_name, bucket, output_path, [f"s3://{bucket}/{dataset_name}/hex/"], s3_dataset=dataset_name, config=config) _generate_workflow_rbac(namespace, output_path) gen_command = (f"cng-datasets mdim-workflow --dataset {dataset_name} " + " ".join(f"--input {shlex.quote(i)}" for i in inputs) + " " + " ".join(f"--variable {shlex.quote(v)}" for v in variables) + f" --bucket {bucket} --h3-resolution {h3_resolution} --fan-out {fan_out}") _generate_raster_configmap(k8s_name, namespace, output_path, gen_command, needs_preprocess=False, needs_merge=bool(merge_chunks)) _generate_raster_argo_workflow(k8s_name, namespace, output_path, output_dir, needs_preprocess=False, needs_merge=bool(merge_chunks)) if backend == "auto": backend = "armada" if (chunk_count or 0) > K8S_CHUNK_COUNT_GUIDELINE else "k8s" what = ("time units" if fan_out == "time" else f"res-{chunk_resolution} chunks" if chunk_resolution else "h0 cells") print(f"\n✓ Generated mdim workflow for {dataset_name}: {completions} hex completions " f"({what}), {len(inputs)} input(s), variables {', '.join(variables)}") if backend == "armada": files = convert_workflow_to_armada( k8s_yaml_dir=str(output_path), dataset_name=k8s_name, queue=armada_queue, priority_class=armada_priority_class, max_cpu=config.armada_max_cpu, max_memory=config.armada_max_memory) print("Armada files:", ", ".join(Path(f).name for f in files)) elif (chunk_count or 0) > K8S_CHUNK_COUNT_GUIDELINE: print(f" ⚠ {chunk_count} completions exceeds the ~{K8S_CHUNK_COUNT_GUIDELINE}-pod " f"guideline; consider --backend auto") print("To run:") print(f" kubectl apply -f {output_dir}/workflow-rbac.yaml # one-time") print(f" kubectl apply -f {output_dir}/configmap.yaml -f {output_dir}/workflow.yaml")
def _generate_raster_merge_job( manager, dataset_name, bucket, output_path, s3_dataset=None, merge_memory="16Gi", merge_storage="50Gi", config: ClusterConfig = None, expect_chunks: Optional[int] = None, years: Optional[List[int]] = None, hex_dir: str = "hex", usage_stem: Optional[str] = None, build_shape: Optional[dict] = None, ): """Generate the job that consolidates sub-h0 chunks into one file per h0. With *years* (issue #172) it merges each ``year=`` partition in turn, each against the same expected chunk count. Only emitted when --chunk-resolution > 0. Sub-h0 chunks each write their own part file, but `h0={cell}/data_0.parquet` is a literal path published in STAC READMEs, so the layout must not depend on how finely the build was chunked (issue #173). Merging is per partition and streamed, so this does not re-materialise what the chunking avoided. Storage is 50Gi rather than the 100Gi first shipped, to stay inside the house limits (50Gi ephemeral per pod, 200 pods). `geo-workflows` enforces neither — it carries no cpu, memory or pod quota, only priority-class bans — but `biodiversity` caps pods at 200, and a build that fits the stricter namespace stays portable between them. The merge holds one partition at a time and deletes it after upload, so it never needed the larger figure. """ if config is None: config = ClusterConfig() s3_dataset = s3_dataset or dataset_name # The generator sized the fan-out, so it is the only place that knows how # many chunks a complete build has. Passing it through means a partly failed # fan-out fails the merge instead of publishing its survivors (issue #173). expect_flag = (f" \\\n --expect-chunks {expect_chunks}" if expect_chunks is not None else "") # The measured use outlives the markers the merge purges, with the shape it # is valid for, so the next build can be sized from it (#369, #308). usage_stem = usage_stem or s3_dataset shape_flag = (f" \\\n --build-shape {shlex.quote(json.dumps(build_shape, sort_keys=True))}" if build_shape else "") usage_flag = (f" \\\n --usage-out " f"{usage_url(bucket, usage_stem, '$YEAR' if years else None)}{shape_flag}") if years: command_str = f"""set -e for YEAR in {' '.join(str(y) for y in years)}; do echo "Merging year=$YEAR" cng-datasets merge-chunks \\ --chunks-dir s3://{bucket}/{s3_dataset}/{hex_dir}-chunks/year=$YEAR \\ --output-dir s3://{bucket}/{s3_dataset}/{hex_dir}/year=$YEAR{(expect_flag + usage_flag).replace(chr(10) + " ", chr(10) + " ")} done """ else: command_str = f"""set -e cng-datasets merge-chunks \\ --chunks-dir s3://{bucket}/{s3_dataset}/{hex_dir}-chunks \\ --output-dir s3://{bucket}/{s3_dataset}/{hex_dir}{expect_flag}{usage_flag} """ pod_spec = { "restartPolicy": "Never", "containers": [{ "name": "merge-task", "image": "ghcr.io/boettiger-lab/datasets:latest", "imagePullPolicy": "Always", "env": _s3_env_vars(config) + [ {"name": "GDAL_DATA", "value": "/usr/share/gdal"}, {"name": "PYTHONPATH", "value": "/usr/lib/python3/dist-packages"}, {"name": "BUCKET", "value": bucket}, # The merge streams one partition at a time, but DuckDB will # happily size its buffers off the node rather than the pod # unless told otherwise. This has to carry DuckDB's spelling of # the quantity, not Kubernetes' — `SET memory_limit='16Gi'` is a # parser error, and it used to kill every merge on its first # statement, after the whole fan-out had run (issue #217). {"name": "DUCKDB_MEMORY_LIMIT", "value": _duckdb_memory_limit(merge_memory)}, ], "volumeMounts": [ {"name": "rclone-config", "mountPath": "/root/.config/rclone", "readOnly": True} ], "command": ["bash", "-c", command_str], "resources": { "requests": {"cpu": "4", "memory": merge_memory, "ephemeral-storage": merge_storage}, "limits": {"cpu": "4", "memory": merge_memory, "ephemeral-storage": merge_storage}, }, }], "volumes": [ {"name": "rclone-config", "secret": {"secretName": config.rclone_secret_name}} ], } _apply_scheduling(pod_spec, config) job_spec = { "apiVersion": "batch/v1", "kind": "Job", "metadata": _job_metadata(manager, f"{dataset_name}-merge"), "spec": { # One long job rather than a fan-out, so a plain job-wide budget is # the right shape — but not zero: it runs after hours of hex work # and a transient S3 failure should not throw that away (#201). "backoffLimit": 2, "ttlSecondsAfterFinished": 10800, "template": { "metadata": {"labels": {"k8s-app": f"{dataset_name}-merge"}}, "spec": pod_spec, }, }, } manager.save_job_yaml(job_spec, str(output_path / f"{dataset_name}-merge.yaml")) def _hex_fanout(bucket: str, s3_dataset: str, chunk_resolution: int, chunk_count: Optional[int], h0_subset: Optional[List[int]], index_var: str = "JOB_COMPLETION_INDEX", partition: str = "", hex_dir: str = "hex"): """(completions, shell preamble, chunk selector flags, output URL) for an indexed hex Job. Shared by the raster and mdim hex jobs (#181), so both fan out over the same chunk list and write where `merge-chunks` reads. *index_var* names the shell variable holding the unit index, and *partition* is a hive path segment such as "year=${YEAR}/" under the output; a multi-year build sets both (#172). Completions are per partition. *hex_dir* is the published hex tree's folder, staged in ``<hex_dir>-chunks`` (``hex-fractions`` for a fractions build, #343). """ # One completion per unit of work: the chunk list at chunk_resolution, or # the h0 fan-out as before. Emitting fewer than the chunk list holds would # drop whole chunks with a clean exit, so this number and the list a pod # indexes into come from the same enumeration. if chunk_resolution: if chunk_count is None: raise ValueError("chunk_count is required when chunk_resolution > 0") completions = chunk_count else: completions = len(h0_subset) if h0_subset else 122 # dataset_name is the k8s name, with '/' flattened to '-' so it is a legal # object name. S3 paths want the original hierarchical name, as the vector # generators already do for their own jobs (issue #189). # One completion per h0 cell the build actually needs. Without a subset # every raster fans out over all 122 base cells, so a regional source # starts a large majority of pods that localize the whole COG, find no # overlap with their h0 and exit (issue #191). h0_index = "${" + index_var + "}" h0_preamble = "" if h0_subset and not chunk_resolution: h0_index = "${H0}" # The guard matters because the lookup is indirect: an unset index # would read as 0 and an index past the end would expand to nothing, # either way processing the wrong cell (or none) and still exiting 0. # It also catches the manifest being hand-edited to more completions # than the list has cells. Written with the plain ${JOB_COMPLETION_INDEX} # form so it stays valid bash after the Armada converter rewrites that # to a literal index. h0_preamble = ( "# Positions in the h0 grid's own ordering, not H3 base cell numbers\n" "# (--h0-subset / --h0-cells). The completion index selects one.\n" f"H0S=({' '.join(str(h) for h in h0_subset)})\n" f"H0=${{H0S[${index_var}]}}\n" 'if [ -z "${JOB_COMPLETION_INDEX}" ] || [ -z "$H0" ]; then\n' ' echo "No h0 cell for completion index ' "'${JOB_COMPLETION_INDEX}' in (${H0S[*]}) — completions must match " 'the --h0-subset length" >&2\n' " exit 1\n" "fi\n\n" ) if chunk_resolution: # Sub-h0 chunks are staged outside the published tree and merged back by # the merge step, so a reader globbing hex/ mid-build never sees parts. out_url = f"s3://{bucket}/{s3_dataset}/{hex_dir}-chunks/{partition}" selector = f"--chunk-resolution {chunk_resolution} --chunk-index {h0_index}" if h0_subset: selector += f" --h0-subset \"{','.join(str(h) for h in h0_subset)}\"" else: out_url = f"s3://{bucket}/{s3_dataset}/{hex_dir}/{partition}" selector = f"--h0-index {h0_index}" return completions, h0_preamble, selector, out_url def _indexed_hex_job_spec(manager, dataset_name, command_str, env, resources, completions, max_parallelism, hex_retries, max_failed_indexes, config: ClusterConfig, volumes=None, volume_mounts=None): """The indexed hex Job around *command_str*: retries per index, preemption ignored, parallelism capped at the completions (#201).""" container = { "name": "hex-task", "image": "ghcr.io/boettiger-lab/datasets:latest", "imagePullPolicy": "Always", "env": env, "command": ["bash", "-c", command_str], "resources": resources, } if volume_mounts: container["volumeMounts"] = volume_mounts pod_spec = {"restartPolicy": "Never", "containers": [container]} if volumes: pod_spec["volumes"] = volumes _apply_scheduling(pod_spec, config) return { "apiVersion": "batch/v1", "kind": "Job", "metadata": _job_metadata(manager, f"{dataset_name}-hex"), "spec": { "completions": completions, # No point starting more pods than there are completions — the # extras would sit against the namespace quota with nothing to do. "parallelism": min(max_parallelism, completions), "completionMode": "Indexed", **_indexed_retry_spec(hex_retries, max_failed_indexes), "podFailurePolicy": { "rules": [{ "action": "Ignore", "onPodConditions": [{"type": "DisruptionTarget"}] }] }, "ttlSecondsAfterFinished": 10800, "template": { "metadata": {"labels": {"k8s-app": f"{dataset_name}-hex"}}, "spec": pod_spec, } } } def _generate_raster_hex_job( manager, dataset_name, source_url, bucket, output_path, git_repo, h3_resolution, parent_resolutions, value_column, nodata_value, hex_memory, max_parallelism, hex_storage="20Gi", hex_resampling: str = "mean", config: ClusterConfig = None, s3_dataset=None, h0_subset: Optional[List[int]] = None, hex_workers: Optional[int] = None, hex_chunk_size: int = DEFAULT_HEX_CHUNK_SIZE, hex_cpu: str = DEFAULT_HEX_CPU, chunk_resolution: int = 0, chunk_count: Optional[int] = None, hex_retries: int = DEFAULT_HEX_RETRIES, max_failed_indexes: int = DEFAULT_MAX_FAILED_INDEXES, years: Optional[List[int]] = None, hex_dir: str = "hex", value_units: Optional[str] = None, ): """Generate raster H3 hex tiling job. With *years* (issue #172), *source_url* holds a ``{year}`` placeholder and the Job runs the whole fan-out once per year, writing ``year=<year>/`` partitions under the output. """ if config is None: config = ClusterConfig() hex_cpu = str(hex_cpu).strip() hex_workers = _resolve_hex_workers(hex_workers, hex_cpu) hex_chunk_size = _validate_hex_chunk_size(hex_chunk_size) s3_dataset = s3_dataset or dataset_name parent_res_str = ','.join(map(str, parent_resolutions)) if years: per_year, h0_preamble, selector, out_url = _hex_fanout( bucket, s3_dataset, chunk_resolution, chunk_count, h0_subset, index_var="UNIT", partition="year=${YEAR}/", hex_dir=hex_dir) completions = per_year * len(years) h0_preamble = _year_preamble(years, per_year) + h0_preamble source_url = _year_template(source_url) else: completions, h0_preamble, selector, out_url = _hex_fanout( bucket, s3_dataset, chunk_resolution, chunk_count, h0_subset, hex_dir=hex_dir) cng_cmd = f"cng-datasets raster --input \"{source_url}\" --output-parquet {out_url} {selector} --resolution {h3_resolution} --parent-resolutions {parent_res_str} --value-column {value_column} --hex-resampling {hex_resampling}" nodata_cli = _nodata_cli_value(nodata_value) if nodata_cli is not None: cng_cmd += f' --nodata "{nodata_cli}"' if value_units: cng_cmd += f" --value-units {shlex.quote(value_units)}" # PROJ database selection is handled deterministically inside the CLI # (cog._configure_proj picks the highest-version proj.db, MINOR>=7). A bash # `find ... | head -1` here would be non-deterministic and could export a # stale PROJ_DATA — see issue #91. command_str = f"""set -e {h0_preamble}{cng_cmd}""" env = _s3_env_vars(config) + [ {"name": "GDAL_DATA", "value": "/usr/share/gdal"}, {"name": "PYTHONPATH", "value": "/usr/lib/python3/dist-packages"}, {"name": "BUCKET", "value": bucket}, # Peak RSS of a hex pod is roughly workers x chunk size x bytes # per cell. Both are pinned here, never left to the runtime, so # the manifest alone determines the pod's memory profile and a # tuned value survives regeneration (issue #195). {"name": "CNG_HEX_WORKERS", "value": str(hex_workers)}, {"name": "CNG_HEX_CHUNK_SIZE", "value": str(hex_chunk_size)}, # The cpu request, for the usage each chunk records (#183): NRP # enforces no cpu quota, so the pod cannot read it from its cgroup. {"name": "CNG_POD_CPU", "value": hex_cpu}, # The hex step's own DuckDB writes the partition by scanning # every part its workers produced. Unset, DuckDB sizes its # buffer manager from the *host's* RAM rather than the pod's # limit, so that scan grows with the chunk's cell count until # the cgroup kills it; bounded, it spills instead. 85% of the # pod, matching the merge and repartition steps, because # memory_limit bounds the buffer manager and not the process # (issue #217). In DuckDB's spelling, not Kubernetes' (#217). {"name": "DUCKDB_MEMORY_LIMIT", "value": _duckdb_memory_limit(hex_memory)}, # GDAL's block cache is per *process* and, left alone, is sized # at 5% of the host's RAM — 12.6 GiB on a 251 GiB node, in every # one of the pod's workers, none of which the manifest asked # for. 512 MB each keeps the whole fan-out's cache under 4 GB at # the default 8 workers. The preprocess-cog step has always # bounded this; the hex step, which is the one that runs many # processes, never did (issue #173). {"name": "GDAL_CACHEMAX", "value": "512"}, ] resources = { "requests": {"cpu": hex_cpu, "memory": hex_memory, "ephemeral-storage": hex_storage}, "limits": {"cpu": hex_cpu, "memory": hex_memory, "ephemeral-storage": hex_storage} } job_spec = _indexed_hex_job_spec( manager, dataset_name, command_str, env, resources, completions, max_parallelism, hex_retries, max_failed_indexes, config, volumes=[{"name": "rclone-config", "secret": {"secretName": config.rclone_secret_name}}], volume_mounts=[{"name": "rclone-config", "mountPath": "/root/.config/rclone", "readOnly": True}], ) manager.save_job_yaml(job_spec, str(output_path / f"{dataset_name}-hex.yaml")) def _generate_raster_configmap(dataset_name, namespace, output_path, gen_command, needs_preprocess=False, needs_merge=False): """Generate ConfigMap for raster workflow.""" import yaml job_files = [f"{dataset_name}-setup-bucket.yaml"] if needs_preprocess: job_files.append(f"{dataset_name}-preprocess-cog.yaml") job_files.append(f"{dataset_name}-hex.yaml") if needs_merge: # The orchestrator applies this from /yamls, so leaving it out of the # ConfigMap fails the build at the merge step rather than at generation. job_files.append(f"{dataset_name}-merge.yaml") if needs_preprocess: job_files.append(f"{dataset_name}-render.yaml") job_files.append(f"{dataset_name}-checksums.yaml") data = {} for job_file in job_files: file_path = output_path / job_file if file_path.exists(): with open(file_path, 'r') as f: data[job_file] = f.read() configmap = { "apiVersion": "v1", "kind": "ConfigMap", "metadata": { "name": f"{dataset_name}-yamls", "namespace": namespace, }, "data": data, } with open(output_path / "configmap.yaml", "w") as f: f.write("# Auto-generated ConfigMap for raster workflow\n") f.write(f"# Generation command: {gen_command}\n") yaml.dump(configmap, f, default_flow_style=False) def _generate_raster_argo_workflow(dataset_name, namespace, output_path, output_dir, needs_preprocess=False, needs_merge=False, wait_scale: int = 1): """Generate orchestrator job for raster workflow. *wait_scale* multiplies each step's timeout: a multi-year build (#172) runs every step once per year. """ step_timeout = 7200 * wait_scale import yaml configmap_name = f"{dataset_name}-yamls" preprocess_steps = "" cleanup_jobs = f"{dataset_name}-setup-bucket {dataset_name}-hex {dataset_name}-checksums {dataset_name}-workflow" if needs_preprocess: preprocess_steps = f""" # Step 1: Preprocess — mosaic tiles into a single COG on S3 echo "Step 1: Preprocessing COG mosaic..." kubectl apply -f /yamls/{dataset_name}-preprocess-cog.yaml -n {namespace} echo "Waiting for preprocess-cog (may take 30-60 min for large tile sets)..." wait_job {dataset_name}-preprocess-cog {namespace} {step_timeout} """ hex_step_num = "2" cleanup_jobs = f"{dataset_name}-setup-bucket {dataset_name}-preprocess-cog {dataset_name}-hex {dataset_name}-checksums {dataset_name}-workflow" else: hex_step_num = "1" render_steps = "" if needs_preprocess: render_steps = f""" echo "Default render and thumbnail of each COG..." kubectl apply -f /yamls/{dataset_name}-render.yaml -n {namespace} wait_job {dataset_name}-render {namespace} {step_timeout} """ cleanup_jobs = cleanup_jobs.replace( f"{dataset_name}-checksums", f"{dataset_name}-render {dataset_name}-checksums") merge_steps = "" if needs_merge: # Sub-h0 chunks land outside the published tree; nothing reads hex/ # until this has consolidated each partition (issue #173). merge_steps = f""" # Step {int(hex_step_num) + 1}: Merge sub-h0 chunks into one file per h0 partition echo "Step {int(hex_step_num) + 1}: Merging hex chunks..." kubectl apply -f /yamls/{dataset_name}-merge.yaml -n {namespace} wait_job {dataset_name}-merge {namespace} {step_timeout} """ cleanup_jobs = cleanup_jobs.replace( f"{dataset_name}-workflow", f"{dataset_name}-merge {dataset_name}-workflow" ) workflow_job = { "apiVersion": "batch/v1", "kind": "Job", "metadata": { "name": f"{dataset_name}-workflow", "namespace": namespace, }, "spec": { "template": { "spec": { "serviceAccountName": "cng-datasets-workflow", "restartPolicy": "OnFailure", "containers": [{ "name": "workflow", "image": "bitnami/kubectl:latest", "command": ["bash", "-c"], "args": [f"""set -e {_WAIT_JOB_SH} echo "Starting {dataset_name} raster workflow..." # Step 0: Setup bucket echo "Step 0: Setting up bucket..." kubectl apply -f /yamls/{dataset_name}-setup-bucket.yaml -n {namespace} wait_job {dataset_name}-setup-bucket {namespace} 600 {preprocess_steps} # Step {hex_step_num}: H3 hexagonal tiling echo "Step {hex_step_num}: H3 hexagonal tiling..." kubectl apply -f /yamls/{dataset_name}-hex.yaml -n {namespace} wait_job {dataset_name}-hex {namespace} {step_timeout} {merge_steps}{render_steps} echo "Sizes and checksums of the outputs..." kubectl apply -f /yamls/{dataset_name}-checksums.yaml -n {namespace} wait_job {dataset_name}-checksums {namespace} {step_timeout} echo "✓ Workflow complete!" echo "Clean up with:" echo " kubectl delete jobs {cleanup_jobs} -n {namespace}" echo " kubectl delete configmap {configmap_name} -n {namespace}" """], "resources": { "requests": {"cpu": "500m", "memory": "512Mi"}, "limits": {"cpu": "500m", "memory": "512Mi"}, }, "volumeMounts": [{"name": "yamls", "mountPath": "/yamls"}], }], "volumes": [{ "name": "yamls", "configMap": {"name": configmap_name}, }], } }, "ttlSecondsAfterFinished": 10800, }, } with open(output_path / "workflow.yaml", "w") as f: yaml.dump(workflow_job, f, default_flow_style=False) def _generate_setup_bucket_job(manager, dataset_name, bucket, output_path, git_repo, config: ClusterConfig = None): """Generate S3 bucket setup job with public access and CORS.""" if config is None: config = ClusterConfig() pod_spec = { "restartPolicy": "Never", "containers": [{ "name": "setup-bucket-task", "image": "ghcr.io/boettiger-lab/datasets:latest", "imagePullPolicy": "Always", "env": _s3_env_vars(config) + [ {"name": "BUCKET", "value": bucket} ], "volumeMounts": [ {"name": "rclone-config", "mountPath": "/root/.config/rclone", "readOnly": True} ], "command": ["bash", "-c", f"""set -e echo "Setting up bucket with public access and CORS..." cng-datasets storage setup-bucket \\ --bucket "${{BUCKET}}" \\ --remote {config.rclone_remote} \\ --verify echo "Bucket setup complete!" """], "resources": { "requests": {"cpu": "1", "memory": "2Gi"}, "limits": {"cpu": "1", "memory": "2Gi"} } }], "volumes": [ {"name": "rclone-config", "secret": {"secretName": config.rclone_secret_name}} ] } _apply_scheduling(pod_spec, config) job_spec = { "apiVersion": "batch/v1", "kind": "Job", "metadata": _job_metadata(manager, f"{dataset_name}-setup-bucket"), "spec": { "completions": 1, "parallelism": 1, "backoffLimit": 2, "ttlSecondsAfterFinished": 10800, "template": { "metadata": {"labels": {"k8s-app": f"{dataset_name}-setup-bucket"}}, "spec": pod_spec, } } } manager.save_job_yaml(job_spec, str(output_path / f"{dataset_name}-setup-bucket.yaml")) def _generate_convert_job(manager, dataset_name, source_urls, bucket, output_path, git_repo, layer=None, memory="8Gi", row_group_size=100000, s3_dataset=None, config: ClusterConfig = None, simplify_tolerance=None, trim_strings=False, lat_column=None, lon_column=None, expect_features=None, spatial_order=True, csv_sample_size=None): """Generate GeoParquet conversion job.""" if config is None: config = ClusterConfig() s3_dataset = s3_dataset or dataset_name # Normalize to list if isinstance(source_urls, str): source_urls = [source_urls] # Build source URLs string (one per line for readability). # Quote each URL: source URLs from ArcGIS Hub / REST endpoints carry query # strings with '&', which bash (this runs under `bash -c`) would otherwise # interpret as job control and split the command apart. See issue #147. sources_str = " \\\n ".join(shlex.quote(url) for url in source_urls) # Build the conversion command with optional layer / simplify / trim parameters layer_flag = f" \\\n --layer {layer}" if layer else "" simplify_flag = ( f" \\\n --simplify-tolerance {simplify_tolerance}" if simplify_tolerance is not None else "" ) trim_flag = " \\\n --trim-strings" if trim_strings else "" # A CSV point source needs its lat/lon columns named here, or it cannot be a # --source-url for a generated pipeline at all (issue #188). latlon_flags = "" if lat_column: latlon_flags += f" \\\n --lat-column {shlex.quote(lat_column)}" if lon_column: latlon_flags += f" \\\n --lon-column {shlex.quote(lon_column)}" # Gate the step on a count the caller knows independently, so a truncated # source fails the job instead of flowing into hex and PMTiles (issue #186). expect_flag = ( f" \\\n --expect-features {int(expect_features)}" if expect_features is not None else "" ) # The way out of a Hilbert sort that will not fit the pod (#276), and the # CSV type-inference sample (#188), passed through from `workflow` (#311). order_flag = "" if spatial_order else " \\\n --no-spatial-order" sample_flag = ( f" \\\n --csv-sample-size {int(csv_sample_size)}" if csv_sample_size is not None else "" ) convert_cmd = f"""set -e cng-convert-to-parquet \\ {sources_str} \\ s3://{bucket}/{s3_dataset}.parquet \\ --row-group-size {row_group_size}{layer_flag}{simplify_flag}{trim_flag}{latlon_flags}{expect_flag}{order_flag}{sample_flag} """ pod_spec = { "restartPolicy": "Never", "containers": [{ "name": "convert-task", "image": "ghcr.io/boettiger-lab/datasets:latest", "imagePullPolicy": "Always", "env": _s3_env_vars(config) + [ {"name": "BUCKET", "value": bucket}, # convert sorts the dataset along a Hilbert curve (issue #276) {"name": "DUCKDB_MEMORY_LIMIT", "value": _duckdb_memory_limit(memory)}, ], "volumeMounts": [ {"name": "rclone-config", "mountPath": "/root/.config/rclone", "readOnly": True} ], "command": ["bash", "-c", convert_cmd], "resources": { "requests": {"cpu": "4", "memory": memory}, "limits": {"cpu": "4", "memory": memory} } }], "volumes": [ {"name": "rclone-config", "secret": {"secretName": config.rclone_secret_name}} ] } _apply_scheduling(pod_spec, config) job_spec = { "apiVersion": "batch/v1", "kind": "Job", "metadata": _job_metadata(manager, f"{dataset_name}-convert"), "spec": { "completions": 1, "parallelism": 1, "backoffLimit": 1, "ttlSecondsAfterFinished": 10800, "template": { "metadata": {"labels": {"k8s-app": f"{dataset_name}-convert"}}, "spec": pod_spec, } } } manager.save_job_yaml(job_spec, str(output_path / f"{dataset_name}-convert.yaml")) def _pmtiles_max_zoom(h3_resolution: Optional[int], max_zoom: Optional[int]) -> int: """Derive PMTiles max zoom. Explicit max_zoom wins; otherwise res+3 (res-10→z13).""" if max_zoom is not None: return max_zoom if h3_resolution is not None: return h3_resolution + 3 return 13 # default matches res-10 # Shell that prepares the environment for tippecanoe, shared by the single-pod # PMTiles job and the chunked parts and overview (#83). _TIPPECANOE_SETUP_SH = """# TIPPECANOE_MAX_THREADS must be a power of 2; Kubernetes nodes can expose # non-power-of-2 logical CPU counts which triggers an internal assertion # failure "N shards not a power of 2" (felt/tippecanoe#216). # Size from the pod's cgroup CPU quota, not os.cpu_count() (the node's cores), # round down to a power of 2, and cap at 128: at 256+ threads tippecanoe caps # its shards at 745, not a power of 2, and aborts anyway (issue #273). # Must be `export`ed: tippecanoe is a child process and reads this from the # environment, not the shell. A plain assignment is invisible to it, so it # falls back to the raw (non-power-of-2) CPU count and crashes (issue #77). export TIPPECANOE_MAX_THREADS=$(python3 -c "from cng_datasets.raster.cog import _cgroup_cpu_count as c; n=min(c() or 4, 128); print(1<<(n.bit_length()-1))") # Raise the soft open-file limit before tippecanoe (issue #154). It opens many # temp files (per-thread x per-tile shards); on high-core nodes os.cpu_count() # reports the node's full core count, so the thread/shard count blows past the # container's default soft nofile limit (often 1024) and aborts with # "Too many open files". `|| true` keeps going if the limit can't be raised. ulimit -n 65536 || true """ def _generate_pmtiles_job(manager, dataset_name, source_url, bucket, output_path, git_repo, memory="8Gi", s3_dataset=None, config: ClusterConfig = None, h3_resolution: Optional[int] = None, max_zoom: Optional[int] = None): """Generate PMTiles job. Uses the optimized GeoParquet from convert job as input (includes ID column). """ if config is None: config = ClusterConfig() s3_dataset = s3_dataset or dataset_name # Use the converted geoparquet instead of original source geoparquet_url = f"https://{config.s3_public_endpoint}/{bucket}/{s3_dataset}.parquet" # For rclone upload, compute the S3 directory that contains the output file if '/' in s3_dataset: s3_parent_dir = '/'.join(s3_dataset.split('/')[:-1]) + '/' else: s3_parent_dir = '' # basename for temp files and tippecanoe layer name s3_basename = s3_dataset.split('/')[-1] pod_spec = { "restartPolicy": "Never", "containers": [{ "name": "pmtiles-task", "image": "ghcr.io/boettiger-lab/datasets:latest", "imagePullPolicy": "Always", "env": _s3_env_vars(config) + [ {"name": "TMPDIR", "value": "/tmp"}, {"name": "BUCKET", "value": bucket}, {"name": "DATASET", "value": s3_basename} ], "volumeMounts": [ {"name": "rclone-config", "mountPath": "/root/.config/rclone", "readOnly": True} ], "command": ["bash", "-c", f"""set -e # Use optimized GeoParquet (has ID column) from convert job # GDAL can read parquet via vsicurl ogr2ogr -wrapdateline -datelineoffset 15 -f GeoJSONSeq /tmp/$DATASET.geojsonl /vsicurl/{geoparquet_url} -progress # Generate PMTiles from GeoJSONSeq {_TIPPECANOE_SETUP_SH}# -r1: keep every point at every zoom (issue #319). Without it tippecanoe thins # points 2.5x per zoom below the max zoom, so a national view of 1,733 points # showed 1 at z0 and 97 at z6. The rate applies only to points, so lines and # polygons tile identically; --drop-densest-as-needed still bounds tile size. tippecanoe -o /tmp/$DATASET.pmtiles -l $DATASET -r1 --coalesce-densest-as-needed --drop-densest-as-needed -z {_pmtiles_max_zoom(h3_resolution, max_zoom)} --force /tmp/$DATASET.geojsonl # Upload to S3 using rclone rclone copy /tmp/$DATASET.pmtiles {config.rclone_remote}:{bucket}/{s3_parent_dir} rm /tmp/$DATASET.geojsonl /tmp/$DATASET.pmtiles """], "resources": { "requests": {"cpu": "4", "memory": memory}, "limits": {"cpu": "4", "memory": memory} } }], "volumes": [ {"name": "rclone-config", "secret": {"secretName": config.rclone_secret_name}} ] } _apply_scheduling(pod_spec, config) job_spec = { "apiVersion": "batch/v1", "kind": "Job", "metadata": _job_metadata(manager, f"{dataset_name}-pmtiles"), "spec": { "completions": 1, "parallelism": 1, "backoffLimit": 1, "ttlSecondsAfterFinished": 10800, "template": { "metadata": {"labels": {"k8s-app": f"{dataset_name}-pmtiles"}}, "spec": pod_spec, } } } manager.save_job_yaml(job_spec, str(output_path / f"{dataset_name}-pmtiles.yaml")) def _generate_pmtiles_chunked_jobs(manager, dataset_name, bucket, output_path, chunks: int, parallelism: int, memory="8Gi", storage="50Gi", s3_dataset=None, config: ClusterConfig = None, h3_resolution: Optional[int] = None, max_zoom: Optional[int] = None, split_zoom: Optional[int] = None, retries: int = DEFAULT_HEX_RETRIES): """Generate the three jobs of a chunked PMTiles build (#83). * ``<name>-pmtiles-parts``: an indexed Job. Pod *i* tiles the *i*-th of *chunks* contiguous row ranges of the converted GeoParquet at zooms ``split_zoom`` and up. Convert writes rows in Hilbert order (#276), so each range is a compact patch of the map. * ``<name>-pmtiles-overview``: one pod tiles every zoom below ``split_zoom`` from the whole dataset, simplified to half a pixel at its highest zoom so its disk stays bounded. * ``<name>-pmtiles-merge``: ``tile-join -pk`` of the overview and the parts. The merge passes ``-pk``. Without it, tile-join drops a merged tile over 500 KB, printing one stderr line and exiting 0, which on a fixture lost two z5 tiles (measured on #83). Kept whole, such a tile loses no features; the merge reports any with ``pmtiles-check`` instead. Every part leaves a marker (its tiles, or ``.empty`` for an empty range), and the merge refuses to run unless all *chunks* markers are there. """ from ..vector.pmtiles_chunks import DEFAULT_SPLIT_ZOOM, overview_tolerance if config is None: config = ClusterConfig() s3_dataset = s3_dataset or dataset_name split_zoom = DEFAULT_SPLIT_ZOOM if split_zoom is None else split_zoom top_zoom = _pmtiles_max_zoom(h3_resolution, max_zoom) if not 1 <= split_zoom <= top_zoom: raise ValueError( f"--pmtiles-split-zoom {split_zoom} must be between 1 and the max zoom " f"{top_zoom}: the overview builds z0..{split_zoom - 1} and the parts " f"z{split_zoom}..z{top_zoom}.") if chunks < 1: raise ValueError(f"--pmtiles-chunks must be at least 1, got {chunks}") input_url = f"s3://{bucket}/{s3_dataset}.parquet" parts_dir = f"{config.rclone_remote}:{bucket}/{s3_dataset}/pmtiles-parts" s3_parent_dir = ('/'.join(s3_dataset.split('/')[:-1]) + '/') if '/' in s3_dataset else '' s3_basename = s3_dataset.split('/')[-1] tippecanoe_flags = "-l $DATASET -r1 --coalesce-densest-as-needed --drop-densest-as-needed --force" def pod_spec(name, script): spec = { "restartPolicy": "Never", "containers": [{ "name": name, "image": "ghcr.io/boettiger-lab/datasets:latest", "imagePullPolicy": "Always", "env": _s3_env_vars(config) + [ {"name": "TMPDIR", "value": "/tmp"}, {"name": "BUCKET", "value": bucket}, {"name": "DATASET", "value": s3_basename}, {"name": "DUCKDB_MEMORY_LIMIT", "value": _duckdb_memory_limit(memory)}, ], "volumeMounts": [ {"name": "rclone-config", "mountPath": "/root/.config/rclone", "readOnly": True} ], "command": ["bash", "-c", script], "resources": { "requests": {"cpu": "4", "memory": memory, "ephemeral-storage": storage}, "limits": {"cpu": "4", "memory": memory, "ephemeral-storage": storage}, }, }], "volumes": [ {"name": "rclone-config", "secret": {"secretName": config.rclone_secret_name}} ], } _apply_scheduling(spec, config) return spec def job(suffix, spec, **extra): return { "apiVersion": "batch/v1", "kind": "Job", "metadata": _job_metadata(manager, f"{dataset_name}-{suffix}"), "spec": { **extra, "ttlSecondsAfterFinished": 10800, "template": { "metadata": {"labels": {"k8s-app": f"{dataset_name}-{suffix}"}}, "spec": spec, }, }, } parts_script = f"""set -eo pipefail PART=part-$(printf %05d $JOB_COMPLETION_INDEX) # Leave no stale marker from an earlier attempt of this index. rclone deletefile {parts_dir}/$PART.empty 2>/dev/null || true cng-datasets pmtiles-chunk --input {input_url} --output /tmp/$PART.parquet \\ --chunks {chunks} --index $JOB_COMPLETION_INDEX if [ ! -f /tmp/$PART.parquet ]; then # More chunks than rows: record that this index ran and had nothing to tile. touch /tmp/$PART.empty rclone copyto /tmp/$PART.empty {parts_dir}/$PART.empty exit 0 fi ogr2ogr -wrapdateline -datelineoffset 15 -f GeoJSONSeq /tmp/$PART.geojsonl /tmp/$PART.parquet rm /tmp/$PART.parquet {_TIPPECANOE_SETUP_SH}# -r1 and the drop flags match the single-pod job (#319). -Z: the parts build # only the high zooms; the overview pod builds the rest (#83). tippecanoe -o /tmp/$PART.pmtiles {tippecanoe_flags} -Z {split_zoom} -z {top_zoom} /tmp/$PART.geojsonl rclone copyto /tmp/$PART.pmtiles {parts_dir}/$PART.pmtiles """ parts = job("pmtiles-parts", pod_spec("pmtiles-part", parts_script), completions=chunks, parallelism=parallelism, completionMode="Indexed", **_indexed_retry_spec(retries, 1), podFailurePolicy={"rules": [{ "action": "Ignore", "onPodConditions": [{"type": "DisruptionTarget"}]}]}) manager.save_job_yaml(parts, str(output_path / f"{dataset_name}-pmtiles-parts.yaml")) tolerance = overview_tolerance(split_zoom) overview_script = f"""set -eo pipefail # The whole dataset, simplified to half a pixel at z{split_zoom - 1}, so the # overview's input and tippecanoe's temporary files stay small (#83). cng-datasets pmtiles-chunk --input {input_url} --output /tmp/overview.parquet --simplify {tolerance!r} {_TIPPECANOE_SETUP_SH}ogr2ogr -wrapdateline -datelineoffset 15 -f GeoJSONSeq /vsistdout/ /tmp/overview.parquet \\ | tippecanoe -o /tmp/overview.pmtiles {tippecanoe_flags} -z {split_zoom - 1} rclone copyto /tmp/overview.pmtiles {parts_dir}/overview.pmtiles """ overview = job("pmtiles-overview", pod_spec("pmtiles-overview", overview_script), completions=1, parallelism=1, backoffLimit=retries) manager.save_job_yaml(overview, str(output_path / f"{dataset_name}-pmtiles-overview.yaml")) merge_script = f"""set -eo pipefail mkdir -p /tmp/parts rclone copy {parts_dir}/ /tmp/parts/ # Every index must have left its tiles or an .empty marker, and the overview # must be there; a merge of what happens to be present would publish a map # with holes (#83). # Only indexes 0..{chunks - 1} are joined, so leftovers of an earlier run cut # into a different number of parts cannot slip in. MISSING=0 PARTS="" for i in $(seq 0 {chunks - 1}); do P=/tmp/parts/part-$(printf %05d $i) if [ -f $P.pmtiles ]; then PARTS="$PARTS $P.pmtiles" elif [ ! -f $P.empty ]; then echo "✗ missing part $i"; MISSING=$((MISSING + 1)); fi done if [ ! -f /tmp/parts/overview.pmtiles ]; then echo "✗ missing overview"; MISSING=$((MISSING + 1)); fi if [ "$MISSING" -gt 0 ]; then echo "✗ $MISSING of {chunks + 1} PMTiles inputs missing; not merging."; exit 1; fi # -pk keeps a merged tile over 500 KB. Without it tile-join drops the tile, # features and all, and still exits 0 (#83). tile-join -pk --force -o /tmp/$DATASET.pmtiles /tmp/parts/overview.pmtiles $PARTS cng-datasets pmtiles-check /tmp/$DATASET.pmtiles rclone copy /tmp/$DATASET.pmtiles {config.rclone_remote}:{bucket}/{s3_parent_dir} rclone purge {parts_dir} """ merge = job("pmtiles-merge", pod_spec("pmtiles-merge", merge_script), completions=1, parallelism=1, backoffLimit=retries) manager.save_job_yaml(merge, str(output_path / f"{dataset_name}-pmtiles-merge.yaml")) print(f" PMTiles: {chunks} parts at z{split_zoom}-z{top_zoom} " f"(parallelism {parallelism}), overview at z0-z{split_zoom - 1}, " f"merged with tile-join") def _hex_plan_url(bucket: str, s3_dataset: str) -> str: """Where the #124 chunk plan lives. Outside `chunks/`, whose `*.parquet` glob repartition reads as hex output.""" return f"s3://{bucket}/{s3_dataset}/_hex_plan.parquet" def _generate_plan_job(manager, dataset_name, bucket, output_path, plan_url, h3_resolution, resolution_by_area, cells_per_chunk, max_chunks, memory="8Gi", s3_dataset=None, config: ClusterConfig = None): """Generate the job that cuts the GeoParquet into hex chunks by cells (#124). It runs after convert, reads every geometry once, writes the plan, and reports its chunk count as the container's termination message — which is how the workflow sizes the hex Job to it without an S3 client of its own. """ if config is None: config = ClusterConfig() s3_dataset = s3_dataset or dataset_name res_flag = (f'--resolution-by-area "{resolution_by_area}"' if resolution_by_area is not None else f"--resolution {h3_resolution}") plan_cmd = ( "set -e\n" f"cng-datasets vector-plan --input s3://{bucket}/{s3_dataset}.parquet " f"--output {plan_url} {res_flag} " f"--cells-per-chunk {cells_per_chunk:.0f} --max-chunks {max_chunks}" ) pod_spec = { "restartPolicy": "Never", "containers": [{ "name": "plan-task", "image": "ghcr.io/boettiger-lab/datasets:latest", "imagePullPolicy": "Always", "env": _s3_env_vars(config) + [{"name": "BUCKET", "value": bucket}], "command": ["bash", "-c", plan_cmd], "terminationMessagePolicy": "File", "resources": { "requests": {"cpu": "2", "memory": memory}, "limits": {"cpu": "2", "memory": memory} } }], } _apply_scheduling(pod_spec, config) job_spec = { "apiVersion": "batch/v1", "kind": "Job", "metadata": _job_metadata(manager, f"{dataset_name}-plan"), "spec": { "completions": 1, "parallelism": 1, "backoffLimit": 1, "ttlSecondsAfterFinished": 10800, "template": { "metadata": {"labels": {"k8s-app": f"{dataset_name}-plan"}}, "spec": pod_spec, } } } manager.save_job_yaml(job_spec, str(output_path / f"{dataset_name}-plan.yaml")) def _generate_hex_job(manager, dataset_name, bucket, output_path, git_repo, chunk_size, completions, parallelism, h3_resolution, parent_resolutions, id_column=None, hex_memory="8Gi", intermediate_chunk_size=10, s3_dataset=None, hex_storage="10Gi", config: ClusterConfig = None, resolution_by_area=None, hex_retries: int = DEFAULT_HEX_RETRIES, max_failed_indexes: int = DEFAULT_MAX_FAILED_INDEXES, plan_url: Optional[str] = None, polyfill: str = "centre"): """Generate H3 hex tiling job. Args: manager: K8sJobManager instance dataset_name: Name for k8s resources bucket: S3 bucket name output_path: Path to write YAML files git_repo: Git repository URL chunk_size: Number of rows per chunk completions: Number of job completions parallelism: Number of parallel jobs h3_resolution: Target H3 resolution (e.g., 10) parent_resolutions: List of parent resolutions (e.g., [9, 8, 0]) id_column: ID column name (auto-detected if None) hex_memory: Memory request/limit (e.g., "8Gi", "16Gi") intermediate_chunk_size: Number of rows to process in pass 2 (unnesting arrays) s3_dataset: S3 path prefix (defaults to dataset_name) """ if config is None: config = ClusterConfig() s3_dataset = s3_dataset or dataset_name # Format parent resolutions as comma-separated string parent_res_str = ','.join(map(str, parent_resolutions)) # Variable-resolution mode (issue #98) passes the per-area spec; otherwise a # single target resolution. The spec needs quoting (it contains commas/colons). res_flag = (f'--resolution-by-area "{resolution_by_area}"' if resolution_by_area is not None else f"--resolution {h3_resolution}") # Build command with optional id-column parameter cmd_parts = [ "set -e", f"cng-datasets vector --input s3://{bucket}/{s3_dataset}.parquet --output s3://{bucket}/{s3_dataset}/chunks --chunk-id ${{JOB_COMPLETION_INDEX}} --chunk-size {chunk_size} --intermediate-chunk-size {intermediate_chunk_size} {res_flag} --parent-resolutions {parent_res_str}" ] if id_column: cmd_parts[-1] += f" --id-column {id_column}" if plan_url: cmd_parts[-1] += f" --plan {plan_url}" if polyfill != "centre": cmd_parts[-1] += f" --polyfill {polyfill}" command_str = "\n".join(cmd_parts) pod_spec = { "restartPolicy": "Never", "containers": [{ "name": "hex-task", "image": "ghcr.io/boettiger-lab/datasets:latest", "imagePullPolicy": "Always", "env": _s3_env_vars(config) + [ {"name": "TMPDIR", "value": "/tmp"}, {"name": "BUCKET", "value": bucket}, {"name": "DATASET", "value": dataset_name}, # Bound DuckDB to the pod rather than the node, so a large # feature spills to /tmp instead of being OOM-killed (#255). # 85%, as for the raster hex step (#227); DuckDB's spelling (#217). {"name": "DUCKDB_MEMORY_LIMIT", "value": _duckdb_memory_limit(hex_memory)}, ], "command": ["bash", "-c", command_str], "resources": { "requests": {"cpu": "4", "memory": hex_memory, "ephemeral-storage": hex_storage}, "limits": {"cpu": "4", "memory": hex_memory, "ephemeral-storage": hex_storage} } }] } _apply_scheduling(pod_spec, config) job_spec = { "apiVersion": "batch/v1", "kind": "Job", "metadata": _job_metadata(manager, f"{dataset_name}-hex"), "spec": { "completions": completions, "parallelism": parallelism, "completionMode": "Indexed", **_indexed_retry_spec(hex_retries, max_failed_indexes), "podFailurePolicy": { "rules": [{ "action": "Ignore", "onPodConditions": [{"type": "DisruptionTarget"}] }] }, "ttlSecondsAfterFinished": 10800, "template": { "metadata": {"labels": {"k8s-app": f"{dataset_name}-hex"}}, "spec": pod_spec, } } } manager.save_job_yaml(job_spec, str(output_path / f"{dataset_name}-hex.yaml")) def _duckdb_memory_limit(memory_str: str, fraction: float = 0.85) -> str: """Return a DuckDB memory_limit string that is *fraction* of *memory_str*. Parses a Kubernetes quantity like "32Gi" and returns e.g. "27GiB", in DuckDB's own spelling — it rejects the k8s one (issue #217). The default fraction leaves headroom for everything the pod allocates outside DuckDB's buffer manager. """ return to_duckdb_memory_limit(memory_str, fraction) def _generate_repartition_job(manager, dataset_name, bucket, output_path, git_repo, s3_dataset=None, repartition_storage: str = "50Gi", repartition_memory: str = "32Gi", config: ClusterConfig = None): """Generate repartition job.""" if config is None: config = ClusterConfig() s3_dataset = s3_dataset or dataset_name pod_spec = { "restartPolicy": "Never", "containers": [{ "name": "repartition-task", "image": "ghcr.io/boettiger-lab/datasets:latest", "imagePullPolicy": "Always", "env": _s3_env_vars(config) + [ {"name": "TMPDIR", "value": "/tmp"}, {"name": "BUCKET", "value": bucket}, # The cpu request, which sets DuckDB's thread count (#339). NRP # enforces no cpu quota, so the pod cannot read it from its # cgroup, and DuckDB would otherwise run a thread per host core. {"name": "CNG_POD_CPU", "value": "4"}, ], "volumeMounts": [ {"name": "rclone-config", "mountPath": "/root/.config/rclone", "readOnly": True} ], "command": ["bash", "-c", f"""set -e cng-datasets repartition --chunks-dir s3://{bucket}/{s3_dataset}/chunks --output-dir s3://{bucket}/{s3_dataset}/hex --source-parquet s3://{bucket}/{s3_dataset}.parquet --cleanup --memory-limit {_duckdb_memory_limit(repartition_memory)} """], "resources": { "requests": {"cpu": "4", "memory": repartition_memory, "ephemeral-storage": repartition_storage}, "limits": {"cpu": "4", "memory": repartition_memory, "ephemeral-storage": repartition_storage} } }], "volumes": [ {"name": "rclone-config", "secret": {"secretName": config.rclone_secret_name}} ] } _apply_scheduling(pod_spec, config) job_spec = { "apiVersion": "batch/v1", "kind": "Job", "metadata": _job_metadata(manager, f"{dataset_name}-repartition"), "spec": { "completions": 1, "parallelism": 1, "backoffLimit": 1, "ttlSecondsAfterFinished": 10800, "template": { "metadata": {"labels": {"k8s-app": f"{dataset_name}-repartition"}}, "spec": pod_spec, } } } manager.save_job_yaml(job_spec, str(output_path / f"{dataset_name}-repartition.yaml")) def hex_dir_name(hex_resampling: str) -> str: """The folder a raster build's hex tree is published under (#343). A `fractions` table has one row per class per cell, a different schema from the one-row-per-cell tables every other reducer writes, so it lives beside them as ``hex-fractions/`` rather than in ``hex/``. """ return "hex-fractions" if hex_resampling == "fractions" else "hex" def checksums_url(bucket: str, s3_dataset: str) -> str: """Where a dataset's sizes and checksums are written (#340).""" return f"s3://{bucket}/{s3_dataset}.checksums.json" def usage_url(bucket: str, stem: str, year: Union[int, str, None] = None) -> str: """Where a hex fan-out's measured resource use is kept (#369). Beside the dataset and outside its hex tree, like the checksums. With --years each year is its own fan-out, so each gets its own file. """ suffix = f".year={year}" if year is not None else "" return f"s3://{bucket}/{stem}{suffix}.usage.json" def _generate_checksums_job(manager, dataset_name, bucket, output_path, targets: List[str], s3_dataset: str, config: ClusterConfig = None): """Generate the Job that writes file:size and file:checksum of every output (#340). It reads each output back from S3, so the orchestrator applies it last, once every step that writes to the bucket has finished. """ if config is None: config = ClusterConfig() target_args = " ".join(shlex.quote(t) for t in targets) pod_spec = { "restartPolicy": "Never", "containers": [{ "name": "checksums-task", "image": "ghcr.io/boettiger-lab/datasets:latest", "imagePullPolicy": "Always", "env": _s3_env_vars(config), "command": ["bash", "-c", f"""set -e cng-datasets checksums {target_args} --output {shlex.quote(checksums_url(bucket, s3_dataset))} --workers 8 """], "resources": { "requests": {"cpu": "4", "memory": "2Gi"}, "limits": {"cpu": "4", "memory": "2Gi"}, }, }], } _apply_scheduling(pod_spec, config) job_spec = { "apiVersion": "batch/v1", "kind": "Job", "metadata": _job_metadata(manager, f"{dataset_name}-checksums"), "spec": { "completions": 1, "parallelism": 1, "backoffLimit": 2, "ttlSecondsAfterFinished": 10800, "template": { "metadata": {"labels": {"k8s-app": f"{dataset_name}-checksums"}}, "spec": pod_spec, }, }, } manager.save_job_yaml(job_spec, str(output_path / f"{dataset_name}-checksums.yaml")) def render_url(bucket: str, s3_dataset: str) -> str: """Where a raster dataset's default renders are written (#340).""" return f"s3://{bucket}/{s3_dataset}.render.json" def _generate_render_job(manager, dataset_name, bucket, output_path, cogs: List[str], s3_dataset: str, config: ClusterConfig = None): """Generate the Job that writes each COG's default render and thumbnail (#340).""" if config is None: config = ClusterConfig() cog_args = " ".join(shlex.quote(c) for c in cogs) pod_spec = { "restartPolicy": "Never", "containers": [{ "name": "render-task", "image": "ghcr.io/boettiger-lab/datasets:latest", "imagePullPolicy": "Always", "env": _s3_env_vars(config), "command": ["bash", "-c", f"""set -e cng-datasets cog-render {cog_args} --output {shlex.quote(render_url(bucket, s3_dataset))} """], "resources": { "requests": {"cpu": "2", "memory": "4Gi"}, "limits": {"cpu": "2", "memory": "4Gi"}, }, }], } _apply_scheduling(pod_spec, config) job_spec = { "apiVersion": "batch/v1", "kind": "Job", "metadata": _job_metadata(manager, f"{dataset_name}-render"), "spec": { "completions": 1, "parallelism": 1, "backoffLimit": 2, "ttlSecondsAfterFinished": 10800, "template": { "metadata": {"labels": {"k8s-app": f"{dataset_name}-render"}}, "spec": pod_spec, }, }, } manager.save_job_yaml(job_spec, str(output_path / f"{dataset_name}-render.yaml")) def _generate_workflow_rbac(namespace, output_path): """Generate generic workflow RBAC configuration for cng-datasets package.""" import yaml rbac = { "apiVersion": "v1", "kind": "ServiceAccount", "metadata": { "name": "cng-datasets-workflow", "namespace": namespace } } with open(output_path / "workflow-rbac.yaml", "w") as f: yaml.dump_all([ rbac, { "apiVersion": "rbac.authorization.k8s.io/v1", "kind": "Role", "metadata": {"name": "cng-datasets-workflow", "namespace": namespace}, "rules": [ {"apiGroups": ["batch"], "resources": ["jobs"], "verbs": ["get", "list", "watch", "create", "delete"]}, {"apiGroups": [""], "resources": ["pods", "pods/log"], "verbs": ["get", "list"]} ] }, { "apiVersion": "rbac.authorization.k8s.io/v1", "kind": "RoleBinding", "metadata": {"name": "cng-datasets-workflow", "namespace": namespace}, "subjects": [{"kind": "ServiceAccount", "name": "cng-datasets-workflow"}], "roleRef": {"kind": "Role", "name": "cng-datasets-workflow", "apiGroup": "rbac.authorization.k8s.io"} } ], f, default_flow_style=False) def _generate_configmap(dataset_name, namespace, output_path, gen_command): """Generate ConfigMap YAML containing all job definitions. Args: dataset_name: Sanitized k8s-compatible dataset name namespace: Kubernetes namespace output_path: Path object where YAML files are written gen_command: Command used to generate this workflow """ import yaml # Read all job YAML files job_files = [f"{dataset_name}-setup-bucket.yaml", f"{dataset_name}-convert.yaml", f"{dataset_name}-plan.yaml", f"{dataset_name}-pmtiles.yaml", f"{dataset_name}-pmtiles-parts.yaml", f"{dataset_name}-pmtiles-overview.yaml", f"{dataset_name}-pmtiles-merge.yaml", f"{dataset_name}-hex.yaml", f"{dataset_name}-repartition.yaml", f"{dataset_name}-checksums.yaml"] data = {} for job_file in job_files: file_path = output_path / job_file if file_path.exists(): with open(file_path, 'r') as f: data[job_file] = f.read() configmap = { "apiVersion": "v1", "kind": "ConfigMap", "metadata": { "name": f"{dataset_name}-yamls", "namespace": namespace }, "data": data } with open(output_path / "configmap.yaml", "w") as f: f.write("# Auto-generated ConfigMap containing job definitions\n") f.write(f"# Generated from: {dataset_name}-setup-bucket.yaml, {dataset_name}-convert.yaml, {dataset_name}-pmtiles.yaml, {dataset_name}-hex.yaml, {dataset_name}-repartition.yaml\n") f.write(f"# Generation command: {gen_command}\n") f.write("#\n") f.write("# This ConfigMap is equivalent to running:\n") f.write(f"# kubectl create configmap {dataset_name}-yamls \\\n") f.write(f"# --from-file={dataset_name}-setup-bucket.yaml \\\n") f.write(f"# --from-file={dataset_name}-convert.yaml \\\n") f.write(f"# --from-file={dataset_name}-pmtiles.yaml \\\n") f.write(f"# --from-file={dataset_name}-hex.yaml \\\n") f.write(f"# --from-file={dataset_name}-repartition.yaml\n") f.write("#\n") f.write("# To update: regenerate workflow with cng-datasets and re-apply with kubectl apply -f configmap.yaml\n") yaml.dump(configmap, f, default_flow_style=False) # Shell for the orchestrator Jobs: wait for a step's Job and stop at once if it # fails. `kubectl wait --for=condition=complete` never returns for a Job that # has *failed*, so a dead step used to hold the orchestrator for its whole # timeout — 48 h for the vector hex step — looking Running throughout (#258). # Spliced into the scripts as a value, since its jsonpath braces would # otherwise be read as f-string fields. _WAIT_JOB_SH = """ wait_job() { local job="$1" ns="$2" timeout="$3" waited=0 state echo "Waiting for $job (up to ${timeout}s)..." while :; do state=$(kubectl get job "$job" -n "$ns" -o jsonpath='{.status.conditions[?(@.status=="True")].type}') case " $state " in *" Complete "*) echo "✓ $job complete"; return 0 ;; *" Failed "*) echo "✗ $job failed, so the workflow stops here:" kubectl get job "$job" -n "$ns" -o jsonpath='{range .status.conditions[*]} {.type}: {.reason} {.message}{"\\n"}{end}' echo " Inspect it with: kubectl logs job/$job -n $ns" exit 1 ;; esac if [ "$waited" -ge "$timeout" ]; then echo "✗ $job did not finish within ${timeout}s" exit 1 fi sleep 30 waited=$((waited + 30)) done } """ def _generate_argo_workflow(dataset_name, namespace, output_path, output_dir, planned: bool = False, max_parallelism: int = 50, pmtiles_chunked: bool = False): """Generate K8s Job that orchestrates the workflow using a ConfigMap. Args: dataset_name: Sanitized k8s-compatible dataset name (with hyphens) namespace: Kubernetes namespace output_path: Path object where YAML files are written output_dir: String path to YAML directory for kubectl create configmap command planned: Run the #124 plan step and size the hex Job from its chunk count, rather than applying the hex Job as generated. max_parallelism: Cap on the hex Job's parallelism when it is resized. pmtiles_chunked: Run the chunked PMTiles parts and overview beside the hex step, then merge them once both finish (#83), instead of one PMTiles Job left running in the background. """ import yaml configmap_name = f"{dataset_name}-yamls" if planned: # The plan pod reports "chunks=N" as its termination message (#124). # The hex Job was generated with an upper bound; patch it to the plan # locally, from the ConfigMap copy, before it is ever created. hex_apply = f"""echo "Planning hex chunks by estimated cells..." kubectl apply -f /yamls/{dataset_name}-plan.yaml -n {namespace} wait_job {dataset_name}-plan {namespace} 7200 MSG=$(kubectl get pods -n {namespace} -l job-name={dataset_name}-plan \\ -o jsonpath='{{.items[*].status.containerStatuses[0].state.terminated.message}}') CHUNKS=$(echo "$MSG" | tr ' ' '\\n' | sed -n 's/^chunks=\\([0-9][0-9]*\\)$/\\1/p' | tail -1) if [ -z "$CHUNKS" ] || [ "$CHUNKS" -lt 1 ]; then echo "The plan step reported no chunk count (termination message: '$MSG'); refusing to guess." exit 1 fi PAR=$(( CHUNKS < {max_parallelism} ? CHUNKS : {max_parallelism} )) echo "Plan: $CHUNKS hex chunks; parallelism $PAR" kubectl patch --local -f /yamls/{dataset_name}-hex.yaml --type merge \\ -p "{{\\"spec\\":{{\\"completions\\":$CHUNKS,\\"parallelism\\":$PAR}}}}" -o yaml \\ | kubectl apply -n {namespace} -f - """ else: hex_apply = f"kubectl apply -f /yamls/{dataset_name}-hex.yaml -n {namespace}\n" if pmtiles_chunked: pmtiles_apply = (f"kubectl apply -f /yamls/{dataset_name}-pmtiles-parts.yaml -n {namespace}\n" f"kubectl apply -f /yamls/{dataset_name}-pmtiles-overview.yaml -n {namespace}\n") pmtiles_finish = f""" echo "Step 4: Merging PMTiles parts..." wait_job {dataset_name}-pmtiles-overview {namespace} 172800 wait_job {dataset_name}-pmtiles-parts {namespace} 172800 kubectl apply -f /yamls/{dataset_name}-pmtiles-merge.yaml -n {namespace} wait_job {dataset_name}-pmtiles-merge {namespace} 14400 """ pmtiles_jobs = (f"{dataset_name}-pmtiles-parts {dataset_name}-pmtiles-overview " f"{dataset_name}-pmtiles-merge") else: pmtiles_apply = f"kubectl apply -f /yamls/{dataset_name}-pmtiles.yaml -n {namespace}\n" # The checksums step reads the PMTiles, so it waits for them here. pmtiles_finish = f""" echo "Step 4: Waiting for PMTiles..." wait_job {dataset_name}-pmtiles {namespace} 172800 """ pmtiles_jobs = f"{dataset_name}-pmtiles" workflow_job = { "apiVersion": "batch/v1", "kind": "Job", "metadata": { "name": f"{dataset_name}-workflow", "namespace": namespace }, "spec": { "template": { "spec": { "serviceAccountName": "cng-datasets-workflow", "restartPolicy": "OnFailure", "containers": [{ "name": "workflow", "image": "bitnami/kubectl:latest", "command": ["bash", "-c"], "args": [f""" set -e {_WAIT_JOB_SH} echo "Starting {dataset_name} workflow..." # Step 0: Setup bucket with public access and CORS echo "Step 0: Setting up bucket..." kubectl apply -f /yamls/{dataset_name}-setup-bucket.yaml -n {namespace} echo "Waiting for bucket setup to complete..." wait_job {dataset_name}-setup-bucket {namespace} 600 # Step 1: Convert to optimized GeoParquet (needed by both pmtiles and hex jobs) echo "Step 1: Converting to optimized GeoParquet..." kubectl apply -f /yamls/{dataset_name}-convert.yaml -n {namespace} echo "Waiting for GeoParquet conversion to complete..." wait_job {dataset_name}-convert {namespace} 3600 # Step 2: Run pmtiles and hex tiling in parallel (both use the converted geoparquet) echo "Step 2: H3 hexagonal tiling and PMTiles generation (parallel)..." {pmtiles_apply}{hex_apply} echo "Waiting for hex tiling to complete (PMTiles continues in background)..." echo "Timeout set to 48 hours (172800s)..." wait_job {dataset_name}-hex {namespace} 172800 echo "Step 3: Repartitioning by h0..." kubectl apply -f /yamls/{dataset_name}-repartition.yaml -n {namespace} echo "Waiting for repartition to complete..." wait_job {dataset_name}-repartition {namespace} 3600 {pmtiles_finish} echo "Step 5: Sizes and checksums of the outputs..." kubectl apply -f /yamls/{dataset_name}-checksums.yaml -n {namespace} wait_job {dataset_name}-checksums {namespace} 14400 echo "✓ Workflow complete!" echo "" echo "Clean up with:" echo " kubectl delete jobs {dataset_name}-setup-bucket {dataset_name}-convert{' ' + dataset_name + '-plan' if planned else ''} {pmtiles_jobs} {dataset_name}-hex {dataset_name}-repartition {dataset_name}-checksums {dataset_name}-workflow -n {namespace} --ignore-not-found" echo " kubectl delete configmap {configmap_name} -n {namespace}" """], "resources": { "requests": {"cpu": "500m", "memory": "512Mi"}, "limits": {"cpu": "500m", "memory": "512Mi"} }, "volumeMounts": [{"name": "yamls", "mountPath": "/yamls"}] }], "volumes": [{ "name": "yamls", "configMap": {"name": configmap_name} }] } }, "ttlSecondsAfterFinished": 10800 } } with open(output_path / "workflow.yaml", "w") as f: yaml.dump(workflow_job, f, default_flow_style=False)
[docs] def generate_sync_job( job_name: str, source: str, destination: str, output_file: str = "sync-job.yaml", namespace: Optional[str] = None, image: str = "ghcr.io/boettiger-lab/datasets:latest", cpu: str = "2", memory: str = "4Gi", dry_run: bool = False, ) -> str: """ Generate Kubernetes job for syncing between two S3 storage locations using rclone. Args: job_name: Name for the Kubernetes job source: Source path in rclone remote format (e.g., 'remote1:bucket/path') destination: Destination path in rclone remote format (e.g., 'remote2:bucket/path') output_file: Path to save the generated YAML file namespace: Kubernetes namespace (default: ClusterConfig's, geo-workflows, the same as the workflow generators; issue #312) image: Container image with rclone (default: ghcr.io/boettiger-lab/datasets:latest) cpu: CPU request/limit (default: 2) memory: Memory request/limit (default: 4Gi) dry_run: If True, only show what would be synced without actually syncing Returns: Path to the generated YAML file Example: >>> generate_sync_job( ... job_name="sync-data", ... source="nrp:public-dataset/data", ... destination="aws:backup-bucket/data", ... output_file="k8s/sync-job.yaml" ... ) """ namespace = namespace or ClusterConfig().namespace dry_run_flag = "--dry-run" if dry_run else "" job_spec = { "apiVersion": "batch/v1", "kind": "Job", "metadata": { "name": job_name, "namespace": namespace, "labels": {"k8s-app": job_name} }, "spec": { "completions": 1, "parallelism": 1, "backoffLimit": 2, "ttlSecondsAfterFinished": 10800, # Clean up after 3 hours "template": { "metadata": {"labels": {"k8s-app": job_name}}, "spec": { "priorityClassName": "opportunistic", "affinity": { "nodeAffinity": { "requiredDuringSchedulingIgnoredDuringExecution": { "nodeSelectorTerms": [{ "matchExpressions": [{ "key": "feature.node.kubernetes.io/pci-10de.present", "operator": "NotIn", "values": ["true"] }] }] } } }, "restartPolicy": "Never", "containers": [{ "name": "sync-task", "image": image, "imagePullPolicy": "Always", "volumeMounts": [ {"name": "rclone-config", "mountPath": "/root/.config/rclone", "readOnly": True} ], "command": ["bash", "-c"], "args": [f"""set -e echo "Starting rclone sync..." echo "Source: {source}" echo "Destination: {destination}" echo "" # Run rclone sync rclone sync {dry_run_flag} -v --progress \\ "{source}" \\ "{destination}" echo "" echo "Sync complete!" # Show summary echo "" echo "Summary:" rclone size "{destination}" """], "resources": { "requests": {"cpu": cpu, "memory": memory}, "limits": {"cpu": cpu, "memory": memory} } }], "volumes": [ {"name": "rclone-config", "secret": {"secretName": "rclone-config"}} ] } } } } # Save to file with custom representer for multiline strings output_path = Path(output_file) output_path.parent.mkdir(parents=True, exist_ok=True) # Custom representer for multi-line strings to use literal style (|) def str_representer(dumper, data): if '\n' in data: return dumper.represent_scalar('tag:yaml.org,2002:str', data, style='|') return dumper.represent_scalar('tag:yaml.org,2002:str', data) yaml.add_representer(str, str_representer) with open(output_path, "w") as f: yaml.dump(job_spec, f, default_flow_style=False, sort_keys=False) print(f"✓ Generated sync job: {output_file}") print("") print("Submit with:") print(f" kubectl apply -f {output_file} -n {namespace}") print("") print("Monitor progress:") print(f" kubectl logs -f job/{job_name} -n {namespace}") print("") print("Clean up:") print(f" kubectl delete -f {output_file} -n {namespace}") return str(output_path)