kentosasaki-jp
initial release
5fa6515
Raw
History Blame Contribute Delete
12.2 kB
#!/usr/bin/env bash
set -euo pipefail
# Download dataset files from the Turing Motors Open Dataset API.
#
# Features:
# - Parallel downloads with configurable concurrency
# - Byte-level progress bar with speed and ETA
# - Resume support: re-run to continue interrupted downloads
# - Automatic pagination for large file lists
# - Post-download size verification
#
# Requirements: bash 4.3+, curl, awk, and standard POSIX utilities
# (grep, sed, paste, find, du, stat, mktemp, wc)
#
# Usage:
# ./download-dataset.sh -u <list-url> [-o <output-dir>] [-p <parallel>]
# ============================================================
# Utilities
# ============================================================
die() { echo "Error: $*" >&2; exit 1; }
usage() {
cat <<'HELP'
Usage: download-dataset.sh -u <list-url> [-o <output-dir>] [-p <parallel>]
Options:
-u List API URL (required)
-o Output directory (default: current directory)
-p Number of parallel downloads (default: 8)
-h Show this help
Examples:
./download-dataset.sh -u "https://open-dataset.turing-motors.net/api/list?token=xxx"
./download-dataset.sh -u "https://...?token=xxx" -o ./dataset -p 16
HELP
exit "${1:-0}"
}
# Format seconds as human-readable duration
format_duration() {
local s=$1
if [ "$s" -ge 3600 ]; then
printf "%dh%02dm%02ds" $((s / 3600)) $((s % 3600 / 60)) $((s % 60))
elif [ "$s" -ge 60 ]; then
printf "%dm%02ds" $((s / 60)) $((s % 60))
else
printf "%ds" "$s"
fi
}
# Format bytes as human-readable size (pure bash)
format_bytes() {
local b=$1 unit=0 int frac
local units=(B KiB MiB GiB TiB)
int=$b
while [ "$int" -ge 1024 ] && [ "$unit" -lt 4 ]; do
frac=$(( (int % 1024) * 10 / 1024 ))
int=$((int / 1024))
unit=$((unit + 1))
done
if [ "$unit" -eq 0 ]; then
printf "%d B" "$b"
else
printf "%d.%d %s" "$int" "$frac" "${units[$unit]}"
fi
}
# Cross-platform file size in bytes (GNU stat / BSD stat)
file_size() {
stat --printf="%s" "$1" 2>/dev/null && return
stat -f %z "$1" 2>/dev/null && return
echo 0
}
# Cross-platform directory size in bytes
dir_size_bytes() {
local val
# GNU du -sb: byte-precise apparent size (Linux)
if read -r val _ < <(du -sb "$1" 2>/dev/null); then
echo "$val"
return
fi
# Fallback: du -sk in KB (macOS / BSD)
if read -r val _ < <(du -sk "$1" 2>/dev/null); then
echo $((val * 1024))
return
fi
echo 0
}
# ============================================================
# JSON parsing (pure shell — no jq dependency)
# ============================================================
# Extract objects as tab-separated lines: key\tsize\turl
parse_objects() {
grep -oE '"key":"[^"]*"|"size":[0-9]*|"url":"[^"]*"' \
| paste - - - \
| sed 's/"key":"//; s/"\t"size":/\t/; s/\t"url":"/\t/; s/"$//'
}
# Extract pagination cursor (empty string if absent)
parse_cursor() {
grep -oE '"cursor":"[^"]*"' | sed 's/"cursor":"//; s/"$//' || true
}
# ============================================================
# Fetch file list (with automatic pagination)
# ============================================================
fetch_file_list() {
local url=$1 response file_list cursor page
echo "Fetching file list..." >&2
response=$(curl -sf "$url") || die "Failed to fetch file list from API"
file_list=$(echo "$response" | parse_objects)
cursor=$(echo "$response" | parse_cursor)
while [ -n "$cursor" ]; do
echo " fetching next page..." >&2
page=$(curl -sf "${url}&cursor=${cursor}") \
|| die "Failed to fetch page (cursor: ${cursor:0:20}...)"
file_list="${file_list}
$(echo "$page" | parse_objects)"
cursor=$(echo "$page" | parse_cursor)
done
echo "$file_list"
}
# ============================================================
# Progress monitor (runs in background)
# ============================================================
# Build a progress bar string: [####..........]
build_bar() {
local filled=$1 empty=$2 bar="" spc=""
if [ "$filled" -gt 0 ]; then bar=$(printf '%*s' "$filled" '' | tr ' ' '#'); fi
if [ "$empty" -gt 0 ]; then spc=$(printf '%*s' "$empty" '' | tr ' ' '.'); fi
printf "[%s%s]" "$bar" "$spc"
}
# Render a single progress line to stderr
render_progress() {
local cur_bytes=$1 total_bytes=$2 done_count=$3 total=$4
local active=$5 speed=$6 elapsed=$7
local bar_w=30
# Completion
if [ "$done_count" -ge "$total" ] && [ "$total" -gt 0 ]; then
printf "\r%s %s/%s %d/%d files elapsed: %s done!%*s\n" \
"$(build_bar "$bar_w" 0)" \
"$(format_bytes "$cur_bytes")" "$(format_bytes "$total_bytes")" \
"$done_count" "$total" "$(format_duration "$elapsed")" 20 "" >&2
return 1 # signal: stop the monitor
fi
# In progress
if [ "$cur_bytes" -gt 0 ] && [ "$total_bytes" -gt 0 ]; then
local filled=$((cur_bytes * bar_w / total_bytes))
if [ "$filled" -gt "$bar_w" ]; then filled=$bar_w; fi
local empty=$((bar_w - filled))
local remaining=$((total_bytes - cur_bytes)) eta=0
if [ "$speed" -gt 0 ]; then eta=$((remaining / speed)); fi
local status="${done_count}/${total} done"
if [ "$active" -gt 0 ]; then status="${status}, ${active} active"; fi
printf "\r%s %s/%s %s %s/s ETA: %s%*s" \
"$(build_bar "$filled" "$empty")" \
"$(format_bytes "$cur_bytes")" "$(format_bytes "$total_bytes")" \
"$status" "$(format_bytes "$speed")" \
"$(format_duration "$eta")" 10 "" >&2
return 0
fi
# Not started
printf "\r%s 0/%s elapsed: %s starting...%*s" \
"$(build_bar 0 "$bar_w")" \
"$(format_bytes "$total_bytes")" \
"$(format_duration "$elapsed")" 10 "" >&2
}
run_progress_monitor() {
# Disable strict mode: the monitor must not die on transient errors
set +eu
local total=$1 total_bytes=$2 output_dir=$3 progress_dir=$4
local max_parallel=$5 start_time=$6
local speed_smooth=0 prev_time=$start_time
local baseline_bytes prev_bytes
baseline_bytes=$(dir_size_bytes "$output_dir")
prev_bytes=0
while true; do
local now elapsed cur_bytes
now=$(date +%s)
elapsed=$((now - start_time))
cur_bytes=$(( $(dir_size_bytes "$output_dir") - baseline_bytes ))
# Speed: exponential moving average (70/30 smoothing)
local dt=$((now - prev_time))
if [ "$dt" -gt 0 ]; then
local instant=$(( (cur_bytes - prev_bytes) / dt ))
if [ "$instant" -lt 0 ]; then instant=0; fi
speed_smooth=$(( (speed_smooth * 7 + instant * 3) / 10 ))
prev_bytes=$cur_bytes
prev_time=$now
fi
# Count completed and failed (single find, split by name)
local all_count fail_count done_count
all_count=$(find "$progress_dir" -maxdepth 1 -type f 2>/dev/null | wc -l)
fail_count=$(find "$progress_dir" -maxdepth 1 -name '*.fail' -type f 2>/dev/null | wc -l)
done_count=$((all_count - fail_count))
# Estimate active downloads: capped at max_parallel
local dispatched=$((done_count + fail_count))
local active=$((total - dispatched))
if [ "$active" -gt "$max_parallel" ]; then active=$max_parallel; fi
if [ "$active" -lt 0 ]; then active=0; fi
render_progress "$cur_bytes" "$total_bytes" "$done_count" "$total" \
"$active" "$speed_smooth" "$elapsed" || break
sleep 1
done
}
# ============================================================
# Download a single file
# ============================================================
download_file() {
local key=$1 size=$2 url=$3 dest=$4
mkdir -p "$(dirname "$dest")"
# Skip if already downloaded with correct size
if [ -f "$dest" ] && [ "$(file_size "$dest")" = "$size" ]; then
return 0
fi
# Download with resume support
curl -fSL -C - -o "$dest" "$url" 2>/dev/null || return 1
# Verify downloaded size
local actual
actual=$(file_size "$dest")
if [ "$actual" != "$size" ]; then
rm -f "$dest"
return 1
fi
}
# ============================================================
# Argument parsing
# ============================================================
parse_args() {
list_url=""
output_dir="."
parallel=8
while getopts "u:o:p:h" opt; do
case "$opt" in
u) list_url="$OPTARG" ;;
o) output_dir="$OPTARG" ;;
p) parallel="$OPTARG" ;;
h) usage 0 ;;
*) usage 1 >&2 ;;
esac
done
if [ -z "$list_url" ]; then
die "-u <list-url> is required"
fi
if ! [[ "$parallel" =~ ^[1-9][0-9]*$ ]]; then
die "-p must be a positive integer (got: '$parallel')"
fi
}
# ============================================================
# Cleanup
# ============================================================
monitor_pid=""
listfile=""
progress_dir=""
cleanup() {
if [ -n "$monitor_pid" ]; then kill "$monitor_pid" 2>/dev/null || true; fi
local pids
pids=$(jobs -p 2>/dev/null) || true
# shellcheck disable=SC2086 # word splitting intentional for multiple PIDs
if [ -n "$pids" ]; then kill $pids 2>/dev/null || true; fi
if [ -n "$listfile" ]; then rm -f "$listfile"; fi
if [ -n "$progress_dir" ]; then rm -rf "$progress_dir"; fi
}
# EXIT handles normal exit; INT/TERM must explicitly exit after cleanup
trap cleanup EXIT
trap 'cleanup; echo ""; exit 130' INT
trap 'cleanup; exit 143' TERM
# ============================================================
# Summary
# ============================================================
print_summary() {
local progress_dir=$1 total=$2
local failed
failed=$(find "$progress_dir" -maxdepth 1 -name '*.fail' -type f 2>/dev/null | wc -l)
echo ""
echo "Complete: $((total - failed))/$total succeeded."
if [ "$failed" -gt 0 ]; then
echo "Failed: $failed file(s). Re-run to retry." >&2
fi
return "$failed"
}
# ============================================================
# Main
# ============================================================
# Fetch file list and write to a temp file (key\tsize\turl per line).
# Sets: listfile, total, total_bytes
prepare_file_list() {
local file_list
file_list=$(fetch_file_list "$list_url")
listfile=$(mktemp)
echo "$file_list" | grep $'\t' > "$listfile"
total=$(wc -l < "$listfile")
total_bytes=$(awk -F'\t' '{s += $2} END {print s + 0}' "$listfile")
}
# Start the background progress monitor.
# Sets: monitor_pid
start_monitor() {
start_time=$(date +%s)
run_progress_monitor "$total" "$total_bytes" "$output_dir" "$progress_dir" \
"$parallel" "$start_time" &
monitor_pid=$!
}
# Stop the background progress monitor.
stop_monitor() {
sleep 2
kill "$monitor_pid" 2>/dev/null || true
wait "$monitor_pid" 2>/dev/null || true
monitor_pid=""
}
# Download all files using a parallel job pool (wait -n).
run_downloads() {
local running=0 idx=0
while IFS=$'\t' read -r key size url; do
if [ -z "$key" ]; then continue; fi
idx=$((idx + 1))
(
if download_file "$key" "$size" "$url" "$output_dir/$key"; then
touch "$progress_dir/$idx"
else
touch "$progress_dir/$idx.fail"
fi
) &
running=$((running + 1))
if [ "$running" -ge "$parallel" ]; then
wait -n 2>/dev/null || true
running=$((running - 1))
fi
done < "$listfile"
wait 2>/dev/null || true
}
main() {
parse_args "$@"
mkdir -p "$output_dir"
prepare_file_list
progress_dir=$(mktemp -d)
echo "Found $total file(s) to download ($(format_bytes "$total_bytes"), parallel: $parallel)."
echo ""
start_monitor
run_downloads
stop_monitor
print_summary "$progress_dir" "$total"
}
main "$@"