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.

1164 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. already_present=
  634. if e "$out" | grep "^II Entry for service .* is already present" >/dev/null 2>&1; then
  635. already_present=1
  636. info "Backup entry is already present in 'compose.yml' of '$vps'"
  637. fi
  638. out="${out%$'\n'}"
  639. out="${out#*$'\n'}"
  640. key="${out%\'*}"
  641. key="${key##*\'}"
  642. if ! [[ "$key" =~ ^"ssh-rsa "[a-zA-Z0-9/+]+" "[a-zA-Z0-9._-]+"@"[a-zA-Z0-9._-]+$ ]]; then
  643. err "Unexpected output from 'vps install backup $server'. Can't find key."
  644. echo "$out" | prefix " ${GRAY}|$NORMAL " >&2
  645. echo " Extracted key:" >&2
  646. echo "$key" | prefix " ${GRAY}|$NORMAL " >&2
  647. return 1
  648. fi
  649. if [ "$type" == "compose" ] && [ -z "$already_present" ]; then
  650. ssh:run "root@$vps" -- compose --debug up || {
  651. err "Command 'compose --debug up' failed."
  652. return 1
  653. }
  654. fi
  655. dest="$server"
  656. dest="${dest%/*}"
  657. ssh_options=()
  658. if [[ "$dest" == *":"* ]]; then
  659. port="${dest##*:}"
  660. dest="${dest%%:*}"
  661. ssh_options=(-p "$port")
  662. else
  663. port=""
  664. dest="${dest%%:*}"
  665. fi
  666. cmd=(ssh "${ssh_options[@]}" "$admin"@"$dest" ssh-key add "$key")
  667. echo "${WHITE}Launching:${NORMAL} ${cmd[@]}"
  668. "${cmd[@]}" || {
  669. err "Failed add key to backup server '$dest'."
  670. return 1
  671. }
  672. echo "${WHITE}Launching backup${NORMAL} from '$vps'"
  673. ssh:run "root@$vps" -- vps backup || {
  674. err "First backup failed to run."
  675. return 1
  676. }
  677. echo "Backup is ${GREEN}up and running${NORMAL}."
  678. }
  679. vps_udpate() {
  680. local vps="$1"
  681. vps_connection_check "$vps" || return 1
  682. ssh:run "root@$vps" -- myc-update </dev/null
  683. }
  684. vps_bash() {
  685. local vps="$1"
  686. vps_connection_check "$vps" </dev/null || return 1
  687. ssh:run "root@$vps" -- bash
  688. }
  689. vps_mux() {
  690. local fn="$1" vps_done VPS max_size vps
  691. shift
  692. VPS=($(printf "%s\n" "$@" | sort))
  693. max_size=0
  694. declare -A vps_done;
  695. new_vps=()
  696. for name in "${VPS[@]}"; do
  697. [ -n "${vps_done[$name]}" ] && {
  698. warn "duplicate vps '$name' provided. Ignoring."
  699. continue
  700. }
  701. vps_done["$name"]=1
  702. new_vps+=("$name")
  703. size_name="${#name}"
  704. [ "$max_size" -lt "${size_name}" ] &&
  705. max_size="$size_name"
  706. done
  707. settmpdir "_0KM_TMP_DIR"
  708. cat > "$_0KM_TMP_DIR/code"
  709. for vps in "${new_vps[@]}"; do
  710. label=$(printf "%-${max_size}s" "$vps")
  711. (
  712. {
  713. {
  714. "$fn" "$vps" < "$_0KM_TMP_DIR/code"
  715. } 3>&1 1>&2 2>&3 | sed -r "s/^/$DARKCYAN$label$NORMAL $DARKRED\!$NORMAL /g"
  716. set_errlvl "${PIPESTATUS[0]}"
  717. } 3>&1 1>&2 2>&3 | sed -r "s/^/$DARKCYAN$label$NORMAL $DARKGRAY\|$NORMAL /g"
  718. set_errlvl "${PIPESTATUS[0]}"
  719. ) &
  720. done
  721. wait
  722. }
  723. [ "$SOURCED" ] && return 0
  724. ##
  725. ## Command line processing
  726. ##
  727. cmdline.spec.gnu
  728. cmdline.spec.reporting
  729. cmdline.spec.gnu vps-setup
  730. cmdline.spec::cmd:vps-setup:run() {
  731. : :posarg: HOST 'Target host to check/fix ssh-access'
  732. depends sshpass shyaml
  733. KEY_PATH="ssh-access.public-keys"
  734. local keys=$(config get-value -y "ssh-access.public-keys") || true
  735. if [ -z "$keys" ]; then
  736. err "No ssh publickeys configured in config file."
  737. echo " Looking for keys in ${WHITE}${KEY_PATH}${NORMAL}" \
  738. "in config file." >&2
  739. config:exists --message 2>&1 | prefix " "
  740. if [ "${PIPESTATUS[0]}" == "0" ]; then
  741. echo " Config file found in $(config:filename)"
  742. fi
  743. return 1
  744. fi
  745. local tkey=$(e "$keys" | shyaml get-type)
  746. if [ "$tkey" != "sequence" ]; then
  747. err "Value type of ${WHITE}${KEY_PATH}${NORMAL} unexpected (is $tkey, expecting sequence)."
  748. echo " Check content of $(config:filename), and make sure to use a sequence." >&2
  749. return 1
  750. fi
  751. local IP NAME keys host_pass_connected
  752. if ! IP=$(resolve "$HOST"); then
  753. err "'$HOST' name unresolvable."
  754. exit 1
  755. fi
  756. NAME="$HOST"
  757. if [ "$IP" != "$HOST" ]; then
  758. NAME="$HOST ($IP)"
  759. fi
  760. if ! is-port-open "$IP" "22"; then
  761. err "$NAME unreachable or port 22 closed."
  762. exit 1
  763. fi
  764. debug "Host $IP's port 22 is open."
  765. if ! host_pass_connected=$(ssh:open-try \
  766. {root,debian}@"$HOST"); then
  767. err "Could not connect to {root,debian}@$HOST with publickey nor password."
  768. exit 1
  769. fi
  770. read-0a host password <<<"$host_pass_connected"
  771. sudo_if_necessary=
  772. if [ "$password" -o "${host%%@*}" != "root" ]; then
  773. if ! ssh:run "$host" -- sudo -n true >/dev/null 2>&1; then
  774. err "Couldn't do a password-less sudo from $host."
  775. echo " This is not yet supported."
  776. exit 1
  777. else
  778. sudo_if_necessary=sudo
  779. fi
  780. fi
  781. Section Checking access
  782. while read-0 key; do
  783. prefix="${key%% *}"
  784. if [ "$prefix" != "ssh-rsa" ]; then
  785. err "Unsupported key:"$'\n'"$key"
  786. return 1
  787. fi
  788. label="${key##* }"
  789. Elt "considering adding key ${DARKYELLOW}$label${NORMAL}"
  790. dest="/root/.ssh/authorized_keys"
  791. if ssh:run "$host" -- $sudo_if_necessary grep "\"$key\"" "$dest" >/dev/null 2>&1 </dev/null; then
  792. print_info "already present"
  793. print_status noop
  794. Feed
  795. else
  796. if echo "$key" | ssh:run "$host" -- $sudo_if_necessary tee -a "$dest" >/dev/null; then
  797. print_info added
  798. else
  799. echo
  800. Feedback failure
  801. return 1
  802. fi
  803. Feedback success
  804. fi
  805. done < <(e "$keys" | shyaml get-values-0)
  806. Section Checking ovh hostname file
  807. Elt "Checking /etc/ovh-hostname"
  808. if ! ssh:run "$host" -- $sudo_if_necessary [ -e "/etc/ovh-hostname" ]; then
  809. print_info "creating"
  810. ssh:run "$host" -- $sudo_if_necessary cp /etc/hostname /etc/ovh-hostname
  811. ovhname=$(ssh:run "$host" -- $sudo_if_necessary cat /etc/ovh-hostname)
  812. Elt "Checking /etc/ovh-hostname: $ovhname"
  813. Feedback || return 1
  814. else
  815. ovhname=$(ssh:run "$host" -- $sudo_if_necessary cat /etc/ovh-hostname)
  816. Elt "Checking /etc/ovh-hostname: $ovhname"
  817. print_info "already present"
  818. print_status noop
  819. Feed
  820. fi
  821. if ! is_ovh_domain_name "$HOST" && ! str_is_ipv4 "$HOST"; then
  822. Section Checking hostname
  823. Elt "Checking /etc/hostname..."
  824. if [ "$old" != "$HOST" ]; then
  825. old="$(ssh:run "$host" -- $sudo_if_necessary cat /etc/hostname)"
  826. Elt "Hostname is '$old'"
  827. if is_ovh_hostname "$old"; then
  828. Elt "Hostname '$old' --> '$HOST'"
  829. print_info "creating"
  830. echo "$HOST" | ssh:run "$host" -- $sudo_if_necessary tee /etc/hostname >/dev/null &&
  831. ssh:run "$host" -- $sudo_if_necessary hostname "$HOST"
  832. Feedback || return 1
  833. else
  834. print_info "not changing"
  835. print_status noop
  836. Feed
  837. fi
  838. else
  839. print_info "already set"
  840. print_status noop
  841. Feed
  842. fi
  843. else
  844. info "Not changing domain as '$HOST' doesn't seem to be final domain."
  845. fi
  846. }
  847. cmdline.spec.gnu vps-check
  848. cmdline.spec::cmd:vps-check:run() {
  849. : :posarg: [VPS...] 'Target host(s) to check'
  850. echo "" |
  851. vps_mux vps_check "${VPS[@]}"
  852. }
  853. cmdline.spec.gnu vps-install
  854. cmdline.spec::cmd:vps-install:run() {
  855. :
  856. }
  857. cmdline.spec.gnu backup
  858. cmdline.spec:vps-install:cmd:backup:run() {
  859. : :posarg: BACKUP_TARGET 'Backup target.
  860. (ie: myadmin@backup.domain.org:10023/256)'
  861. : :posarg: [VPS...] 'Target host(s) to check'
  862. if [ "${#VPS[@]}" == 0 ]; then
  863. warn "VPS list provided in command line is empty. Nothing will be done."
  864. return 0
  865. fi
  866. if ! [[ "$BACKUP_TARGET" == *"@"* ]]; then
  867. err "Missing admin account identifier in backup target."
  868. echo " Have you forgottent to specify an account, ie 'myadmin@<MYBACKUP_SERVER>' ?)"
  869. return 1
  870. fi
  871. admin=${BACKUP_TARGET%%@*}
  872. server=${BACKUP_TARGET#*@}
  873. p0 "$admin" "$server" |
  874. vps_mux vps_install_backup "${VPS[@]}"
  875. }
  876. cmdline.spec.gnu vps-backup
  877. cmdline.spec::cmd:vps-backup:run() {
  878. :
  879. }
  880. cmdline.spec.gnu ls
  881. cmdline.spec:vps-backup:cmd:ls:run() {
  882. : :posarg: BACKUP_ID 'Backup id.
  883. (ie: myadmin@backup.domain.org:10023)'
  884. if ! [[ "$BACKUP_ID" == *"@"* ]]; then
  885. err "Missing admin account identifier in backup id."
  886. echo " Have you forgottent to specify an admin account ?" \
  887. "ie 'myadmin@<MYBACKUP_SERVER>#<BACKUP_IDENT>' ?)"
  888. return 1
  889. fi
  890. id=${BACKUP_ID##*#}
  891. BACKUP_TARGET=${BACKUP_ID%#*}
  892. admin=${BACKUP_TARGET%%@*}
  893. server=${BACKUP_TARGET#*@}
  894. ## XXXvlab: in this first implementation we expect to have access
  895. ## to the server main ssh port 22, so we won't use the provided port.
  896. ssh_options=()
  897. if [[ "$server" == *":"* ]]; then
  898. ssh_options+=(-p "${server#*:}")
  899. server=${server%%:*}
  900. fi
  901. ssh "${ssh_options[@]}" "$admin"@"$server" ssh-key ls
  902. }
  903. cmdline.spec.gnu recover
  904. cmdline.spec:vps-backup:cmd:recover:run() {
  905. : :posarg: BACKUP_ID 'Backup id.
  906. (ie: myadmin@backup.domain.org:10023#mx.myvps.org
  907. myadmin@ark-01.org#myid:/a/path
  908. admin@ark-02.io#myid:myqsl,mailcow)'
  909. : :posarg: VPS_PATH 'Target host(s) to check.
  910. (ie: myvps.com
  911. myvps.com:/a/path)'
  912. : :optval: --date,-D '"last", or label of version to recover. (Default: "last").'
  913. : :optfla: --force,-f 'Will allow you to bypass some checks.'
  914. if ! [[ "$BACKUP_ID" == *"@"* ]]; then
  915. err "Missing admin account identifier in backup id."
  916. echo " Have you forgottent to specify an admin account ?" \
  917. "ie 'myadmin@<MYBACKUP_SERVER>#<BACKUP_IDENT>' ?)"
  918. return 1
  919. fi
  920. if ! [[ "$BACKUP_ID" == *"@"*"#"* ]]; then
  921. err "Missing backup label identifier in backup id."
  922. echo " Have you forgottent to specify a backup label identifier ?" \
  923. "ie 'myadmin@<MYBACKUP_SERVER>#<BACKUP_IDENT>' ?)"
  924. return 1
  925. fi
  926. id_path=${BACKUP_ID#*#}
  927. if [[ "$id_path" == *":"* ]]; then
  928. id=${id_path%%:*}
  929. path=${id_path#*:}
  930. else
  931. id="$id_path"
  932. path=
  933. fi
  934. BACKUP_TARGET=${BACKUP_ID%#*}
  935. admin=${BACKUP_TARGET%%@*}
  936. server=${BACKUP_TARGET#*@}
  937. ssh_options=()
  938. if [[ "$server" == *":"* ]]; then
  939. ssh_options+=(-p "${server#*:}")
  940. ssh_server=${server%%:*}
  941. fi
  942. BACKUP_PATH="/srv/datastore/data/rsync-backup-target/var/mirror"
  943. if ! content=$(ssh:run "$admin"@"${ssh_server}" "${ssh_options[@]}" -- ssh-key ls 2>/dev/null); then
  944. err "Access denied to '$admin@${server}'."
  945. return 1
  946. fi
  947. idents=$(echo "$content" | sed -r "s/"$'\e'"\[[0-9]+(;[0-9]+)*m//g" | cut -f 2 -d " ")
  948. if ! [[ $'\n'"$idents"$'\n' == *$'\n'"$id"$'\n'* ]]; then
  949. err "Given backup id '$id' not found in $admin@${server}'s idents."
  950. return 1
  951. fi
  952. rtype=$(ssh:run "$admin"@"${ssh_server}" "${ssh_options[@]}" -- ssh-key get-type "$id" ) &&
  953. info "Backup archive matches ${WHITE}${rtype}${NORMAL} type"
  954. p0 "$admin" "$server" "$id" "$path" "$rtype" "$opt_force" |
  955. vps_backup_recover "${VPS_PATH}"
  956. }
  957. cmdline.spec.gnu vps-update
  958. cmdline.spec::cmd:vps-update:run() {
  959. : :posarg: [VPS...] 'Target host to check'
  960. echo "" |
  961. vps_mux vps_update "${VPS[@]}"
  962. }
  963. cmdline.spec.gnu vps-mux
  964. cmdline.spec::cmd:vps-mux:run() {
  965. : :posarg: [VPS...] 'Target host(s) to check'
  966. cat | vps_mux vps_bash "${VPS[@]}"
  967. }
  968. cmdline.spec.gnu vps-space
  969. cmdline.spec::cmd:vps-space:run() {
  970. : :posarg: [VPS...] 'Target host(s) to check'
  971. echo "df /srv -h | tail -n +2 | sed -r 's/ +/ /g' | cut -f 2-5 -d ' '" |
  972. vps_mux vps_bash "${VPS[@]}"
  973. }
  974. cmdline::parse "$@"