# shellcheck shell=bash # common.sh: sourced by every script in scripts/, once SAMPLE and GENOME_DIR # are read from the arguments and the environment: # # shellcheck source=lib/common.sh # . "$(dirname "$0")/lib/common.sh" # validate_sample "$SAMPLE" # # It gives each script the same: # versions.env every image tag and coupled data version, sourced with no # fallback: a missing file or a typo stops the script. # umask 077 files the host side writes are readable by their owner only. # GENOME_DIR as exported by the caller (not required here: setup.sh and # validate-setup.sh run without it). # REF_FASTA host path of the GRCh38 FASTA. Default: the NCBI GRCh38 # no-ALT analysis set setup.sh installs. Override from the # environment, absolute or relative to GENOME_DIR; it must lie # inside GENOME_DIR, the only directory containers see. # REF_FASTA_C is the same file inside a container, REF_DICT # its GATK sequence dictionary. # THREADS CPU budget of one step. Default 8; a script that wants another # default sets THREADS=${THREADS:-N} before sourcing this file. # CONTAINER_ENGINE docker by default. # and the helpers validate_sample, require_image, cpath, run_in, have_output, # wrote_vcf, atomic_out, fetch, data_file / install_data_file, install_vep_cache, # lock_acquire / lock_release, pipeline_images, pinned_tag / tag_pinned_image / # pinned_tag_present, image_is_dangling, # scatter_beds, scatter_jobs and run_parallel, PAR_BED / sample_sex / # ploidy_line / ploidy_units, FASTQ_RECORDS_AWK / fastp_total_reads / # read_count_mode / read_count_check, input_stamp / trimmed_reads_current / # trimmed_reads_usable, # described where they are # defined. Keep it bash 3.2 compatible: macOS runs setup.sh with /bin/bash. PGP_ROOT=$(cd "$(dirname "${BASH_SOURCE[0]}")/../.." && pwd) # shellcheck source=../versions.env . "${PGP_ROOT}/versions.env" umask 077 CONTAINER_ENGINE=${CONTAINER_ENGINE:-docker} THREADS=${THREADS:-8} # validate_sample NAME: exit 2 unless NAME is a plain sample name. Scripts put # it into container paths and `bash -c` bodies, so only letters, digits, '.', # '_' and '-' are allowed (the same rule as main.nf), and '.' and '..' are not # names at all. Nor is a name that starts with '-': CPSR and og summary collect # take it as an argument value, and both read '-x' as an option. # CPSR's 3 to 40 characters are bin/cpsr_sample_id's job. validate_sample() { local s=${1:-} if [[ ! "$s" =~ ^[A-Za-z0-9._-]+$ ]] || [ "$s" = "." ] || [ "$s" = ".." ]; then echo "ERROR: invalid sample name '${s}'. Use only letters, digits, '.', '_' and '-' (and not '.' or '..')." >&2 exit 2 fi if [[ "$s" == -* ]]; then echo "ERROR: invalid sample name '${s}': it starts with '-', which tools read as an option. Start it with a letter or digit." >&2 exit 2 fi } # require_image VAR...: exit 1 unless each VAR is set by versions.env. require_image() { local v for v in "$@"; do if [ -z "${!v:-}" ]; then echo "ERROR: ${v} is not set; add it to versions.env." >&2 exit 1 fi done } # cpath HOST_PATH: the path a container sees for a host path inside GENOME_DIR. cpath() { case "$1" in "${GENOME_DIR:?}") printf '/genome' ;; "${GENOME_DIR}"/*) printf '/genome%s' "${1#"$GENOME_DIR"}" ;; "${OG_DOWNLOADS:-/nonexistent}"/*) printf '/downloads%s' "${1#"$OG_DOWNLOADS"}" ;; *) echo "ERROR: ${1} is outside GENOME_DIR (${GENOME_DIR}); containers only see GENOME_DIR (and OG_DOWNLOADS)." >&2 return 1 ;; esac } # shellcheck disable=SC2034 # REF_DICT and REF_FASTA_C are read by the scripts if [ -n "${GENOME_DIR:-}" ]; then GENOME_DIR=${GENOME_DIR%/} # The downloads folder: every raw download of setup, kept (og setup fetch, # scripts/lib/common.sh fetch). OG_DOWNLOADS may name one folder that # several installs share; og reads the same variable. A relative one is # taken from the working directory, so a container mount names a folder. OG_DOWNLOADS=${OG_DOWNLOADS:-} case "$OG_DOWNLOADS" in ""|/*) ;; *) OG_DOWNLOADS="${PWD}/${OG_DOWNLOADS}" ;; esac export OG_DOWNLOADS="${OG_DOWNLOADS:-${GENOME_DIR}/downloads}" OG_DOWNLOADS=${OG_DOWNLOADS%/} # A new file name on purpose: a reference with ALT contigs left from an # older version is never picked up by accident (docs/realignment.md). REF_FASTA=${REF_FASTA:-${GENOME_DIR}/reference/GRCh38_no_alt_analysis_set.fasta} case "$REF_FASTA" in /*) ;; *) REF_FASTA="${GENOME_DIR}/${REF_FASTA}" ;; esac # GATK names the dictionary after the FASTA without its extensions: # ref.fasta and ref.fa.gz both give ref.dict. REF_DICT="${REF_FASTA%.gz}" REF_DICT="${REF_DICT%.*}.dict" REF_FASTA_C=$(cpath "$REF_FASTA") || exit 2 fi # run_in [--net] [--root] [--rw DIR]... [docker run options] IMAGE [COMMAND...] # # `docker run --rm` with these defaults: # --network none the analysis steps need no network; a tool that # reaches out at run time fails loudly instead. # GENOME_DIR at /genome:ro references, ClinVar, caches and bundles are # read-only, and only # GENOME_DIR/SAMPLE (when SAMPLE is set) is writable, at /genome/SAMPLE. # --user UID:GID, HOME=/tmp outputs belong to the caller, not to root. # Opt-outs, each named at the call site with the reason: # --net the step downloads something (a database, a pip package). # --root the image cannot run as an unprivileged user: the container runs # as root (--user 0:0), also when the image names another user. # --rw DIR DIR (inside GENOME_DIR) is writable too, e.g. a shared index. # Everything after the opt-outs goes to `docker run` unchanged. # When an unprivileged run fails and the sample directory holds a path the # caller does not own (versions before this library ran every container as # root), run_in says how to take the directory back. run_in() { local isolate=true root=false d c rc=0 other local -a extra=() while [ $# -gt 0 ]; do case "$1" in --net) isolate=false; shift ;; --root) root=true; shift ;; --rw) d=${2:?run_in --rw needs a directory} c=$(cpath "$d") || exit 2 mkdir -p "$d" extra+=(-v "${d}:${c}") shift 2 ;; *) break ;; esac done local -a args=(run --rm) if $isolate; then args+=(--network none); fi # --root is explicit: the container runs as root (--user 0:0) even when # the image names another user. It is for an image that has not been shown # to run unprivileged, for example PCGR in scripts/17-cpsr.sh. if $root; then args+=(--user 0:0) else args+=(--user "$(id -u):$(id -g)" -e HOME=/tmp) fi args+=(-v "${GENOME_DIR:?}:/genome:ro") case "${OG_DOWNLOADS:-}" in ""|"${GENOME_DIR}"/*) ;; *) [ ! -d "$OG_DOWNLOADS" ] || args+=(-v "${OG_DOWNLOADS}:/downloads:ro") ;; esac if [ -n "${SAMPLE:-}" ]; then mkdir -p "${GENOME_DIR}/${SAMPLE}" args+=(-v "${GENOME_DIR}/${SAMPLE}:/genome/${SAMPLE}") fi "$CONTAINER_ENGINE" "${args[@]}" ${extra[@]+"${extra[@]}"} "$@" || rc=$? if [ "$rc" -ne 0 ] && ! $root && [ -n "${SAMPLE:-}" ]; then # A root-owned *.lock (left by a Nextflow CRAM_ARCHIVE task under # --user root) is opened read-only and blocks nothing: not worth the hint. other=$(find "${GENOME_DIR}/${SAMPLE}" ! -user "$(id -u)" ! -name '*.lock' -print 2>/dev/null | head -n 1) if [ -n "$other" ]; then echo "NOTE: ${other} is not yours. Older versions of this pipeline ran every container as root;" >&2 echo " steps now run as you and cannot write over such files. If the error above is" >&2 echo " 'Permission denied', take the sample directory back and run the step again:" >&2 echo " sudo chown -R \"$(id -u):$(id -g)\" \"${GENOME_DIR}/${SAMPLE}\"" >&2 fi fi return "$rc" } # --- The alignment read count (steps 02 and 02a, validate-setup.sh) ---------- # minimap2 and bwa-mem2 write every read they are given, mapped or not, as one # primary record (neither 0x100 secondary nor 0x800 supplementary), and samtools # fixmate, sort and markdup drop none. So a finished BAM holds as many primary # records as R1 and R2 together hold FASTQ records: reads, not pairs, which is # also the unit of fastp's summary.after_filtering.total_reads. Both aligners # stop at the end of the shorter file of a pair with only a warning, so a cut # R1 or R2 loses reads without an error. The ALIGN_MINIMAP2 module applies the # same rule. READ_COUNT_CHECK=warn turns a difference into a warning. # FASTQ_RECORDS_AWK: an awk program that prints the number of FASTQ records in # its decompressed input, or exits 3 when the line count is not a multiple of # 4 (a record cut short). %.0f, not %d: a 30x file has more than 2^31 lines. # shellcheck disable=SC2034 # read by the step scripts FASTQ_RECORDS_AWK='END { if (NR % 4) { printf "%.0f lines, not a multiple of 4: a record is cut short\n", NR > "/dev/stderr"; exit 3 } printf "%.0f\n", NR / 4 }' # fastp_total_reads JSON: summary.after_filtering.total_reads of a fastp # report (the reads fastp wrote, R1 plus R2 records). Exit status 1 when the # report has none. The summary block comes first in fastp's report, so the # first "after_filtering" object is the summary's. fastp_total_reads() { tr -d ' \t\r\n' < "$1" | awk ' { k = "\"after_filtering\":{\"total_reads\":" i = index($0, k) if (i) { v = substr($0, i + length(k)); sub(/[^0-9].*/, "", v); if (v != "") { print v; found = 1 } } exit } END { exit !found }' } # input_stamp FILE...: one tab-separated line per FILE: its name (no # directory), its size in bytes, its modification time in seconds, and the # sha256 of its first and of its last MiB. A step stores the stamp of its # inputs beside its output and redoes the work when the stamp differs, so a # replaced input is never answered with the output of the one before. Reading # 2 MiB keeps it quick on a 60 GB FASTQ; a copy that kept the old file's time # still differs in size or in its first or last MiB. A symlink is followed # (stat -L): its size and time are those of the file it points to, so a # replaced target changes the stamp. A file that cannot be read fails the # stamp (the pipes run under pipefail) instead of hashing an empty stream. input_stamp() { local f sm head tail for f in "$@"; do [ -f "$f" ] || { echo "ERROR: input_stamp: no file ${f}" >&2; return 1; } sm=$(stat -L -c '%s %Y' "$f" 2>/dev/null || stat -L -f '%z %m' "$f") || return 1 head=$(set -o pipefail; head -c 1048576 "$f" | _digest sha256 -) && [ -n "$head" ] \ && tail=$(set -o pipefail; tail -c 1048576 "$f" | _digest sha256 -) && [ -n "$tail" ] \ || { echo "ERROR: input_stamp: could not checksum ${f}" >&2; return 1; } printf '%s\t%s\t%s\t%s\t%s\n' "${f##*/}" "${sm% *}" "${sm#* }" "$head" "$tail" done } # trimmed_reads_current SAMPLE_DIR SAMPLE: true when fastq_trimmed/ holds the # trimmed pair of the raw reads now in fastq/: its _fastp_inputs.tsv # (written by step 01b) equals input_stamp of fastq/_R1.fastq.gz and # _R2. False when the record is missing (a pair trimmed before the record # existed) or differs (a raw file was replaced since). trimmed_reads_current() { local d=$1 s=$2 now [ -s "${d}/fastq_trimmed/${s}_fastp_inputs.tsv" ] || return 1 now=$(input_stamp "${d}/fastq/${s}_R1.fastq.gz" "${d}/fastq/${s}_R2.fastq.gz") || return 1 [ "$now" = "$(cat "${d}/fastq_trimmed/${s}_fastp_inputs.tsv")" ] } # trimmed_reads_usable SAMPLE_DIR SAMPLE: the check steps 02 and 02a make # before they align fastq_trimmed/. True when the raw pair is not in fastq/ # (nothing to compare with) or trimmed_reads_current holds. Otherwise it says # why on stderr, and what to run, and returns 1: the old trimmed pair would # give a BAM of the old reads. trimmed_reads_usable() { local d=$1 s=$2 [ -f "${d}/fastq/${s}_R1.fastq.gz" ] && [ -f "${d}/fastq/${s}_R2.fastq.gz" ] || return 0 trimmed_reads_current "$d" "$s" && return 0 echo "ERROR: ${d}/fastq_trimmed/ was not trimmed from the raw reads in fastq/ now:" >&2 if [ -s "${d}/fastq_trimmed/${s}_fastp_inputs.tsv" ]; then echo " fastq/${s}_R1.fastq.gz or _R2 changed since step 01b trimmed them." >&2 else echo " it has no ${s}_fastp_inputs.tsv, the record of the reads step 01b trimmed." >&2 fi echo " Run scripts/01b-fastp-qc.sh ${s} first (it trims the reads again), or set" >&2 echo " FASTQ_SUBDIR=fastq to align the raw reads." >&2 return 1 } # read_count_mode: prints READ_COUNT_CHECK (fail, the default, or warn), or # says what is wrong and returns 2. A step calls it before it starts work. read_count_mode() { case "${READ_COUNT_CHECK:-fail}" in fail|warn) echo "${READ_COUNT_CHECK:-fail}" ;; *) echo "ERROR: READ_COUNT_CHECK must be 'fail' or 'warn', got '${READ_COUNT_CHECK}'" >&2; return 2 ;; esac } # read_count_check PRIMARY SOURCE TABLE COUNT...: compare the primary records # of a BAM with the reads that went into the aligner, the sum of the COUNTs # (one per FASTQ, or fastp's total). SOURCE names where the COUNTs come from. # Returns 0 when they are equal; 1 when they differ (what is missing goes to # stderr); 3 when they differ and READ_COUNT_CHECK=warn (the same text, as a # warning); 2 when a count is not a whole number or READ_COUNT_CHECK is bad. # TABLE, unless empty, gets the key/value table the reports read: input_reads, # input_source, primary_records, missing_reads (input minus primary) and # read_count_check (ok or mismatch). read_count_check() { local primary=$1 src=$2 table=$3 mode c total=0 missing verdict=ok level pct shift 3 mode=$(read_count_mode) || return 2 for c in "$primary" "$@"; do if [[ ! "$c" =~ ^(0|[1-9][0-9]*)$ ]]; then echo "ERROR: could not count the reads: '${primary}' primary records in the BAM, '$*' reads in (${src})" >&2 return 2 fi done [ "$#" -gt 0 ] || { echo "ERROR: read_count_check got no input count" >&2; return 2; } for c in "$@"; do total=$((total + c)); done missing=$((total - primary)) [ "$missing" -eq 0 ] || verdict=mismatch if [ -n "$table" ]; then printf 'key\tvalue\ninput_reads\t%s\ninput_source\t%s\nprimary_records\t%s\nmissing_reads\t%s\nread_count_check\t%s\n' \ "$total" "$src" "$primary" "$missing" "$verdict" > "$table" fi if [ "$verdict" = ok ]; then echo "Read count: the BAM holds ${primary} primary records, the ${total} reads that went in (${src})." return 0 fi level=ERROR [ "$mode" = fail ] || level=WARNING if [ "$missing" -gt 0 ]; then pct=$(awk -v m="$missing" -v n="$total" 'BEGIN { printf "%.1f", 100 * m / n }') echo "${level}: the BAM holds ${primary} primary records, but ${total} reads went in (${src}): ${missing} reads (${pct}%) are missing." >&2 else echo "${level}: the BAM holds ${primary} primary records, more than the ${total} reads that went in (${src}): it was not made from these reads." >&2 fi echo " The aligner writes every read it is given, mapped or not, once, so the two counts must be equal." >&2 echo " Depth, copy number (CYP2D6), CNV, telomere content and every call that depends on coverage would be off." >&2 echo " An R1 and R2 with different numbers of records is one cause: minimap2 and bwa-mem2 stop at the end" >&2 echo " of the shorter file with only a warning. See docs/troubleshooting.md, \"The BAM lost reads\"." >&2 if [ "$mode" = warn ]; then echo " READ_COUNT_CHECK=warn: going on." >&2 return 3 fi echo " For an input you know is odd, READ_COUNT_CHECK=warn goes on anyway." >&2 return 1 } # have_output FILE...: true when every FILE is a finished output, the test a # step uses before it skips work. Every FILE must be non-empty, and by name: # .vcf starts with ##fileformat=VCF and has a #CHROM line; # .vcf.gz, .bcf, .bam ends with the BGZF end-of-file block, which htslib # and htsjdk write only when they close the file, and # starts with the format's own header. # So an empty file left by a failed redirect, or one cut short by a killed # run, is redone instead of trusted. have_output() { local f first for f in "$@"; do [ -s "$f" ] || return 1 case "$f" in *.vcf) first=$(head -n 1 "$f") [[ "$first" == "##fileformat=VCF"* ]] || return 1 grep -q '^#CHROM' "$f" || return 1 ;; *.vcf.gz|*.bcf|*.bam) _bgzf_complete "$f" || return 1 first=$(gzip -cd "$f" 2>/dev/null | head -c 16 | tr -d '\000') || true case "$f" in *.vcf.gz) [[ "$first" == "##fileformat=VCF"* ]] || return 1 ;; *.bcf) [[ "$first" == BCF* ]] || return 1 ;; *.bam) [[ "$first" == BAM* ]] || return 1 ;; esac ;; esac done } # wrote_vcf FILE: true when FILE is non-empty and starts with a VCF header, # plain or gzip-compressed. The check after a tool that exited 0: it catches # a run that wrote nothing where the tool said it succeeded. wrote_vcf() { local first [ -s "$1" ] || return 1 first=$(gzip -cdf "$1" 2>/dev/null | head -c 16) || true [[ "$first" == "##fileformat=VCF"* ]] } # vcf_header_samples: the sample names of the VCF header on stdin, one per # line: the #CHROM columns after FORMAT. Nothing for a sites-only VCF. The # pipeline analyses one sample per run (VCF_PRECHECK applies the same rule). vcf_header_samples() { awk -F'\t' '/^#CHROM/ { for (i = 10; i <= NF; i++) print $i }' } # _bgzf_complete FILE: true when FILE ends with the 28-byte BGZF EOF block. _bgzf_complete() { local last last=$(tail -c 28 "$1" | od -An -v -tx1 | tr -d ' \n') [ "$last" = "1f8b08040000000000ff0600424302001b0003000000000000000000" ] } # atomic_out FILE COMMAND [ARGS...]: run COMMAND with its standard output in # FILE.tmp, and rename that to FILE only when COMMAND exits 0 and wrote # something. Otherwise FILE.tmp is removed, FILE is left as it was and the # exit code is returned, so a failed image pull or a crash never leaves an # empty FILE behind for the next run to accept. atomic_out() { local out=$1 rc=0 shift rm -f "${out}.tmp" "$@" > "${out}.tmp" || rc=$? if [ "$rc" -eq 0 ] && [ ! -s "${out}.tmp" ]; then echo "ERROR: $1 wrote nothing for ${out}." >&2 rc=1 fi if [ "$rc" -ne 0 ]; then rm -f "${out}.tmp" return "$rc" fi mv -f "${out}.tmp" "$out" } # _digest md5|sha256|sum FILE: the checksum of FILE (sum = BSD sum, the # format of Ensembl's CHECKSUMS files; only its first field is printed). _digest() { case "$1" in md5) if command -v md5sum >/dev/null 2>&1; then md5sum "$2" | awk '{print $1}' elif command -v md5 >/dev/null 2>&1; then md5 -q "$2" else openssl md5 -r "$2" | awk '{print $1}'; fi ;; sha256) if command -v sha256sum >/dev/null 2>&1; then sha256sum "$2" | awk '{print $1}'; else shasum -a 256 "$2" | awk '{print $1}'; fi ;; sum) sum "$2" | awk '{print $1 + 0}' ;; *) echo "ERROR: unknown checksum type '${1}'" >&2; return 2 ;; esac } # consumer_sites_digest TABLE: the sha256 of the step-40 site table's content, # read through gzip. The gzip wrapper holds the time it was written, so two # builds of the same table differ as files and agree here. setup.sh and # validate-setup.sh compare it with CONSUMER_SITES_TABLE_SHA256. consumer_sites_digest() { _digest sha256 <(gzip -dc "$1") } # consumer_sites_current TABLE: true when the step-40 site table has the format # og consumer export reads, a "## table_format: 2" line. og consumer # build-sites writes it since each site's strand comes from the liftover chain; # a table built before has no such line, has the wrong bases at sites on # inverted blocks, and og consumer export refuses it. Only the header is read. consumer_sites_current() { local f f=$({ gzip -dc "$1" 2>/dev/null || true; } | awk '/^## table_format: / { print $3; exit } /^#rsid/ { exit }') [ "$f" = 2 ] } # og_bin: the og that downloads, OG when set (the unit tests set it), # else bin/og of this checkout. og_bin() { printf '%s' "${OG:-${PGP_ROOT}/bin/og}"; } # og_setup TOOL ARGS: `og setup TOOL ARGS`, reading the table and versions.env # of this checkout (PGP_ROOT). og_setup() { PGP_ROOT=$PGP_ROOT "$(og_bin)" setup "$@" } # _get URL OUT: one transfer of URL to OUT (resuming a partial OUT), or to # stdout when OUT is "-", with no retry: `og setup fetch --get`. curl does it, # or wget when there is no curl, each from PATH; a transfer slower than 1 KB/s # for FETCH_STALL seconds (default 120) fails instead of hanging. _get() { og_setup fetch --get "$@" } # fetch URL DEST [md5|sha256|sum|gzip-ends|crc32c VALUE|CHECKSUM_URL] # # Every download of setup, through `og setup fetch` (rust/crates/og-setup/src/ # fetch.rs, which says it all): URL goes to DEST.part (an interrupted one is # resumed), is checked, and only then renamed to DEST, so a DEST that exists # is whole. A DEST already there that matches its checksum is used with no # download; when the checksum is a list on the server, that small list is # read first (and when it cannot be read, a kept file that matches the # checksum saved beside it, DEST.checksum, is used). One that does not match # is downloaded again, with a message, or, in the downloads folder # (OG_DOWNLOADS), refused and left as it is. A failed # try is tried FETCH_TRIES times (default 3), FETCH_WAIT seconds apart # (default 5, then 10, ...). fetch() { og_setup fetch "$@" } # source_of ID [--part P] FIELD: one field (path, url, check, value, bytes) # of row ID of assets/data-sources.tsv, expanded: `og setup source`. An # installer reads a URL the table holds from here, never spells it again. source_of() { og_setup source "$@" } # dl NAME: where setup keeps the raw download NAME, in the downloads folder. dl() { printf '%s/%s' "${OG_DOWNLOADS:?GENOME_DIR or OG_DOWNLOADS must be set}" "$1" } # done_with FILE...: each FILE, a raw download, is installed. It stays in the # downloads folder, so a rerun, another install sharing OG_DOWNLOADS or # another use of the same data does not download it again; og setup prune # deletes the kept downloads later. With SETUP_KEEP_DOWNLOADS=false # (setup.sh --no-keep-downloads) each is deleted here instead, with the # checksum fetch saved beside it. done_with() { [ "${SETUP_KEEP_DOWNLOADS:-true}" = false ] || return 0 local f for f in "$@"; do [ -e "$f" ] || continue rm -rf -- "$f" "${f}.part" "${f}.checksum" && echo " Deleted the raw download ${f} (SETUP_KEEP_DOWNLOADS=false)." done } # adopt OLD NEW [URL [CHECK VALUE]]: a raw download an older setup left at # OLD (before the downloads folder; an install stopped before it deleted it) # moves to NEW in the downloads folder, with its OLD.part, so fetch checks it # there by its checksum instead of downloading it again. When NEW is already # there, one of the two goes only once a check says which: URL, CHECK and # VALUE are the fetch that follows (a file there is checked, never # downloaded). NEW that matches: OLD is a second copy and goes. NEW that # does not, and OLD that does: OLD replaces it. Otherwise (no check given, # neither matches, the checksum list cannot be read) both stay, and fetch # then refuses NEW and says so. OLD.part beside a whole NEW goes once NEW # passes that check; with no check, or one that fails, it stays where it is # and setup says it is safe to delete. Of two partial downloads neither is # deleted: the larger resumes at NEW.part and the other is kept at OLD.part. adopt() { local old=$1 new=$2 x shift 2 if [ -e "$old" ] && [ -e "$new" ]; then # Only files are checked: fetch downloads into a NEW that is no file. if [ ! -f "$old" ] || [ ! -f "$new" ]; then set --; fi if [ $# -gt 0 ] && fetch "$1" "$new" "${@:2}" > /dev/null 2>&1; then rm -rf -- "$old" "${old}.part" # not kept: a second copy of a checked file in the downloads folder echo " Deleted ${old}, left by an older setup: ${new} is the same download, checked." return 0 fi if [ $# -gt 0 ] && mv -- "$new" "${new}.adopt" \ && { mv -- "$old" "$new" || { mv -- "${new}.adopt" "$new"; false; }; }; then if fetch "$1" "$new" "${@:2}" > /dev/null 2>&1; then rm -rf -- "${new}.adopt" # not kept: the copy that failed its check, replaced by the one that passed echo " ${new} failed its check; replaced it with ${old}, left by an older setup, which passes." return 0 fi mv -- "$new" "$old" && mv -- "${new}.adopt" "$new" fi echo " [WARN] ${old}, left by an older setup, and ${new} are both here; neither is deleted, as no check says which is the download." return 0 fi for x in "" .part; do [ -e "${old}${x}" ] || continue if [ "$x" = .part ] && [ -e "$new" ]; then # A whole NEW is there, which fetch checks. A partial copy beside it # would be an orphan: it goes once NEW passes the check given here, and # with no check, or one that fails, it stays where it is. if [ $# -ge 3 ] && [ -f "$new" ] && fetch "$1" "$new" "${@:2}" > /dev/null 2>&1; then rm -rf -- "${old}.part" # not kept: a partial copy of a checked file in the downloads folder echo " Deleted ${old}.part, a partial download left by an older setup: ${new} is the whole download, checked." else echo " [WARN] ${old}.part, a partial download left by an older setup, stays: ${new} is already there and fetch checks it. Once setup has finished, ${old}.part is safe to delete." fi elif [ -e "${new}${x}" ]; then # Two partial downloads: neither is deleted unchecked. The larger one # moves to NEW.part, so fetch resumes the most progress. if [ "$x" = .part ] && [ -f "${old}.part" ] && [ -f "${new}.part" ] \ && [ -r "${old}.part" ] && [ -r "${new}.part" ] \ && [ "$(wc -c < "${old}.part")" -gt "$(wc -c < "${new}.part")" ] \ && mv -- "${new}.part" "${new}.part.adopt" \ && { mv -- "${old}.part" "${new}.part" || { mv -- "${new}.part.adopt" "${new}.part"; false; }; } \ && mv -- "${new}.part.adopt" "${old}.part"; then echo " [WARN] ${old}.part, left by an older setup, was the larger partial download: it resumes at ${new}.part, and the smaller one is kept at ${old}.part." else echo " [WARN] ${old}${x}, left by an older setup, and ${new}${x} are both here; neither is deleted, and ${new}${x} is the one fetch uses." fi elif mkdir -p "$(dirname "$new")" && mv -- "${old}${x}" "${new}${x}"; then echo " Moved ${old}${x}, left by an older setup, to ${new}${x}." fi done } # --- Pinned data files ---------------------------------------------------------- # Small reference files from a fixed commit or release, each checked before it # is stored, or copied from the repository (cytoband). setup.sh installs them # (install_data_file); a step only reads them (data_file) and runs no download # of its own. HLA_DB_RELEASE can be # overridden from the environment; step 08 keys its T1K index on it, so a new # release builds a new index. HLA_DB_RELEASE=${HLA_DB_RELEASE:-3.66.0} GENCODE_RELEASE=50 DELLY_EXCL_COMMIT=72a05f3cd23bf55f1edd723b9504a0faf1fba230 # shellcheck disable=SC2034 # read by setup.sh and validate-setup.sh DATA_FILES="delly_exclude cytoband hla_dat gencode_genes gencode_exons" # The chromosome bands ship with the repository; setup copies them, so step 10, # --cytoband and the genome map read the same bytes (assets/reference/README.md # says how the file was made). CYTOBAND_ASSET="${PGP_ROOT}/assets/reference/cytoBand.hg38.txt" # data_file NAME: print the host path of data file NAME and return 0 when it # is installed, 1 when it is not (the path is printed either way). # delly_exclude Delly's GRCh38 exclude map: telomeres, centromeres and the # extra contigs (step 19) # cytoband UCSC's GRCh38 chromosome bands, chr1-22, X and Y (step 10) # hla_dat hla.dat of IPD-IMGT/HLA release HLA_DB_RELEASE (step 08) # gencode_genes the gene lines of GENCODE's basic annotation, release # GENCODE_RELEASE: T1K takes HLA gene coordinates from it (step 08) # gencode_exons the exons of the same annotation as a BED (chrom, 0-based # start, end, once each): the cDNA read check of steps 06 and 17 data_file() { local out case "$1" in delly_exclude) out="${GENOME_DIR:?}/reference/delly_human.hg38.excl.tsv" ;; cytoband) out="${GENOME_DIR:?}/reference/cytoBand.hg38.txt" ;; hla_dat) out="${GENOME_DIR:?}/hla/IPD-IMGT-HLA_${HLA_DB_RELEASE}/hla.dat" ;; gencode_genes) out="${GENOME_DIR:?}/reference/gencode.v${GENCODE_RELEASE}.basic.genes.gtf" ;; gencode_exons) out="${GENOME_DIR:?}/reference/gencode.v${GENCODE_RELEASE}.basic.exons.bed" ;; *) echo "ERROR: unknown data file '${1}'" >&2; return 2 ;; esac printf '%s\n' "$out" [ -s "$out" ] } # install_data_file NAME: download and check (or, for cytoband, copy from # assets/reference) and store data file NAME unless it is installed. Progress # goes to stderr. Returns 1 when it cannot. install_data_file() { local out url gz md5 zip out=$(data_file "$1") && return 0 [ -n "$out" ] || return 2 case "$1" in delly_exclude) fetch "https://raw.githubusercontent.com/dellytools/delly/${DELLY_EXCL_COMMIT}/excludeTemplates/human.hg38.excl.tsv" \ "$out" sha256 caef8593f82f513694ae41b429680eab8abe39c057a119dae7760715aef006ee >&2 || return 1 ;; cytoband) # No download: the asset holds the chr1-22, X and Y rows of UCSC's # cytoBand.txt.gz, sha256 # e514e48b0a12a516fd5231b44241a20a282f290bdd6131cadcddc6276ee26082. # TelomereHunter reports every other row (ALT, random, chrM) as invalid. mkdir -p "$(dirname "$out")" || return 1 if ! { cp "$CYTOBAND_ASSET" "${out}.tmp" && mv -f "${out}.tmp" "$out"; }; then rm -f "${out}.tmp" echo "ERROR: could not copy ${CYTOBAND_ASSET} to ${out}" >&2 return 1 fi ;; hla_dat) url="https://raw.githubusercontent.com/ANHIG/IMGTHLA/v${HLA_DB_RELEASE}-alpha" zip=$(source_of hla_dat path) || return 1 adopt "${out}.zip" "$zip" # md5checksum.txt lines read "MD5 (hla.dat.zip) = ". # net: checksum, the md5 of hla.dat.zip that the release lists md5=$(_get "${url}/md5checksum.txt" - 2>/dev/null | awk '$2 == "(hla.dat.zip)" {print $NF}') || md5="" if [ -z "$md5" ]; then echo "ERROR: no md5 for hla.dat.zip in ${url}/md5checksum.txt (is ${HLA_DB_RELEASE} an IPD-IMGT/HLA release?)" >&2 return 1 fi fetch "${url}/hla.dat.zip" "$zip" md5 "$md5" >&2 || return 1 # The T1K image has Perl's unzip module; the host may have no unzip. # shellcheck disable=SC2154 # T1K_IMAGE comes from versions.env run_in --rw "$(dirname "$out")" "$T1K_IMAGE" perl -e \ 'use IO::Uncompress::Unzip qw(unzip $UnzipError); unzip($ARGV[0] => $ARGV[1]) or die "unzip failed: $UnzipError\n";' \ "$(cpath "$zip")" "$(cpath "${out}.tmp")" >&2 || { rm -f "${out}.tmp"; return 1; } if ! grep -q 'IPD-IMGT/HLA' "${out}.tmp" 2>/dev/null; then rm -f "${out}.tmp" echo "ERROR: ${zip} held no IPD-IMGT/HLA hla.dat" >&2 return 1 fi mv -f "${out}.tmp" "$out" done_with "$zip" >&2 ;; gencode_genes|gencode_exons) _install_gencode || return 1 ;; esac [ -s "$out" ] } # _install_gencode: download GENCODE's basic annotation once and write from it # each of gencode_genes and gencode_exons that is missing; the download is # kept (done_with). Fails when one of them cannot be written. _install_gencode() { local genes exons url gz md5s rc=0 genes=$(data_file gencode_genes) || true exons=$(data_file gencode_exons) || true url=$(source_of gencode url) && gz=$(source_of gencode path) && md5s=$(source_of gencode value) || return 1 adopt "${genes}.download.gz" "$gz" "$url" md5 "$md5s" fetch "$url" "$gz" md5 "$md5s" >&2 || return 1 # The download is in the downloads folder: the tables' own folder may not # be there yet. mkdir -p "$(dirname "$genes")" "$(dirname "$exons")" if [ ! -s "$genes" ]; then _gz_to "$gz" "$genes" awk -F'\t' '$3 == "gene"' || rc=1 fi if [ ! -s "$exons" ]; then _gz_to "$gz" "$exons" _gtf_exons || rc=1 fi [ "$rc" -ne 0 ] || done_with "$gz" >&2 return "$rc" } # _gtf_exons: the exon lines of a GTF on stdin as a sorted BED, once each. _gtf_exons() { awk -F'\t' -v OFS='\t' '$3 == "exon" {print $1, $4 - 1, $5}' | LC_ALL=C sort -k1,1 -k2,2n -k3,3n -u } # _gz_to GZ OUT COMMAND...: write GZ, uncompressed and piped through COMMAND, # to OUT (through OUT.tmp). Fails, keeping no OUT, when COMMAND writes nothing. _gz_to() { local gz=$1 out=$2 shift 2 if gzip -cd "$gz" | "$@" > "${out}.tmp" && [ -s "${out}.tmp" ]; then mv -f "${out}.tmp" "$out" else rm -f "${out}.tmp" echo "ERROR: no usable lines for $(basename "$out") in $(basename "$gz")" >&2 return 1 fi } # _keep_lines GZ OUT AWK_CONDITION: write the tab-separated lines of GZ that # match AWK_CONDITION to OUT (through OUT.tmp) and remove GZ. Fails, keeping # no OUT, when no line matches. _keep_lines() { if gzip -cd "$1" | awk -F'\t' "$3" > "${2}.tmp" && [ -s "${2}.tmp" ]; then mv -f "${2}.tmp" "$2" rm -f "$1" else rm -f "${2}.tmp" "$1" echo "ERROR: no usable lines in $(basename "$1")" >&2 return 1 fi } # vep_cache_row RELEASE: the row of assets/data-sources.tsv of the VEP cache # of RELEASE, VEP_CACHE_RELEASE's (vep_cache) or PCGR_VEP_CACHE_RELEASE's # (pcgr_vep_cache). vep_cache_row() { case "$1" in "${VEP_CACHE_RELEASE:-}") printf 'vep_cache' ;; "${PCGR_VEP_CACHE_RELEASE:-}") printf 'pcgr_vep_cache' ;; *) echo "ERROR: VEP cache ${1} is neither VEP_CACHE_RELEASE nor PCGR_VEP_CACHE_RELEASE" >&2; return 1 ;; esac } # vep_cache_url RELEASE: where Ensembl publishes the indexed GRCh38 VEP cache # of RELEASE (the url of its row). vep_cache_url() { local row row=$(vep_cache_row "$1") && source_of "$row" url } # install_vep_cache DIR RELEASE: download the cache (checked against Ensembl's # CHECKSUMS file), unpack it in a temporary directory and move it to # DIR/homo_sapiens/RELEASE_GRCh38 only when complete. The tarball is kept in # the downloads folder (done_with). install_vep_cache() { local dir=$1 rel=$2 row url tarball sums tmp final row=$(vep_cache_row "$rel") || return 1 url=$(source_of "$row" url) && tarball=$(source_of "$row" path) && sums=$(source_of "$row" value) || return 1 final="${dir}/homo_sapiens/${rel}_GRCh38" if [ -f "${final}/info.txt" ]; then echo "[OK] VEP ${rel} cache already present." return 0 fi if [ -e "$final" ]; then echo "ERROR: ${final} exists but has no info.txt (an interrupted extraction?)." >&2 echo " Remove it and run again." >&2 return 1 fi mkdir -p "${dir}/homo_sapiens" adopt "${dir}/${tarball##*/}" "$tarball" "$url" sum "$sums" # fetch uses a kept tarball that matches its CHECKSUMS line with no # download (it reads that small list first), so an install stopped during # extraction unpacks it again. fetch "$url" "$tarball" sum "$sums" || return 1 echo " Extracting $(basename "$tarball")..." rm -rf "${dir}"/.extract.* tmp=$(mktemp -d "${dir}/.extract.XXXXXX") if ! tar xzf "$tarball" -C "$tmp" || [ ! -f "${tmp}/homo_sapiens/${rel}_GRCh38/info.txt" ]; then rm -rf "$tmp" echo "ERROR: could not unpack ${tarball} into a ${rel}_GRCh38 cache." >&2 return 1 fi if ! mv "${tmp}/homo_sapiens/${rel}_GRCh38" "$final"; then rm -rf "$tmp" return 1 fi rm -rf "$tmp" done_with "$tarball" } # clinical_disk_ok DIR PEAK_GB LABEL [ARCHIVE]: GB as du counts them # (2^30 bytes), plus a 5 GB margin. # Use the destination's filesystem, creating the directory when it is new. # Allocated blocks of ARCHIVE, or of its interrupted ARCHIVE.part, are already # part of the peak, so a resumed download needs only the rest. # An unreadable df is a failed preflight, never permission to fill the disk. clinical_disk_ok() { local dir=$1 peak=$2 label=$3 archive=${4:-} free have=0 f mkdir -p "$dir" || return 1 # A stopped extraction is disposable. Reclaim it before measuring space, # otherwise its staging tree can prevent every retry from reaching cleanup. rm -rf "${dir}"/.extract.* || return 1 free=$(df -Pk "$dir" 2>/dev/null | awk 'NR == 2 {print $4}') || free="" case "$free" in ''|*[!0-9]*) echo "[WARN] Cannot read free space for ${label}; run: ./scripts/setup.sh --clinical-data \"${GENOME_DIR}\""; return 1 ;; esac if [ -n "$archive" ]; then for f in "$archive" "${archive}.part"; do if [ -f "$f" ]; then have=$(du -k "$f" 2>/dev/null | awk 'NR == 1 {print $1}') || have="" case "$have" in ''|*[!0-9]*) echo "[WARN] Cannot read allocated space for ${label}; retry the clinical install."; return 1 ;; esac break fi done fi if [ "$(( free + have ))" -lt "$(( (peak + 5) * 1048576 ))" ]; then echo "[WARN] Skipping ${label}: needs ${peak} GB peak plus a 5 GB margin; $(awk -v k="$free" 'BEGIN {printf "%.1f", k / 1048576}') GB free." echo " Install later: ./scripts/setup.sh --clinical-data \"${GENOME_DIR}\"" return 1 fi } # install_pcgr_bundle DIR: check the pinned archive before extracting into a # staging tree. Upstream ships data/ at the root; CPSR reads BUNDLE/data/. # fetch resumes an interrupted transfer, deletes a bad one, uses a kept # archive that matches the pin and refuses one that does not. # shellcheck disable=SC2154 # PCGR_DATA_BUNDLE and PCGR_DATA_SHA256 are pins in versions.env install_pcgr_bundle() { local dir=$1 url tarball tmp if [ -d "${dir}/${PCGR_DATA_BUNDLE}/data" ]; then echo "[OK] PCGR/CPSR ${PCGR_DATA_BUNDLE} bundle already present." return 0 fi echo "PCGR/CPSR reference data includes third-party databases with their own terms:" echo " https://sigven.github.io/pcgr/articles/annotation_resources.html" echo " Review those terms before use; --no-clinical-data skips this download." url=$(source_of pcgr_bundle url) && tarball=$(source_of pcgr_bundle path) || return 1 mkdir -p "$dir" || return 1 adopt "${dir}/${tarball##*/}" "$tarball" "$url" sha256 "$PCGR_DATA_SHA256" fetch "$url" "$tarball" sha256 "$PCGR_DATA_SHA256" || return 1 rm -rf "${dir}"/.extract.* tmp=$(mktemp -d "${dir}/.extract.XXXXXX") || return 1 if ! tar xzf "$tarball" -C "$tmp" || [ ! -d "${tmp}/data/grch38" ]; then rm -rf "$tmp" echo "ERROR: could not unpack ${tarball} into PCGR data/grch38." >&2 return 1 fi # An incomplete destination is never mistaken for a completed bundle. if [ -e "${dir}/${PCGR_DATA_BUNDLE}" ]; then rm -rf "$tmp" echo "ERROR: ${dir}/${PCGR_DATA_BUNDLE} exists without data; remove it and retry." >&2 return 1 fi if ! mv "$tmp" "${dir}/${PCGR_DATA_BUNDLE}"; then rm -rf "$tmp" return 1 fi done_with "$tarball" echo "[OK] PCGR/CPSR ${PCGR_DATA_BUNDLE} bundle installed." } # lock_acquire DIR / lock_release DIR: a lock shared by concurrent runs. The # lock is a directory holding the owner's PID. It is stale when that PID is # gone (a killed run), or when it has no PID a minute after it was made (a run # killed between mkdir and writing the PID). A stale lock is renamed before it # is removed, so of two waiters that judged it stale only one takes it over. lock_acquire() { local lock=$1 pid stale until mkdir "$lock" 2>/dev/null; do pid=$(cat "${lock}/pid" 2>/dev/null || true) stale=false if [ -n "$pid" ]; then kill -0 "$pid" 2>/dev/null || stale=true elif [ -n "$(find "$lock" -maxdepth 0 -mmin +1 2>/dev/null)" ]; then stale=true fi if $stale; then if mv "$lock" "${lock}.stale.$$" 2>/dev/null; then if [ -n "$pid" ]; then echo " Removing stale lock ${lock} (process ${pid} is gone)." else echo " Removing stale lock ${lock} (no owner after a minute)." fi rm -rf "${lock}.stale.$$" fi continue fi echo " Waiting for ${lock} (held by process ${pid:-starting})..." sleep 5 done echo "$$" > "${lock}/pid" } lock_release() { rm -rf "$1" } # pipeline_images: the value of every *_IMAGE in versions.env, one per line, # except those whose line is marked `# optional` (pulled on first use). pipeline_images() { local line name while IFS= read -r line || [ -n "$line" ]; do case "$line" in *"# optional"*) continue ;; esac if [[ "$line" =~ ^([A-Z0-9_]+_IMAGE)= ]]; then name=${BASH_REMATCH[1]} printf '%s\n' "${!name}" fi done < "${PGP_ROOT}/versions.env" } # pinned_tag IMAGE: the local tag setup.sh gives an image versions.env pins by # digest (name[:tag]@sha256:HEX), printed as localhost/pgp-pinned/NAME:sha256-HEX; # nothing for an image pinned by tag alone. An image pulled by digest gets no # tag, so Docker's classic image store lists it as dangling, and # `docker image prune` or `docker rmi $(docker images -qf dangling=true)` # deletes it. This second name keeps it out of that list. (The containerd # image store keeps the digest reference as the image's name, so it never lists # such an image as dangling.) The tag does not stop `docker system prune -a` or # an explicit `docker rmi`. Every task still runs the digest reference: the tag # only names the same image id. `localhost` is a registry host no one else can # own, so the name can never be pulled from, or pushed to, a public registry. pinned_tag() { local name hex last [[ "$1" =~ ^([a-z0-9][^@]*)@sha256:([0-9a-f]{64})$ ]] || return 0 name=${BASH_REMATCH[1]} hex=${BASH_REMATCH[2]} last=${name##*/} [[ "$last" == *:* ]] && name=${name%:*} # drop the tag, keep a registry port printf 'localhost/pgp-pinned/%s:sha256-%s\n' "${name//:/-}" "$hex" } # tag_pinned_image IMAGE: give a pulled digest-pinned image its pinned_tag. # Safe to repeat: tagging an image with the name it already has changes nothing. tag_pinned_image() { local tag tag=$(pinned_tag "$1") [ -z "$tag" ] || "$CONTAINER_ENGINE" tag "$1" "$tag" } # pinned_tag_present IMAGE: true when IMAGE needs no pinned_tag (it is pinned # by tag alone) or its pinned_tag already names the same image id. pinned_tag_present() { local tag tag=$(pinned_tag "$1") [ -z "$tag" ] || [ "$("$CONTAINER_ENGINE" image inspect --format '{{.Id}}' "$tag" 2>/dev/null)" = \ "$("$CONTAINER_ENGINE" image inspect --format '{{.Id}}' "$1" 2>/dev/null)" ] } # image_is_dangling IMAGE: 0 when Docker lists IMAGE's id as dangling (no tag # of any name), the images `docker image prune` deletes; 1 when it does not # (another local tag on the same id, the pinned_tag or not, or the containerd # image store, where the digest reference is the image's name); 2 when # Docker gives no id or no dangling list, so the answer is unknown. image_is_dangling() { local id dangling id=$("$CONTAINER_ENGINE" image inspect --format '{{.Id}}' "$1" 2>/dev/null) && [ -n "$id" ] || return 2 dangling=$("$CONTAINER_ENGINE" images --no-trunc --quiet --filter dangling=true 2>/dev/null) || return 2 grep -qxF "$id" <<< "$dangling" } # scatter_beds DIR [INTERVALS]: split the calling of a single-process caller # into units, one BED file each (DIR/001.bed, ...), and print their paths in # reference order. Without INTERVALS: chr1-22, chrX, chrY and chrM of # REF_FASTA's .fai one unit each, and every other contig in one last unit. # With INTERVALS (space-separated contigs or contig:start-end regions, 1-based # inclusive): one unit per region. SCATTER=false puts every region in one unit, # so the caller runs once over all of them. A region must lie on its contig # (start 1 or more, end at most the contig's length in the .fai, start not # after end), and no two regions may overlap: a base in two units would be # called twice and its record joined twice. Any of these stops the step # before a caller starts. scatter_beds() { local dir=$1 intervals=${2:-} fai="${REF_FASTA}.fai" r rm -rf "$dir" mkdir -p "$dir" [ -s "$fai" ] || { echo "ERROR: ${fai} not found" >&2; return 1; } { if [ -n "$intervals" ]; then for r in $intervals; do printf 'R\t%s\n' "$r"; done fi } | awk -F'\t' -v d="$dir" -v all="${SCATTER:-true}" -v given="${intervals:+1}" ' FNR == NR { len[$1] = $2; order[++n] = $1; rank[$1] = n; next } function unit(name) { if (all == "false") return sprintf("%s/001.bed", d); return sprintf("%s/%03d.bed", d, ++u) } { r = $2; gsub(/,/, "", r); c = r; s = 0; e = "" if (match(r, /:[0-9]+-[0-9]+$/)) { c = substr(r, 1, RSTART - 1); split(substr(r, RSTART + 1), p, "-"); s = p[1] - 1; e = p[2] } if (!(c in len)) { print "ERROR: contig " c " (INTERVALS) is not in the reference" > "/dev/stderr"; bad = 1; exit 1 } if (e == "") e = len[c] if (s < 0 || e + 0 <= s || e + 0 > len[c]) { print "ERROR: region " $2 " (INTERVALS) is not on " c " (1-" len[c] "): a start of 1 or more, an end no larger than the contig, and the start not after the end" > "/dev/stderr" bad = 1; exit 1 } k++; rk[k] = rank[c]; st[k] = s + 0; en[k] = e + 0; txt[k] = $2; reg[k] = c "\t" s "\t" e } END { if (bad) exit 1 if (given) { # Reference order, then start, whatever the order of INTERVALS: the # units are joined in this order. for (i = 2; i <= k; i++) for (j = i; j > 1 && (rk[j - 1] > rk[j] || (rk[j - 1] == rk[j] && st[j - 1] > st[j])); j--) { t = rk[j]; rk[j] = rk[j - 1]; rk[j - 1] = t t = st[j]; st[j] = st[j - 1]; st[j - 1] = t t = reg[j]; reg[j] = reg[j - 1]; reg[j - 1] = t t = en[j]; en[j] = en[j - 1]; en[j - 1] = t t = txt[j]; txt[j] = txt[j - 1]; txt[j - 1] = t } for (i = 2; i <= k; i++) if (rk[i] == rk[i - 1] && st[i] < en[i - 1]) { print "ERROR: regions " txt[i - 1] " and " txt[i] " (INTERVALS) overlap: the bases they share would be called twice" > "/dev/stderr" exit 1 } for (i = 1; i <= k; i++) { f = unit(); print reg[i] >> f; close(f) } exit 0 } for (i = 1; i <= n; i++) if (order[i] ~ /^chr([0-9]+|X|Y|M)$/) { f = unit(); print order[i] "\t0\t" len[order[i]] >> f; close(f) } rest = (all == "false") ? sprintf("%s/001.bed", d) : sprintf("%s/%03d.bed", d, u + 1) for (i = 1; i <= n; i++) if (order[i] !~ /^chr([0-9]+|X|Y|M)$/) print order[i] "\t0\t" len[order[i]] >> rest }' "$fai" - || return 1 ls "$dir"/*.bed } # scatter_jobs GB: how many units of a scattered caller run at once, when # each unit's container may use GB gigabytes. SCATTER_JOBS when it is set. # Else THREADS/2 (at least 1), lowered to the number of units whose GB fit # in the memory the container engine has (`info`'s MemTotal, to the nearest # GB; at least 1), with a NOTE on stderr that says so. Four 8 GB units do # not fit a 16 GB engine, and the kernel kills a container that runs out. # The rounding is on purpose: a VM given 16 GB reports a little less, and # two units should still run there. So the units' limits may exceed the # reported memory by up to half a GB; a limit is a ceiling, not what a unit # uses. # When the engine does not say, THREADS alone counts. scatter_jobs() { local gb=$1 jobs mem have fit if [ -n "${SCATTER_JOBS:-}" ]; then echo "$SCATTER_JOBS"; return 0; fi jobs=$(( THREADS / 2 > 1 ? THREADS / 2 : 1 )) mem=$("$CONTAINER_ENGINE" info --format '{{.MemTotal}}' 2>/dev/null || true) if [[ "$mem" =~ ^[0-9]+$ ]] && [ "$mem" -gt 0 ]; then have=$(( (mem + 536870912) / 1073741824 )) fit=$(( have / gb > 1 ? have / gb : 1 )) if [ "$fit" -lt "$jobs" ]; then echo "NOTE: ${fit} unit(s) at a time, not ${jobs}: ${CONTAINER_ENGINE} has ${have} GB and each unit may use ${gb} GB. SCATTER_JOBS sets the number." >&2 jobs=$fit fi fi echo "$jobs" } # run_parallel MAX FUNC ARG...: run `FUNC ARG` for every ARG in the # background, at most MAX at a time, and return 1 when any of them failed, # after all have ended. Each unit's status comes from `wait PID`, never from # `wait -n`: in CI (bash 5.2) `wait -n` sometimes returned 127, "no job to # wait for", where a unit had ended, and that unit was counted as failed. # Here `wait -n` only throttles and its status is not counted. # Needs bash 4.3 (wait -n); the step scripts need 4.4. run_parallel() { local max=$1 fn=$2 a p rc=0 local pids=() live=() still=() shift 2 for a in "$@"; do # Start the next unit once fewer than MAX are alive. `live` drops a PID # the first time `kill -0` fails, so a PID the kernel later reuses for # another process never holds a slot. A 127 from `wait -n` ends the wait # rather than looping on it. while :; do still=() for p in ${live[@]+"${live[@]}"}; do if kill -0 "$p" 2>/dev/null; then still+=("$p"); fi done live=(${still[@]+"${still[@]}"}) [ "${#live[@]}" -ge "$max" ] || break wait -n || [ $? -ne 127 ] || break done "$fn" "$a" & pids+=("$!") live+=("$!") done for p in ${pids[@]+"${pids[@]}"}; do wait "$p" || rc=1 done return "$rc" } # --- Sex and the ploidy of chrX and chrY (steps 03a-03d) ---------------------- # A male sample has one X and one Y. Outside the pseudoautosomal regions of # PAR_BED, a heterozygous call there cannot be real, so the alternative # callers call those parts with ploidy 1, as step 03 does with `male`. # shellcheck disable=SC2034 # read by the step scripts PAR_BED="${PGP_ROOT}/assets/par_grch38.bed" # sample_sex [SEX]: the sex a step calls chrX and chrY by. SEX (the step's # second argument) when given. Else the sex run-all.sh was given for this # sample: run-all.sh starts the alternative callers with the sample name only, # and records the sex as `meta declared_sex` in GENOME_DIR/SAMPLE/logs/ # run_status.tsv before any step runs; a NOTE on stderr says the sex came # from there. Else nothing. Prints male, female or nothing; any other value # exits 2. sample_sex() { local sex=${1:-} status="${GENOME_DIR:?}/${SAMPLE:?}/logs/run_status.tsv" if [ -z "$sex" ] && [ -f "$status" ]; then sex=$(awk -F'\t' '$1 == "meta" && $2 == "declared_sex" { s = $3 } END { print s }' "$status") [ -z "$sex" ] || echo "NOTE: sex ${sex}, as run-all.sh was given it (${status})" >&2 fi case "$sex" in ''|male|female) printf '%s' "$sex" ;; *) echo "ERROR: sex must be 'male' or 'female' (or left out), got '${sex}'." >&2; exit 2 ;; esac } # ploidy_line SEX: the line a step prints about how it calls chrX and chrY. ploidy_line() { case "$1" in male) echo "Ploidy: male, chrX and chrY haploid outside the PARs (${PAR_BED#"${PGP_ROOT}"/})" ;; female) echo "Ploidy: female, every contig diploid" ;; *) echo "Ploidy: no sex given, chrX and chrY are called diploid. Pass male or female as the second argument." ;; esac } # ploidy_units SEX UNIT...: the calling units (BED files, as scatter_beds # writes them) split by ploidy. For SEX male every row on chrX or chrY is cut # at PAR_BED: the parts inside a PAR stay in UNIT and are called diploid, the # parts outside go to UNIT's haploid twin, the same name ending in .hap.bed, # called with ploidy 1. A unit left with no row is removed. Prints each unit # that has rows, followed by its twin when it has one. For any other SEX, # prints UNIT... unchanged. PAR_BED's rows must be in order on each contig. ploidy_units() { local sex=$1 u hap shift for u in "$@"; do if [ "$sex" != male ]; then echo "$u"; continue; fi hap="${u%.bed}.hap.bed" rm -f "${u}.dip" "$hap" awk -F'\t' -v OFS='\t' -v dip="${u}.dip" -v hap="$hap" ' FNR == NR { n[$1]++; ps[$1, n[$1]] = $2 + 0; pe[$1, n[$1]] = $3 + 0; next } $1 != "chrX" && $1 != "chrY" { print > dip; next } { c = $1; s = $2 + 0; e = $3 + 0 for (i = 1; i <= n[c] && s < e; i++) { a = ps[c, i]; b = pe[c, i] if (b <= s || a >= e) continue if (a > s) print c, s, a > hap if (a < s) a = s if (b > e) b = e print c, a, b > dip s = b } if (s < e) print c, s, e > hap }' "$PAR_BED" "$u" || return 1 if [ -s "${u}.dip" ]; then mv -f "${u}.dip" "$u" || return 1; echo "$u"; else rm -f "${u}.dip" "$u"; fi if [ -s "$hap" ]; then echo "$hap"; fi done } # live_post RUN JSON: send one message to the live site (og live serve, # docs/live-site.md) at OWNGENOME_LIVE_URL/ingest/RUN; nothing without OWNGENOME_LIVE_URL. # The site's ingest token (OWNGENOME_LIVE_TOKEN, or the last part of a # OWNGENOME_LIVE_URL of the form http://host:port/) goes as the HTTP # Basic password of user og, in a curl config curl reads from a pipe (fd 3): # it is in no argument of any process and in no output line. # A site that is down or slow (3 s) costs one warning per script and never the # step: it always returns 0. live_post() { [ -n "${OWNGENOME_LIVE_URL:-}" ] || return 0 local site=${OWNGENOME_LIVE_URL%/} tok=${OWNGENOME_LIVE_TOKEN:-} if [[ "$site" =~ ^(http://[^/]+)/([A-Za-z0-9_-]{43})$ ]]; then site=${BASH_REMATCH[1]} tok=${BASH_REMATCH[2]}; fi if printf '%s' "$2" | curl -fsS -m 3 -o /dev/null -H 'Content-Type: application/json' -d @- -K/dev/fd/3 \ "${site}/ingest/$1" 3< <([ -z "$tok" ] || printf 'user = "og:%s"\n' "$tok") 2>/dev/null; then return 0 fi if [ -z "${OWNGENOME_LIVE_WARNED:-}" ]; then echo "WARNING: the live site at ${site} did not take a message; the run goes on without it" >&2 OWNGENOME_LIVE_WARNED=1 fi return 0 }