use std::fs;
use std::io::Write as _;
use std::path::{Path, PathBuf};
use std::process::Command;
use std::time::Duration;
use crate::error::{DatasetError, IoOp, IoResultExt as _, Result, WithinExt as _};
use crate::cli::FetchArgs;
use crate::country::{BoundaryFile, BoundarySource};
use crate::exit::Exit;
use crate::layout::{self, Settings, hex, read_json, sha256_file};
use crate::lists::{write_lists, write_lists_quiet};
use crate::settings;
const FINAL_LISTING: &str = "/products/CHIRPS/v3.0/pentads/global/cogs/";
const PRELIM_LISTING: &str = "/products/CHIRPS/v3.0/prelim/pentads/global/tifs/";
const ATTEMPTS: u32 = 10;
const RETRY_DELAY: u64 = 10;
const DEFAULT_HOST: &str = "https://data.chc.ucsb.edu";
fn hosts() -> Result<Vec<String>> {
checked_hosts(&settings::current().sources.chirps_hosts)
}
fn checked_hosts(configured: &[String]) -> Result<Vec<String>> {
if configured.is_empty() {
return Ok(vec![DEFAULT_HOST.to_owned()]);
}
if let Some(host) = configured.iter().find(|host| !host.starts_with("https://")) {
return Err(DatasetError::fetch(format!(
"the CHIRPS host {host} is not https: rasters are only fetched over TLS"
)));
}
Ok(configured.to_vec())
}
fn agent(https_only: bool) -> Result<ureq::Agent> {
Ok(ureq::Agent::config_builder()
.timeout_global(Some(Duration::from_secs(1800)))
.http_status_as_error(false)
.https_only(https_only)
.build()
.into())
}
fn is_tiff_header(bytes: &[u8]) -> bool {
matches!(
bytes.get(..4),
Some(b"II*\0" | b"MM\0*" | b"II+\0" | b"MM\0+")
)
}
fn starts_like_tiff(path: &Path) -> bool {
use std::io::Read as _;
let mut head = [0_u8; 4];
fs::File::open(path)
.and_then(|mut file| file.read_exact(&mut head))
.is_ok()
&& is_tiff_header(&head)
}
fn remote_size(agent: &ureq::Agent, url: &str) -> Option<u64> {
let response = agent.head(url).call().ok()?;
if !(200..300).contains(&response.status().as_u16()) {
return None;
}
response
.headers()
.get("content-length")
.and_then(|value| value.to_str().ok())
.and_then(|value| value.parse::<u64>().ok())
}
fn file_size(path: &Path) -> u64 {
fs::metadata(path).map(|meta| meta.len()).unwrap_or(0)
}
fn get_from(agent: &ureq::Agent, url: &str, start: u64) -> Result<Vec<u8>> {
let mut attempt = 0;
loop {
attempt += 1;
let mut request = agent.get(url);
if start > 0 {
request = request.header("range", &format!("bytes={start}-"));
}
match request.call() {
Ok(mut response) if (200..300).contains(&response.status().as_u16()) => {
return response
.body_mut()
.with_config()
.limit(512 * 1024 * 1024)
.read_to_vec()
.within(format!("reading the body of {url}"));
}
Ok(response) => {
if attempt >= ATTEMPTS {
return Err(DatasetError::fetch(format!(
"{url} answered {}",
response.status()
)));
}
}
Err(error) => {
if attempt >= ATTEMPTS {
return Err(error).within(format!("GET {url}"));
}
}
}
std::thread::sleep(Duration::from_secs(RETRY_DELAY));
}
}
pub fn fetch_one(agent: &ureq::Agent, hosts: &[String], path: &str, dest: &Path) -> Result<()> {
let name = dest
.file_name()
.map(|name| name.to_string_lossy().into_owned())
.unwrap_or_default();
let sizes: Vec<Option<u64>> = hosts
.iter()
.map(|host| remote_size(agent, &format!("{host}{path}")))
.collect();
let part = dest.with_extension("part");
if sizes.iter().all(Option::is_none) && dest.is_file() && !part.exists() {
println!("SKIP {name} (no size)");
return Ok(());
}
for (host, size) in hosts.iter().zip(&sizes) {
let url = format!("{host}{path}");
if let Some(size) = size {
if dest.is_file() && file_size(dest) == *size {
println!("SKIP {name}");
return Ok(());
}
if part.is_file() && file_size(&part) == *size && starts_like_tiff(&part) {
fs::rename(&part, dest).io_at(IoOp::Rename, &part)?;
println!("OK {name}");
return Ok(());
}
if part.is_file() && file_size(&part) == *size {
fs::remove_file(&part).io_at(IoOp::Remove, &part)?;
}
if part.is_file() && file_size(&part) > *size {
fs::remove_file(&part).io_at(IoOp::Remove, &part)?;
}
}
let start = if part.is_file() { file_size(&part) } else { 0 };
if start > 0 {
println!("RESUME {name} from {start}");
}
if let Some(parent) = dest.parent() {
fs::create_dir_all(parent).io_at(IoOp::Create, parent)?;
}
let Ok(bytes) = get_from(agent, &url, start) else {
continue;
};
let mut file = fs::OpenOptions::new()
.create(true)
.append(true)
.open(&part)
.io_at(IoOp::Open, &part)?;
file.write_all(&bytes).io_at(IoOp::Write, &part)?;
drop(file);
if let Some(size) = size
&& file_size(&part) != *size
{
eprintln!(
"size mismatch for {url}: got {}, expected {size}",
file_size(&part)
);
fs::remove_file(&part).io_at(IoOp::Remove, &part)?;
continue;
}
if !starts_like_tiff(&part) {
eprintln!("{url} is not a TIFF: discarded");
fs::remove_file(&part).io_at(IoOp::Remove, &part)?;
continue;
}
fs::rename(&part, dest).io_at(IoOp::Rename, &part)?;
println!("OK {name}");
return Ok(());
}
if sizes.iter().all(Option::is_none) && dest.is_file() {
println!("SKIP {name} (no size)");
return Ok(());
}
Err(DatasetError::fetch(format!("no host delivered {path}")))
}
pub fn chirps(list: &Path, src: &Path) -> Result<()> {
let text = fs::read_to_string(list).io_at(IoOp::Read, list)?;
let agent = agent(true)?;
let hosts = hosts()?;
let mut failed = Vec::new();
for line in text.lines() {
let line = line.trim_end();
if line.is_empty() || line.starts_with('#') {
continue;
}
let mut parts = line.split_whitespace();
let (Some(status), Some(path)) = (parts.next(), parts.next()) else {
eprintln!("bad list line: {line}");
failed.push(line.to_owned());
continue;
};
if status != "final" && status != "prelim" || !path.starts_with('/') {
eprintln!("bad list line: {line}");
failed.push(line.to_owned());
continue;
}
let name = path.rsplit('/').next().unwrap_or_default();
let dest = src.join(status).join(name);
if fetch_one(&agent, &hosts, path, &dest).is_err() {
failed.push(path.to_owned());
}
}
if !failed.is_empty() {
for path in &failed {
println!("FAILED {path}");
}
return Err(Exit(1).into());
}
Ok(())
}
fn get_text(agent: &ureq::Agent, url: &str) -> Result<String> {
let bytes = get_from(agent, url, 0)?;
String::from_utf8(bytes).within(format!("{url} is not UTF-8"))
}
fn fetch_listings(s: &Settings) -> Result<PathBuf> {
let lists = s
.data_root
.join("datasets")
.join(&s.dataset)
.join(&s.cc)
.join("lists");
fs::create_dir_all(&lists).io_at(IoOp::Create, &lists)?;
let agent = agent(true)?;
let hosts = hosts()?;
for (listing, name) in [
(FINAL_LISTING, "listing-final.html"),
(PRELIM_LISTING, "listing-prelim.html"),
] {
let mut written = false;
for host in &hosts {
if let Ok(text) = get_text(&agent, &format!("{host}{listing}")) {
let path = lists.join(name);
let partial = path.with_extension("partial");
fs::write(&partial, text).io_at(IoOp::Write, &partial)?;
fs::rename(&partial, &path).io_at(IoOp::RenameTo, &path)?;
written = true;
break;
}
}
if !written {
return Err(DatasetError::fetch(format!(
"no host of {hosts:?} served the listing {listing}"
)));
}
}
Ok(lists)
}
pub fn boundaries(s: &Settings) -> Result<PathBuf> {
let config = crate::country::CountryConfig::load(&s.country_config_path)?;
if config.boundaries.source != BoundarySource::Shapefile {
return Err(DatasetError::fetch(format!(
"{} has no boundary download",
s.cc
)));
}
let dir = s
.data_root
.join("datasets/boundaries")
.join(&s.cc)
.join("src")
.join(&config.boundaries.release);
fs::create_dir_all(&dir).io_at(IoOp::Create, &dir)?;
let agent = agent(false)?;
let archives: Vec<(PathBuf, &BoundaryFile)> = [
config.boundaries.units.as_ref(),
config.boundaries.parents.as_ref(),
]
.into_iter()
.flatten()
.map(|file| {
let name = file.url.rsplit('/').next().unwrap_or_default().to_owned();
(dir.join(name), file)
})
.collect();
for (dest, file) in &archives {
fetch_archive(&agent, dest, file)?;
}
for (dest, file) in &archives {
unzip_members(dest, &dir, file)?;
}
for (dest, file) in &archives {
let member = dir.join(file.member.rsplit('/').next().unwrap_or(&file.member));
if !member.is_file() {
return Err(DatasetError::fetch(format!(
"{} holds no {}",
dest.display(),
file.member
)));
}
}
println!("{}", dir.display());
Ok(dir)
}
fn fetch_archive(agent: &ureq::Agent, dest: &Path, file: &BoundaryFile) -> Result<()> {
let name = dest
.file_name()
.map(|name| name.to_string_lossy().into_owned())
.unwrap_or_default();
if dest.is_file() {
let digest = hex(&sha256_file(dest)?);
if digest == file.sha256 {
println!("SKIP {name} ({digest})");
return Ok(());
}
}
let url = settings::current()
.sources
.boundaries_url_base
.as_deref()
.map_or_else(
|| file.url.clone(),
|base| format!("{}/{name}", base.trim_end_matches('/')),
);
let part = dest.with_extension("part");
let start = if part.is_file() { file_size(&part) } else { 0 };
let bytes = get_from(agent, &url, start).within(format!("downloading {url}"))?;
let mut out = fs::OpenOptions::new()
.create(true)
.append(true)
.open(&part)
.io_at(IoOp::Open, &part)?;
out.write_all(&bytes).io_at(IoOp::Write, &part)?;
drop(out);
fs::rename(&part, dest).io_at(IoOp::Rename, &part)?;
let digest = hex(&sha256_file(dest)?);
if digest != file.sha256 {
return Err(DatasetError::Exit(Exit(3)));
}
println!("FETCHED {name} ({digest})");
Ok(())
}
fn unzip_members(archive: &Path, dir: &Path, file: &BoundaryFile) -> Result<()> {
let output = Command::new("unzip")
.args(["-o", "-q"])
.arg(archive)
.arg("-d")
.arg(dir)
.output();
match output {
Ok(output) if output.status.success() => {
let _ = file;
Ok(())
}
Ok(output) => Err(DatasetError::fetch(format!(
"unzip {} failed (exit {}): {}",
archive.display(),
output.status.code().unwrap_or(1),
String::from_utf8_lossy(&output.stderr).trim()
))),
Err(error) => Err(DatasetError::fetch(format!("cannot run unzip: {error}"))),
}
}
pub fn overture(release: &str, data_root: &Path) -> Result<()> {
let dest = data_root
.join("inputs/overture")
.join(release)
.join("search/theme=divisions/type=division_area");
fs::create_dir_all(&dest).io_at(IoOp::Create, &dest)?;
let source = format!(
"s3://overturemaps-us-west-2/release/{release}/theme=divisions/type=division_area/*"
);
let output = Command::new("s5cmd")
.args(["--no-sign-request", "sync", &source])
.arg(&dest)
.output();
match output {
Ok(output) if output.status.success() => Ok(()),
Ok(output) => Err(DatasetError::fetch(format!(
"s5cmd sync failed (exit {}): {}",
output.status.code().unwrap_or(1),
String::from_utf8_lossy(&output.stderr).trim()
))),
Err(error) => Err(DatasetError::fetch(format!(
"cannot run s5cmd: {error} (brew install s5cmd)"
))),
}
}
pub fn source_lists(s: &Settings, quiet: bool) -> Result<PathBuf> {
let lists = fetch_listings(s)?;
let season_start = season_start(s)?;
let final_listing = lists.join("listing-final.html");
let prelim_listing = lists.join("listing-prelim.html");
if quiet {
write_lists_quiet(
&final_listing,
&prelim_listing,
&season_start,
&s.baseline,
&lists,
)?;
} else {
write_lists(
&final_listing,
&prelim_listing,
&season_start,
&s.baseline,
&lists,
)?;
}
Ok(lists)
}
pub fn run(args: &FetchArgs) -> Result<()> {
let s = layout::settings(args.dataset.as_deref(), Some(args.country.as_str()))?;
if args.boundaries {
boundaries(&s)?;
return Ok(());
}
if s.dataset == "ndvi" {
return ndvi(args, &s);
}
if args.mode.is_some() {
return Err(DatasetError::Exit(Exit(2)));
}
if s.dataset == "ndvi" {
return ndvi(args, &s);
}
let lists = source_lists(&s, false)?;
let src = s.data_root.join("datasets").join(&s.dataset).join("src");
let mut failed = false;
for name in if args.baseline {
vec!["series.txt", "season.txt", "baseline.txt"]
} else {
vec!["series.txt", "season.txt"]
} {
if chirps(&lists.join(name), &src).is_err() {
failed = true;
}
}
if let Some(config) = s.country_config()
&& config.boundaries.source == BoundarySource::Overture
&& !s
.data_root
.join("inputs/overture")
.join(&s.boundary_release)
.join("search")
.is_dir()
{
overture(&s.boundary_release, &s.data_root)?;
}
if failed {
return Err(Exit(1).into());
}
Ok(())
}
fn ndvi(args: &FetchArgs, s: &Settings) -> Result<()> {
let mode = args.mode.as_deref().unwrap_or("clip");
if !matches!(mode, "clip" | "full") {
return Err(DatasetError::Exit(Exit(2)));
}
if args.baseline {
return crate::baseline::run(&crate::cli::BaselinePassArgs {
mode: args.mode.clone(),
country: args.country.clone(),
dataset: args.dataset.clone(),
min_free_gb: None,
});
}
let list = crate::cdse::source_lists(s, false)?.join("series.txt");
let src = s
.data_root
.join("datasets")
.join(&s.dataset)
.join("src")
.join(&s.cc)
.join("final");
if mode == "full" {
return crate::cdse::download_full(&list, &src);
}
let country = s.country_config();
if let Some(config) = &country
&& config.boundaries.source == BoundarySource::Overture
&& !s
.data_root
.join("inputs/overture")
.join(&s.boundary_release)
.join("search")
.is_dir()
{
overture(&s.boundary_release, &s.data_root)?;
}
let areas = crate::run::ensure_areas(s)?.join("areas.geojson");
let outline = country
.as_ref()
.filter(|config| config.boundaries.holds_soi_land)
.map(|_| s.data_root.join("inputs/india/india-composite.geojson"));
let window = crate::cdse::window(
&areas,
outline.as_deref(),
&s.cc.to_uppercase(),
crate::cdse::NDVI_GRID,
512,
)?;
println!("window {} {} {} {}", window.0, window.1, window.2, window.3);
crate::cdse::probe(&list, window)?;
crate::cdse::download_clip(&list, &src, window)
}
fn season_start(s: &Settings) -> Result<String> {
read_json(&s.config_path)?
.get("season_start")
.and_then(serde_json::Value::as_str)
.map(str::to_owned)
.ok_or_else(|| {
DatasetError::fetch(format!("{} has no season_start", s.config_path.display()))
})
}
#[cfg(test)]
mod tests {
use super::*;
use std::io::{BufRead as _, BufReader};
use std::net::{TcpListener, TcpStream};
fn serve(body: Vec<u8>, seen: std::sync::Arc<std::sync::Mutex<Vec<String>>>) -> String {
let listener = TcpListener::bind("127.0.0.1:0").expect("bind");
let address = listener.local_addr().expect("address").to_string();
std::thread::spawn(move || {
for stream in listener.incoming() {
let Ok(stream) = stream else { continue };
let body = body.clone();
let seen = std::sync::Arc::clone(&seen);
std::thread::spawn(move || {
let _ = answer(stream, &body, &seen);
});
}
});
address
}
fn answer(
mut stream: TcpStream,
body: &[u8],
seen: &std::sync::Arc<std::sync::Mutex<Vec<String>>>,
) -> std::io::Result<()> {
let mut reader = BufReader::new(stream.try_clone()?);
let mut line = String::new();
reader.read_line(&mut line)?;
let mut method = line.split_whitespace();
let verb = method.next().unwrap_or_default().to_owned();
let mut range: Option<String> = None;
loop {
let mut header = String::new();
reader.read_line(&mut header)?;
if header.trim().is_empty() {
break;
}
if let Some(value) = header
.to_ascii_lowercase()
.strip_prefix("range:")
.map(str::trim)
.map(str::to_owned)
{
seen.lock().expect("seen").push(value.clone());
range = Some(value);
}
}
let (status, slice) = match range {
Some(range) => {
let from = range
.trim_start_matches("bytes=")
.split('-')
.next()
.and_then(|value| value.parse::<usize>().ok())
.unwrap_or(0);
("206 Partial Content", &body[from.min(body.len())..])
}
None => ("200 OK", body),
};
if verb == "HEAD" {
let head = format!(
"HTTP/1.1 200 OK\r\nContent-Length: {}\r\nConnection: close\r\n\r\n",
body.len()
);
stream.write_all(head.as_bytes())?;
return stream.flush();
}
let head = format!(
"HTTP/1.1 {status}\r\nContent-Length: {}\r\nConnection: close\r\n\r\n",
slice.len()
);
stream.write_all(head.as_bytes())?;
stream.write_all(slice)?;
stream.flush()
}
fn one_file(size: usize) -> Vec<u8> {
let mut bytes = vec![0_u8; size];
for (index, byte) in bytes.iter_mut().enumerate() {
*byte = u8::try_from(index % 251).unwrap_or_default();
}
bytes[..4].copy_from_slice(b"II*\0");
bytes
}
#[test]
fn the_default_hosts_are_https_only() {
for host in hosts().expect("the default hosts") {
assert!(host.starts_with("https://"), "{host}");
}
}
#[test]
fn a_configured_http_host_is_refused() {
let error = checked_hosts(&[
"https://a.example.test".into(),
"http://b.example.test".into(),
])
.expect_err("a cleartext host");
assert!(
error.to_string().contains("http://b.example.test"),
"{error}"
);
assert_eq!(
checked_hosts(&["https://a.example.test".into()]).expect("https"),
vec!["https://a.example.test".to_owned()]
);
assert_eq!(
checked_hosts(&[]).expect("default"),
vec!["https://data.chc.ucsb.edu".to_owned()]
);
}
#[test]
fn the_download_agent_refuses_cleartext() {
let address = serve(one_file(100), std::sync::Arc::default());
let agent = agent(true).expect("agent");
assert!(agent.get(&format!("http://{address}/file")).call().is_err());
}
#[test]
fn a_download_that_is_not_a_tiff_is_discarded() {
let seen = std::sync::Arc::new(std::sync::Mutex::new(Vec::new()));
let body = vec![b'<'; 400];
let address = serve(body, std::sync::Arc::clone(&seen));
let dir = tempfile::tempdir().expect("a temp dir");
let dest = dir.path().join("chirps.cog");
let agent = agent(false).expect("agent");
let result = fetch_one(&agent, &[format!("http://{address}")], "/file", &dest);
assert!(result.is_err(), "an HTML body is not a raster");
assert!(!dest.exists());
assert!(!dest.with_extension("part").exists());
}
#[test]
fn a_file_with_a_tiff_header_is_accepted_in_every_byte_order() {
for magic in [&b"II*\0"[..], b"MM\0*", b"II+\0", b"MM\0+"] {
let mut body = vec![1_u8; 300];
body[..4].copy_from_slice(magic);
let address = serve(body.clone(), std::sync::Arc::default());
let dir = tempfile::tempdir().expect("a temp dir");
let dest = dir.path().join("chirps.tif");
let agent = agent(false).expect("agent");
fetch_one(&agent, &[format!("http://{address}")], "/file", &dest)
.unwrap_or_else(|e| panic!("{magic:?}: {e}"));
assert_eq!(fs::read(&dest).expect("read"), body);
}
}
#[test]
fn a_partial_file_is_resumed_from_its_length() {
let seen = std::sync::Arc::new(std::sync::Mutex::new(Vec::new()));
let body = one_file(1000);
let address = serve(body.clone(), std::sync::Arc::clone(&seen));
let dir = tempfile::tempdir().expect("a temp dir");
let dest = dir.path().join("src/final/chirps.cog");
fs::create_dir_all(dest.parent().expect("parent")).expect("mkdir");
fs::write(dest.with_extension("part"), &body[..400]).expect("write");
let agent = agent(false).expect("agent");
let url = format!("http://{address}/file");
let start = file_size(&dest.with_extension("part"));
let bytes = get_from(&agent, &url, start).expect("resume");
let mut file = fs::OpenOptions::new()
.append(true)
.open(dest.with_extension("part"))
.expect("open");
file.write_all(&bytes).expect("write");
drop(file);
assert_eq!(fs::read(dest.with_extension("part")).expect("read"), body);
assert_eq!(seen.lock().expect("seen").as_slice(), ["bytes=400-"]);
}
#[test]
fn a_part_longer_than_the_remote_is_discarded() {
let seen = std::sync::Arc::new(std::sync::Mutex::new(Vec::new()));
let body = one_file(500);
let address = serve(body.clone(), std::sync::Arc::clone(&seen));
let dir = tempfile::tempdir().expect("a temp dir");
let dest = dir.path().join("chirps.cog");
fs::write(dest.with_extension("part"), vec![9_u8; 900]).expect("write");
let agent = agent(false).expect("agent");
fetch_one(&agent, &[format!("http://{address}")], "/file", &dest).expect("fetch");
assert_eq!(fs::read(&dest).expect("read"), body);
assert!(!dest.with_extension("part").exists());
}
#[test]
fn a_file_of_the_remote_size_is_skipped() {
let seen = std::sync::Arc::new(std::sync::Mutex::new(Vec::new()));
let body = one_file(321);
let address = serve(body.clone(), std::sync::Arc::clone(&seen));
let dir = tempfile::tempdir().expect("a temp dir");
let dest = dir.path().join("chirps.cog");
fs::write(&dest, &body).expect("write");
let agent = agent(false).expect("agent");
fetch_one(&agent, &[format!("http://{address}")], "/file", &dest).expect("fetch");
assert!(seen.lock().expect("seen").is_empty());
}
#[test]
fn a_malformed_list_line_is_named_and_fails() {
let dir = tempfile::tempdir().expect("a temp dir");
let list = dir.path().join("series.txt");
fs::write(&list, "midday /somewhere/x.cog\n").expect("write");
let err = chirps(&list, &dir.path().join("src")).expect_err("a failure");
let exit = err.exit();
assert_eq!(exit, Some(Exit(1)));
}
}