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.
 
 

262 line
9.5 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. statuscodes=() # Exit status for each `batch` element's codearchiver process (-1 for 'end' markers)
  114. newfiles=()
  115. newfilejobindices=() # One entry for each element of `newfiles`, containing the corresponding index in `batch` to which the file belongs
  116. for ((i=0; i<${#batch[@]}; ++i)); do
  117. line="${batch[${i}]}"
  118. singlejobid="${line%% *}"
  119. line="${line#* }"
  120. nick="${line%% *}"
  121. url="${line#* }"
  122. # Handle marker for end of list job: tell the user it's done and move on.
  123. if [[ "${url}" == 'end' ]]; then
  124. # No status code reflection here because the start of the list job might not even have been in this batch.
  125. respond "${nick}" "Job ${singlejobid} finished."
  126. statuscodes+=(-1)
  127. continue
  128. fi
  129. # Find nonexistent filename for log file (*not* concurrency-safe!)
  130. logbasename="$(date +%Y%m%dT%H%M%SZ)_${singlejobid}"
  131. if [[ -e "${logbasename}_codearchiver.log" ]]; then
  132. for ((j=0; ; ++j)); do
  133. if [[ ! -e "${logbasename}_coll${j}_codearchiver.log" ]]; then
  134. break
  135. fi
  136. done
  137. logbasename="${logbasename}_coll${j}"
  138. fi
  139. logname="${logbasename}_codearchiver.log"
  140. artefactsname="${logbasename}_codearchiver_artefacts.txt"
  141. # Run codearchiver, duplicating WARNINGs and higher in the bot output
  142. log "Running ${url} (${singlejobid}), logging into ${logname}"
  143. timeout --signal=INT "${timeout}" \
  144. codearchiver --verbose --write-artefacts-fd-3 "${url}" \
  145. 2> >(tee "${logname}" | grep -Fv -e ' INFO ' | log_loop "From codearchiver ${singlejobid}: ") \
  146. 3> >(tee "${artefactsname}" | log_loop "New artefacts from codearchiver ${singlejobid}: ")
  147. status="$?"
  148. log "codearchiver ${url} finished with status code ${status}"
  149. statuscodes+=("${status}")
  150. #TODO Integrate this into the pipe from codearchiver above to avoid rereading the entire log file
  151. declare -i badcount=$(awk '! ($3 ~ /^INFO$/) { cnt += 1; } END { printf "%d\n", cnt; }' "${logname}")
  152. # Compress log file with zstd -19
  153. log "Compressing log file ${logname}"
  154. zstd -19 --rm "${logname}" 2> >(log_loop 'zstd err: ')
  155. if [[ -e "${logname}.zst" && ! -e "${logname}" ]]; then
  156. # Compression successful
  157. logname="${logname}.zst"
  158. fi
  159. # Move everything but the log file to ./failed/ if codearchiver exited non-zero
  160. readarray -t artefacts <"${artefactsname}"
  161. if [[ "${status}" -ne 0 ]]; then
  162. msg="$(printf 'Moving artefact files'; printf ' %q' "${artefacts[@]}" "${artefactsname}"; printf ' from non-zero exit for job %s to ./failed/\n' "${singlejobid}";)"
  163. log "${msg}"
  164. mkdir --parents ./failed/
  165. mv --verbose -- "${artefacts[@]}" "${artefactsname}" ./failed/ 2> >(log_loop 'mv err: ') | log_loop 'mv out: '
  166. else
  167. for file in "${artefacts[@]}"; do
  168. newfiles+=("${file}")
  169. newfilejobindices+=("${i}")
  170. done
  171. newfiles+=("${artefactsname}")
  172. newfilejobindices+=("${i}")
  173. fi
  174. newfiles+=("${logname}")
  175. newfilejobindices+=("${i}")
  176. # For individual jobs, tell the user about warnings and success/failure
  177. if [[ "${singlejobid}" != *_* ]]; then
  178. if [[ "${status}" -eq 0 ]]; then
  179. respond "${nick}" "Job ${singlejobid} succeeded."
  180. else
  181. respond "${nick}" "Job ${singlejobid} failed."
  182. fi
  183. if [[ ${badcount} -gt 0 ]]; then
  184. respond "${nick}" "Job ${singlejobid} produced ${badcount} warnings or errors."
  185. fi
  186. fi
  187. done
  188. # Record SHA-256 hashes for new files
  189. log "SHA-256 hashes:"
  190. sha256sum "${newfiles[@]}" > >(log_loop 'sha256sum: ')
  191. # Upload
  192. date="$(date '+%Y-%m-%d')"
  193. identifier="codearchiver_${date//-/}"
  194. if [[ -z "${CODEARCHIVER_BOT_TEST}" ]]; then
  195. collection='archiveteam_codearchiver'
  196. else
  197. identifier="test_${identifier}"
  198. collection='test_collection'
  199. fi
  200. uploadsfine=y
  201. for f in "${newfiles[@]}"; do
  202. ia-upload-stream --no-derive "${identifier}" "${f}" \
  203. "collection:${collection}" \
  204. 'mediatype:software' \
  205. "date:${date}" \
  206. <"${f}" 2> >(log_loop 'ia-upload-stream: ')
  207. status="$?"
  208. if [[ "${status}" -ne 0 ]]; then
  209. log "Upload failed: exit status ${status}"
  210. if [[ "${uploadsfine}" ]]; then
  211. send "Upload failed: exit status ${status}"
  212. fi
  213. uploadsfine=
  214. fi
  215. done
  216. if [[ "${uploadsfine}" ]]; then
  217. # Wait until all tasks for the item are done
  218. while :; do
  219. 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: ')))"
  220. if [[ "${tasks}" == '0' ]]; then
  221. break
  222. fi
  223. sleep 60
  224. done
  225. # Replace non-metadata files with a symlink to .uploaded dummy file
  226. touch '.uploaded'
  227. for f in "${newfiles[@]}"; do
  228. if [[ "${f}" != *_codearchiver_metadata.txt ]]; then
  229. log "Replacing ${f} with symlink to .uploaded"
  230. { rm --verbose -- "${f}" && ln --symbolic --verbose '.uploaded' "${f}"; } |& log_loop 'rm/ln: '
  231. fi
  232. done
  233. fi
  234. done
  235. }