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.
 
 

303 rivejä
11 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. function taint_block {
  39. message="Storage is tainted, not ${1}"
  40. if [[ -e '.tainted' ]]; then
  41. log "${message}"
  42. while [[ -e '.tainted' ]]; do
  43. sleep 1
  44. done
  45. fi
  46. }
  47. { # Group the pipeline without requiring a backslash every time
  48. while :; do
  49. # Read from http2irc
  50. log 'Starting http2irc GET stream...'
  51. curl --silent --verbose --no-buffer "${HTTP2IRC_GET_URL}" 2> >(log_loop 'curl http2irc GET: ')
  52. printf '\n' # Ensure that there's a trailing LF for `read`
  53. done |
  54. # Log all raw input
  55. tee >(log_loop 'Received http2irc line: ') |
  56. # Transform the JSONL data into a more suitable format for the following: lines of 'modes SP nick SP message'
  57. 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"}' |
  58. # 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.
  59. while read -r modes nick message; do
  60. if [[ "${message}" == '!help' ]]; then
  61. respond "${nick}" '`!a URL`: archives a single repository'
  62. respond "${nick}" '`!a < URL`: archives a list of repositories (no success/failure report, no warnings/errors report, check logs manually!)'
  63. continue
  64. fi
  65. if [[ "${message}" != '!a '* ]]; then
  66. continue
  67. fi
  68. if [[ "${modes}" != *[@+]* ]]; then
  69. respond "${nick}" 'Only voiced or opped users may use this command.'
  70. continue
  71. fi
  72. if [[ "${message}" =~ ^'!a '([a-z-]+\+)?[a-z]+://[^\ ]+$ ]]; then
  73. # Individual job
  74. jobs=("${message:3}")
  75. src="${message:3}"
  76. elif [[ "${message}" =~ ^'!a < 'https://transfer\.archivete\.am/[a-zA-Z0-9]+/.+$ ]]; then
  77. # List job
  78. jobs=()
  79. url="${message:5}"
  80. bad=
  81. log "Retrieving list job list: ${url}"
  82. while read -r line; do
  83. if [[ "${line}" =~ ^'!a '([a-z-]+\+)?[a-z]+://[^\ ]+$ ]]; then
  84. jobs+=("${line}")
  85. elif [[ "${line}" == '' ]]; then
  86. # Ignore empty lines
  87. continue
  88. else
  89. respond "${nick}" "Malformed line in ${url}: ${line}"
  90. bad=1
  91. break
  92. fi
  93. done < <({ curl --silent --verbose --fail --max-time 10 "${message:5}" 2> >(log_loop 'curl list job: '); printf '\n'; } | tee >(log_loop 'List input line: '))
  94. if [[ "${bad}" ]]; then
  95. continue
  96. fi
  97. src="${url}"
  98. else
  99. respond "${nick}" "I don't understand your command. Please forgive me."
  100. continue
  101. fi
  102. read -r jobid </proc/sys/kernel/random/uuid
  103. respond "${nick}" "Queueing job ${jobid} for ${src}"
  104. appendcounter=; if [[ ${#jobs[@]} -gt 1 ]]; then appendcounter=yes; fi
  105. for ((i=0; i<${#jobs[@]}; ++i)); do
  106. job="${jobs[${i}]}"
  107. singlejobid="${jobid}"; if [[ "${appendcounter}" ]]; then singlejobid+="_${i}"; fi
  108. printf '%s %s %s\n' "${singlejobid}" "${nick}" "${job}"
  109. done
  110. if [[ "${appendcounter}" ]]; then printf '%s %s end\n' "${jobid}" "${nick}"; fi # Special value for sending a message when all list URLs have been processed
  111. done |
  112. # The actual work loop
  113. while IFS= read -r line; do
  114. singlejobid="${line%% *}"
  115. line="${line#* }"
  116. nick="${line%% *}"
  117. url="${line#* }"
  118. # Handle marker for end of list job: tell the user it's done and move on.
  119. if [[ "${url}" == 'end' ]]; then
  120. # No status code reflection here because the start of the list job might not even have been in this batch.
  121. respond "${nick}" "Job ${singlejobid} finished."
  122. continue
  123. fi
  124. taint_block 'continuing with work loop'
  125. # Find nonexistent filename for log file with lock
  126. # mkdir is pretty much always atomic, creating files might not be depending on the underlying file system (e.g. networked ones like NFS).
  127. while ! mkdir '.loglock' 2> >(log_loop 'mkdir loglock (work) err: '); do
  128. sleep 1
  129. done
  130. trap 'rmdir ".loglock"' EXIT # Unlock if something below fails
  131. logbasename="$(date +%Y%m%dT%H%M%SZ)_${singlejobid}"
  132. if [[ -e "${logbasename}_codearchiver.log" || -e "${logbasename}_codearchiver.log.zst" ]]; then
  133. for ((j=0; ; ++j)); do
  134. if [[ ! -e "${logbasename}_coll${j}_codearchiver.log" || -e "${logbasename}_coll${j}_codearchiver.log.zst" ]]; then
  135. break
  136. fi
  137. done
  138. logbasename="${logbasename}_coll${j}"
  139. fi
  140. logname="${logbasename}_codearchiver.log"
  141. artefactsname="${logbasename}_codearchiver_artefacts.txt"
  142. # Create the log file already in case spawning the tee process for it below is too slow
  143. touch "${logname}"
  144. trap - EXIT # Reset trap
  145. rmdir '.loglock' # Unlock
  146. # Run codearchiver in a background shell, duplicating WARNINGs and higher in the bot output
  147. # Produces lines of filenames to upload on stdout
  148. log "Running ${url} (${singlejobid}), logging into ${logname}"
  149. (
  150. taint_block "launching job ${singlejobid}"
  151. timeout --signal=INT "${timeout}" \
  152. codearchiver --verbose --write-artefacts-fd-3 "${url}" \
  153. > >(log_loop "codearchiver ${singlejobid} out: ") \
  154. 2> >(tee "${logname}" | grep -Fv -e ' INFO ' | log_loop "codearchiver ${singlejobid} err: ") \
  155. 3> >(tee "${artefactsname}" | log_loop "Artefact from codearchiver ${singlejobid}: ")
  156. status="$?"
  157. log "codearchiver ${url} finished with status code ${status}"
  158. #TODO Integrate this into the pipe from codearchiver above to avoid rereading the entire log file
  159. declare -i badcount=$(awk '! ($3 ~ /^INFO$/) { cnt += 1; } END { printf "%d\n", cnt; }' "${logname}")
  160. # Compress log file with zstd -19
  161. log "Compressing log file ${logname}"
  162. zstd -19 --rm "${logname}" 2> >(log_loop 'zstd err: ')
  163. if [[ -e "${logname}.zst" && ! -e "${logname}" ]]; then
  164. # Compression successful
  165. logname="${logname}.zst"
  166. fi
  167. # Verify that there are no artefacts if codearchiver exited non-zero
  168. # Since codearchiver handles errors internally normally, this should not usually happen, but it could occur e.g. if running out of disk space and leaving partial files in the storage.
  169. # With parallelism, this could in theory lead to artefacts of a successful run depending on artefacts from a failed run, which we wouldn't want.
  170. # So, if there are artefacts of a failed process, touch the .tainted file to stop the uploader and new processes starting and send a warning to IRC.
  171. # Emit the log filename for upload always (even on tainted storage), artefacts list and artefacts only on zero exit.
  172. readarray -t artefacts <"${artefactsname}"
  173. if [[ "${status}" -ne 0 && "${#artefacts[@]}" -ne 0 ]]; then
  174. touch '.tainted'
  175. send "Job ${singlejobid} exited non-zero but left artefacts behind!"
  176. msg="$(printf 'Artefact files by non-zero exit process: '; printf ' %q' "${artefacts[@]}")"
  177. log "${msg}"
  178. elif [[ "${status}" -eq 0 ]]; then
  179. for file in "${artefacts[@]}"; do
  180. printf '%s\n' "${file}"
  181. done
  182. printf '%s\n' "${artefactsname}"
  183. fi
  184. printf '%s\n' "${logname}"
  185. # For individual jobs, tell the user about warnings and success/failure
  186. if [[ "${singlejobid}" != *_* ]]; then
  187. if [[ "${status}" -eq 0 ]]; then
  188. respond "${nick}" "Job ${singlejobid} succeeded."
  189. else
  190. respond "${nick}" "Job ${singlejobid} failed."
  191. fi
  192. if [[ ${badcount} -gt 0 ]]; then
  193. respond "${nick}" "Job ${singlejobid} produced ${badcount} warnings or errors."
  194. fi
  195. fi
  196. ) &
  197. wait
  198. done |
  199. # Upload
  200. while :; do
  201. # Process in batches for efficiency of parallel IA upload processing
  202. declare -a filenames=()
  203. while read -r -t 1 filename; do
  204. filenames+=("${filename}")
  205. done
  206. if [[ ${#filenames[@]} -eq 0 ]]; then
  207. continue
  208. fi
  209. log 'Starting upload batch'
  210. # Record SHA-256 hashes for new files
  211. sha256sum "${filenames[@]}" > >(log_loop 'sha256sum: ')
  212. taint_block 'uploading anything'
  213. # Upload
  214. date="$(date '+%Y-%m-%d')"
  215. identifier="codearchiver_${date//-/}"
  216. if [[ -z "${CODEARCHIVER_BOT_TEST}" ]]; then
  217. collection='archiveteam_codearchiver'
  218. else
  219. identifier="test_${identifier}"
  220. collection='test_collection'
  221. fi
  222. uploadsfine=y
  223. for f in "${filenames[@]}"; do
  224. taint_block "starting upload for $(printf '%q' "${f}")"
  225. log "Uploading $(printf '%q' "${f}") to ${identifier}"
  226. ia-upload-stream --no-derive "${identifier}" "${f}" \
  227. "collection:${collection}" \
  228. 'mediatype:software' \
  229. "date:${date}" \
  230. <"${f}" 2> >(log_loop 'ia-upload-stream: ')
  231. status="$?"
  232. if [[ "${status}" -ne 0 ]]; then
  233. log "Upload failed: exit status ${status}"
  234. if [[ "${uploadsfine}" ]]; then
  235. send "Upload failed: exit status ${status}"
  236. fi
  237. uploadsfine=
  238. fi
  239. done
  240. if [[ -z "${uploadsfine}" ]]; then
  241. log 'At least one upload in the batch failed, not removing anything'
  242. continue
  243. fi
  244. # Wait until all tasks for the item are done
  245. while :; do
  246. 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: ')))"
  247. if [[ "${tasks}" == '0' ]]; then
  248. break
  249. fi
  250. sleep 60
  251. done
  252. taint_block 'removing any files after upload'
  253. # Replace non-metadata files with a symlink to .uploaded dummy file
  254. # No locking with codearchiver processes is necessary because those will only read metadata (which is left alone) or write files.
  255. # However, a lock with the log filename finding is required.
  256. while ! mkdir '.loglock' 2> >(log_loop 'mkdir loglock (upload) err: '); do
  257. sleep 1.1 # Slightly longer than above to minimise repeated collisions
  258. done
  259. trap 'rmdir ".loglock"' EXIT
  260. touch '.uploaded'
  261. for f in "${filenames[@]}"; do
  262. if [[ "${f}" != *_codearchiver_metadata.txt ]]; then
  263. log "Replacing $(printf '%q' "${f}") with symlink to .uploaded"
  264. { rm --verbose -- "${f}" && ln --symbolic --verbose '.uploaded' "${f}"; } |& log_loop 'rm/ln: '
  265. fi
  266. done
  267. trap - EXIT
  268. rmdir '.loglock'
  269. done
  270. }