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.

1758 lines
59 KiB

  1. #!/bin/bash
  2. . /etc/shlib
  3. include common
  4. include parse
  5. include cmdline
  6. include config
  7. [[ "${BASH_SOURCE[0]}" != "${0}" ]] && SOURCED=true
  8. version=0.1
  9. desc='Manage 0k related installs'
  10. help=""
  11. ##
  12. ## Functions
  13. ##
  14. is-port-open() {
  15. local host="$1" port="$2" timeout=5
  16. start="$SECONDS"
  17. debug "Testing if $host's port $2 is open ..."
  18. while true; do
  19. timeout 1 bash -c "</dev/tcp/${host}/${port}" >/dev/null 2>&1 && break
  20. sleep 0.2
  21. if [ "$((SECONDS - start))" -gt "$timeout" ]; then
  22. return 1
  23. fi
  24. done
  25. debug " .. $host's port $2 is open."
  26. return 0
  27. }
  28. resolve() {
  29. local ent hostname="$1"
  30. debug "Resolving $1 ..."
  31. if ent=$(getent ahosts "$hostname"); then
  32. ent=$(echo "$ent" | egrep ^"[0-9]+.[0-9]+.[0-9]+.[0-9]+\s+" | \
  33. head -n 1 | awk '{ print $1 }')
  34. debug " .. resolved $1 to $ent."
  35. echo "$ent"
  36. else
  37. debug " .. couldn't resolve $1."
  38. return 1
  39. fi
  40. }
  41. set_errlvl() { return "${1:-1}"; }
  42. export master_pid=$$
  43. ssh:open() {
  44. local hostname ssh_cmd ssh_options
  45. ssh_cmd=(ssh)
  46. ssh_options=()
  47. while [ "$#" != 0 ]; do
  48. case "$1" in
  49. "--stdin-password")
  50. ssh_cmd=(sshpass "${ssh_cmd[@]}")
  51. ;;
  52. -o)
  53. ssh_options+=("$1" "$2")
  54. shift
  55. ;;
  56. *)
  57. [ -z "$hostname" ] && hostname="$1" || {
  58. err "Surnumerous positional argument '$1'. Expecting only hostname."
  59. return 1
  60. }
  61. ;;
  62. esac
  63. shift
  64. done
  65. full_cmd=(
  66. "${ssh_cmd[@]}"
  67. -o ControlPath=/tmp/ssh-control-master-${master_pid}-$hostname \
  68. -o ControlMaster=auto -o ControlPersist=900 \
  69. -o ConnectTimeout=5 -o StrictHostKeyChecking=no \
  70. "${ssh_options[@]}" \
  71. "$hostname" "$@" -- true)
  72. "${full_cmd[@]}" >/dev/null 2>&1 || {
  73. err "Failed: ${full_cmd[*]}"
  74. return 1
  75. }
  76. trap_add EXIT,INT 'ssh:quit "$hostname"'
  77. }
  78. ssh:rsync() {
  79. local src="$1" dst="$2"
  80. hostname=${src%%:*}
  81. hostname=${hostname#*@}
  82. local rsync_ssh_options=(
  83. -o ControlPath="/tmp/ssh-control-master-${master_pid}-$hostname"
  84. -o ControlMaster=auto
  85. -o ControlPersist=900
  86. -o ConnectTimeout=10
  87. -o StrictHostKeyChecking=no
  88. )
  89. if ! ssh:run "root@$hostname" -- type -p rsync </dev/null >/dev/null; then
  90. info "No 'rsync' available on '$hostname'. Requesting installation..."
  91. ssh:run "root@$hostname" -- apt-get install rsync -y || {
  92. err "Installation of 'rsync' failed on '$hostname'"
  93. return 1
  94. }
  95. fi
  96. local cmd=(
  97. rsync -e "ssh ${rsync_ssh_options[*]}"
  98. -azvArH --delete --delete-excluded
  99. --partial --partial-dir .rsync-partial
  100. "$src" "$dst"
  101. )
  102. "${cmd[@]}"
  103. }
  104. ssh:open-try() {
  105. local opts hostnames
  106. opts=()
  107. hostnames=()
  108. while [ "$#" != 0 ]; do
  109. case "$1" in
  110. -o)
  111. opts+=("$1" "$2")
  112. shift
  113. ;;
  114. *)
  115. hostnames+=("$1")
  116. ;;
  117. esac
  118. shift
  119. done
  120. password=''
  121. for host in "${hostnames[@]}"; do
  122. debug "Trying $host with publickey."
  123. ssh:open -o PreferredAuthentications=publickey \
  124. "${opts[@]}" \
  125. "$host" >/dev/null 2>&1 && {
  126. echo "$host"$'\n'"$password"$'\n'
  127. return 0
  128. }
  129. debug " .. failed connecting to $host with publickey."
  130. done
  131. local times=0 password
  132. while [ "$((++times))" -le 3 ]; do
  133. read -sp "$HOST's password: " password
  134. errlvl="$?"
  135. echo >&2
  136. if [ "$errlvl" -gt 0 ]; then
  137. exit 1
  138. fi
  139. for host in "${hostnames[@]}"; do
  140. debug "Trying $host with password ($times/3)"
  141. echo "$password" | ssh:open -o PreferredAuthentications=password \
  142. --stdin-password \
  143. "${opts[@]}" \
  144. "$host" >/dev/null 2>&1 && {
  145. echo "$host"$'\n'"$password"$'\n'
  146. return 0
  147. }
  148. debug " .. failed connecting to $host with password."
  149. done
  150. err "login failed. Try again... ($((times+1))/3)"
  151. done
  152. return 1
  153. }
  154. ssh:run() {
  155. local hostname="$1" ssh_options cmd
  156. shift
  157. ssh_options=()
  158. cmd=()
  159. while [ "$#" != 0 ]; do
  160. case "$1" in
  161. "--")
  162. shift
  163. cmd+=("$@")
  164. break
  165. ;;
  166. *)
  167. ssh_options+=("$1")
  168. ;;
  169. esac
  170. shift
  171. done
  172. ## XXXvlab: keeping in case we need some debug
  173. # debug "$DARKCYAN$hostname$NORMAL $WHITE\$$NORMAL" "$@"
  174. # debug "Running cmd: ${cmd[*]}"
  175. # for arg in "${cmd[@]}"; do
  176. # debug "$arg"
  177. # done
  178. {
  179. {
  180. ssh -o ControlPath=/tmp/ssh-control-master-${master_pid}-$hostname \
  181. -o ControlMaster=auto -o ControlPersist=900 \
  182. -o "StrictHostKeyChecking=no" \
  183. "${ssh_options[@]}" "$hostname" -- "${cmd[@]}"
  184. } 3>&1 1>&2 2>&3 ## | sed -r "s/^/$DARKCYAN$hostname$NORMAL $DARKRED\!$NORMAL /g"
  185. set_errlvl "${PIPESTATUS[0]}"
  186. } 3>&1 1>&2 2>&3
  187. }
  188. ssh:quit() {
  189. local hostname="$1"
  190. shift
  191. ssh -o ControlPath=/tmp/ssh-control-master-${master_pid} \
  192. -o ControlMaster=auto -o ControlPersist=900 -O exit \
  193. "$hostname" 2>/dev/null
  194. }
  195. is_ovh_domain_name() {
  196. local domain="$1"
  197. [[ "$domain" == *.ovh.net ]] && return 0
  198. [[ "$domain" == "ns"*".ip-"*".eu" ]] && return 0
  199. return 1
  200. }
  201. is_ovh_hostname() {
  202. local domain="$1"
  203. [[ "$domain" =~ ^vps-[0-9a-f]*$ ]] && return 0
  204. [[ "$domain" =~ ^vps[0-9]*$ ]] && return 0
  205. return 1
  206. }
  207. vps_connection_check() {
  208. local vps="$1"
  209. ip=$(resolve "$vps") ||
  210. { echo "${DARKRED}no-resolve${NORMAL}"; return 1; }
  211. is-port-open "$ip" "22" </dev/null ||
  212. { echo "${DARKRED}no-port-22-open${NORMAL}"; return 1; }
  213. ssh:open -o ConnectTimeout=10 -o PreferredAuthentications=publickey \
  214. "root@$vps" >/dev/null 2>&1 ||
  215. { echo "${DARKRED}no-ssh-root-access${NORMAL}"; return 1; }
  216. }
  217. vps_check() {
  218. local vps="$1"
  219. vps_connection_check "$vps" </dev/null || return 1
  220. if size=$(
  221. echo "df /srv -h | tail -n +2 | sed -r 's/ +/ /g' | cut -f 5 -d ' ' | cut -f 1 -d %" |
  222. ssh:run "root@$vps" -- bash); then
  223. if [ "$size" -gt "90" ]; then
  224. echo "${DARKRED}above-90%-disk-usage${NORMAL}"
  225. elif [ "$size" -gt "75" ]; then
  226. echo "${DARKYELLOW}above-75%-disk-usage${NORMAL}"
  227. fi
  228. else
  229. echo "${DARKRED}no-size${NORMAL}"
  230. fi </dev/null
  231. compose_content=$(ssh:run "root@$vps" -- cat /opt/apps/myc-deploy/compose.yml </dev/null) ||
  232. { echo "${DARKRED}no-compose${NORMAL}"; return 1; }
  233. echo "$compose_content" | yq -e ".rsync-backup" >/dev/null 2>&1 ||
  234. { echo "${DARKRED}no-backup${NORMAL}"; return 1; }
  235. }
  236. backup:setup-rsync() {
  237. local admin="$1" vps="$2" server="$3" id="$4"
  238. [ -z "${BACKUP_SSH_SERVER}" ] || {
  239. err "Unexpected error: '\$BACKUP_SSH_SERVER' is already set in '$FUNCNAME'."
  240. return 1
  241. }
  242. BACKUP_SSH_OPTIONS=(-o StrictHostKeyChecking=no)
  243. if [[ "$server" == *":"* ]]; then
  244. BACKUP_SSH_OPTIONS+=(-p "${server#*:}")
  245. BACKUP_SSH_SERVER=${server%%:*}
  246. else
  247. BACKUP_SSH_SERVER="$server"
  248. fi
  249. if ! private_key=$(ssh "${BACKUP_SSH_OPTIONS[@]}" \
  250. "$admin"@"${BACKUP_SSH_SERVER}" request-recovery-key "$id"); then
  251. err "Couldn't request a recovery key for '$id' with account '$admin'."
  252. return 1
  253. fi
  254. if ! VPS_TMP_DIR=$(echo "mktemp -d" | ssh:run "root@$vps" -- bash); then
  255. err "Couldn't create a temporary directory on vps"
  256. return 1
  257. fi
  258. cat <<EOF | ssh:run "root@$vps" -- bash || return 1
  259. touch "$VPS_TMP_DIR/recover_key" &&
  260. chmod go-rwx "$VPS_TMP_DIR/recover_key" &&
  261. printf "%s\n" "$private_key" >> "$VPS_TMP_DIR/recover_key"
  262. EOF
  263. BACKUP_SSH_OPTIONS+=(-i "$VPS_TMP_DIR/recover_key" -l rsync)
  264. BACKUP_VPS_TARGET="$vps"
  265. BACKUP_IDENT="$id"
  266. echo "type -p rsync >/dev/null 2>&1 || apt-get install -y rsync </dev/null" |
  267. ssh:run "root@$vps" -- bash || return 1
  268. }
  269. backup:rsync() {
  270. local ssh_options
  271. [ -n "${BACKUP_SSH_SERVER}" ] || {
  272. err "Unexpected error: '\$BACKUP_SSH_SERVER' is not set in 'rsync_exists'."
  273. return 1
  274. }
  275. rsync_options=()
  276. while [[ "$1" == "-"* ]]; do
  277. rsync_options+=("$1")
  278. shift
  279. done
  280. local src="$1" dst="$2"
  281. cat <<EOF | ssh:run "root@${BACKUP_VPS_TARGET}" -- bash
  282. rsync -e "ssh ${BACKUP_SSH_OPTIONS[*]}" \
  283. -azvArH --delete --delete-excluded \
  284. --partial --partial-dir .rsync-partial \
  285. --numeric-ids ${rsync_options[*]} \
  286. "${BACKUP_SSH_SERVER}":/var/mirror/"${BACKUP_IDENT}${src}" "${dst}"
  287. EOF
  288. }
  289. backup:path_exists() {
  290. local src="$1"
  291. [ -n "${BACKUP_SSH_SERVER}" ] || {
  292. err "Unexpected error: '\$BACKUP_SSH_SERVER' is not set in 'rsync_exists'."
  293. return 1
  294. }
  295. cat <<EOF | ssh:run "root@${BACKUP_VPS_TARGET}" -- bash >/dev/null 2>&1
  296. rsync -e "ssh ${BACKUP_SSH_OPTIONS[*]}" \
  297. -nazvArH --numeric-ids \
  298. "${BACKUP_SSH_SERVER}":/var/mirror/"${BACKUP_IDENT}${src}" "/tmp/dummy"
  299. EOF
  300. }
  301. file:vps_backup_recover() {
  302. local admin="$1" server="$2" id="$3" path="$4" vps="$5" vps_path="$6"
  303. backup:rsync "${path}" "${vps_path}" || return 1
  304. if [[ "$path" == *"/" ]]; then
  305. if [ "$path" == "$vps_path"/ ]; then
  306. msg_target="Directory '$path'"
  307. else
  308. msg_target="Directory '$path' -> '$vps_path'"
  309. fi
  310. else
  311. if [ "$path" == "$vps_path" ]; then
  312. msg_target="File '$path'"
  313. else
  314. msg_target="File '$path' -> '$vps_path'"
  315. fi
  316. fi
  317. info "$msg_target was ${GREEN}successfully${NORMAL} restored on $vps."
  318. }
  319. mailcow:vps_backup_recover() {
  320. local admin="$1" server="$2" id="$3" path="$4" vps="$5" vps_path="$6"
  321. if ! compose_yml_files=$(cat <<EOF | ssh:run "root@$vps" -- bash
  322. urn=com.docker.compose.project
  323. docker ps -f "label=\$urn=mailcowdockerized" \
  324. --format="{{.Label \"\$urn.working_dir\"}}/{{.Label \"\$urn.config_files\"}}" |
  325. uniq
  326. EOF
  327. ); then
  328. err "Couldn't get list of running projects"
  329. return 1
  330. fi
  331. stopped_containers=
  332. if [ -n "$compose_yml_files" ]; then
  333. echo "Found running mailcowdockerized containers" >&2
  334. if [[ "$compose_yml_files" == *$'\n'* ]]; then
  335. err "Running containers are confusing, did not find only one mailcowdockerized project."
  336. return 1
  337. fi
  338. if ! echo "[ -e \"$compose_yml_files\" ]" | ssh:run "root@$vps" -- bash ; then
  339. ## For some reason, sometimes $urn.config_files holds an absolute path
  340. compose_yml_files=/${compose_yml_files#*//}
  341. if ! echo "[ -e \"$compose_yml_files\" ]" | ssh:run "root@$vps" -- bash ; then
  342. err "Running containers are confusing, they don't point to an existing docker-compose.yml."
  343. return 1
  344. fi
  345. fi
  346. echo "Containers where launched from '$compose_yml_files'" >&2
  347. COMPOSE_FILE="$compose_yml_files"
  348. ENV_FILE="${COMPOSE_FILE%/*}/.env"
  349. if ! echo "[ -e \"${ENV_FILE}\" ]" | ssh:run "root@$vps" -- bash ; then
  350. err "Running containers are confusing, docker-compose.yml has no '.env' next to it."
  351. return 1
  352. fi
  353. echo "${WHITE}Bringing mailcowdockerized down${NORMAL}"
  354. echo "docker-compose -f \"${COMPOSE_FILE}\" --env-file \"${ENV_FILE}\" down" |
  355. ssh:run "root@$vps" -- bash
  356. stopped_containers=1
  357. fi
  358. if [[ "$path" == "/"* ]]; then
  359. ##
  360. ## Additional intelligence to simple file copy
  361. ##
  362. if [[ "$path" == "/var/lib/docker/volumes/mailcowdockerized_*-vol-1/_data"* ]]; then
  363. volume_name=${path#/var/lib/docker/volumes/}
  364. volume_name=${volume_name%%/*}
  365. volume_dir=${path%%"$volume_name"*}
  366. ## Create volumes if not existent
  367. if ! ssh:run "root@$vps" -- "
  368. [ -d '${volume_dir}' ] ||
  369. docker run --rm -v ${volume_name}:/tmp/dummy docker.0k.io/alpine:3.9
  370. [ -d '${volume_dir}' ]
  371. "; then
  372. err "Couldn't find nor create '${volume_dir}'."
  373. return 1
  374. fi
  375. fi
  376. echo "${WHITE}Sync from backup ${path} to VPS ${vps_path}${NORMAL}" >&2
  377. backup:rsync "${path}" "${vps_path}" || return 1
  378. if [[ "$path" == *"/" ]]; then
  379. if [ "$path" == "$vps_path"/ ]; then
  380. msg_target="Directory '$path'"
  381. else
  382. msg_target="Directory '$path' -> '$vps_path'"
  383. fi
  384. else
  385. if [ "$path" == "$vps_path" ]; then
  386. msg_target="File '$path'"
  387. else
  388. msg_target="File '$path' -> '$vps_path'"
  389. fi
  390. fi
  391. else
  392. ALL_TARGETS=(mailcow postfix rspamd redis crypt vmail{,-attachments} mysql)
  393. if [[ -n "$path" ]]; then
  394. targets=()
  395. bad_targets=()
  396. for target in ${path//,/ }; do
  397. if [[ " ${ALL_TARGETS[*]} " != *" $target "* ]]; then
  398. bad_targets+=("$target")
  399. fi
  400. targets+=("$target")
  401. done
  402. if [ "${#bad_targets[@]}" -gt 0 ]; then
  403. bad_target_msg=$(printf "%s, " "${bad_targets[@]}")
  404. err "Unknown components: ${bad_target_msg%, }. These are allowed components:"
  405. printf " - %s\n" "${ALL_TARGETS[@]}" >&2
  406. return 1
  407. fi
  408. msg_target="Partial mailcow backup"
  409. else
  410. targets=("${ALL_TARGETS[@]}")
  411. msg_target="Full mailcow backup"
  412. fi
  413. for target in "${targets[@]}"; do
  414. case "$target" in
  415. postfix|rspamd|redis|crypt|vmail|vmail-attachments)
  416. volume_name="mailcowdockerized_${target}-vol-1"
  417. volume_dir="/var/lib/docker/volumes/${volume_name}/_data"
  418. if ! backup:path_exists "${volume_dir}/"; then
  419. warn "No '$volume_name' in backup. This might be expected."
  420. continue
  421. fi
  422. ## Create volumes if not existent
  423. if ! ssh:run "root@$vps" -- "
  424. [ -d '${volume_dir}' ] ||
  425. docker run --rm -v ${volume_name}:/tmp/dummy docker.0k.io/alpine:3.9
  426. [ -d '${volume_dir}' ]
  427. "; then
  428. err "Couldn't find nor create '${volume_dir}'."
  429. return 1
  430. fi
  431. echo "${WHITE}Downloading of $volume_name${NORMAL}"
  432. backup:rsync "${volume_dir}/" "${volume_dir}" || return 1
  433. ;;
  434. mailcow)
  435. ## Mailcow git base
  436. COMPOSE_FILE=
  437. for mailcow_dir in /opt/{apps/,}mailcow-dockerized; do
  438. backup:path_exists "${mailcow_dir}/" || continue
  439. ## this possibly change last value
  440. COMPOSE_FILE="$mailcow_dir/docker-compose.yml"
  441. ENV_FILE="$mailcow_dir/.env"
  442. echo "${WHITE}Download of $mailcow_dir${NORMAL}"
  443. backup:rsync "${mailcow_dir}"/ "${mailcow_dir}" || return 1
  444. break
  445. done
  446. if [ -z "$COMPOSE_FILE" ]; then
  447. err "Can't find mailcow base installation path in backup."
  448. return 1
  449. fi
  450. ;;
  451. mysql)
  452. if [ -z "$COMPOSE_FILE" ]; then
  453. ## Mailcow git base
  454. compose_files=()
  455. for mailcow_dir in /opt/{apps/,}mailcow-dockerized; do
  456. ssh:run "root@$vps" -- "[ -e \"$mailcow_dir/docker-compose.yml\" ]" || continue
  457. ## this possibly change last value
  458. compose_files+=("$mailcow_dir/docker-compose.yml")
  459. done
  460. if [ "${#compose_files[@]}" == 0 ]; then
  461. err "No compose file found for mailcow installation."
  462. return 1
  463. elif [ "${#compose_files[@]}" -gt 1 ]; then
  464. err "Multiple compose files for mailcow found:"
  465. for f in "${compose_files[@]}"; do
  466. echo " - $f" >&2
  467. done
  468. echo "Can't decide which to use for mounting mysql container." >&2
  469. return 1
  470. fi
  471. COMPOSE_FILE="${compose_files[0]}"
  472. ENV_FILE="${COMPOSE_FILE%/*}/.env"
  473. if ! ssh:run "root@$vps" -- "[ -e \"${COMPOSE_FILE%/*}/.env\" ]"; then
  474. err "No env file in '$ENV_FILE' found."
  475. return 1
  476. fi
  477. fi
  478. ## Mysql database
  479. echo "${WHITE}Downloading last backup of mysql backups${NORMAL}"
  480. backup:rsync "/var/backups/mysql/" "/var/backups/mysql" || return 1
  481. if ! env_content=$(echo "cat '$ENV_FILE'" | ssh:run "root@$vps" -- bash); then
  482. err "Can't access env file: '$ENV_FILE'."
  483. return 1
  484. fi
  485. root_password=$(printf "%s\n" "$env_content" | grep ^DBROOT= | cut -f 2 -d =)
  486. echo "${WHITE}Bringing mysql-mailcow up${NORMAL}"
  487. if ! image=$(cat <<EOF | ssh:run "root@$vps" -- bash
  488. shyaml get-value services.mysql-mailcow.image < "${COMPOSE_FILE}"
  489. EOF
  490. ); then
  491. err "Failed to get image name of service 'mysql-mailcow' in 'compose.yml'."
  492. return 1
  493. fi
  494. if [ -z "$(ssh:run "root@$vps" -- docker images -q "$image")" ]; then
  495. info "Image '$image' not available, pull it."
  496. if ! ssh:run "root@$vps" -- \
  497. docker-compose -f "${COMPOSE_FILE}" --env-file "${ENV_FILE}" \
  498. pull mysql-mailcow; then
  499. err "Failed to pull image of service 'mysql-mailcow'."
  500. return 1
  501. fi
  502. fi
  503. if ! container_id=$(cat <<EOF | ssh:run "root@$vps" -- bash
  504. echo "[client]
  505. password=$root_password" > "$VPS_TMP_DIR/my.cnf"
  506. docker-compose -f "${COMPOSE_FILE}" --env-file "${ENV_FILE}" \
  507. run -d \
  508. -v "$VPS_TMP_DIR/my.cnf:/root/.my.cnf:ro" \
  509. mysql-mailcow
  510. EOF
  511. ); then
  512. err "Failed to bring up mysql-mailcow"
  513. return 1
  514. fi
  515. START="$SECONDS"
  516. retries=0
  517. timeout=600
  518. while true; do
  519. ((retries++))
  520. echo " waiting for mysql db..." \
  521. "(retry $retries, $(($SECONDS - $START))s elapsed, timeout is ${timeout}s)" >&2
  522. cat <<EOF | ssh:run "root@$vps" -- bash && break
  523. echo "SELECT 1;" | docker exec -i "$container_id" mysql >/dev/null 2>&1
  524. EOF
  525. if (($SECONDS - $START > $timeout)); then
  526. err "Failed to connect to mysql-mailcow."
  527. echo "docker-compose -f \"${COMPOSE_FILE}\" --env-file \"${ENV_FILE}\" down" |
  528. ssh:run "root@$vps" -- bash
  529. return 1
  530. fi
  531. sleep 0.4
  532. done
  533. DBUSER=$(printf "%s\n" "$env_content" | grep ^DBUSER= | cut -f 2 -d =)
  534. DBPASS=$(printf "%s\n" "$env_content" | grep ^DBPASS= | cut -f 2 -d =)
  535. echo "${WHITE}Uploading mysql dump${NORMAL}"
  536. cat <<EOF | ssh:run "root@$vps" -- bash
  537. echo "
  538. DROP DATABASE IF EXISTS mailcow;
  539. CREATE DATABASE mailcow;
  540. GRANT ALL PRIVILEGES ON mailcow.* TO '$DBUSER'@'%' IDENTIFIED BY '$DBPASS';
  541. " | docker exec -i "$container_id" mysql
  542. zcat /var/backups/mysql/mailcow/*.gz | docker exec -i "$container_id" mysql mailcow
  543. EOF
  544. if [ "$?" != 0 ]; then
  545. err "Failed to load mysql dump."
  546. echo "docker-compose -f \"${COMPOSE_FILE}\" --env-file \"${ENV_FILE}\" down" |
  547. ssh:run "root@$vps" -- bash
  548. return 1
  549. fi
  550. echo "${WHITE}Bringing mysql-mailcow down${NORMAL}"
  551. echo "docker-compose -f \"${COMPOSE_FILE}\" --env-file \"${ENV_FILE}\" down" |
  552. ssh:run "root@$vps" -- bash
  553. ;;
  554. *)
  555. err "Unknown component '$target'. Bailing out."
  556. return 1
  557. esac
  558. done
  559. ssh:run "root@$vps" -- "rm -rf '$VPS_TMP_DIR'"
  560. fi
  561. if [ -n "$stopped_containers" ]; then
  562. echo "${WHITE}Starting mailcow${NORMAL}" >&2
  563. echo "docker-compose -f \"${COMPOSE_FILE}\" --env-file \"${ENV_FILE}\" up -d" |
  564. ssh:run "root@$vps" -- bash
  565. fi
  566. info "$msg_target was ${GREEN}successfully${NORMAL} restored on $vps."
  567. }
  568. NTFY_TOPIC_FILE="/etc/ntfy/topics.yml"
  569. subscribe:ntfy:exists() {
  570. local vps="$1"
  571. if ! out=$(echo "[ -f \"$NTFY_TOPIC_FILE\" ] && echo ok || true" | \
  572. ssh:run "root@$vps" -- bash); then
  573. err "Unable to check for existence of '$NTFY_TOPIC_FILE'."
  574. fi
  575. if [ -z "$out" ]; then
  576. err "File '$NTFY_TOPIC_FILE' not found on $vps."
  577. return 1
  578. fi
  579. }
  580. ntfy:rm() {
  581. local channel="$1" topic="$2" vps="$3"
  582. subscribe:ntfy:exists "$vps" || return 1
  583. if ! out=$(echo "yq -i 'del(.[\"$channel\"][] | select(. == \"$TOPIC\"))' \"$NTFY_TOPIC_FILE\"" | \
  584. ssh:run "root@$vps" -- bash); then
  585. err "Failed to remove channel '$channel' from '$NTFY_TOPIC_FILE'."
  586. return 1
  587. fi
  588. info "Channel '$channel' removed from '$NTFY_TOPIC_FILE' on $vps."
  589. ssh:run "root@$vps" -- cat "$NTFY_TOPIC_FILE"
  590. }
  591. ntfy:add() {
  592. local channel="$1" topic="$2" vps="$3"
  593. vps_connection_check "$vps" </dev/null || return 1
  594. subscribe:ntfy:exists "$vps" || return 1
  595. if ! out=$(echo "yq '. | has(\"$channel\")' \"$NTFY_TOPIC_FILE\"" | \
  596. ssh:run "root@$vps" -- bash); then
  597. err "Failed to check if channel '$channel' with topic '$topic' is already in '$NTFY_TOPIC_FILE'."
  598. return 1
  599. fi
  600. if [ "$out" != "true" ]; then
  601. ## Channel does not exist
  602. if ! out=$(echo "yq -i '.[\"$channel\"] = []' \"$NTFY_TOPIC_FILE\"" | \
  603. ssh:run "root@$vps" -- bash); then
  604. err "Failed to create a new channel '$channel' entry in '$NTFY_TOPIC_FILE'."
  605. return 1
  606. fi
  607. else
  608. ## Channel exists
  609. if ! out=$(echo "yq '.[\"$channel\"] | any_c(. == \"$topic\")' \"$NTFY_TOPIC_FILE\"" | \
  610. ssh:run "root@$vps" -- bash); then
  611. err "Failed to check if channel '$channel' with topic '$topic' is already in '$NTFY_TOPIC_FILE'."
  612. return 1
  613. fi
  614. if [ "$out" == "true" ]; then
  615. info "Channel '$channel' with topic '$topic' already exists in '$NTFY_TOPIC_FILE'."
  616. return 0
  617. fi
  618. fi
  619. if ! out=$(echo "yq -i '.[\"$channel\"] += [\"$topic\"]' \"$NTFY_TOPIC_FILE\"" | \
  620. ssh:run "root@$vps" -- bash); then
  621. err "Failed to add channel '$channel' with topic '$topic' to '$NTFY_TOPIC_FILE'."
  622. return 1
  623. fi
  624. info "Channel '$channel' added with topic '$topic' to '$NTFY_TOPIC_FILE' on $vps."
  625. }
  626. NTFY_BROKER_SERVER="ntfy@core-01.0k.io"
  627. ntfy:topic-access() {
  628. local action="$1" topic="$2" vps="$3"
  629. vps_connection_check "$vps" </dev/null || return 1
  630. subscribe:ntfy:exists "$vps" || return 1
  631. local user=$(ntfy:get-login "$vps") || return 1
  632. if [ -z "$user" ]; then
  633. err "Couldn't find ntfy login on '$vps'."
  634. return 1
  635. fi
  636. if [ $action != "write" ] && [ $action != "remove" ]; then
  637. err "Invalid action '$action'."
  638. return 1
  639. fi
  640. ssh "$NTFY_BROKER_SERVER" topic-$action-access "$user" "$topic" </dev/null || {
  641. err "Failed to grant '$action' access to '$user' for topic '$topic'."
  642. return 1
  643. }
  644. info "Topic '$topic' '$action' access granted to '$user' for '$vps'."
  645. }
  646. ntfy:get-login() {
  647. local vps="$1"
  648. ## TODO: how to interpret NTYF_CONFIG_DIR on remote host ?
  649. # ${NTFY_CONFIG_DIR:-/etc/ntfy}
  650. if ! out=$(echo "grep '^LOGIN=' /etc/ntfy/ntfy.conf | cut -d '=' -f 2-" | \
  651. ssh:run "root@$vps" -- bash); then
  652. err "Failed to get ntfy login from '/etc/ntfy/ntfy.conf'."
  653. return 1
  654. fi
  655. echo "$out"
  656. }
  657. NTFY_SERVER="https://ntfy.0k.io"
  658. subscribe:add() {
  659. local vps="$1"
  660. read-0 channel topic || {
  661. err "Couldn't read CHANNEL and TOPIC arguments."
  662. return 1
  663. }
  664. vps_connection_check "$vps" </dev/null || return 1
  665. ntfy:topic-access "write" "$topic" "$vps" </dev/null || return 1
  666. ntfy:add "$channel" "$topic" "$vps"
  667. }
  668. subscribe:rm() {
  669. local vps="$1"
  670. read-0 channel topic || {
  671. err "Couldn't read CHANNEL and TOPIC arguments."
  672. return 1
  673. }
  674. vps_connection_check "$vps" </dev/null || return 1
  675. ntfy:rm "$channel" "$topic" "$vps" || return 1
  676. ntfy:topic-access "remove" "$topic" "$vps" </dev/null
  677. }
  678. vps_backup_recover() {
  679. local vps="$1" admin server id path rtype force type
  680. read-0 admin server id path rtype force
  681. if [[ "$vps" == *":"* ]]; then
  682. vps_path=${vps#*:}
  683. vps=${vps%%:*}
  684. else
  685. vps_path=
  686. fi
  687. vps_connection_check "$vps" </dev/null || {
  688. err "Failed to access '$vps'."
  689. return 1
  690. }
  691. if type=$(ssh:run "root@$vps" -- vps get-type); then
  692. info "VPS $vps seems to be of ${WHITE}$type${NORMAL} type"
  693. else
  694. warn "Couldn't find type of vps '$vps' (command 'vps get-type' failed on vps)."
  695. fi
  696. if [ -z "$path" ]; then
  697. if [ -n "$vps_path" ]; then
  698. err "You can't provide a VPS with path as destination if you don't provide a path in backup source."
  699. return 1
  700. fi
  701. info "No path provided in backup, so we assume you want ${WHITE}full recovery${NORMAL}."
  702. if [ "$rtype" != "$type" ]; then
  703. if [ -n "$force" ]; then
  704. warn "Backup found is of ${rtype:-unknown} type, while vps is of ${type:-unknown} type."
  705. else
  706. err "Backup found is of ${rtype:-unknown} type, while vps is of ${type:-unknown} type. (use \`\`-f\`\` to force)"
  707. return 1
  708. fi
  709. fi
  710. else
  711. if [ "$path" == "/" ]; then
  712. if [ -z "$vps_path" ]; then
  713. err "Recovery of '/' (full backup files) requires that you provide a vps path also."
  714. return 1
  715. fi
  716. if [ "$vps_path" == "/" ]; then
  717. err "Recovery of '/' (full backup files) requires that you provide" \
  718. "a vps path different from '/' also."
  719. return 1
  720. fi
  721. fi
  722. fi
  723. ## Sets VPS and internal global variable to allow rsync to work
  724. ## from vps to backup server.
  725. backup:setup-rsync "$admin" "$vps" "$server" "$id" || return 1
  726. if [[ "$path" == "/"* ]]; then
  727. if ! backup:path_exists "${path}"; then
  728. err "File or directory '$path' not found in backup."
  729. return 1
  730. fi
  731. if [ -z "$vps_path" ]; then
  732. if [[ "$path" != *"/" ]] && backup:path_exists "${path}"/ ; then
  733. path="$path/"
  734. fi
  735. vps_path=${path%/}
  736. vps_path=${vps_path:-/}
  737. fi
  738. fi
  739. case "$rtype-$type" in
  740. mailcow-*)
  741. ## Supports having $path and $vps_path set or unset, with additional behavior
  742. mailcow:vps_backup_recover "$admin" "$server" "$id" "$path" "$vps" "$vps_path"
  743. ;;
  744. *-*)
  745. if [[ "$path" == "/"* ]]; then
  746. ## For now, will require having $path and $vps_path set, no additional behaviors
  747. file:vps_backup_recover "$admin" "$server" "$id" "$path" "$vps" "$vps_path"
  748. else
  749. if [ -n "$path" ]; then
  750. err "Partial component recover of ${rtype:-unknown} backup type on" \
  751. "${type:-unknown} type VPS is not yet implemented."
  752. return 1
  753. else
  754. err "Full recover of ${rtype:-unknown} backup type on" \
  755. "${type:-unknown} type VPS is not yet implemented."
  756. return 1
  757. fi
  758. fi
  759. ;;
  760. esac
  761. }
  762. vps_install_backup() {
  763. local vps="$1" admin server
  764. vps_connection_check "$vps" </dev/null || return 1
  765. read-0 admin server
  766. if ! type=$(ssh:run "root@$vps" -- vps get-type); then
  767. err "Could not get type."
  768. return 1
  769. fi
  770. if ! out=$(ssh:run "root@$vps" -- vps install backup "$server" 2>&1); then
  771. err "Command 'vps install backup $server' on $vps failed:"
  772. echo "$out" | prefix " ${DARKGRAY}|${NORMAL} " >&2
  773. return 1
  774. fi
  775. ## Format of output:
  776. ##
  777. ## II Entry for service rsync-backup is already present in '/opt/apps/myc-deploy/compose.yml'.
  778. ## II You can run this following command from an host having admin access to core-07.0k.io:
  779. ## (Or send it to a backup admin of core-07.0k.io)
  780. ## ssh -p 10023 myadmin@core-07.0k.io ssh-key add 'ssh-rsa AAAAAAAD...QCJ\
  781. ## 8HH6pVgEpu1twyxpr9xTt7eh..WaJdgPoxmiEwGfjMMNGxs39ggOTKUuSFSmOv8TiA1fzY\
  782. ## s85hF...dKP1qByJU1k= compose@odoo.sikle.fr'
  783. key="ssh-rsa ${out##*\'ssh-rsa }" ## remove everything before last "'ssh-rsa"
  784. key="${key%\'*}" ## remove everything after last '
  785. if ! [[ "$key" =~ ^"ssh-rsa "[a-zA-Z0-9/+=]+" "[a-zA-Z0-9._-]+"@"[a-zA-Z0-9._-]+$ ]]; then
  786. err "Unexpected output from 'vps install backup $server'. Can't find key."
  787. echo "$out" | prefix " ${GRAY}|$NORMAL " >&2
  788. echo " Extracted key:" >&2
  789. echo "$key" | prefix " ${GRAY}|$NORMAL " >&2
  790. return 1
  791. fi
  792. if [ "$type" == "compose" ]; then
  793. if ! ssh:run "root@$vps" -- \
  794. docker exec myc_cron_1 \
  795. cat /etc/cron.d/rsync-backup >/dev/null 2>&1; then
  796. ssh:run "root@$vps" -- compose --debug up || {
  797. err "Command 'compose --debug up' failed."
  798. return 1
  799. }
  800. if ! ssh:run "root@$vps" -- \
  801. docker exec myc_cron_1 \
  802. cat /etc/cron.d/rsync-backup >/dev/null 2>&1; then
  803. err "Launched 'compose up' successfully but ${YELLOW}cron${NORMAL} container is not setup as expected."
  804. echo " Was waiting for existence of '/etc/cron.d/rsync-backup' in it." >&2
  805. return 1
  806. fi
  807. fi
  808. fi
  809. dest="$server"
  810. dest="${dest%/*}"
  811. ssh_options=()
  812. if [[ "$dest" == *":"* ]]; then
  813. port="${dest##*:}"
  814. dest="${dest%%:*}"
  815. ssh_options=(-p "$port")
  816. else
  817. port=""
  818. dest="${dest%%:*}"
  819. fi
  820. cmd=(ssh "${ssh_options[@]}" "$admin"@"$dest" ssh-key add "$key")
  821. echo "${WHITE}Launching:${NORMAL} ${cmd[@]}"
  822. "${cmd[@]}" || {
  823. err "Failed add key to backup server '$dest'."
  824. return 1
  825. }
  826. echo "${WHITE}Launching backup${NORMAL} from '$vps'"
  827. ssh:run "root@$vps" -- vps backup || {
  828. err "First backup failed to run."
  829. return 1
  830. }
  831. echo "Backup is ${GREEN}up and running${NORMAL}."
  832. }
  833. vps_update() {
  834. local vps="$1"
  835. vps_connection_check "$vps" || return 1
  836. ssh:run "root@$vps" -- myc-update </dev/null
  837. }
  838. vps_bash() {
  839. local vps="$1"
  840. vps_connection_check "$vps" </dev/null || return 1
  841. ssh:run "root@$vps" -- bash
  842. }
  843. vps_mux() {
  844. local fn="$1" vps_done VPS max_size vps
  845. shift
  846. VPS=($(printf "%s\n" "$@" | sort))
  847. max_size=0
  848. declare -A vps_done;
  849. new_vps=()
  850. for name in "${VPS[@]}"; do
  851. [ -n "${vps_done[$name]}" ] && {
  852. warn "duplicate vps '$name' provided. Ignoring."
  853. continue
  854. }
  855. vps_done["$name"]=1
  856. new_vps+=("$name")
  857. size_name="${#name}"
  858. [ "$max_size" -lt "${size_name}" ] &&
  859. max_size="$size_name"
  860. done
  861. settmpdir "_0KM_TMP_DIR"
  862. cat > "$_0KM_TMP_DIR/code"
  863. for vps in "${new_vps[@]}"; do
  864. label=$(printf "%-${max_size}s" "$vps")
  865. (
  866. {
  867. {
  868. "$fn" "$vps" < "$_0KM_TMP_DIR/code"
  869. } 3>&1 1>&2 2>&3 | sed -r "s/^/$DARKCYAN$label$NORMAL $DARKRED\!$NORMAL /g"
  870. set_errlvl "${PIPESTATUS[0]}"
  871. } 3>&1 1>&2 2>&3 | sed -r "s/^/$DARKCYAN$label$NORMAL $DARKGRAY\|$NORMAL /g"
  872. set_errlvl "${PIPESTATUS[0]}"
  873. ) &
  874. done
  875. wait
  876. }
  877. [ "$SOURCED" ] && return 0
  878. ##
  879. ## Command line processing
  880. ##
  881. cmdline.spec.gnu
  882. cmdline.spec.reporting
  883. cmdline.spec.gnu vps-setup
  884. cmdline.spec::cmd:vps-setup:run() {
  885. : :posarg: HOST 'Target host to check/fix ssh-access'
  886. : :optfla: --force,-f "Will force domain name change, even if
  887. current hostname was not recognized as
  888. an ovh domain name. "
  889. depends sshpass shyaml
  890. KEY_PATH="ssh-access.public-keys"
  891. local keys=$(config get-value -y "ssh-access.public-keys") || true
  892. if [ -z "$keys" ]; then
  893. err "No ssh publickeys configured in config file."
  894. echo " Looking for keys in ${WHITE}${KEY_PATH}${NORMAL}" \
  895. "in config file." >&2
  896. config:exists --message 2>&1 | prefix " "
  897. if [ "${PIPESTATUS[0]}" == "0" ]; then
  898. echo " Config file found in $(config:filename)"
  899. fi
  900. return 1
  901. fi
  902. local tkey=$(e "$keys" | shyaml get-type)
  903. if [ "$tkey" != "sequence" ]; then
  904. err "Value type of ${WHITE}${KEY_PATH}${NORMAL} unexpected (is $tkey, expecting sequence)."
  905. echo " Check content of $(config:filename), and make sure to use a sequence." >&2
  906. return 1
  907. fi
  908. local IP NAME keys host_pass_connected
  909. if ! IP=$(resolve "$HOST"); then
  910. err "'$HOST' name unresolvable."
  911. exit 1
  912. fi
  913. NAME="$HOST"
  914. if [ "$IP" != "$HOST" ]; then
  915. NAME="$HOST ($IP)"
  916. fi
  917. if ! is-port-open "$IP" "22"; then
  918. err "$NAME unreachable or port 22 closed."
  919. exit 1
  920. fi
  921. debug "Host $IP's port 22 is open."
  922. if ! host_pass_connected=$(ssh:open-try \
  923. {root,debian}@"$HOST"); then
  924. err "Could not connect to {root,debian}@$HOST with publickey nor password."
  925. exit 1
  926. fi
  927. read-0a host password <<<"$host_pass_connected"
  928. sudo_if_necessary=
  929. if [ "$password" -o "${host%%@*}" != "root" ]; then
  930. if ! ssh:run "$host" -- sudo -n true >/dev/null 2>&1; then
  931. err "Couldn't do a password-less sudo from $host."
  932. echo " This is not yet supported."
  933. exit 1
  934. else
  935. sudo_if_necessary=sudo
  936. fi
  937. fi
  938. SUPPORTED_KEY_TYPE=(ssh-rsa ssh-ed25519)
  939. Section Checking access
  940. while read-0 key; do
  941. prefix="${key%% *}"
  942. if ! [[ " ${SUPPORTED_KEY_TYPE[*]} " == *" $prefix "* ]]; then
  943. err "Unsupported key:"$'\n'"$key"
  944. echo " Please use only key of the following type:" >&2
  945. printf " - %s\n" "${SUPPORTED_KEY_TYPE[@]}" >&2
  946. return 1
  947. fi
  948. label="${key##* }"
  949. Elt "considering adding key ${DARKYELLOW}$label${NORMAL}"
  950. dest="/root/.ssh/authorized_keys"
  951. if ssh:run "$host" -- $sudo_if_necessary grep "\"$key\"" "$dest" >/dev/null 2>&1 </dev/null; then
  952. print_info "already present"
  953. print_status noop
  954. Feed
  955. else
  956. if echo "$key" | ssh:run "$host" -- $sudo_if_necessary tee -a "$dest" >/dev/null; then
  957. print_info added
  958. else
  959. echo
  960. Feedback failure
  961. return 1
  962. fi
  963. Feedback success
  964. fi
  965. done < <(e "$keys" | shyaml get-values-0)
  966. Section Checking ovh hostname file
  967. Elt "Checking /etc/ovh-hostname"
  968. if ! ssh:run "$host" -- $sudo_if_necessary [ -e "/etc/ovh-hostname" ]; then
  969. print_info "creating"
  970. ssh:run "$host" -- $sudo_if_necessary cp /etc/hostname /etc/ovh-hostname
  971. ovhname=$(ssh:run "$host" -- $sudo_if_necessary cat /etc/ovh-hostname)
  972. Elt "Checking /etc/ovh-hostname: $ovhname"
  973. Feedback || return 1
  974. else
  975. ovhname=$(ssh:run "$host" -- $sudo_if_necessary cat /etc/ovh-hostname)
  976. Elt "Checking /etc/ovh-hostname: $ovhname"
  977. print_info "already present"
  978. print_status noop
  979. Feed
  980. fi
  981. if ! is_ovh_domain_name "$HOST" && ! str_is_ipv4 "$HOST"; then
  982. Section Checking hostname
  983. Elt "Checking /etc/hostname..."
  984. old_etc_hostname="$(ssh:run "$host" -- $sudo_if_necessary cat /etc/hostname)"
  985. if [ "$old_etc_hostname" != "$HOST" ]; then
  986. Elt "/etc/hostname is '$old_etc_hostname'"
  987. if is_ovh_hostname "$old_etc_hostname" || [ -n "$opt_force" ]; then
  988. Elt "Hostname '$old_etc_hostname' --> '$HOST'"
  989. print_info "creating"
  990. echo "$HOST" | ssh:run "$host" -- $sudo_if_necessary tee /etc/hostname >/dev/null &&
  991. ssh:run "$host" -- $sudo_if_necessary hostname "$HOST"
  992. Feedback || return 1
  993. else
  994. Elt "Hostname '$old_etc_hostname' isn't an ovh domain"
  995. print_info "no change"
  996. print_status noop
  997. Feed
  998. warn "Domain name was not changed because it was already set"
  999. echo " (use \`-f\` or \`--force\`) to force domain name change to $HOST." >&2
  1000. fi
  1001. else
  1002. print_info "already set"
  1003. print_status noop
  1004. Feed
  1005. fi
  1006. Elt "Checking consistency between /etc/hostname and \`hostname\`..."
  1007. etc_hostname="$(ssh:run "$host" -- $sudo_if_necessary cat /etc/hostname)"
  1008. transient_hostname="$(ssh:run "$host" -- $sudo_if_necessary hostname)"
  1009. if [ "$etc_hostname" != "$transient_hostname" ]; then
  1010. print_info "change"
  1011. ssh:run "$host" -- $sudo_if_necessary hostname "$etc_hostname"
  1012. Feedback || return 1
  1013. else
  1014. print_info "consistent"
  1015. print_status noop
  1016. Feed
  1017. fi
  1018. else
  1019. info "Not changing domain as '$HOST' doesn't seem to be final domain."
  1020. fi
  1021. }
  1022. cmdline.spec.gnu vps-check
  1023. cmdline.spec::cmd:vps-check:run() {
  1024. : :posarg: [VPS...] 'Target host(s) to check'
  1025. echo "" |
  1026. vps_mux vps_check "${VPS[@]}"
  1027. }
  1028. cmdline.spec.gnu vps-install
  1029. cmdline.spec::cmd:vps-install:run() {
  1030. :
  1031. }
  1032. cmdline.spec.gnu backup
  1033. cmdline.spec:vps-install:cmd:backup:run() {
  1034. : :posarg: BACKUP_TARGET 'Backup target.
  1035. (ie: myadmin@backup.domain.org:10023/256)'
  1036. : :posarg: [VPS...] 'Target host(s) to check'
  1037. if [ "${#VPS[@]}" == 0 ]; then
  1038. warn "VPS list provided in command line is empty. Nothing will be done."
  1039. return 0
  1040. fi
  1041. if ! [[ "$BACKUP_TARGET" == *"@"* ]]; then
  1042. err "Missing admin account identifier in backup target."
  1043. echo " Have you forgottent to specify an account, ie 'myadmin@<MYBACKUP_SERVER>' ?)"
  1044. return 1
  1045. fi
  1046. admin=${BACKUP_TARGET%%@*}
  1047. server=${BACKUP_TARGET#*@}
  1048. p0 "$admin" "$server" |
  1049. vps_mux vps_install_backup "${VPS[@]}"
  1050. }
  1051. cmdline.spec.gnu vps-backup
  1052. cmdline.spec::cmd:vps-backup:run() {
  1053. :
  1054. }
  1055. cmdline.spec.gnu ls
  1056. cmdline.spec:vps-backup:cmd:ls:run() {
  1057. : :posarg: BACKUP_ID 'Backup id.
  1058. (ie: myadmin@backup.domain.org:10023)'
  1059. if ! [[ "$BACKUP_ID" == *"@"* ]]; then
  1060. err "Missing admin account identifier in backup id."
  1061. echo " Have you forgottent to specify an admin account ?" \
  1062. "ie 'myadmin@<MYBACKUP_SERVER>#<BACKUP_IDENT>' ?)"
  1063. return 1
  1064. fi
  1065. id=${BACKUP_ID##*#}
  1066. BACKUP_TARGET=${BACKUP_ID%#*}
  1067. admin=${BACKUP_TARGET%%@*}
  1068. server=${BACKUP_TARGET#*@}
  1069. ## XXXvlab: in this first implementation we expect to have access
  1070. ## to the server main ssh port 22, so we won't use the provided port.
  1071. ssh_options=()
  1072. if [[ "$server" == *":"* ]]; then
  1073. ssh_options+=(-p "${server#*:}")
  1074. server=${server%%:*}
  1075. fi
  1076. ssh "${ssh_options[@]}" "$admin"@"$server" ssh-key ls
  1077. }
  1078. cmdline.spec.gnu recover
  1079. cmdline.spec:vps-backup:cmd:recover:run() {
  1080. : :posarg: BACKUP_ID 'Backup id.
  1081. (ie: myadmin@backup.domain.org:10023#mx.myvps.org
  1082. myadmin@ark-01.org#myid:/a/path
  1083. admin@ark-02.io#myid:myqsl,mailcow)'
  1084. : :posarg: VPS_PATH 'Target host(s) to check.
  1085. (ie: myvps.com
  1086. myvps.com:/a/path)'
  1087. : :optval: --date,-D '"last", or label of version to recover. (Default: "last").'
  1088. : :optfla: --force,-f 'Will allow you to bypass some checks.'
  1089. if ! [[ "$BACKUP_ID" == *"@"* ]]; then
  1090. err "Missing admin account identifier in backup id."
  1091. echo " Have you forgottent to specify an admin account ?" \
  1092. "ie 'myadmin@<MYBACKUP_SERVER>#<BACKUP_IDENT>' ?)"
  1093. return 1
  1094. fi
  1095. if ! [[ "$BACKUP_ID" == *"@"*"#"* ]]; then
  1096. err "Missing backup label identifier in backup id."
  1097. echo " Have you forgottent to specify a backup label identifier ?" \
  1098. "ie 'myadmin@<MYBACKUP_SERVER>#<BACKUP_IDENT>' ?)"
  1099. return 1
  1100. fi
  1101. id_path=${BACKUP_ID#*#}
  1102. if [[ "$id_path" == *":"* ]]; then
  1103. id=${id_path%%:*}
  1104. path=${id_path#*:}
  1105. else
  1106. id="$id_path"
  1107. path=
  1108. fi
  1109. BACKUP_TARGET=${BACKUP_ID%#*}
  1110. admin=${BACKUP_TARGET%%@*}
  1111. server=${BACKUP_TARGET#*@}
  1112. ssh_options=()
  1113. if [[ "$server" == *":"* ]]; then
  1114. ssh_options+=(-p "${server#*:}")
  1115. ssh_server=${server%%:*}
  1116. fi
  1117. BACKUP_PATH="/srv/datastore/data/rsync-backup-target/var/mirror"
  1118. if ! content=$(ssh:run "$admin"@"${ssh_server}" "${ssh_options[@]}" -- ssh-key ls 2>/dev/null); then
  1119. err "Access denied to '$admin@${server}'."
  1120. return 1
  1121. fi
  1122. idents=$(echo "$content" | sed -r "s/"$'\e'"\[[0-9]+(;[0-9]+)*m//g" | cut -f 2 -d " ")
  1123. if ! [[ $'\n'"$idents"$'\n' == *$'\n'"$id"$'\n'* ]]; then
  1124. err "Given backup id '$id' not found in $admin@${server}'s idents."
  1125. return 1
  1126. fi
  1127. rtype=$(ssh:run "$admin"@"${ssh_server}" "${ssh_options[@]}" -- ssh-key get-type "$id" ) &&
  1128. info "Backup archive matches ${WHITE}${rtype}${NORMAL} type"
  1129. p0 "$admin" "$server" "$id" "$path" "$rtype" "$opt_force" |
  1130. vps_backup_recover "${VPS_PATH}"
  1131. }
  1132. cmdline.spec.gnu vps-update
  1133. cmdline.spec::cmd:vps-update:run() {
  1134. : :posarg: [VPS...] 'Target host to check'
  1135. echo "" |
  1136. vps_mux vps_update "${VPS[@]}"
  1137. }
  1138. cmdline.spec.gnu vps-mux
  1139. cmdline.spec::cmd:vps-mux:run() {
  1140. : :posarg: [VPS...] 'Target host(s) to check'
  1141. cat | vps_mux vps_bash "${VPS[@]}"
  1142. }
  1143. cmdline.spec.gnu vps-space
  1144. cmdline.spec::cmd:vps-space:run() {
  1145. : :posarg: [VPS...] 'Target host(s) to check'
  1146. echo "df /srv -h | tail -n +2 | sed -r 's/ +/ /g' | cut -f 2-5 -d ' '" |
  1147. vps_mux vps_bash "${VPS[@]}"
  1148. }
  1149. cmdline.spec.gnu vps-stats
  1150. cmdline.spec::cmd:vps-stats:run() {
  1151. : :posarg: [VPS...] 'Target host(s) to get stats'
  1152. : :optfla: --follow,-f 'Refresh graph every 2m'
  1153. : :optval: --timespan,-t 'timespan START[..END]'
  1154. : :optval: --resource,-r 'resource(s) separated with a comma'
  1155. : :optval: --interval,-i 'refersh interval (default: 60s)'
  1156. local opts_rrdfetch=( -a )
  1157. if [ -n "${opt_timespan}" ]; then
  1158. start=${opt_timespan%\.\.*}
  1159. opts_rrdfetch+=(-s "$start")
  1160. if [ "$start" != "${opt_timespan}" ]; then
  1161. end=${opt_timespan#*..}
  1162. opts_rrdfetch+=(-e "$end")
  1163. fi
  1164. fi
  1165. local resources=(c.memory c.network load_avg)
  1166. if [ -n "${opt_resource}" ]; then
  1167. resources=(${opt_resource//,/ })
  1168. fi
  1169. local not_found=()
  1170. for resource in "${resources[@]}"; do
  1171. if ! fn.exists "graph:def:$resource"; then
  1172. not_found+=("$resource")
  1173. fi
  1174. done
  1175. if [[ "${#not_found[@]}" -gt 0 ]]; then
  1176. not_found_msg=$(printf "%s, " "${not_found[@]}")
  1177. not_found_msg=${not_found_msg%, }
  1178. err "Unsupported resource(s) provided: ${not_found_msg}"
  1179. echo " resource must be one-of:" >&2
  1180. declare -F | egrep 'graph:def:[a-zA-Z_.]+$' | cut -f 3- -d " " | cut -f 3- -d ":" | prefix " - " >&2
  1181. return 1
  1182. fi
  1183. if [ "${#VPS[@]}" == 0 ]; then
  1184. err "You must provide a VPS list as positional arguments"
  1185. return 1
  1186. fi
  1187. include cache
  1188. if [ -z "$VAR_DIR" ]; then
  1189. err "Unset \$VAR_DIR, can't downlowd rrd graph"
  1190. return 1
  1191. fi
  1192. mkdir -p "$VAR_DIR/rrd"
  1193. if ! [ -d "$VAR_DIR/rrd" ]; then
  1194. err "Invalid \$VAR_DIR: '$VAR_DIR/rrd' is not a directory"
  1195. return 1
  1196. fi
  1197. (
  1198. for vps in "${VPS[@]}"; do
  1199. (
  1200. {
  1201. {
  1202. ssh:open "root@$vps" 2>/dev/null || {
  1203. err "Can't open connection $vps."
  1204. return 1
  1205. }
  1206. while true; do
  1207. if ssh:run "root@$vps" -- "[ -d '/var/lib/vps/rrd' ]"; then
  1208. echo "${WHITE}Collecting stats${NORMAL}..."
  1209. {
  1210. {
  1211. ssh:rsync "root@$vps:/var/lib/vps/rrd/" "${VAR_DIR}/rrd/${vps}"
  1212. } 3>&1 1>&2 2>&3 | prefix " ${DARKRED}\!${NORMAL} "
  1213. set_errlvl "${PIPESTATUS[0]}"
  1214. } 3>&1 1>&2 2>&3 | prefix " ${GRAY}|${NORMAL} "
  1215. echo " ${GRAY}..${NORMAL} ${DARKGREEN}done${NORMAL} collecting stats"
  1216. else
  1217. warn "No stats found. Did you run 'myc-update' on the vps ?."
  1218. fi
  1219. [ -z "$opt_follow" ] && break
  1220. echo "${WHITE}Sleeping ${DARKYELLOW}${opt_interval:-60}${NORMAL}s..."
  1221. sleep "${opt_interval:-60}"
  1222. echo " ${GRAY}..${NORMAL} ${DARKGREEN}done${NORMAL} sleeping"
  1223. done
  1224. } 3>&1 1>&2 2>&3 | prefix " ${DARKRED}\!${GRAY} collect(${DARKCYAN}$vps${GRAY})${NORMAL} "
  1225. set_errlvl "${PIPESTATUS[0]}"
  1226. } 3>&1 1>&2 2>&3 | prefix " ${GRAY}| collect(${DARKCYAN}$vps${GRAY})${NORMAL} " >&2
  1227. ) &
  1228. done
  1229. wait
  1230. ) &
  1231. collect_pid="$!"
  1232. if [ -z "$opt_follow" ]; then
  1233. echo "${WHITE}Fetching last stats${NORMAL}${GRAY}..${NORMAL}" >&2
  1234. wait
  1235. echo " ${GRAY}..${DARKGREEN} done${NORMAL} fetching stats" >&2
  1236. else
  1237. collect_end_msg=" ${GRAY}..${NORMAL} ${DARKGREEN}stop${NORMAL} collecting daemon (pid: ${DARKYELLOW}$collect_pid${NORMAL})"
  1238. trap_add EXIT \
  1239. "printf '%s\n' \"$collect_end_msg\" && kill $collect_pid"
  1240. echo "${WHITE}Start collecting daemon${NORMAL} (pid: ${DARKYELLOW}$collect_pid${NORMAL}) ${GRAY}..${NORMAL}" >&2
  1241. fi
  1242. ( depends gnuplot ) || {
  1243. echo ""
  1244. echo " Gnuplot is required to display graphs..." \
  1245. "You might want to try to install ${WHITE}gnuplot${NORMAL} with:"
  1246. echo ""
  1247. echo " apt install gnuplot"
  1248. echo ""
  1249. return 1
  1250. } >&2
  1251. ( depends rrdtool ) || {
  1252. echo ""
  1253. echo " Rrdtool is required to display graphs..." \
  1254. "You might want to try to install ${WHITE}rrdtool${NORMAL} with:"
  1255. echo ""
  1256. echo " apt install rrdtool"
  1257. echo ""
  1258. return 1
  1259. } >&2
  1260. export GNUTERM=qt
  1261. ## rrdtool fetch will use comma for floating point depending on some locals !
  1262. export LC_ALL=C
  1263. exec {PFD}> >(exec gnuplot 2>/dev/null)
  1264. gnuplot_pid="$!"
  1265. if [ -z "$opt_follow" ]; then
  1266. echo "${WHITE}Draw gnuplot graph${GRAY}..${NORMAL}" >&2
  1267. else
  1268. gnuplot_end_msg=" ${GRAY}..${NORMAL} ${DARKGREEN}stop${NORMAL} gnuplot process (pid: $gnuplot_pid)"
  1269. trap_add EXIT \
  1270. "printf '%s\n' \"$gnuplot_end_msg\" && kill $gnuplot_pid"
  1271. echo "${WHITE}Start gnuplot process${NORMAL} (pid: $gnuplot_pid) ${GRAY}..${NORMAL}" >&2
  1272. fi
  1273. echo "set term qt noraise replotonresize" >&$PFD
  1274. while true; do
  1275. {
  1276. i=0
  1277. data_start_ts=
  1278. data_stop_ts=
  1279. for resource in "${resources[@]}"; do
  1280. for vps in "${VPS[@]}"; do
  1281. ((i++))
  1282. {
  1283. {
  1284. rrd_vps_path="$VAR_DIR/rrd/$vps"
  1285. if [ -d "$rrd_vps_path" ]; then
  1286. graph:def:"${resource}" "$vps" "$i" "${opts_rrdfetch[@]}"
  1287. else
  1288. warn "No data yet, ignoring..."
  1289. fi
  1290. } 3>&1 1>&2 2>&3 | prefix " ${DARKRED}\!${GRAY} graph(${DARKCYAN}$vps${GRAY}:${WHITE}$resource${NORMAL})${NORMAL} "
  1291. set_errlvl "${PIPESTATUS[0]}"
  1292. } 3>&1 1>&2 2>&3 || continue 1
  1293. done
  1294. done
  1295. } >&$PFD
  1296. if [ -z "$opt_follow" ]; then
  1297. echo " ${GRAY}..${DARKGREEN} done${NORMAL} gnuplot graphing" >&2
  1298. break
  1299. else
  1300. {
  1301. echo "${WHITE}Sleeping ${DARKYELLOW}${opt_interval:-60}${NORMAL}s..."
  1302. sleep "${opt_interval:-60}"
  1303. echo " ${GRAY}..${NORMAL} ${DARKGREEN}done${NORMAL} sleeping"
  1304. } | prefix " ${GRAY}| gnuplot:${NORMAL} " >&2
  1305. fi
  1306. done
  1307. if [ -n "$opt_follow" ]; then
  1308. echo "Waiting for child process to finish.." >&2
  1309. wait
  1310. echo " ..done" >&2
  1311. else
  1312. echo "pause mouse close" >&$PFD
  1313. fi
  1314. }
  1315. graph:def:c.memory() {
  1316. local vps="$1" i="$2"
  1317. shift 2
  1318. local opts_rrdfetch=("$@")
  1319. local resource="memory"
  1320. rrd_vps_path="$VAR_DIR/rrd/$vps"
  1321. [ -d "$rrd_vps_path/containers" ] || {
  1322. warn "No containers data yet for vps '$vps'... Ignoring"
  1323. return 0
  1324. }
  1325. containers=(
  1326. $(
  1327. cd "$rrd_vps_path/containers";
  1328. find -maxdepth 3 -mindepth 3 -name "${resource}.rrd" -type f |
  1329. sed -r 's%^./([^/]+/[^/]+)/[^/]+.rrd$%\1%g'
  1330. )
  1331. )
  1332. gnuplot_line_config=(
  1333. "set term qt $i title \"$vps $resource\" replotonresize noraise"
  1334. "set title '$vps'"
  1335. "set xdata time"
  1336. "set timefmt '%s'"
  1337. "set ylabel '$resource Usage'"
  1338. "set format y '%s'"
  1339. "set ytics format ' %g'"
  1340. "set mouse mouseformat 6"
  1341. "set yrange [0:*] "
  1342. "set border behind"
  1343. )
  1344. printf "%s\n" "${gnuplot_line_config[@]}"
  1345. first=1
  1346. for container in "${containers[@]}"; do
  1347. rrdfetch_cmd="'< rrdtool fetch \"$rrd_vps_path/containers/$container/$resource.rrd\""
  1348. rrdfetch_cmd+=" AVERAGE ${opts_rrdfetch[*]} | \\"$'\n'
  1349. rrdfetch_cmd+=" tail -n +2 | \\"$'\n'
  1350. rrdfetch_cmd+=" egrep -v \"^$\" | sed -r \"s/ -?nan/ -/g;s/^([0-9]+): /\\1 /g\"'"
  1351. rrdfetch_cmd_bash=$(eval echo "${rrdfetch_cmd}")
  1352. rrdfetch_cmd_bash=${rrdfetch_cmd_bash#< }
  1353. first_ts=
  1354. first_ts=$(eval "$rrdfetch_cmd_bash" | head -n 1 | cut -f 1 -d " ")
  1355. if [ -z "$first_ts" ]; then
  1356. warn "No data for $container on vps $vps, skipping..."
  1357. continue
  1358. fi
  1359. last_ts=$(eval "$rrdfetch_cmd_bash" | tail -n 1 | cut -f 1 -d " ")
  1360. if [[ -z "$data_start_ts" ]] || [[ "$data_start_ts" > "$first_ts" ]]; then
  1361. data_start_ts="$first_ts"
  1362. fi
  1363. if [[ -z "$data_stop_ts" ]] || [[ "$data_stop_ts" < "$last_ts" ]]; then
  1364. data_stop_ts="$last_ts"
  1365. fi
  1366. if [ -n "$first" ]; then
  1367. first=
  1368. echo "plot \\"
  1369. else
  1370. echo ", \\"
  1371. fi
  1372. container="${container//\'/}"
  1373. container="${container//@/\\@}"
  1374. echo -n " ${rrdfetch_cmd} u 1:((\$3 - \$2)/1000000000) w lines title '${container//_/\\_}'"
  1375. done
  1376. echo
  1377. }
  1378. graph:def:c.network() {
  1379. local vps="$1" i="$2"
  1380. shift 2
  1381. local opts_rrdfetch=("$@")
  1382. local resource="network"
  1383. rrd_vps_path="$VAR_DIR/rrd/$vps"
  1384. [ -d "$rrd_vps_path/containers" ] || {
  1385. warn "No containers data yet for vps '$vps'... Ignoring"
  1386. return 0
  1387. }
  1388. containers=(
  1389. $(
  1390. cd "$rrd_vps_path/containers";
  1391. find -maxdepth 3 -mindepth 3 -name "${resource}.rrd" -type f |
  1392. sed -r 's%^./([^/]+/[^/]+)/[^/]+.rrd$%\1%g'
  1393. )
  1394. )
  1395. gnuplot_line_config=(
  1396. "set term qt $i title \"$vps $resource\" replotonresize noraise"
  1397. "set title '$vps'"
  1398. "set xdata time"
  1399. "set timefmt '%s'"
  1400. "set ylabel '$resource Usage'"
  1401. "set format y '%s'"
  1402. "set ytics format ' %.2f MiB/s'"
  1403. "set mouse mouseformat 6"
  1404. "set yrange [0:*] "
  1405. "set border behind"
  1406. )
  1407. printf "%s\n" "${gnuplot_line_config[@]}"
  1408. first=1
  1409. for container in "${containers[@]}"; do
  1410. rrdfetch_cmd="'< rrdtool fetch \"$rrd_vps_path/containers/$container/$resource.rrd\""
  1411. rrdfetch_cmd+=" AVERAGE ${opts_rrdfetch[*]} | \\"$'\n'
  1412. rrdfetch_cmd+=" tail -n +2 | \\"$'\n'
  1413. rrdfetch_cmd+=" egrep -v \"^$\" | sed -r \"s/ -?nan/ -/g;s/^([0-9]+): /\\1 /g\"'"
  1414. rrdfetch_cmd_bash=$(eval echo "${rrdfetch_cmd}")
  1415. rrdfetch_cmd_bash=${rrdfetch_cmd_bash#< }
  1416. first_ts=
  1417. first_ts=$(eval "$rrdfetch_cmd_bash" | head -n 1 | cut -f 1 -d " ")
  1418. if [ -z "$first_ts" ]; then
  1419. warn "No data for $container on vps $vps, skipping..."
  1420. continue
  1421. fi
  1422. last_ts=$(eval "$rrdfetch_cmd_bash" | tail -n 1 | cut -f 1 -d " ")
  1423. if [[ -z "$data_start_ts" ]] || [[ "$data_start_ts" > "$first_ts" ]]; then
  1424. data_start_ts="$first_ts"
  1425. fi
  1426. if [[ -z "$data_stop_ts" ]] || [[ "$data_stop_ts" < "$last_ts" ]]; then
  1427. data_stop_ts="$last_ts"
  1428. fi
  1429. if [ -n "$first" ]; then
  1430. first=
  1431. echo "plot \\"
  1432. else
  1433. echo ", \\"
  1434. fi
  1435. container="${container//\'/}"
  1436. container="${container//@/\\@}"
  1437. echo -n " ${rrdfetch_cmd} u 1:((\$3 / 1024) / 1024) w lines title '${container//_/\\_}'"
  1438. done
  1439. echo
  1440. }
  1441. graph:def:load_avg() {
  1442. local vps="$1" i="$2"
  1443. shift 2
  1444. local opts_rrdfetch=("$@")
  1445. rrd_vps_path="$VAR_DIR/rrd/$vps"
  1446. [ -f "$rrd_vps_path/$resource.rrd" ] || {
  1447. warn "No containers data yet for vps '$vps'... Ignoring"
  1448. return 0
  1449. }
  1450. gnuplot_line_config=(
  1451. "set term qt $i title \"$vps $resource\" replotonresize noraise"
  1452. "set title '$vps'"
  1453. "set xdata time"
  1454. "set timefmt '%s'"
  1455. "set ylabel '${resource//_/\\_} Usage'"
  1456. "set format y '%s'"
  1457. "set ytics format '%g'"
  1458. "set mouse mouseformat 6"
  1459. "set yrange [0:*] "
  1460. "set border behind"
  1461. )
  1462. printf "%s\n" "${gnuplot_line_config[@]}"
  1463. first=1
  1464. for value in 1m:2 5m:3 15m:4; do
  1465. label="${value%:*}"
  1466. col_num="${value#*:}"
  1467. rrdfetch_cmd="'< rrdtool fetch \"$rrd_vps_path/$resource.rrd\""
  1468. rrdfetch_cmd+=" AVERAGE ${opts_rrdfetch[*]} | \\"$'\n'
  1469. rrdfetch_cmd+=" tail -n +2 | \\"$'\n'
  1470. rrdfetch_cmd+=" egrep -v \"^$\" | sed -r \"s/ -?nan/ -/g;s/^([0-9]+): /\\1 /g\"'"
  1471. rrdfetch_cmd_bash=$(eval echo "${rrdfetch_cmd}")
  1472. rrdfetch_cmd_bash=${rrdfetch_cmd_bash#< }
  1473. first_ts=
  1474. first_ts=$(eval "$rrdfetch_cmd_bash" | head -n 1 | cut -f 1 -d " ")
  1475. if [ -z "$first_ts" ]; then
  1476. warn "No data for $resource on vps $vps, skipping..."
  1477. continue
  1478. fi
  1479. last_ts=$(eval "$rrdfetch_cmd_bash" | tail -n 1 | cut -f 1 -d " ")
  1480. if [[ -z "$data_start_ts" ]] || [[ "$data_start_ts" > "$first_ts" ]]; then
  1481. data_start_ts="$first_ts"
  1482. fi
  1483. if [[ -z "$data_stop_ts" ]] || [[ "$data_stop_ts" < "$last_ts" ]]; then
  1484. data_stop_ts="$last_ts"
  1485. fi
  1486. if [ -n "$first" ]; then
  1487. first=
  1488. echo "plot \\"
  1489. else
  1490. echo ", \\"
  1491. fi
  1492. container="${container//\'/}"
  1493. container="${container//@/\\@}"
  1494. echo -n " ${rrdfetch_cmd} u 1:$col_num w lines title '${label}'"
  1495. done
  1496. echo
  1497. }
  1498. cmdline.spec.gnu vps-subscribe
  1499. cmdline.spec::cmd:vps-subscribe:run() {
  1500. :
  1501. }
  1502. cmdline.spec.gnu add
  1503. cmdline.spec:vps-subscribe:cmd:add:run() {
  1504. : :posarg: CHANNEL 'Channel which will be sent to given topic'
  1505. : :posarg: TOPIC 'Ntfy topic to recieve messages of given channel
  1506. (format: "[MYSERVER:]MYTOPICS"
  1507. Examples: "ntfy.0k.io:main,storage,alerts",
  1508. "main{1,3,7}"
  1509. )'
  1510. : :posarg: [VPS...] 'Target host(s) to get stats'
  1511. printf "%s\0" "$CHANNEL" "$TOPIC" |
  1512. vps_mux subscribe:add "${VPS[@]}"
  1513. }
  1514. cmdline.spec.gnu rm
  1515. cmdline.spec:vps-subscribe:cmd:rm:run() {
  1516. : :posarg: CHANNEL 'Channel which will be sent to given topic'
  1517. : :posarg: TOPIC 'Ntfy topic to recieve messages of given channel
  1518. (format: "[MYSERVER:]MYTOPICS"
  1519. Examples: "ntfy.0k.io:main,storage,alerts",
  1520. "main{1,3,7}"
  1521. )'
  1522. : :posarg: [VPS...] 'Target host(s) to get stats'
  1523. printf "%s\0" "$CHANNEL" "$TOPIC" |
  1524. vps_mux subscribe:rm "${VPS[@]}"
  1525. }
  1526. cmdline::parse "$@"