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.

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