You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
 
 

255 regels
9.2 KiB

  1. #!/bin/bash
  2. export TZ=UTC
  3. envvars=(HTTP2IRC_GET_URL HTTP2IRC_POST_URL IA_S3_ACCESS IA_S3_SECRET)
  4. for envvar in "${envvars[@]}"; do
  5. if [[ ! -v "${envvar}" ]]; then
  6. { printf 'Error: one or more of the required environment variables (%s' "${envvars[0]}"; printf ', %s' "${envvars[@]:1}"; printf ') missing\n'; } >&2
  7. exit 1
  8. fi
  9. done
  10. # Optional env variables
  11. declare -i timeout="${CODEARCHIVER_BOT_TIMEOUT:-0}"
  12. for dep in awk codearchiver curl ia-upload-stream python3 sha256sum tee zstd; do
  13. if ! command -v "${dep}" &>/dev/null; then
  14. printf 'Error: %s not found\n' "${dep}" >&2
  15. exit 1
  16. fi
  17. done
  18. function log {
  19. printf '%s %s\n' "${EPOCHREALTIME}" "$1" >&2
  20. }
  21. function log_loop {
  22. prefix="$1"
  23. # If the output does not end with a LF, add one. Then replace CRLF with LF and replace remaining CR with LF.
  24. { lastchar="$(tee /dev/fd/3 | tail -c 1 | xxd -p)"; if [[ "${lastchar}" != '0a' ]]; then printf '\n'; fi } 3>&1 |
  25. sed -u 's,\r$,,; s,\r,\n,g' |
  26. while IFS= read -r line; do log "${prefix}${line}"; done
  27. }
  28. function send {
  29. local message="$1"
  30. log "Sending message: ${message}"
  31. curl --silent --verbose --max-time 10 --data "${message}" "${HTTP2IRC_POST_URL}" 2> >(log_loop 'curl http2irc POST: ') | log_loop 'http2irc POST response: '
  32. }
  33. function respond {
  34. local nick="$1"
  35. local message="$2"
  36. send "${nick}: ${message}"
  37. }
  38. { # Group the pipeline without requiring a backslash every time
  39. while :; do
  40. # Read from http2irc
  41. log 'Starting http2irc GET stream...'
  42. curl --silent --verbose --no-buffer "${HTTP2IRC_GET_URL}" 2> >(log_loop 'curl http2irc GET: ')
  43. printf '\n' # Ensure that there's a trailing LF for `read`
  44. done |
  45. # Log all raw input
  46. tee >(log_loop 'Received http2irc line: ') |
  47. # Transform the JSONL data into a more suitable format for the following: lines of 'modes SP nick SP message'
  48. python3 -u -c 'import json, sys'$'\n''def json_parse_or_none(s):'$'\n'' try: return json.loads(s)'$'\n'' except json.JSONDecodeError as e:'$'\n'' print(f"Could not parse {s[:100]}…: {type(e).__name__}: {e!s}")'$'\n''{print(o["user"]["modes"] or "_", o["user"]["nick"], o["message"]) for o in map(json_parse_or_none, sys.stdin) if o and o.get("command") == "PRIVMSG"}' |
  49. # For valid bot commands with adequate permissions, assign a job ID and respond. Suppress everything else. Print lines of 'jobid SP nick SP URL' for the processing below.
  50. while read -r modes nick message; do
  51. if [[ "${message}" == '!help' ]]; then
  52. respond "${nick}" '`!a URL`: archives a single repository'
  53. respond "${nick}" '`!a < URL`: archives a list of repositories (no success/failure report, no warnings/errors report, check logs manually!)'
  54. continue
  55. fi
  56. if [[ "${message}" != '!a '* ]]; then
  57. continue
  58. fi
  59. if [[ "${modes}" != *[@+]* ]]; then
  60. respond "${nick}" 'Only voiced or opped users may use this command.'
  61. continue
  62. fi
  63. if [[ "${message}" =~ ^'!a '([a-z-]+\+)?[a-z]+://[^\ ]+$ ]]; then
  64. # Individual job
  65. jobs=("${message:3}")
  66. src="${message:3}"
  67. elif [[ "${message}" =~ ^'!a < 'https://transfer\.archivete\.am/[a-zA-Z0-9]+/.+$ ]]; then
  68. # List job
  69. jobs=()
  70. url="${message:5}"
  71. bad=
  72. log "Retrieving list job list: ${url}"
  73. while read -r line; do
  74. if [[ "${line}" =~ ^'!a '([a-z-]+\+)?[a-z]+://[^\ ]+$ ]]; then
  75. jobs+=("${line}")
  76. elif [[ "${line}" == '' ]]; then
  77. # Ignore empty lines
  78. continue
  79. else
  80. respond "${nick}" "Malformed line in ${url}: ${line}"
  81. bad=1
  82. break
  83. fi
  84. done < <({ curl --silent --verbose --fail --max-time 10 "${message:5}" 2> >(log_loop 'curl list job: '); printf '\n'; } | tee >(log_loop 'List input line: '))
  85. if [[ "${bad}" ]]; then
  86. continue
  87. fi
  88. src="${url}"
  89. else
  90. respond "${nick}" "I don't understand your command. Please forgive me."
  91. continue
  92. fi
  93. read -r jobid </proc/sys/kernel/random/uuid
  94. respond "${nick}" "Queueing job ${jobid} for ${src}"
  95. appendcounter=; if [[ ${#jobs[@]} -gt 1 ]]; then appendcounter=yes; fi
  96. for ((i=0; i<${#jobs[@]}; ++i)); do
  97. job="${jobs[${i}]}"
  98. singlejobid="${jobid}"; if [[ "${appendcounter}" ]]; then singlejobid+="_${i}"; fi
  99. printf '%s %s %s\n' "${singlejobid}" "${nick}" "${job}"
  100. done
  101. if [[ "${appendcounter}" ]]; then printf '%s %s end\n' "${jobid}" "${nick}"; fi # Special value for sending a message when all list URLs have been processed
  102. done |
  103. # The actual work loop
  104. while :; do
  105. # Process in batches for efficiency of parallel IA processing after uploads
  106. declare -a batch=()
  107. while read -r -t 1 line; do
  108. batch+=("${line}")
  109. done
  110. if [[ ${#batch[@]} -eq 0 ]]; then
  111. continue
  112. fi
  113. newfiles=()
  114. for ((i=0; i<${#batch[@]}; ++i)); do
  115. line="${batch[${i}]}"
  116. singlejobid="${line%% *}"
  117. line="${line#* }"
  118. nick="${line%% *}"
  119. url="${line#* }"
  120. # Handle marker for end of list job: tell the user it's done and move on.
  121. if [[ "${url}" == 'end' ]]; then
  122. # No status code reflection here because the start of the list job might not even have been in this batch.
  123. respond "${nick}" "Job ${singlejobid} finished."
  124. continue
  125. fi
  126. # Find nonexistent filename for log file (*not* concurrency-safe!)
  127. logbasename="$(date +%Y%m%dT%H%M%SZ)_${singlejobid}"
  128. if [[ -e "${logbasename}_codearchiver.log" || -e "${logbasename}_codearchiver.log.zst" ]]; then
  129. for ((j=0; ; ++j)); do
  130. if [[ ! -e "${logbasename}_coll${j}_codearchiver.log" || -e "${logbasename}_coll${j}_codearchiver.log.zst" ]]; then
  131. break
  132. fi
  133. done
  134. logbasename="${logbasename}_coll${j}"
  135. fi
  136. logname="${logbasename}_codearchiver.log"
  137. artefactsname="${logbasename}_codearchiver_artefacts.txt"
  138. # Run codearchiver, duplicating WARNINGs and higher in the bot output
  139. log "Running ${url} (${singlejobid}), logging into ${logname}"
  140. timeout --signal=INT "${timeout}" \
  141. codearchiver --verbose --write-artefacts-fd-3 "${url}" \
  142. 2> >(tee "${logname}" | grep -Fv -e ' INFO ' | log_loop "From codearchiver ${singlejobid}: ") \
  143. 3> >(tee "${artefactsname}" | log_loop "New artefacts from codearchiver ${singlejobid}: ")
  144. status="$?"
  145. log "codearchiver ${url} finished with status code ${status}"
  146. #TODO Integrate this into the pipe from codearchiver above to avoid rereading the entire log file
  147. declare -i badcount=$(awk '! ($3 ~ /^INFO$/) { cnt += 1; } END { printf "%d\n", cnt; }' "${logname}")
  148. # Compress log file with zstd -19
  149. log "Compressing log file ${logname}"
  150. zstd -19 --rm "${logname}" 2> >(log_loop 'zstd err: ')
  151. if [[ -e "${logname}.zst" && ! -e "${logname}" ]]; then
  152. # Compression successful
  153. logname="${logname}.zst"
  154. fi
  155. # Move everything but the log file to ./failed/ if codearchiver exited non-zero
  156. readarray -t artefacts <"${artefactsname}"
  157. if [[ "${status}" -ne 0 ]]; then
  158. msg="$(printf 'Moving artefact files'; printf ' %q' "${artefacts[@]}" "${artefactsname}"; printf ' from non-zero exit for job %s to ./failed/\n' "${singlejobid}";)"
  159. log "${msg}"
  160. mkdir --parents ./failed/
  161. mv --verbose -- "${artefacts[@]}" "${artefactsname}" ./failed/ 2> >(log_loop 'mv err: ') | log_loop 'mv out: '
  162. else
  163. for file in "${artefacts[@]}"; do
  164. newfiles+=("${file}")
  165. done
  166. newfiles+=("${artefactsname}")
  167. fi
  168. newfiles+=("${logname}")
  169. # For individual jobs, tell the user about warnings and success/failure
  170. if [[ "${singlejobid}" != *_* ]]; then
  171. if [[ "${status}" -eq 0 ]]; then
  172. respond "${nick}" "Job ${singlejobid} succeeded."
  173. else
  174. respond "${nick}" "Job ${singlejobid} failed."
  175. fi
  176. if [[ ${badcount} -gt 0 ]]; then
  177. respond "${nick}" "Job ${singlejobid} produced ${badcount} warnings or errors."
  178. fi
  179. fi
  180. done
  181. # Record SHA-256 hashes for new files
  182. log "SHA-256 hashes:"
  183. sha256sum "${newfiles[@]}" > >(log_loop 'sha256sum: ')
  184. # Upload
  185. date="$(date '+%Y-%m-%d')"
  186. identifier="codearchiver_${date//-/}"
  187. if [[ -z "${CODEARCHIVER_BOT_TEST}" ]]; then
  188. collection='archiveteam_codearchiver'
  189. else
  190. identifier="test_${identifier}"
  191. collection='test_collection'
  192. fi
  193. uploadsfine=y
  194. for f in "${newfiles[@]}"; do
  195. ia-upload-stream --no-derive "${identifier}" "${f}" \
  196. "collection:${collection}" \
  197. 'mediatype:software' \
  198. "date:${date}" \
  199. <"${f}" 2> >(log_loop 'ia-upload-stream: ')
  200. status="$?"
  201. if [[ "${status}" -ne 0 ]]; then
  202. log "Upload failed: exit status ${status}"
  203. if [[ "${uploadsfine}" ]]; then
  204. send "Upload failed: exit status ${status}"
  205. fi
  206. uploadsfine=
  207. fi
  208. done
  209. if [[ "${uploadsfine}" ]]; then
  210. # Wait until all tasks for the item are done
  211. while :; do
  212. tasks="$(python3 -c 'import json, sys; o = json.load(sys.stdin); print(sum(o["value"]["summary"].values()))' < <({ curl --silent --verbose --fail --max-time 10 --header "Authorization: LOW ${IA_S3_ACCESS}:${IA_S3_SECRET}" "https://archive.org/services/tasks.php?identifier=${identifier}&summary=1&history=0" 2> >(log_loop 'curl IA tasks err: '); } | tee >(log_loop 'curl IA tasks out: ')))"
  213. if [[ "${tasks}" == '0' ]]; then
  214. break
  215. fi
  216. sleep 60
  217. done
  218. # Replace non-metadata files with a symlink to .uploaded dummy file
  219. touch '.uploaded'
  220. for f in "${newfiles[@]}"; do
  221. if [[ "${f}" != *_codearchiver_metadata.txt ]]; then
  222. log "Replacing ${f} with symlink to .uploaded"
  223. { rm --verbose -- "${f}" && ln --symbolic --verbose '.uploaded' "${f}"; } |& log_loop 'rm/ln: '
  224. fi
  225. done
  226. fi
  227. done
  228. }