Kubernetes API¶
Generate Kubernetes and Armada job manifests for the cluster workflows.
Kubernetes job generation and management utilities.
- class cng_datasets.k8s.ClusterConfig(s3_endpoint: str = 'rook-ceph-rgw-nautiluss3.rook', s3_public_endpoint: str = 's3-west.nrp-nautilus.io', s3_secret_name: str = 'aws', rclone_secret_name: str = 'rclone-config', rclone_remote: str = 'nrp', namespace: str = 'geo-workflows', armada_queue: str | None = None, armada_max_cpu: str = '16', armada_max_memory: str = '32Gi', priority_class: str = '', node_affinity: str = 'gpu-avoid')[source]¶
Bases:
objectConfiguration 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
load_profile().- __init__(s3_endpoint: str = 'rook-ceph-rgw-nautiluss3.rook', s3_public_endpoint: str = 's3-west.nrp-nautilus.io', s3_secret_name: str = 'aws', rclone_secret_name: str = 'rclone-config', rclone_remote: str = 'nrp', namespace: str = 'geo-workflows', armada_queue: str | None = None, armada_max_cpu: str = '16', armada_max_memory: str = '32Gi', priority_class: str = '', node_affinity: str = 'gpu-avoid') None¶
- class cng_datasets.k8s.K8sJobManager(namespace: str = 'geo-workflows', image: str = 'python:3.12-slim', service_account: str | None = None, secrets: List[str] | None = None)[source]¶
Bases:
objectManage Kubernetes jobs for dataset processing.
Generates job YAML configurations and submits them to a Kubernetes cluster.
- __init__(namespace: str = 'geo-workflows', image: str = 'python:3.12-slim', service_account: str | None = None, secrets: List[str] | None = None)[source]¶
Initialize the K8s job manager.
- Parameters:
namespace – Kubernetes namespace for jobs (default geo-workflows, the same as ClusterConfig; issue #312)
image – Container image to use
service_account – Service account name for jobs
secrets – List of secret names to mount
- generate_chunked_job(job_name: str, script_path: str, num_chunks: int, base_args: List[str] | None = None, **kwargs) Dict[str, Any][source]¶
Generate a job for processing data in chunks.
- Parameters:
job_name – Base name for the job
script_path – Path to processing script in container
num_chunks – Total number of chunks to process
base_args – Base arguments for the script
**kwargs – Additional arguments passed to generate_job_yaml
- Returns:
Job specification with indexed completions
- generate_job_yaml(job_name: str, command: List[str], args: List[str] | None = None, env_vars: Dict[str, str] | None = None, cpu: str = '1', memory: str = '4Gi', completions: int = 1, parallelism: int = 1, restart_policy: str = 'OnFailure') Dict[str, Any][source]¶
Generate Kubernetes job specification.
- Parameters:
job_name – Name for the job
command – Container command
args – Command arguments
env_vars – Environment variables
cpu – CPU request/limit
memory – Memory request/limit
completions – Number of job completions needed
parallelism – Number of parallel pods
restart_policy – Pod restart policy
- Returns:
Job specification as dictionary
- cng_datasets.k8s.cluster_config_from_args(profile: str | None = None, **cli_overrides) ClusterConfig[source]¶
Build a ClusterConfig by merging a profile with explicit CLI overrides.
Precedence (highest to lowest): 1. Values in
cli_overridesthat are notNone2. Values from the profile file (ifprofileis given) 3.ClusterConfigfield defaults (NRP Nautilus values)- Parameters:
profile – Profile name or path, or
Noneto use bare defaults.**cli_overrides – Keyword arguments matching
ClusterConfigfield names. PassNonefor any flag the user did not explicitly set.
- Returns:
A fully-populated
ClusterConfig.
- cng_datasets.k8s.convert_workflow_to_armada(k8s_yaml_dir: str, dataset_name: str, queue: str = 'geo-workflows', output_dir: str | None = None, priority_class: str | None = None, max_cpu: str | None = None, max_memory: str | None = None) List[str][source]¶
Convert a directory of k8s Job YAMLs to Armada submission YAMLs.
Reads each job YAML from k8s_yaml_dir, converts to Armada format, and writes to output_dir (defaults to k8s_yaml_dir).
- Parameters:
k8s_yaml_dir – Directory containing k8s Job YAML files
dataset_name – Dataset name (used for job set IDs)
queue – Armada queue name. On NRP, queues map one-to-one onto cluster namespaces, so callers normally pass the workflow’s namespace.
output_dir – Output directory (defaults to k8s_yaml_dir)
priority_class – Armada priority class applied to every converted job, as a literal name or a shorthand (“default”, “preemptible”, “high”). Defaults to DEFAULT_ARMADA_PRIORITY_CLASS when None (issue #183).
max_cpu – The largest pod the cluster admits for Armada, e.g. “16” and “32Gi” on NRP, where Armada pods have no controller and an admission webhook refuses bigger ones. A job asking for more raises before any file is written: submitted, every one of its jobs would fail at admission, and armadactl submit –dry-run does not catch it (#183). None skips the check.
max_memory – The largest pod the cluster admits for Armada, e.g. “16” and “32Gi” on NRP, where Armada pods have no controller and an admission webhook refuses bigger ones. A job asking for more raises before any file is written: submitted, every one of its jobs would fail at admission, and armadactl submit –dry-run does not catch it (#183). None skips the check.
- Returns:
List of generated Armada YAML file paths
- Raises:
ValueError – If a job asks for more than max_cpu or max_memory.
- cng_datasets.k8s.generate_dataset_workflow(dataset_name: str, source_urls: str | List[str] = None, bucket: str = None, output_dir: str = '.', namespace: str | None = None, image: str = 'ghcr.io/boettiger-lab/datasets:latest', git_repo: str = 'https://github.com/boettiger-lab/datasets.git', h3_resolution: int | None = None, resolution_by_area: str | None = None, parent_resolutions: List[int] | None = None, polyfill: str = 'centre', id_column: str | None = None, layer: str | None = None, hex_memory: str = '8Gi', convert_memory: str | None = None, hex_retries: int = 2, max_failed_indexes: int = 1, max_parallelism: int = 50, max_completions: int = 200, chunk_size: int | None = None, cells_per_chunk: float | None = None, intermediate_chunk_size: int = 10, row_group_size: int = 100000, simplify_tolerance: float | None = None, trim_strings: bool = False, lat_column: str | None = None, lon_column: str | None = None, expect_features: int | None = None, spatial_order: bool = True, csv_sample_size: int | None = None, pmtiles_max_zoom: int | None = None, pmtiles_chunks: int | None = None, pmtiles_split_zoom: int | None = None, pmtiles_storage: str = '50Gi', backend: str = 'k8s', armada_priority_class: str | None = None, armada_queue: str | None = None, hex_storage: str = '10Gi', repartition_storage: str = '50Gi', repartition_memory: str = '32Gi', profile: str | None = None, s3_endpoint: str | None = None, s3_public_endpoint: str | None = None, s3_secret_name: str | None = None, rclone_secret_name: str | None = None, rclone_remote: str | None = None, priority_class: str | None = None, node_affinity: str | None = None, source_url: str | List[str] = None)[source]¶
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
- Parameters:
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-orderto 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.
- cng_datasets.k8s.generate_job_yaml(job_name: str, command: List[str], namespace: str = 'default', **kwargs) Dict[str, Any][source]¶
Convenience function to generate a job YAML specification.
- Parameters:
job_name – Name for the job
command – Container command
namespace – Kubernetes namespace
**kwargs – Additional arguments passed to K8sJobManager
- Returns:
Job specification dictionary
- cng_datasets.k8s.generate_mdim_workflow(dataset_name: str, inputs: str | List[str], variables: str | List[str], bucket: str, output_dir: str = '.', namespace: str | None = None, image: str = 'ghcr.io/boettiger-lab/datasets:latest', h3_resolution: int = 6, parent_resolutions: List[int] | None = None, hex_resampling: str = 'mean', time_agg: str = 'none', time_start: str | None = None, time_end: str | None = None, placement: str = 'auto', hex_memory: str = '16Gi', hex_cpu: str = '4', hex_storage: str = '10Gi', max_parallelism: int = 50, h0_subset: List[int] | None = None, chunk_resolution: int = 0, hex_retries: int = 2, max_failed_indexes: int = 1, 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: str | None = None, armada_queue: str | None = None, profile: str | None = None, s3_endpoint: str | None = None, s3_public_endpoint: str | None = None, s3_secret_name: str | None = None, rclone_secret_name: str | None = None, rclone_remote: str | None = None, priority_class: str | None = None, node_affinity: str | None = None)[source]¶
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.
- cng_datasets.k8s.generate_raster_workflow(dataset_name: str, source_urls: str | List[str], bucket: str, output_dir: str = '.', namespace: str | None = 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: List[int] | None = None, value_column: str = 'value', nodata_value: float | None = None, hex_resampling: str = 'mean', hex_memory: str = '32Gi', max_parallelism: int = 61, h0_subset: List[int] | None = None, hex_storage: str = '20Gi', hex_workers: int | None = None, hex_chunk_size: int = 100000, hex_cpu: str = '4', chunk_resolution: int = 0, max_hex_memory: str | None = None, hex_retries: int = 2, max_failed_indexes: int = 1, merge_memory: str = '16Gi', merge_storage: str = '50Gi', cog_storage: str = '50Gi', target_extent: tuple | None = None, target_resolution: float | None = None, band: int | None = None, output_cog_name: str | None = None, years: str | List[int] | None = None, cutline: str | None = None, cutline_where: str | None = None, value_units: str | None = None, backend: str = 'k8s', armada_priority_class: str | None = None, armada_queue: str | None = None, profile: str | None = None, s3_endpoint: str | None = None, s3_public_endpoint: str | None = None, s3_secret_name: str | None = None, rclone_secret_name: str | None = None, rclone_remote: str | None = None, priority_class: str | None = None, node_affinity: str | None = None, source_url: str | None = None)[source]¶
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.
- Parameters:
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 onyearand 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).
- cng_datasets.k8s.generate_sync_job(job_name: str, source: str, destination: str, output_file: str = 'sync-job.yaml', namespace: str | None = None, image: str = 'ghcr.io/boettiger-lab/datasets:latest', cpu: str = '2', memory: str = '4Gi', dry_run: bool = False) str[source]¶
Generate Kubernetes job for syncing between two S3 storage locations using rclone.
- Parameters:
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" ... )
- cng_datasets.k8s.k8s_indexed_job_to_armada(job_spec: Dict[str, Any], queue: str, job_set_id: str, priority_class: str | None = None, indices: List[int] | None = None) Dict[str, Any][source]¶
Convert a k8s Indexed Job to multiple Armada jobs.
Each indexed completion becomes a separate Armada job with ${JOB_COMPLETION_INDEX} replaced by the literal index value in all command/args strings.
- Parameters:
job_spec – k8s Job spec with completionMode: Indexed
queue – Armada queue
job_set_id – Unique identifier for this job set
priority_class – Armada priority class, either a literal name (“armada-default”) or a shorthand (“default”, “preemptible”, “high”). Defaults to DEFAULT_ARMADA_PRIORITY_CLASS when None.
indices – Expand only these completion indices instead of all of them. Armada exposes no retry service on NRP (armadactl get retry-policies returns Unimplemented) and a preempted job is not rescheduled, so re-running the handful of units that failed is a normal pipeline stage rather than an exception (issue #183).
- Returns:
Armada submission dict with one job per expanded completion index
- cng_datasets.k8s.k8s_job_to_armada(job_spec: Dict[str, Any], queue: str, job_set_id: str, priority_class: str | None = None) Dict[str, Any][source]¶
Convert a single-pod k8s Job spec to Armada submission format.
- Parameters:
job_spec – Standard k8s batch/v1 Job spec dict
queue – Armada queue (typically matches k8s namespace)
job_set_id – Unique identifier for this job set
priority_class – Armada priority class, either a literal name (“armada-default”) or a shorthand (“default”, “preemptible”, “high”). Defaults to DEFAULT_ARMADA_PRIORITY_CLASS when None.
- Returns:
Armada submission dict ready for YAML serialization
- cng_datasets.k8s.load_profile(name_or_path: str) Dict[str, Any][source]¶
Load a cluster profile and return its values as a dict.
Resolution order:
Treat as a file path if it ends in
.yaml/.ymlor contains a path separator — resolved relative to the current working directory.~/.config/cng-datasets/profiles/<name>.yamlBuilt-in profiles shipped with the package (currently:
nrp).
- Parameters:
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.