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.

1170 lines
37 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. }
  26. resolve() {
  27. local ent hostname="$1"
  28. debug "Resolving $1 ..."
  29. if ent=$(getent ahosts "$hostname"); then
  30. ent=$(echo "$ent" | egrep ^"[0-9]+.[0-9]+.[0-9]+.[0-9]+\s+" | \
  31. head -n 1 | awk '{ print $1 }')
  32. debug " .. resolved $1 to $ent."
  33. echo "$ent"
  34. else
  35. debug " .. couldn't resolve $1."
  36. return 1
  37. fi
  38. }
  39. set_errlvl() { return "${1:-1}"; }
  40. export master_pid=$$
  41. ssh:open() {
  42. local hostname ssh_cmd ssh_options
  43. ssh_cmd=(ssh)
  44. ssh_options=()
  45. while [ "$#" != 0 ]; do
  46. case "$1" in
  47. "--stdin-password")
  48. ssh_cmd=(sshpass "${ssh_cmd[@]}")
  49. ;;
  50. -o)
  51. ssh_options+=("$1" "$2")
  52. shift
  53. ;;
  54. *)
  55. [ -z "$hostname" ] && hostname="$1" || {
  56. err "Surnumerous positional argument '$1'. Expecting only hostname."
  57. return 1
  58. }
  59. ;;
  60. esac
  61. shift
  62. done
  63. full_cmd=(
  64. "${ssh_cmd[@]}"
  65. -o ControlPath=/tmp/ssh-control-master-${master_pid}-$hostname \
  66. -o ControlMaster=auto -o ControlPersist=900 \
  67. -o ConnectTimeout=5 -o StrictHostKeyChecking=no \
  68. "${ssh_options[@]}" \
  69. "$hostname" "$@" -- true)
  70. "${full_cmd[@]}" </dev/null >/dev/null 2>&1 || {
  71. err "Failed: ${full_cmd[*]}"
  72. return 1
  73. }
  74. trap_add EXIT,INT 'ssh:quit "$hostname"'
  75. }
  76. ssh:open-try() {
  77. local opts hostnames
  78. opts=()
  79. hostnames=()
  80. while [ "$#" != 0 ]; do
  81. case "$1" in
  82. -o)
  83. opts+=("$1" "$2")
  84. shift
  85. ;;
  86. *)
  87. hostnames+=("$1")
  88. ;;
  89. esac
  90. shift
  91. done
  92. password=''
  93. for host in "${hostnames[@]}"; do
  94. debug "Trying $host with publickey."
  95. ssh:open -o PreferredAuthentications=publickey \
  96. "${opts[@]}" \
  97. "$host" >/dev/null 2>&1 && {
  98. echo "$host"$'\n'"$password"$'\n'
  99. return 0
  100. }
  101. debug " .. failed connecting to $host with publickey."
  102. done
  103. local times=0 password
  104. while [ "$((++times))" -le 3 ]; do
  105. read -sp "$HOST's password: " password
  106. errlvl="$?"
  107. echo >&2
  108. if [ "$errlvl" -gt 0 ]; then
  109. exit 1
  110. fi
  111. for host in "${hostnames[@]}"; do
  112. debug "Trying $host with password ($times/3)"
  113. echo "$password" | ssh:open -o PreferredAuthentications=password \
  114. --stdin-password \
  115. "${opts[@]}" \
  116. "$host" >/dev/null 2>&1 && {
  117. echo "$host"$'\n'"$password"$'\n'
  118. return 0
  119. }
  120. debug " .. failed connecting to $host with password."
  121. done
  122. err "login failed. Try again... ($((times+1))/3)"
  123. done
  124. return 1
  125. }
  126. ssh:run() {
  127. local hostname="$1" ssh_options cmd
  128. shift
  129. ssh_options=()
  130. cmd=()
  131. while [ "$#" != 0 ]; do
  132. case "$1" in
  133. "--")
  134. shift
  135. cmd+=("$@")
  136. break
  137. ;;
  138. *)
  139. ssh_options+=("$1")
  140. ;;
  141. esac
  142. shift
  143. done
  144. #echo "$DARKCYAN$hostname$NORMAL $WHITE\$$NORMAL" "$@"
  145. debug "Running cmd: ${cmd[@]}"
  146. for arg in "${cmd[@]}"; do
  147. debug "$arg"
  148. done
  149. {
  150. {
  151. ssh -o ControlPath=/tmp/ssh-control-master-${master_pid}-$hostname \
  152. -o ControlMaster=auto -o ControlPersist=900 \
  153. -o "StrictHostKeyChecking=no" \
  154. "${ssh_options[@]}" "$hostname" -- "${cmd[@]}"
  155. } 3>&1 1>&2 2>&3 ## | sed -r "s/^/$DARKCYAN$hostname$NORMAL $DARKRED\!$NORMAL /g"
  156. set_errlvl "${PIPESTATUS[0]}"
  157. } 3>&1 1>&2 2>&3
  158. }
  159. ssh:quit() {
  160. local hostname="$1"
  161. shift
  162. ssh -o ControlPath=/tmp/ssh-control-master-${master_pid} \
  163. -o ControlMaster=auto -o ControlPersist=900 -O exit \
  164. "$hostname" 2>/dev/null
  165. }
  166. is_ovh_domain_name() {
  167. local domain="$1"
  168. [[ "$domain" == *.ovh.net ]] && return 0
  169. [[ "$domain" == "ns"*".ip-"*".eu" ]] && return 0
  170. return 1
  171. }
  172. is_ovh_hostname() {
  173. local domain="$1"
  174. [[ "$domain" =~ ^vps-[0-9a-f]*$ ]] && return 0
  175. [[ "$domain" =~ ^vps[0-9]*$ ]] && return 0
  176. return 1
  177. }
  178. vps_connection_check() {
  179. local vps="$1"
  180. ip=$(resolve "$vps") ||
  181. { echo "${DARKRED}no-resolve${NORMAL}"; return 1; }
  182. is-port-open "$ip" "22" </dev/null ||
  183. { echo "${DARKRED}no-port-22-open${NORMAL}"; return 1; }
  184. ssh:open -o ConnectTimeout=10 -o PreferredAuthentications=publickey \
  185. "root@$vps" >/dev/null 2>&1 ||
  186. { echo "${DARKRED}no-ssh-root-access${NORMAL}"; return 1; }
  187. }
  188. vps_check() {
  189. local vps="$1"
  190. vps_connection_check "$vps" </dev/null || return 1
  191. if size=$(
  192. echo "df /srv -h | tail -n +2 | sed -r 's/ +/ /g' | cut -f 5 -d ' ' | cut -f 1 -d %" |
  193. ssh:run "root@$vps" -- bash); then
  194. if [ "$size" -gt "90" ]; then
  195. echo "${DARKRED}above-90%-disk-usage${NORMAL}"
  196. elif [ "$size" -gt "75" ]; then
  197. echo "${DARKYELLOW}above-75%-disk-usage${NORMAL}"
  198. fi
  199. else
  200. echo "${DARKRED}no-size${NORMAL}"
  201. fi </dev/null
  202. compose_content=$(ssh:run "root@$vps" -- cat /opt/apps/myc-deploy/compose.yml </dev/null) ||
  203. { echo "${DARKRED}no-compose${NORMAL}"; return 1; }
  204. echo "$compose_content" | grep backup >/dev/null 2>&1 ||
  205. { echo "${DARKRED}no-backup${NORMAL}"; return 1; }
  206. }
  207. backup:setup-rsync() {
  208. local admin="$1" vps="$2" server="$3" id="$4"
  209. [ -z "${BACKUP_SSH_SERVER}" ] || {
  210. err "Unexpected error: '\$BACKUP_SSH_SERVER' is already set in '$FUNCNAME'."
  211. return 1
  212. }
  213. BACKUP_SSH_OPTIONS=(-o StrictHostKeyChecking=no)
  214. if [[ "$server" == *":"* ]]; then
  215. BACKUP_SSH_OPTIONS+=(-p "${server#*:}")
  216. BACKUP_SSH_SERVER=${server%%:*}
  217. else
  218. BACKUP_SSH_SERVER="$server"
  219. fi
  220. if ! private_key=$(ssh "${BACKUP_SSH_OPTIONS[@]}" \
  221. "$admin"@"${BACKUP_SSH_SERVER}" request-recovery-key "$id"); then
  222. err "Couldn't request a recovery key for '$id' with account '$admin'."
  223. return 1
  224. fi
  225. if ! VPS_TMP_DIR=$(echo "mktemp -d" | ssh:run "root@$vps" -- bash); then
  226. err "Couldn't create a temporary directory on vps"
  227. return 1
  228. fi
  229. cat <<EOF | ssh:run "root@$vps" -- bash || return 1
  230. touch "$VPS_TMP_DIR/recover_key" &&
  231. chmod go-rwx "$VPS_TMP_DIR/recover_key" &&
  232. printf "%s\n" "$private_key" >> "$VPS_TMP_DIR/recover_key"
  233. EOF
  234. BACKUP_SSH_OPTIONS+=(-i "$VPS_TMP_DIR/recover_key" -l rsync)
  235. BACKUP_VPS_TARGET="$vps"
  236. BACKUP_IDENT="$id"
  237. echo "type -p rsync >/dev/null 2>&1 || apt-get install -y rsync </dev/null" |
  238. ssh:run "root@$vps" -- bash || return 1
  239. }
  240. backup:rsync() {
  241. local ssh_options
  242. [ -n "${BACKUP_SSH_SERVER}" ] || {
  243. err "Unexpected error: '\$BACKUP_SSH_SERVER' is not set in 'rsync_exists'."
  244. return 1
  245. }
  246. rsync_options=()
  247. while [[ "$1" == "-"* ]]; do
  248. rsync_options+=("$1")
  249. shift
  250. done
  251. local src="$1" dst="$2"
  252. cat <<EOF | ssh:run "root@${BACKUP_VPS_TARGET}" -- bash
  253. rsync -e "ssh ${BACKUP_SSH_OPTIONS[*]}" \
  254. -azvArH --delete --delete-excluded \
  255. --partial --partial-dir .rsync-partial \
  256. --numeric-ids ${rsync_options[*]} \
  257. "${BACKUP_SSH_SERVER}":/var/mirror/"${BACKUP_IDENT}${src}" "${dst}"
  258. EOF
  259. }
  260. backup:path_exists() {
  261. local src="$1"
  262. [ -n "${BACKUP_SSH_SERVER}" ] || {
  263. err "Unexpected error: '\$BACKUP_SSH_SERVER' is not set in 'rsync_exists'."
  264. return 1
  265. }
  266. cat <<EOF | ssh:run "root@${BACKUP_VPS_TARGET}" -- bash >/dev/null 2>&1
  267. rsync -e "ssh ${BACKUP_SSH_OPTIONS[*]}" \
  268. -nazvArH --numeric-ids \
  269. "${BACKUP_SSH_SERVER}":/var/mirror/"${BACKUP_IDENT}${src}" "/tmp/dummy"
  270. EOF
  271. }
  272. file:vps_backup_recover() {
  273. local admin="$1" server="$2" id="$3" path="$4" vps="$5" vps_path="$6"
  274. backup:rsync "${path}" "${vps_path}" || return 1
  275. if [[ "$path" == *"/" ]]; then
  276. if [ "$path" == "$vps_path"/ ]; then
  277. msg_target="Directory '$path'"
  278. else
  279. msg_target="Directory '$path' -> '$vps_path'"
  280. fi
  281. else
  282. if [ "$path" == "$vps_path" ]; then
  283. msg_target="File '$path'"
  284. else
  285. msg_target="File '$path' -> '$vps_path'"
  286. fi
  287. fi
  288. info "$msg_target was ${GREEN}successfully${NORMAL} restored on $vps."
  289. }
  290. mailcow:vps_backup_recover() {
  291. local admin="$1" server="$2" id="$3" path="$4" vps="$5" vps_path="$6"
  292. if ! compose_yml_files=$(cat <<EOF | ssh:run "root@$vps" -- bash
  293. urn=com.docker.compose.project
  294. docker ps -f "label=\$urn=mailcowdockerized" \
  295. --format="{{.Label \"\$urn.working_dir\"}}/{{.Label \"\$urn.config_files\"}}" |
  296. uniq
  297. EOF
  298. ); then
  299. err "Couldn't get list of running projects"
  300. return 1
  301. fi
  302. stopped_containers=
  303. if [ -n "$compose_yml_files" ]; then
  304. echo "Found running mailcowdockerized containers" >&2
  305. if [[ "$compose_yml_files" == *$'\n'* ]]; then
  306. err "Running containers are confusing, did not find only one mailcowdockerized project."
  307. return 1
  308. fi
  309. if ! echo "[ -e \"$compose_yml_files\" ]" | ssh:run "root@$vps" -- bash ; then
  310. ## For some reason, sometimes $urn.config_files holds an absolute path
  311. compose_yml_files=/${compose_yml_files#*//}
  312. if ! echo "[ -e \"$compose_yml_files\" ]" | ssh:run "root@$vps" -- bash ; then
  313. err "Running containers are confusing, they don't point to an existing docker-compose.yml."
  314. return 1
  315. fi
  316. fi
  317. echo "Containers where launched from '$compose_yml_files'" >&2
  318. COMPOSE_FILE="$compose_yml_files"
  319. ENV_FILE="${COMPOSE_FILE%/*}/.env"
  320. if ! echo "[ -e \"${ENV_FILE}\" ]" | ssh:run "root@$vps" -- bash ; then
  321. err "Running containers are confusing, docker-compose.yml has no '.env' next to it."
  322. return 1
  323. fi
  324. echo "${WHITE}Bringing mailcowdockerized down${NORMAL}"
  325. echo "docker-compose -f \"${COMPOSE_FILE}\" --env-file \"${ENV_FILE}\" down" |
  326. ssh:run "root@$vps" -- bash
  327. stopped_containers=1
  328. fi
  329. if [[ "$path" == "/"* ]]; then
  330. ##
  331. ## Additional intelligence to simple file copy
  332. ##
  333. if [[ "$path" == "/var/lib/docker/volumes/mailcowdockerized_*-vol-1/_data"* ]]; then
  334. volume_name=${path#/var/lib/docker/volumes/}
  335. volume_name=${volume_name%%/*}
  336. volume_dir=${path%%"$volume_name"*}
  337. ## Create volumes if not existent
  338. if ! ssh:run "root@$vps" -- "
  339. [ -d '${volume_dir}' ] ||
  340. docker run --rm -v ${volume_name}:/tmp/dummy docker.0k.io/alpine:3.9
  341. [ -d '${volume_dir}' ]
  342. "; then
  343. err "Couldn't find nor create '${volume_dir}'."
  344. return 1
  345. fi
  346. fi
  347. echo "${WHITE}Sync from backup ${path} to VPS ${vps_path}${NORMAL}" >&2
  348. backup:rsync "${path}" "${vps_path}" || return 1
  349. if [[ "$path" == *"/" ]]; then
  350. if [ "$path" == "$vps_path"/ ]; then
  351. msg_target="Directory '$path'"
  352. else
  353. msg_target="Directory '$path' -> '$vps_path'"
  354. fi
  355. else
  356. if [ "$path" == "$vps_path" ]; then
  357. msg_target="File '$path'"
  358. else
  359. msg_target="File '$path' -> '$vps_path'"
  360. fi
  361. fi
  362. else
  363. ALL_TARGETS=(mailcow postfix rspamd redis crypt vmail{,-attachments} mysql)
  364. if [[ -n "$path" ]]; then
  365. targets=()
  366. bad_targets=()
  367. for target in ${path//,/ }; do
  368. if [[ " ${ALL_TARGETS[*]} " != *" $target "* ]]; then
  369. bad_targets+=("$target")
  370. fi
  371. targets+=("$target")
  372. done
  373. if [ "${#bad_targets[@]}" -gt 0 ]; then
  374. bad_target_msg=$(printf "%s, " "${bad_targets[@]}")
  375. err "Unknown components: ${bad_target_msg%, }. These are allowed components:"
  376. printf " - %s\n" "${ALL_TARGETS[@]}" >&2
  377. return 1
  378. fi
  379. msg_target="Partial mailcow backup"
  380. else
  381. targets=("${ALL_TARGETS[@]}")
  382. msg_target="Full mailcow backup"
  383. fi
  384. for target in "${targets[@]}"; do
  385. case "$target" in
  386. postfix|rspamd|redis|crypt|vmail|vmail-attachments)
  387. volume_name="mailcowdockerized_${target}-vol-1"
  388. volume_dir="/var/lib/docker/volumes/${volume_name}/_data"
  389. if ! backup:path_exists "${volume_dir}/"; then
  390. warn "No '$volume_name' in backup. This might be expected."
  391. continue
  392. fi
  393. ## Create volumes if not existent
  394. if ! ssh:run "root@$vps" -- "
  395. [ -d '${volume_dir}' ] ||
  396. docker run --rm -v ${volume_name}:/tmp/dummy docker.0k.io/alpine:3.9
  397. [ -d '${volume_dir}' ]
  398. "; then
  399. err "Couldn't find nor create '${volume_dir}'."
  400. return 1
  401. fi
  402. echo "${WHITE}Downloading of $volume_name${NORMAL}"
  403. backup:rsync "${volume_dir}/" "${volume_dir}" || return 1
  404. ;;
  405. mailcow)
  406. ## Mailcow git base
  407. COMPOSE_FILE=
  408. for mailcow_dir in /opt/{apps/,}mailcow-dockerized; do
  409. backup:path_exists "${mailcow_dir}/" || continue
  410. ## this possibly change last value
  411. COMPOSE_FILE="$mailcow_dir/docker-compose.yml"
  412. ENV_FILE="$mailcow_dir/.env"
  413. echo "${WHITE}Download of $mailcow_dir${NORMAL}"
  414. backup:rsync "${mailcow_dir}"/ "${mailcow_dir}" || return 1
  415. break
  416. done
  417. if [ -z "$COMPOSE_FILE" ]; then
  418. err "Can't find mailcow base installation path in backup."
  419. return 1
  420. fi
  421. ;;
  422. mysql)
  423. if [ -z "$COMPOSE_FILE" ]; then
  424. ## Mailcow git base
  425. compose_files=()
  426. for mailcow_dir in /opt/{apps/,}mailcow-dockerized; do
  427. ssh:run "root@$vps" -- "[ -e \"$mailcow_dir/docker-compose.yml\" ]" || continue
  428. ## this possibly change last value
  429. compose_files+=("$mailcow_dir/docker-compose.yml")
  430. done
  431. if [ "${#compose_files[@]}" == 0 ]; then
  432. err "No compose file found for mailcow installation."
  433. return 1
  434. elif [ "${#compose_files[@]}" -gt 1 ]; then
  435. err "Multiple compose files for mailcow found:"
  436. for f in "${compose_files[@]}"; do
  437. echo " - $f" >&2
  438. done
  439. echo "Can't decide which to use for mounting mysql container." >&2
  440. return 1
  441. fi
  442. COMPOSE_FILE="${compose_files[0]}"
  443. ENV_FILE="${COMPOSE_FILE%/*}/.env"
  444. if ! ssh:run "root@$vps" -- "[ -e \"${COMPOSE_FILE%/*}/.env\" ]"; then
  445. err "No env file in '$ENV_FILE' found."
  446. return 1
  447. fi
  448. fi
  449. ## Mysql database
  450. echo "${WHITE}Downloading last backup of mysql backups${NORMAL}"
  451. backup:rsync "/var/backups/mysql/" "/var/backups/mysql" || return 1
  452. if ! env_content=$(echo "cat '$ENV_FILE'" | ssh:run "root@$vps" -- bash); then
  453. err "Can't access env file: '$ENV_FILE'."
  454. return 1
  455. fi
  456. root_password=$(printf "%s\n" "$env_content" | grep ^DBROOT= | cut -f 2 -d =)
  457. echo "${WHITE}Bringing mysql-mailcow up${NORMAL}"
  458. if ! image=$(cat <<EOF | ssh:run "root@$vps" -- bash
  459. shyaml get-value services.mysql-mailcow.image < "${COMPOSE_FILE}"
  460. EOF
  461. ); then
  462. err "Failed to get image name of service 'mysql-mailcow' in 'compose.yml'."
  463. return 1
  464. fi
  465. if [ -z "$(ssh:run "root@$vps" -- docker images -q "$image")" ]; then
  466. info "Image '$image' not available, pull it."
  467. if ! ssh:run "root@$vps" -- \
  468. docker-compose -f "${COMPOSE_FILE}" --env-file "${ENV_FILE}" \
  469. pull mysql-mailcow; then
  470. err "Failed to pull image of service 'mysql-mailcow'."
  471. return 1
  472. fi
  473. fi
  474. if ! container_id=$(cat <<EOF | ssh:run "root@$vps" -- bash
  475. echo "[client]
  476. password=$root_password" > "$VPS_TMP_DIR/my.cnf"
  477. docker-compose -f "${COMPOSE_FILE}" --env-file "${ENV_FILE}" \
  478. run -d \
  479. -v "$VPS_TMP_DIR/my.cnf:/root/.my.cnf:ro" \
  480. mysql-mailcow
  481. EOF
  482. ); then
  483. err "Failed to bring up mysql-mailcow"
  484. return 1
  485. fi
  486. START="$SECONDS"
  487. retries=0
  488. timeout=600
  489. while true; do
  490. ((retries++))
  491. echo " waiting for mysql db..." \
  492. "(retry $retries, $(($SECONDS - $START))s elapsed, timeout is ${timeout}s)" >&2
  493. cat <<EOF | ssh:run "root@$vps" -- bash && break
  494. echo "SELECT 1;" | docker exec -i "$container_id" mysql >/dev/null 2>&1
  495. EOF
  496. if (($SECONDS - $START > $timeout)); then
  497. err "Failed to connect to mysql-mailcow."
  498. echo "docker-compose -f \"${COMPOSE_FILE}\" --env-file \"${ENV_FILE}\" down" |
  499. ssh:run "root@$vps" -- bash
  500. return 1
  501. fi
  502. sleep 0.4
  503. done
  504. DBUSER=$(printf "%s\n" "$env_content" | grep ^DBUSER= | cut -f 2 -d =)
  505. DBPASS=$(printf "%s\n" "$env_content" | grep ^DBPASS= | cut -f 2 -d =)
  506. echo "${WHITE}Uploading mysql dump${NORMAL}"
  507. cat <<EOF | ssh:run "root@$vps" -- bash
  508. echo "
  509. DROP DATABASE IF EXISTS mailcow;
  510. CREATE DATABASE mailcow;
  511. GRANT ALL PRIVILEGES ON mailcow.* TO '$DBUSER'@'%' IDENTIFIED BY '$DBPASS';
  512. " | docker exec -i "$container_id" mysql
  513. zcat /var/backups/mysql/mailcow/*.gz | docker exec -i "$container_id" mysql mailcow
  514. EOF
  515. if [ "$?" != 0 ]; then
  516. err "Failed to load mysql dump."
  517. echo "docker-compose -f \"${COMPOSE_FILE}\" --env-file \"${ENV_FILE}\" down" |
  518. ssh:run "root@$vps" -- bash
  519. return 1
  520. fi
  521. echo "${WHITE}Bringing mysql-mailcow down${NORMAL}"
  522. echo "docker-compose -f \"${COMPOSE_FILE}\" --env-file \"${ENV_FILE}\" down" |
  523. ssh:run "root@$vps" -- bash
  524. ;;
  525. *)
  526. err "Unknown component '$target'. Bailing out."
  527. return 1
  528. esac
  529. done
  530. ssh:run "root@$vps" -- "rm -rf '$VPS_TMP_DIR'"
  531. fi
  532. if [ -n "$stopped_containers" ]; then
  533. echo "${WHITE}Starting mailcow${NORMAL}" >&2
  534. echo "docker-compose -f \"${COMPOSE_FILE}\" --env-file \"${ENV_FILE}\" up -d" |
  535. ssh:run "root@$vps" -- bash
  536. fi
  537. info "$msg_target was ${GREEN}successfully${NORMAL} restored on $vps."
  538. }
  539. vps_backup_recover() {
  540. local vps="$1" admin server id path rtype force type
  541. read-0 admin server id path rtype force
  542. if [[ "$vps" == *":"* ]]; then
  543. vps_path=${vps#*:}
  544. vps=${vps%%:*}
  545. else
  546. vps_path=
  547. fi
  548. vps_connection_check "$vps" </dev/null || {
  549. err "Failed to access '$vps'."
  550. return 1
  551. }
  552. type=$(ssh:run "root@$vps" -- vps get-type) && {
  553. info "VPS $vps seems to be of ${WHITE}$type${NORMAL} type"
  554. }
  555. if [ -z "$path" ]; then
  556. if [ -n "$vps_path" ]; then
  557. err "You can't provide a VPS with path as destination if you don't provide a path in backup source."
  558. return 1
  559. fi
  560. info "No path provided in backup, so we assume you want ${WHITE}full recovery${NORMAL}."
  561. if [ "$rtype" != "$type" ]; then
  562. if [ -n "$force" ]; then
  563. warn "Backup found is of ${rtype:-unknown} type, while vps is of ${type:-unknown} type."
  564. else
  565. err "Backup found is of ${rtype:-unknown} type, while vps is of ${type:-unknown} type. (use \`\`-f\`\` to force)"
  566. return 1
  567. fi
  568. fi
  569. else
  570. if [ "$path" == "/" ]; then
  571. if [ -z "$vps_path" ]; then
  572. err "Recovery of '/' (full backup files) requires that you provide a vps path also."
  573. return 1
  574. fi
  575. if [ "$vps_path" == "/" ]; then
  576. err "Recovery of '/' (full backup files) requires that you provide" \
  577. "a vps path different from '/' also."
  578. return 1
  579. fi
  580. fi
  581. fi
  582. ## Sets VPS and internal global variable to allow rsync to work
  583. ## from vps to backup server.
  584. backup:setup-rsync "$admin" "$vps" "$server" "$id" || return 1
  585. if [[ "$path" == "/"* ]]; then
  586. if ! backup:path_exists "${path}"; then
  587. err "File or directory '$path' not found in backup."
  588. return 1
  589. fi
  590. if [ -z "$vps_path" ]; then
  591. if [[ "$path" != *"/" ]] && backup:path_exists "${path}"/ ; then
  592. path="$path/"
  593. fi
  594. vps_path=${path%/}
  595. vps_path=${vps_path:-/}
  596. fi
  597. fi
  598. case "$rtype-$type" in
  599. mailcow-*)
  600. ## Supports having $path and $vps_path set or unset, with additional behavior
  601. mailcow:vps_backup_recover "$admin" "$server" "$id" "$path" "$vps" "$vps_path"
  602. ;;
  603. *-*)
  604. if [[ "$path" == "/"* ]]; then
  605. ## For now, will require having $path and $vps_path set, no additional behaviors
  606. file:vps_backup_recover "$admin" "$server" "$id" "$path" "$vps" "$vps_path"
  607. else
  608. if [ -n "$path" ]; then
  609. err "Partial component recover of ${rtype:-unknown} backup type on" \
  610. "${type:-unknown} type VPS is not yet implemented."
  611. return 1
  612. else
  613. err "Full recover of ${rtype:-unknown} backup type on" \
  614. "${type:-unknown} type VPS is not yet implemented."
  615. return 1
  616. fi
  617. fi
  618. ;;
  619. esac
  620. }
  621. vps_install_backup() {
  622. local vps="$1" admin server
  623. vps_connection_check "$vps" </dev/null || return 1
  624. read-0 admin server
  625. if ! type=$(ssh:run "root@$vps" -- vps get-type); then
  626. err "Could not get type."
  627. return 1
  628. fi
  629. if ! out=$(ssh:run "root@$vps" -- vps install backup "$server" 2>&1); then
  630. err "Command 'vps install backup $server' failed."
  631. return 1
  632. fi
  633. out="${out%$'\n'}"
  634. out="${out#*$'\n'}"
  635. key="${out%\'*}"
  636. key="${key##*\'}"
  637. if ! [[ "$key" =~ ^"ssh-rsa "[a-zA-Z0-9/+]+" "[a-zA-Z0-9._-]+"@"[a-zA-Z0-9._-]+$ ]]; then
  638. err "Unexpected output from 'vps install backup $server'. Can't find key."
  639. echo "$out" | prefix " ${GRAY}|$NORMAL " >&2
  640. echo " Extracted key:" >&2
  641. echo "$key" | prefix " ${GRAY}|$NORMAL " >&2
  642. return 1
  643. fi
  644. if [ "$type" == "compose" ]; then
  645. if ! ssh:run "root@$vps" -- \
  646. docker exec myc_cron_1 \
  647. cat /etc/cron.d/rsync-backup >/dev/null 2>&1; then
  648. ssh:run "root@$vps" -- compose --debug up || {
  649. err "Command 'compose --debug up' failed."
  650. return 1
  651. }
  652. if ! ssh:run "root@$vps" -- \
  653. docker exec myc_cron_1 \
  654. cat /etc/cron.d/rsync-backup >/dev/null 2>&1; then
  655. err "Launched 'compose up' successfully but ${YELLOW}cron${NORMAL} container is not setup as expected."
  656. echo " Was waiting for existence of '/etc/cron.d/rsync-backup' in it." >&2
  657. return 1
  658. fi
  659. fi
  660. fi
  661. dest="$server"
  662. dest="${dest%/*}"
  663. ssh_options=()
  664. if [[ "$dest" == *":"* ]]; then
  665. port="${dest##*:}"
  666. dest="${dest%%:*}"
  667. ssh_options=(-p "$port")
  668. else
  669. port=""
  670. dest="${dest%%:*}"
  671. fi
  672. cmd=(ssh "${ssh_options[@]}" "$admin"@"$dest" ssh-key add "$key")
  673. echo "${WHITE}Launching:${NORMAL} ${cmd[@]}"
  674. "${cmd[@]}" || {
  675. err "Failed add key to backup server '$dest'."
  676. return 1
  677. }
  678. echo "${WHITE}Launching backup${NORMAL} from '$vps'"
  679. ssh:run "root@$vps" -- vps backup || {
  680. err "First backup failed to run."
  681. return 1
  682. }
  683. echo "Backup is ${GREEN}up and running${NORMAL}."
  684. }
  685. vps_udpate() {
  686. local vps="$1"
  687. vps_connection_check "$vps" || return 1
  688. ssh:run "root@$vps" -- myc-update </dev/null
  689. }
  690. vps_bash() {
  691. local vps="$1"
  692. vps_connection_check "$vps" </dev/null || return 1
  693. ssh:run "root@$vps" -- bash
  694. }
  695. vps_mux() {
  696. local fn="$1" vps_done VPS max_size vps
  697. shift
  698. VPS=($(printf "%s\n" "$@" | sort))
  699. max_size=0
  700. declare -A vps_done;
  701. new_vps=()
  702. for name in "${VPS[@]}"; do
  703. [ -n "${vps_done[$name]}" ] && {
  704. warn "duplicate vps '$name' provided. Ignoring."
  705. continue
  706. }
  707. vps_done["$name"]=1
  708. new_vps+=("$name")
  709. size_name="${#name}"
  710. [ "$max_size" -lt "${size_name}" ] &&
  711. max_size="$size_name"
  712. done
  713. settmpdir "_0KM_TMP_DIR"
  714. cat > "$_0KM_TMP_DIR/code"
  715. for vps in "${new_vps[@]}"; do
  716. label=$(printf "%-${max_size}s" "$vps")
  717. (
  718. {
  719. {
  720. "$fn" "$vps" < "$_0KM_TMP_DIR/code"
  721. } 3>&1 1>&2 2>&3 | sed -r "s/^/$DARKCYAN$label$NORMAL $DARKRED\!$NORMAL /g"
  722. set_errlvl "${PIPESTATUS[0]}"
  723. } 3>&1 1>&2 2>&3 | sed -r "s/^/$DARKCYAN$label$NORMAL $DARKGRAY\|$NORMAL /g"
  724. set_errlvl "${PIPESTATUS[0]}"
  725. ) &
  726. done
  727. wait
  728. }
  729. [ "$SOURCED" ] && return 0
  730. ##
  731. ## Command line processing
  732. ##
  733. cmdline.spec.gnu
  734. cmdline.spec.reporting
  735. cmdline.spec.gnu vps-setup
  736. cmdline.spec::cmd:vps-setup:run() {
  737. : :posarg: HOST 'Target host to check/fix ssh-access'
  738. depends sshpass shyaml
  739. KEY_PATH="ssh-access.public-keys"
  740. local keys=$(config get-value -y "ssh-access.public-keys") || true
  741. if [ -z "$keys" ]; then
  742. err "No ssh publickeys configured in config file."
  743. echo " Looking for keys in ${WHITE}${KEY_PATH}${NORMAL}" \
  744. "in config file." >&2
  745. config:exists --message 2>&1 | prefix " "
  746. if [ "${PIPESTATUS[0]}" == "0" ]; then
  747. echo " Config file found in $(config:filename)"
  748. fi
  749. return 1
  750. fi
  751. local tkey=$(e "$keys" | shyaml get-type)
  752. if [ "$tkey" != "sequence" ]; then
  753. err "Value type of ${WHITE}${KEY_PATH}${NORMAL} unexpected (is $tkey, expecting sequence)."
  754. echo " Check content of $(config:filename), and make sure to use a sequence." >&2
  755. return 1
  756. fi
  757. local IP NAME keys host_pass_connected
  758. if ! IP=$(resolve "$HOST"); then
  759. err "'$HOST' name unresolvable."
  760. exit 1
  761. fi
  762. NAME="$HOST"
  763. if [ "$IP" != "$HOST" ]; then
  764. NAME="$HOST ($IP)"
  765. fi
  766. if ! is-port-open "$IP" "22"; then
  767. err "$NAME unreachable or port 22 closed."
  768. exit 1
  769. fi
  770. debug "Host $IP's port 22 is open."
  771. if ! host_pass_connected=$(ssh:open-try \
  772. {root,debian}@"$HOST"); then
  773. err "Could not connect to {root,debian}@$HOST with publickey nor password."
  774. exit 1
  775. fi
  776. read-0a host password <<<"$host_pass_connected"
  777. sudo_if_necessary=
  778. if [ "$password" -o "${host%%@*}" != "root" ]; then
  779. if ! ssh:run "$host" -- sudo -n true >/dev/null 2>&1; then
  780. err "Couldn't do a password-less sudo from $host."
  781. echo " This is not yet supported."
  782. exit 1
  783. else
  784. sudo_if_necessary=sudo
  785. fi
  786. fi
  787. Section Checking access
  788. while read-0 key; do
  789. prefix="${key%% *}"
  790. if [ "$prefix" != "ssh-rsa" ]; then
  791. err "Unsupported key:"$'\n'"$key"
  792. return 1
  793. fi
  794. label="${key##* }"
  795. Elt "considering adding key ${DARKYELLOW}$label${NORMAL}"
  796. dest="/root/.ssh/authorized_keys"
  797. if ssh:run "$host" -- $sudo_if_necessary grep "\"$key\"" "$dest" >/dev/null 2>&1 </dev/null; then
  798. print_info "already present"
  799. print_status noop
  800. Feed
  801. else
  802. if echo "$key" | ssh:run "$host" -- $sudo_if_necessary tee -a "$dest" >/dev/null; then
  803. print_info added
  804. else
  805. echo
  806. Feedback failure
  807. return 1
  808. fi
  809. Feedback success
  810. fi
  811. done < <(e "$keys" | shyaml get-values-0)
  812. Section Checking ovh hostname file
  813. Elt "Checking /etc/ovh-hostname"
  814. if ! ssh:run "$host" -- $sudo_if_necessary [ -e "/etc/ovh-hostname" ]; then
  815. print_info "creating"
  816. ssh:run "$host" -- $sudo_if_necessary cp /etc/hostname /etc/ovh-hostname
  817. ovhname=$(ssh:run "$host" -- $sudo_if_necessary cat /etc/ovh-hostname)
  818. Elt "Checking /etc/ovh-hostname: $ovhname"
  819. Feedback || return 1
  820. else
  821. ovhname=$(ssh:run "$host" -- $sudo_if_necessary cat /etc/ovh-hostname)
  822. Elt "Checking /etc/ovh-hostname: $ovhname"
  823. print_info "already present"
  824. print_status noop
  825. Feed
  826. fi
  827. if ! is_ovh_domain_name "$HOST" && ! str_is_ipv4 "$HOST"; then
  828. Section Checking hostname
  829. Elt "Checking /etc/hostname..."
  830. if [ "$old" != "$HOST" ]; then
  831. old="$(ssh:run "$host" -- $sudo_if_necessary cat /etc/hostname)"
  832. Elt "Hostname is '$old'"
  833. if is_ovh_hostname "$old"; then
  834. Elt "Hostname '$old' --> '$HOST'"
  835. print_info "creating"
  836. echo "$HOST" | ssh:run "$host" -- $sudo_if_necessary tee /etc/hostname >/dev/null &&
  837. ssh:run "$host" -- $sudo_if_necessary hostname "$HOST"
  838. Feedback || return 1
  839. else
  840. print_info "not changing"
  841. print_status noop
  842. Feed
  843. fi
  844. else
  845. print_info "already set"
  846. print_status noop
  847. Feed
  848. fi
  849. else
  850. info "Not changing domain as '$HOST' doesn't seem to be final domain."
  851. fi
  852. }
  853. cmdline.spec.gnu vps-check
  854. cmdline.spec::cmd:vps-check:run() {
  855. : :posarg: [VPS...] 'Target host(s) to check'
  856. echo "" |
  857. vps_mux vps_check "${VPS[@]}"
  858. }
  859. cmdline.spec.gnu vps-install
  860. cmdline.spec::cmd:vps-install:run() {
  861. :
  862. }
  863. cmdline.spec.gnu backup
  864. cmdline.spec:vps-install:cmd:backup:run() {
  865. : :posarg: BACKUP_TARGET 'Backup target.
  866. (ie: myadmin@backup.domain.org:10023/256)'
  867. : :posarg: [VPS...] 'Target host(s) to check'
  868. if [ "${#VPS[@]}" == 0 ]; then
  869. warn "VPS list provided in command line is empty. Nothing will be done."
  870. return 0
  871. fi
  872. if ! [[ "$BACKUP_TARGET" == *"@"* ]]; then
  873. err "Missing admin account identifier in backup target."
  874. echo " Have you forgottent to specify an account, ie 'myadmin@<MYBACKUP_SERVER>' ?)"
  875. return 1
  876. fi
  877. admin=${BACKUP_TARGET%%@*}
  878. server=${BACKUP_TARGET#*@}
  879. p0 "$admin" "$server" |
  880. vps_mux vps_install_backup "${VPS[@]}"
  881. }
  882. cmdline.spec.gnu vps-backup
  883. cmdline.spec::cmd:vps-backup:run() {
  884. :
  885. }
  886. cmdline.spec.gnu ls
  887. cmdline.spec:vps-backup:cmd:ls:run() {
  888. : :posarg: BACKUP_ID 'Backup id.
  889. (ie: myadmin@backup.domain.org:10023)'
  890. if ! [[ "$BACKUP_ID" == *"@"* ]]; then
  891. err "Missing admin account identifier in backup id."
  892. echo " Have you forgottent to specify an admin account ?" \
  893. "ie 'myadmin@<MYBACKUP_SERVER>#<BACKUP_IDENT>' ?)"
  894. return 1
  895. fi
  896. id=${BACKUP_ID##*#}
  897. BACKUP_TARGET=${BACKUP_ID%#*}
  898. admin=${BACKUP_TARGET%%@*}
  899. server=${BACKUP_TARGET#*@}
  900. ## XXXvlab: in this first implementation we expect to have access
  901. ## to the server main ssh port 22, so we won't use the provided port.
  902. ssh_options=()
  903. if [[ "$server" == *":"* ]]; then
  904. ssh_options+=(-p "${server#*:}")
  905. server=${server%%:*}
  906. fi
  907. ssh "${ssh_options[@]}" "$admin"@"$server" ssh-key ls
  908. }
  909. cmdline.spec.gnu recover
  910. cmdline.spec:vps-backup:cmd:recover:run() {
  911. : :posarg: BACKUP_ID 'Backup id.
  912. (ie: myadmin@backup.domain.org:10023#mx.myvps.org
  913. myadmin@ark-01.org#myid:/a/path
  914. admin@ark-02.io#myid:myqsl,mailcow)'
  915. : :posarg: VPS_PATH 'Target host(s) to check.
  916. (ie: myvps.com
  917. myvps.com:/a/path)'
  918. : :optval: --date,-D '"last", or label of version to recover. (Default: "last").'
  919. : :optfla: --force,-f 'Will allow you to bypass some checks.'
  920. if ! [[ "$BACKUP_ID" == *"@"* ]]; then
  921. err "Missing admin account identifier in backup id."
  922. echo " Have you forgottent to specify an admin account ?" \
  923. "ie 'myadmin@<MYBACKUP_SERVER>#<BACKUP_IDENT>' ?)"
  924. return 1
  925. fi
  926. if ! [[ "$BACKUP_ID" == *"@"*"#"* ]]; then
  927. err "Missing backup label identifier in backup id."
  928. echo " Have you forgottent to specify a backup label identifier ?" \
  929. "ie 'myadmin@<MYBACKUP_SERVER>#<BACKUP_IDENT>' ?)"
  930. return 1
  931. fi
  932. id_path=${BACKUP_ID#*#}
  933. if [[ "$id_path" == *":"* ]]; then
  934. id=${id_path%%:*}
  935. path=${id_path#*:}
  936. else
  937. id="$id_path"
  938. path=
  939. fi
  940. BACKUP_TARGET=${BACKUP_ID%#*}
  941. admin=${BACKUP_TARGET%%@*}
  942. server=${BACKUP_TARGET#*@}
  943. ssh_options=()
  944. if [[ "$server" == *":"* ]]; then
  945. ssh_options+=(-p "${server#*:}")
  946. ssh_server=${server%%:*}
  947. fi
  948. BACKUP_PATH="/srv/datastore/data/rsync-backup-target/var/mirror"
  949. if ! content=$(ssh:run "$admin"@"${ssh_server}" "${ssh_options[@]}" -- ssh-key ls 2>/dev/null); then
  950. err "Access denied to '$admin@${server}'."
  951. return 1
  952. fi
  953. idents=$(echo "$content" | sed -r "s/"$'\e'"\[[0-9]+(;[0-9]+)*m//g" | cut -f 2 -d " ")
  954. if ! [[ $'\n'"$idents"$'\n' == *$'\n'"$id"$'\n'* ]]; then
  955. err "Given backup id '$id' not found in $admin@${server}'s idents."
  956. return 1
  957. fi
  958. rtype=$(ssh:run "$admin"@"${ssh_server}" "${ssh_options[@]}" -- ssh-key get-type "$id" ) &&
  959. info "Backup archive matches ${WHITE}${rtype}${NORMAL} type"
  960. p0 "$admin" "$server" "$id" "$path" "$rtype" "$opt_force" |
  961. vps_backup_recover "${VPS_PATH}"
  962. }
  963. cmdline.spec.gnu vps-update
  964. cmdline.spec::cmd:vps-update:run() {
  965. : :posarg: [VPS...] 'Target host to check'
  966. echo "" |
  967. vps_mux vps_update "${VPS[@]}"
  968. }
  969. cmdline.spec.gnu vps-mux
  970. cmdline.spec::cmd:vps-mux:run() {
  971. : :posarg: [VPS...] 'Target host(s) to check'
  972. cat | vps_mux vps_bash "${VPS[@]}"
  973. }
  974. cmdline.spec.gnu vps-space
  975. cmdline.spec::cmd:vps-space:run() {
  976. : :posarg: [VPS...] 'Target host(s) to check'
  977. echo "df /srv -h | tail -n +2 | sed -r 's/ +/ /g' | cut -f 2-5 -d ' '" |
  978. vps_mux vps_bash "${VPS[@]}"
  979. }
  980. cmdline::parse "$@"