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.

1351 lines
40 KiB

  1. #!/bin/bash
  2. . /etc/shlib
  3. include common
  4. include parse
  5. include cmdline
  6. include config
  7. include cache
  8. include fn
  9. include docker
  10. [[ "${BASH_SOURCE[0]}" != "${0}" ]] && SOURCED=true
  11. version=0.1
  12. desc='Install backup'
  13. help=""
  14. docker:running-container-projects() {
  15. :cache: scope=session
  16. docker ps --format '{{.Label "com.docker.compose.project"}}' | sort | uniq
  17. }
  18. decorator._mangle_fn docker:running-container-projects
  19. ssh:mk-private-key() {
  20. local host="$1" service_name="$2"
  21. (
  22. settmpdir VPS_TMPDIR
  23. ssh-keygen -t rsa -N "" -f "$VPS_TMPDIR/rsync_rsa" -C "$service_name@$host" >/dev/null
  24. cat "$VPS_TMPDIR/rsync_rsa"
  25. )
  26. }
  27. mailcow:has-images-running() {
  28. local images
  29. images=$(docker ps --format '{{.Image}}' | sort | uniq)
  30. [[ $'\n'"$images" == *$'\n'"mailcow/"* ]]
  31. }
  32. mailcow:has-container-project-mentionning-mailcow() {
  33. local projects
  34. projects=$(docker:running-container-projects) || return 1
  35. [[ $'\n'"$projects"$'\n' == *mailcow* ]]
  36. }
  37. mailcow:has-running-containers() {
  38. mailcow:has-images-running ||
  39. mailcow:has-container-project-mentionning-mailcow
  40. }
  41. mailcow:get-root() {
  42. :cache: scope=session
  43. local dir
  44. for dir in {/opt{,/apps},/root}/mailcow-dockerized; do
  45. [ -d "$dir" ] || continue
  46. [ -r "$dir/mailcow.conf" ] || continue
  47. echo "$dir"
  48. return 0
  49. done
  50. return 1
  51. }
  52. decorator._mangle_fn mailcow:get-root
  53. compose:get-compose-yml() {
  54. :cache: scope=session
  55. local path
  56. [ -e "/etc/compose/local.conf" ] && . "/etc/compose/local.conf"
  57. path=${DEFAULT_COMPOSE_FILE:-/etc/compose/compose.yml}
  58. [ -e "$path" ] || return 1
  59. echo "$path"
  60. }
  61. decorator._mangle_fn compose:get-compose-yml
  62. compose:has-container-project-myc() {
  63. local projects
  64. projects=$(docker:running-container-projects) || return 1
  65. [[ $'\n'"$projects"$'\n' == *$'\n'"myc"$'\n'* ]]
  66. }
  67. type:is-mailcow() {
  68. mailcow:get-root >/dev/null ||
  69. mailcow:has-running-containers
  70. }
  71. type:is-compose() {
  72. compose:get-compose-yml >/dev/null &&
  73. compose:has-container-project-myc
  74. }
  75. vps:get-type() {
  76. :cache: scope=session
  77. local fn
  78. for fn in $(declare -F | cut -f 3 -d " " | egrep "^type:is-"); do
  79. "$fn" && {
  80. echo "${fn#type:is-}"
  81. return 0
  82. }
  83. done
  84. return 1
  85. }
  86. decorator._mangle_fn vps:get-type
  87. mirror-dir:sources() {
  88. :cache: scope=session
  89. if ! shyaml get-values default.sources < /etc/mirror-dir/config.yml; then
  90. err "Couldn't query 'default.sources' in '/etc/mirror-dir/config.yml'."
  91. return 1
  92. fi
  93. }
  94. decorator._mangle_fn mirror-dir:sources
  95. mirror-dir:check-add() {
  96. local elt="$1" sources
  97. sources=$(mirror-dir:sources) || return 1
  98. if [[ $'\n'"$sources"$'\n' == *$'\n'"$elt"$'\n'* ]]; then
  99. info "Volume $elt already in sources"
  100. else
  101. Elt "Adding directory $elt"
  102. sed -i "/sources:/a\ - \"${elt}\"" \
  103. /etc/mirror-dir/config.yml
  104. Feedback || return 1
  105. fi
  106. }
  107. mirror-dir:check-add-vol() {
  108. local elt="$1"
  109. mirror-dir:check-add "/var/lib/docker/volumes/*_${elt}-*/_data"
  110. }
  111. ## The first colon is to prevent auto-export of function from shlib
  112. : ; bash-bug-5() { { cat; } < <(e) >/dev/null; ! cat "$1"; } && bash-bug-5 <(e) 2>/dev/null &&
  113. export BASH_BUG_5=1 && unset -f bash_bug_5
  114. wrap() {
  115. local label="$1" code="$2"
  116. shift 2
  117. export VERBOSE=1
  118. interpreter=/bin/bash
  119. if [ -n "$BASH_BUG_5" ]; then
  120. (
  121. settmpdir tmpdir
  122. fname=${label##*/}
  123. e "$code" > "$tmpdir/$fname" &&
  124. chmod +x "$tmpdir/$fname" &&
  125. Wrap -vsd "$label" -- "$interpreter" "$tmpdir/$fname" "$@"
  126. )
  127. else
  128. Wrap -vsd "$label" -- "$interpreter" <(e "$code") "$@"
  129. fi
  130. }
  131. ping_check() {
  132. #global ignore_ping_check
  133. local host="$1"
  134. ip=$(getent ahosts "$host" | egrep "^[0-9]+\.[0-9]+\.[0-9]+\.[0-9]+\s+" |
  135. head -n 1 | cut -f 1 -d " ") || return 1
  136. my_ip=$(curl -s myip.kal.fr)
  137. if [ "$ip" != "$my_ip" ]; then
  138. if [ -n "$ignore_ping_check" ]; then
  139. warn "IP of '$host' ($ip) doesn't match mine ($my_ip). Ignoring due to ``--ignore-ping-check`` option."
  140. else
  141. err "IP of '$host' ($ip) doesn't match mine ($my_ip). Use ``--ignore-ping-check`` to ignore check."
  142. return 1
  143. fi
  144. fi
  145. }
  146. mailcow:install-backup() {
  147. local BACKUP_SERVER="$1" ignore_ping_check="$2" mailcow_root DOMAIN
  148. ## find installation
  149. mailcow_root=$(mailcow:get-root) || {
  150. err "Couldn't find a valid mailcow root directory."
  151. return 1
  152. }
  153. ## check ok
  154. DOMAIN=$(cat "$mailcow_root/.env" | grep ^MAILCOW_HOSTNAME= | cut -f 2 -d =) || {
  155. err "Couldn't find MAILCOW_HOSTNAME in file \"$mailcow_root/.env\"."
  156. return 1
  157. }
  158. ping_check "$DOMAIN" || return 1
  159. MYSQL_ROOT_PASSWORD=$(cat "$mailcow_root/.env" | grep ^DBROOT= | cut -f 2 -d =) || {
  160. err "Couldn't find DBROOT in file \"$mailcow_root/.env\"."
  161. return 1
  162. }
  163. MYSQL_CONTAINER=${MYSQL_CONTAINER:-mailcowdockerized_mysql-mailcow_1}
  164. container_id=$(docker ps -f name="$MYSQL_CONTAINER" --format "{{.ID}}")
  165. if [ -z "$container_id" ]; then
  166. err "Couldn't find docker container named '$MYSQL_CONTAINER'."
  167. return 1
  168. fi
  169. export KEY_BACKUP_ID="mailcow"
  170. export MYSQL_ROOT_PASSWORD
  171. export MYSQL_CONTAINER
  172. export BACKUP_SERVER
  173. export DOMAIN
  174. wrap "Install rsync-backup on host" "
  175. cd /srv/charm-store/rsync-backup
  176. bash ./hooks/install.d/60-install.sh
  177. " || return 1
  178. wrap "Mysql dump install" "
  179. cd /srv/charm-store/mariadb
  180. bash ./hooks/install.d/60-backup.sh
  181. " || return 1
  182. ## Using https://github.com/mailcow/mailcow-dockerized/blob/master/helper-scripts/backup_and_restore.sh
  183. for elt in "vmail{,-attachments-vol}" crypt redis rspamd postfix; do
  184. mirror-dir:check-add-vol "$elt" || return 1
  185. done
  186. mirror-dir:check-add "$mailcow_root" || return 1
  187. mirror-dir:check-add "/var/backups/mysql" || return 1
  188. mirror-dir:check-add "/etc" || return 1
  189. dest="$BACKUP_SERVER"
  190. dest="${dest%/*}"
  191. ssh_options=()
  192. if [[ "$dest" == *":"* ]]; then
  193. port="${dest##*:}"
  194. dest="${dest%%:*}"
  195. ssh_options=(-p "$port")
  196. else
  197. port=""
  198. dest="${dest%%:*}"
  199. fi
  200. info "You can run this following command from an host having admin access to $dest:"
  201. echo " (Or send it to a backup admin of $dest)" >&2
  202. echo "ssh ${ssh_options[@]} myadmin@$dest ssh-key add '$(cat /var/lib/rsync/.ssh/id_rsa.pub)'"
  203. }
  204. compose:has_domain() {
  205. local compose_file="$1" host="$2" name conf relation relation_value domain server_aliases
  206. while read-0 name conf ; do
  207. name=$(e "$name" | shyaml get-value)
  208. if [[ "$name" =~ ^[a-zA-Z0-9-]+\.[a-zA-Z0-9-]+ ]]; then
  209. [ "$host" == "$name" ] && return 0
  210. fi
  211. rel=$(e "$conf" | shyaml -y get-value relations 2>/dev/null) || continue
  212. for relation in web-proxy publish-dir; do
  213. relation_value=$(e "$rel" | shyaml -y get-value "$relation" 2>/dev/null) || continue
  214. while read-0 label conf_relation; do
  215. domain=$(e "$conf_relation" | shyaml get-value "domain" 2>/dev/null) && {
  216. [ "$host" == "$domain" ] && return 0
  217. }
  218. server_aliases=$(e "$conf_relation" | shyaml get-values "server-aliases" 2>/dev/null) && {
  219. [[ $'\n'"$server_aliases" == *$'\n'"$host"$'\n'* ]] && return 0
  220. }
  221. done < <(e "$relation_value" | shyaml -y key-values-0)
  222. done
  223. done < <(shyaml -y key-values-0 < "$compose_file")
  224. return 1
  225. }
  226. compose:install-backup() {
  227. local BACKUP_SERVER="$1" service_name="$2" compose_file="$3" ignore_ping_check="$4" ignore_domain_check="$5"
  228. ## XXXvlab: far from perfect as it mimics and depends internal
  229. ## logic of current default way to get a domain in compose-core
  230. host=$(hostname)
  231. if ! compose:has_domain "$compose_file" "$host"; then
  232. if [ -n "$ignore_domain_check" ]; then
  233. warn "domain of '$host' not found in compose file '$compose_file'. Ignoring due to ``--ignore-domain-check`` option."
  234. else
  235. err "domain of '$host' not found in compose file '$compose_file'. Use ``--ignore-domain-check`` to ignore check."
  236. return 1
  237. fi
  238. fi
  239. ping_check "$host" || return 1
  240. if [ -e "/root/.ssh/rsync_rsa" ]; then
  241. warn "deleting private key in /root/.ssh/rsync_rsa, has we are not using it anymore."
  242. rm -fv /root/.ssh/rsync_rsa
  243. fi
  244. if [ -e "/root/.ssh/rsync_rsa.pub" ]; then
  245. warn "deleting public key in /root/.ssh/rsync_rsa.pub, has we are not using it anymore."
  246. rm -fv /root/.ssh/rsync_rsa.pub
  247. fi
  248. if service_cfg=$(cat "$compose_file" |
  249. shyaml get-value -y "$service_name" 2>/dev/null); then
  250. info "Entry for service ${DARKYELLOW}$service_name${NORMAL}" \
  251. "is already present in '$compose_file'."
  252. cfg=$(e "$service_cfg" | shyaml get-value -y options) || {
  253. err "No ${WHITE}options${NORMAL} in ${DARKYELLOW}$service_name${NORMAL}'s" \
  254. "entry in '$compose_file'."
  255. return 1
  256. }
  257. private_key=$(e "$cfg" | shyaml get-value private-key) || return 1
  258. target=$(e "$cfg" | shyaml get-value target) || return 1
  259. if [ "$target" != "$BACKUP_SERVER" ]; then
  260. err "Existing backup target '$target' is different" \
  261. "from specified '$BACKUP_SERVER'"
  262. return 1
  263. fi
  264. else
  265. private_key=$(ssh:mk-private-key "$host" "$service_name")
  266. cat <<EOF >> "$compose_file"
  267. $service_name:
  268. options:
  269. ident: $host
  270. target: $BACKUP_SERVER
  271. private-key: |
  272. $(e "$private_key" | sed -r 's/^/ /g')
  273. EOF
  274. fi
  275. dest="$BACKUP_SERVER"
  276. dest="${dest%/*}"
  277. ssh_options=()
  278. if [[ "$dest" == *":"* ]]; then
  279. port="${dest##*:}"
  280. dest="${dest%%:*}"
  281. ssh_options=(-p "$port")
  282. else
  283. port=""
  284. dest="${dest%%:*}"
  285. fi
  286. info "You can run this following command from an host having admin access to $dest:"
  287. echo " (Or send it to a backup admin of $dest)" >&2
  288. public_key=$(ssh-keygen -y -f <(e "$private_key"$'\n'))
  289. echo "ssh ${ssh_options[@]} myadmin@$dest ssh-key add '$public_key compose@$host'"
  290. }
  291. backup-action() {
  292. local action="$1"
  293. shift
  294. vps_type=$(vps:get-type) || {
  295. err "Failed to get type of installation."
  296. return 1
  297. }
  298. if ! fn.exists "${vps_type}:${action}"; then
  299. err "type '${vps_type}' has no ${vps_type}:${action} implemented yet."
  300. return 1
  301. fi
  302. "${vps_type}:${action}" "$@"
  303. }
  304. compose:get_default_backup_host_ident() {
  305. local service_name="$1" ## Optional
  306. local compose_file service_cfg cfg target
  307. compose_file=$(compose:get-compose-yml)
  308. service_name="${service_name:-rsync-backup}"
  309. if ! service_cfg=$(cat "$compose_file" |
  310. shyaml get-value -y "$service_name" 2>/dev/null); then
  311. err "No service named '$service_name' found in 'compose.yml'."
  312. return 1
  313. fi
  314. cfg=$(e "$service_cfg" | shyaml get-value -y options) || {
  315. err "No ${WHITE}options${NORMAL} in ${DARKYELLOW}$service_name${NORMAL}'s" \
  316. "entry in '$compose_file'."
  317. return 1
  318. }
  319. if ! target=$(e "$cfg" | shyaml get-value target); then
  320. err "No ${WHITE}options.target${NORMAL} in ${DARKYELLOW}$service_name${NORMAL}'s" \
  321. "entry in '$compose_file'."
  322. fi
  323. if ! target=$(e "$cfg" | shyaml get-value target); then
  324. err "No ${WHITE}options.target${NORMAL} in ${DARKYELLOW}$service_name${NORMAL}'s" \
  325. "entry in '$compose_file'."
  326. fi
  327. if ! ident=$(e "$cfg" | shyaml get-value ident); then
  328. err "No ${WHITE}options.ident${NORMAL} in ${DARKYELLOW}$service_name${NORMAL}'s" \
  329. "entry in '$compose_file'."
  330. fi
  331. echo "$target $ident"
  332. }
  333. mailcow:get_default_backup_host_ident() {
  334. local content cron_line ident found dest cmd_line
  335. if ! [ -e "/etc/cron.d/mirror-dir" ]; then
  336. err "No '/etc/cron.d/mirror-dir' found."
  337. return 1
  338. fi
  339. content=$(cat /etc/cron.d/mirror-dir) || {
  340. err "Can't read '/etc/cron.d/mirror-dir'."
  341. return 1
  342. }
  343. if ! cron_line=$(e "$content" | grep "mirror-dir backup"); then
  344. err "Can't find 'mirror-dir backup' line in '/etc/cron.d/mirror-dir'."
  345. return 1
  346. fi
  347. cron_line=${cron_line%|*}
  348. cmd_line=(${cron_line#*root})
  349. found=
  350. dest=
  351. for arg in "${cmd_line[@]}"; do
  352. [ -n "$found" ] && {
  353. dest="$arg"
  354. break
  355. }
  356. [ "$arg" == "-d" ] && {
  357. found=1
  358. }
  359. done
  360. if ! [[ "$dest" =~ ^[\'\"a-zA-Z0-9:/.-]+$ ]]; then
  361. err "Can't find valid destination in 'mirror-dir backup' arguments from '/etc/cron.d/mirror-dir'."
  362. return 1
  363. fi
  364. if [[ "$dest" == \"*\" ]] || [[ "$dest" == \'*\' ]]; then
  365. ## unquoting, the eval should be safe because of previous check
  366. dest=$(eval e "$dest")
  367. fi
  368. if [ -z "$dest" ]; then
  369. err "Can't find destination in 'mirror-dir backup' arguments from '/etc/cron.d/mirror-dir'."
  370. return 1
  371. fi
  372. ## looking for ident
  373. found=
  374. ident=
  375. for arg in "${cmd_line[@]}"; do
  376. [ -n "$found" ] && {
  377. ident="$arg"
  378. break
  379. }
  380. [ "$arg" == "-h" ] && {
  381. found=1
  382. }
  383. done
  384. if ! [[ "$ident" =~ ^[\'\"a-zA-Z0-9.-]+$ ]]; then
  385. err "Can't find valid identifier in 'mirror-dir backup' arguments from '/etc/cron.d/mirror-dir'."
  386. return 1
  387. fi
  388. if [[ "$ident" == \"*\" ]] || [[ "$ident" == \'*\' ]]; then
  389. ## unquoting, the eval should be safe because of previous check
  390. ident=$(eval e "$ident")
  391. fi
  392. if [ -z "$ident" ]; then
  393. err "Can't find destination in 'mirror-dir backup' arguments from '/etc/cron.d/mirror-dir'."
  394. return 1
  395. fi
  396. echo "$dest $ident"
  397. }
  398. compose:service:containers() {
  399. local project="$1" service="$2"
  400. docker ps \
  401. --filter label="com.docker.compose.project=$project" \
  402. --filter label="compose.master-service=$service" \
  403. --format="{{.ID}}"
  404. }
  405. export -f compose:service:containers
  406. compose:service:container_one() {
  407. local project="$1" service="$2" container_id
  408. {
  409. read-0a container_id || {
  410. err "service ${DARKYELLOW}$service${NORMAL} has no running container."
  411. return 1
  412. }
  413. if read-0a _; then
  414. err "service ${DARKYELLOW}$service${NORMAL} has more than one running container."
  415. return 1
  416. fi
  417. } < <(compose:service:containers "$project" "$service")
  418. echo "$container_id"
  419. }
  420. export -f compose:service:container_one
  421. compose:service:container_first() {
  422. local project="$1" service="$2" container_id
  423. {
  424. read-0a container_id || {
  425. err "service ${DARKYELLOW}$service${NORMAL} has no running container."
  426. return 1
  427. }
  428. if read-0a _; then
  429. warn "service ${DARKYELLOW}$service${NORMAL} has more than one running container."
  430. fi
  431. } < <(compose:service:containers "$project" "$service")
  432. echo "$container_id"
  433. }
  434. export -f compose:service:container_first
  435. compose:charm:containers() {
  436. local project="$1" charm="$2"
  437. docker ps \
  438. --filter label="com.docker.compose.project=$project" \
  439. --filter label="compose.charm=$charm" \
  440. --format="{{.ID}}"
  441. }
  442. export -f compose:charm:containers
  443. compose:charm:container_one() {
  444. local project="$1" charm="$2" container_id
  445. {
  446. read-0a container_id || {
  447. err "charm ${DARKPINK}$charm${NORMAL} has no running container in project '$project'."
  448. return 1
  449. }
  450. if read-0a _; then
  451. err "charm ${DARKPINK}$charm${NORMAL} has more than one running container."
  452. return 1
  453. fi
  454. } < <(compose:charm:containers "$project" "$charm")
  455. echo "$container_id"
  456. }
  457. export -f compose:charm:container_one
  458. compose:charm:container_first() {
  459. local project="$1" charm="$2" container_id
  460. {
  461. read-0a container_id || {
  462. warn "charm ${DARKYELLOW}$charm${NORMAL} has no running container in project '$project'."
  463. }
  464. if read-0a _; then
  465. warn "charm ${DARKYELLOW}$charm${NORMAL} has more than one running container."
  466. fi
  467. } < <(compose:charm:containers "$project" "$charm")
  468. echo "$container_id"
  469. }
  470. export -f compose:charm:container_first
  471. compose:get_url() {
  472. local project_name="$1" service="$2" data_file network ip
  473. data_file="/var/lib/compose/relations/${project_name}/${service}-frontend/web-proxy/data"
  474. if [ -e "$data_file" ]; then
  475. (
  476. set -o pipefail
  477. cat "$data_file" | shyaml get-value url
  478. )
  479. else
  480. ## Assume there are no frontend relation here, the url is direct IP
  481. container_id=$(compose:service:container_one "${project_name}" "${service}") || return 1
  482. network_ip=$(docker:container:network_ip_one "${container_id}") || return 1
  483. IFS=":" read -r network ip <<<"$network_ip"
  484. echo "http://$ip"
  485. fi || {
  486. err "Failed querying ${service} to frontend relation to get url."
  487. return 1
  488. }
  489. }
  490. export -f compose:get_url
  491. compose:container:service() {
  492. local container="$1" service
  493. if ! service=$(docker:container:label "$container" "compose.service"); then
  494. err "Failed to get service name from container ${container}."
  495. return 1
  496. fi
  497. if [ -z "$service" ]; then
  498. err "No service found for container ${container}."
  499. return 1
  500. fi
  501. echo "$service"
  502. }
  503. export -f compose:container:service
  504. compose:psql() {
  505. local project_name="$1" dbname="$2"
  506. container_id=$(compose:charm:container_one "$project_name" "postgres") || return 1
  507. docker exec -i "${container_id}" psql -U postgres "$dbname"
  508. }
  509. export -f compose:psql
  510. compose:pgm() {
  511. local project_name="$1" container_network_ip container_ip container_network
  512. shift
  513. container_id=$(compose:charm:container_one "$project_name" "postgres") || return 1
  514. service_name=$(compose:container:service "$container_id") || return 1
  515. image_id=$(docker:container:image "$container_id") || return 1
  516. container_network_ip=$(docker:container:network_ip_one "$container_id") || return 1
  517. IFS=":" read -r container_network container_ip <<<"$container_network_ip"
  518. pgpass="/srv/datastore/data/${service_name}/var/lib/postgresql/data/pgpass"
  519. local final_pgm_docker_run_opts+=(
  520. -u 0 -e prefix_pg_local_command=" "
  521. --network "${container_network}"
  522. -e PGHOST="$container_ip"
  523. -e PGUSER=postgres
  524. -v "$pgpass:/root/.pgpass"
  525. "${pgm_docker_run_opts[@]}"
  526. )
  527. cmd=(docker run --rm \
  528. "${final_pgm_docker_run_opts[@]}" \
  529. "${image_id}" pgm "$@"
  530. )
  531. echo "${cmd[@]}"
  532. "${cmd[@]}"
  533. }
  534. export -f compose:pgm
  535. postgres:dump() {
  536. local project_name="$1" src="$2" dst="$3"
  537. (
  538. settmpdir PGM_TMP_LOCATION
  539. pgm_docker_run_opts=('-v' "${PGM_TMP_LOCATION}:/tmp/dump")
  540. compose:pgm "$project_name" cp -f "$src" "/tmp/dump/dump.gz" &&
  541. mv "$PGM_TMP_LOCATION/dump.gz" "$dst"
  542. ) || return 1
  543. }
  544. export -f postgres:dump
  545. postgres:restore() {
  546. local project_name="$1" src="$2" dst="$3"
  547. full_src_path=$(readlink -e "$src") || exit 1
  548. (
  549. pgm_docker_run_opts=('-v' "${full_src_path}:/tmp/dump.gz")
  550. compose:pgm "$project_name" cp -f "/tmp/dump.gz" "$dst"
  551. ) || return 1
  552. }
  553. export -f postgres:restore
  554. cyclos:set_root_url() {
  555. local project_name="$1" dbname="$2" url="$3"
  556. echo "UPDATE configurations SET root_url = '$url';" |
  557. compose:psql "$project_name" "$dbname" || {
  558. err "Failed to set cyclos url value in '$dbname' database."
  559. return 1
  560. }
  561. }
  562. export -f cyclos:set_root_url
  563. compose:project_name() {
  564. if [ -z "$PROJECT_NAME" ]; then
  565. PROJECT_NAME=$(compose --get-project-name) || {
  566. err "Couldn't get project name."
  567. return 1
  568. }
  569. if [ -z "$PROJECT_NAME" -o "$PROJECT_NAME" == "orphan" ]; then
  570. err "Couldn't get project name, probably because 'compose.yml' wasn't found."
  571. echo " Please ensure to either configure a global 'compose.yml' or run this command" >&2
  572. echo " in a compose project (with 'compose.yml' on the top level directory)." >&2
  573. return 1
  574. fi
  575. export PROJECT_NAME
  576. fi
  577. echo "$PROJECT_NAME"
  578. }
  579. export -f compose:project_name
  580. compose:get_cron_docker_cmd() {
  581. local cron_line cmd_line docker_cmd
  582. project_name=$(compose:project_name) || return 1
  583. if ! cron_line=$(docker exec "${project_name}"_cron_1 cat /etc/cron.d/rsync-backup | grep "\* \* \*"); then
  584. err "Can't find cron_line in cron container."
  585. echo " Have you forgotten to run 'compose up' ?" >&2
  586. return 1
  587. fi
  588. cron_line=${cron_line%|*}
  589. cron_line=${cron_line%"2>&1"*}
  590. cmd_line="${cron_line#*root}"
  591. eval "args=($cmd_line)"
  592. ## should be last argument
  593. docker_cmd=$(echo ${args[@]: -1})
  594. if ! [[ "$docker_cmd" == "docker run --rm -e "* ]]; then
  595. echo "docker command found should start with 'docker run'." >&2
  596. echo "Here's command:" >&2
  597. echo " $docker_cmd" >&2
  598. return 1
  599. fi
  600. e "$docker_cmd"
  601. }
  602. compose:recover-target() {
  603. local backup_host="$1" ident="$2" src="$3" dst="$4" service_name="${5:-rsync-backup}" project_name
  604. project_name=$(compose:project_name) || return 1
  605. docker_image="${project_name}_${service_name}"
  606. if ! docker_has_image "$docker_image"; then
  607. compose build "${service_name}" || {
  608. err "Couldn't find nor build image for service '$service_name'."
  609. return 1
  610. }
  611. fi
  612. dst="${dst%/}" ## remove final slash
  613. ssh_options=(-o StrictHostKeyChecking=no)
  614. if [[ "$backup_host" == *":"* ]]; then
  615. port="${backup_host##*:}"
  616. backup_host="${backup_host%%:*}"
  617. ssh_options+=(-p "$port")
  618. else
  619. port=""
  620. backup_host="${backup_host%%:*}"
  621. fi
  622. rsync_opts=(
  623. -e "ssh ${ssh_options[*]} -i /var/lib/rsync/.ssh/id_rsa -l rsync"
  624. -azvArH --delete --delete-excluded
  625. --partial --partial-dir .rsync-partial
  626. --numeric-ids
  627. )
  628. if [ "$DRY_RUN" ]; then
  629. rsync_opts+=("-n")
  630. fi
  631. cmd=(
  632. docker run --rm --entrypoint rsync \
  633. -v "/srv/datastore/config/${service_name}/var/lib/rsync":/var/lib/rsync \
  634. -v "${dst%/*}":/mnt/dest \
  635. "$docker_image" \
  636. "${rsync_opts[@]}" "$backup_host":"/var/mirror/$ident/$src" "/mnt/dest/${dst##*/}"
  637. )
  638. echo "${WHITE}Launching: ${NORMAL} ${cmd[@]}"
  639. "${cmd[@]}"
  640. }
  641. mailcow:recover-target() {
  642. local backup_host="$1" ident="$2" src="$3" dst="$4"
  643. dst="${dst%/}" ## remove final slash
  644. ssh_options=(-o StrictHostKeyChecking=no)
  645. if [[ "$backup_host" == *":"* ]]; then
  646. port="${backup_host##*:}"
  647. backup_host="${backup_host%%:*}"
  648. ssh_options+=(-p "$port")
  649. else
  650. port=""
  651. backup_host="${backup_host%%:*}"
  652. fi
  653. rsync_opts=(
  654. -e "ssh ${ssh_options[*]} -i /var/lib/rsync/.ssh/id_rsa -l rsync"
  655. -azvArH --delete --delete-excluded
  656. --partial --partial-dir .rsync-partial
  657. --numeric-ids
  658. )
  659. if [ "$DRY_RUN" ]; then
  660. rsync_opts+=("-n")
  661. fi
  662. cmd=(
  663. rsync "${rsync_opts[@]}" "$backup_host":"/var/mirror/$ident/$src" "${dst}"
  664. )
  665. echo "${WHITE}Launching: ${NORMAL} ${cmd[@]}"
  666. "${cmd[@]}"
  667. }
  668. [ "$SOURCED" ] && return 0
  669. ##
  670. ## Command line processing
  671. ##
  672. cmdline.spec.gnu
  673. cmdline.spec.reporting
  674. cmdline.spec.gnu install
  675. cmdline.spec::cmd:install:run() {
  676. :
  677. }
  678. cmdline.spec.gnu get-type
  679. cmdline.spec::cmd:get-type:run() {
  680. vps:get-type
  681. }
  682. cmdline.spec:install:cmd:backup:run() {
  683. : :posarg: BACKUP_SERVER 'Target backup server'
  684. : :optfla: --ignore-domain-check \
  685. "Allow to bypass the domain check in
  686. compose file (only used in compose
  687. installation)."
  688. : :optfla: --ignore-ping-check "Allow to bypass the ping check of host."
  689. local vps_type
  690. vps_type=$(vps:get-type) || {
  691. err "Failed to get type of installation."
  692. return 1
  693. }
  694. if ! fn.exists "${vps_type}:install-backup"; then
  695. err "type '${vps_type}' has no backup installation implemented yet."
  696. return 1
  697. fi
  698. opts=()
  699. [ "$opt_ignore_ping_check" ] &&
  700. opts+=("--ignore-ping-check")
  701. if [ "$vps_type" == "compose" ]; then
  702. [ "$opt_ignore_domain_check" ] &&
  703. opts+=("--ignore-domain-check")
  704. fi
  705. "cmdline.spec:install:cmd:${vps_type}-backup:run" "${opts[@]}" "$BACKUP_SERVER"
  706. }
  707. DEFAULT_BACKUP_SERVICE_NAME=rsync-backup
  708. cmdline.spec.gnu compose-backup
  709. cmdline.spec:install:cmd:compose-backup:run() {
  710. : :posarg: BACKUP_SERVER 'Target backup server'
  711. : :optval: --service-name,-s "YAML service name in compose
  712. file to check for existence of key.
  713. Defaults to '$DEFAULT_BACKUP_SERVICE_NAME'"
  714. : :optval: --compose-file,-f "Compose file location. Defaults to
  715. the value of '\$DEFAULT_COMPOSE_FILE'"
  716. : :optfla: --ignore-domain-check \
  717. "Allow to bypass the domain check in
  718. compose file."
  719. : :optfla: --ignore-ping-check "Allow to bypass the ping check of host."
  720. local service_name compose_file
  721. [ -e "/etc/compose/local.conf" ] && source /etc/compose/local.conf
  722. compose_file=${opt_compose_file:-$DEFAULT_COMPOSE_FILE}
  723. service_name=${opt_service_name:-$DEFAULT_BACKUP_SERVICE_NAME}
  724. if ! [ -e "$compose_file" ]; then
  725. err "Compose file not found in '$compose_file'."
  726. return 1
  727. fi
  728. compose:install-backup "$BACKUP_SERVER" "$service_name" "$compose_file" \
  729. "$opt_ignore_ping_check" "$opt_ignore_domain_check"
  730. }
  731. cmdline.spec:install:cmd:mailcow-backup:run() {
  732. : :posarg: BACKUP_SERVER 'Target backup server'
  733. : :optfla: --ignore-ping-check "Allow to bypass the ping check of host."
  734. "mailcow:install-backup" "$BACKUP_SERVER" "$opt_ignore_ping_check"
  735. }
  736. cmdline.spec.gnu backup
  737. cmdline.spec::cmd:backup:run() {
  738. local vps_type
  739. vps_type=$(vps:get-type) || {
  740. err "Failed to get type of installation."
  741. return 1
  742. }
  743. if ! fn.exists "cmdline.spec:backup:cmd:${vps_type}:run"; then
  744. err "type '${vps_type}' has no backup process implemented yet."
  745. return 1
  746. fi
  747. "cmdline.spec:backup:cmd:${vps_type}:run"
  748. }
  749. cmdline.spec:backup:cmd:mailcow:run() {
  750. local cmd_line cron_line cmd
  751. for f in mysql-backup mirror-dir; do
  752. [ -e "/etc/cron.d/$f" ] || {
  753. err "Can't find '/etc/cron.d/$f'."
  754. echo " Have you forgotten to run 'vps install backup BACKUP_HOST' ?" >&2
  755. return 1
  756. }
  757. if ! cron_line=$(cat "/etc/cron.d/$f" |
  758. grep -v "^#" | grep "\* \* \*"); then
  759. err "Can't find cron_line in '/etc/cron.d/$f'." \
  760. "Have you modified it ?"
  761. return 1
  762. fi
  763. cron_line=${cron_line%|*}
  764. cmd_line=(${cron_line#*root})
  765. if [ "$f" == "mirror-dir" ]; then
  766. cmd=()
  767. for arg in "${cmd_line[@]}"; do
  768. [ "$arg" != "-q" ] && cmd+=("$arg")
  769. done
  770. else
  771. cmd=("${cmd_line[@]}")
  772. fi
  773. code="${cmd[*]}"
  774. echo "${WHITE}Launching:${NORMAL} ${code}"
  775. {
  776. {
  777. (
  778. ## Some commands are using colors that are already
  779. ## set by this current program and will trickle
  780. ## down unwantedly
  781. ansi_color no
  782. eval "${code}"
  783. ) | sed -r "s/^/ ${GRAY}|${NORMAL} /g"
  784. set_errlvl "${PIPESTATUS[0]}"
  785. } 3>&1 1>&2 2>&3 | sed -r "s/^/ $DARKRED\!$NORMAL /g"
  786. set_errlvl "${PIPESTATUS[0]}"
  787. } 3>&1 1>&2 2>&3
  788. if [ "$?" != "0" ]; then
  789. err "Failed."
  790. return 1
  791. fi
  792. done
  793. info "Mysql backup and subsequent mirror-dir ${DARKGREEN}succeeded${NORMAL}."
  794. }
  795. set_errlvl() { return "${1:-1}"; }
  796. cmdline.spec:backup:cmd:compose:run() {
  797. local cron_line args
  798. project_name=$(compose:project_name) || return 1
  799. docker_cmd=$(compose:get_cron_docker_cmd) || return 1
  800. echo "${WHITE}Launching:${NORMAL} docker exec -i "${project_name}_cron_1" $docker_cmd"
  801. {
  802. {
  803. eval "docker exec -i \"${project_name}_cron_1\" $docker_cmd" | sed -r "s/^/ ${GRAY}|${NORMAL} /g"
  804. set_errlvl "${PIPESTATUS[0]}"
  805. } 3>&1 1>&2 2>&3 | sed -r "s/^/ $DARKRED\!$NORMAL /g"
  806. set_errlvl "${PIPESTATUS[0]}"
  807. } 3>&1 1>&2 2>&3
  808. if [ "$?" != "0" ]; then
  809. err "Failed."
  810. return 1
  811. fi
  812. info "mirror-dir ${DARKGREEN}succeeded${NORMAL}."
  813. }
  814. cmdline.spec.gnu recover-target
  815. cmdline.spec::cmd:recover-target:run() {
  816. : :posarg: BACKUP_DIR 'Source directory on backup side'
  817. : :posarg: HOST_DIR 'Target directory on host side'
  818. : :optval: --backup-host,-B "The backup host"
  819. : :optfla: --dry-run,-n "Don't do anything, instead tell what it
  820. would do."
  821. ## if no backup host take the one by default
  822. backup_host="$opt_backup_host"
  823. if [ -z "$backup_host" ]; then
  824. backup_host_ident=$(backup-action get_default_backup_host_ident) || return 1
  825. read -r backup_host ident <<<"$backup_host_ident"
  826. fi
  827. if [[ "$BACKUP_DIR" == /* ]]; then
  828. err "BACKUP_DIR must be a relative path from the root of your backup."
  829. return 1
  830. fi
  831. REAL_HOST_DIR=$(realpath "$HOST_DIR") || {
  832. err "Can't find HOST_DIR '$HOST_DIR'."
  833. return 1
  834. }
  835. export DRY_RUN="${opt_dry_run}"
  836. backup-action recover-target "$backup_host" "$ident" "$BACKUP_DIR" "$REAL_HOST_DIR"
  837. }
  838. cmdline.spec.gnu odoo
  839. cmdline.spec::cmd:odoo:run() {
  840. :
  841. }
  842. cmdline.spec.gnu restart
  843. cmdline.spec:odoo:cmd:restart:run() {
  844. : :optval: --service,-s "The service (defaults to 'odoo')"
  845. local out odoo_service
  846. odoo_service="${opt_service:-odoo}"
  847. project_name=$(compose:project_name) || return 1
  848. if ! out=$(docker restart "${project_name}_${odoo_service}_1" 2>&1); then
  849. if [[ "$out" == *"no matching entries in passwd file" ]]; then
  850. warn "Catched docker bug. Restarting once more."
  851. if ! out=$(docker restart "${project_name}_${odoo_service}_1"); then
  852. err "Can't restart container ${project_name}_${odoo_service}_1 (restarted twice)."
  853. echo " output:" >&2
  854. echo "$out" | prefix " ${GRAY}|${NORMAL} " >&2
  855. exit 1
  856. fi
  857. else
  858. err "Couldn't restart container ${project_name}_${odoo_service}_1 (and no restart bug detected)."
  859. exit 1
  860. fi
  861. fi
  862. info "Container ${project_name}_${odoo_service}_1 was ${DARKGREEN}successfully${NORMAL} restarted."
  863. }
  864. cmdline.spec.gnu restore
  865. cmdline.spec:odoo:cmd:restore:run() {
  866. : :posarg: ZIP_DUMP_LOCATION 'Source odoo dump file to restore
  867. (can be a local file or an url)'
  868. : :optval: --service,-s "The service (defaults to 'odoo')"
  869. : :optval: --database,-d 'Target database (default if not specified)'
  870. local out
  871. odoo_service="${opt_service:-odoo}"
  872. if [[ "$ZIP_DUMP_LOCATION" == "http://"* ]] ||
  873. [[ "$ZIP_DUMP_LOCATION" == "https://"* ]]; then
  874. settmpdir ZIP_TMP_LOCATION
  875. tmp_location="$ZIP_TMP_LOCATION/dump.zip"
  876. curl -k -s -L "$ZIP_DUMP_LOCATION" > "$tmp_location" || {
  877. err "Couldn't get '$ZIP_DUMP_LOCATION'."
  878. exit 1
  879. }
  880. if [[ "$(dd if="$tmp_location" count=2 bs=1 2>/dev/null)" != "PK" ]]; then
  881. err "Download doesn't seem to be a zip file."
  882. dd if="$tmp_location" count=1 bs=256 | hd | prefix " ${GRAY}|${NORMAL} " >&2
  883. exit 1
  884. fi
  885. info "Successfully downloaded '$ZIP_DUMP_LOCATION'"
  886. echo " in '$tmp_location'." >&2
  887. ZIP_DUMP_LOCATION="$tmp_location"
  888. fi
  889. [ -e "$ZIP_DUMP_LOCATION" ] || {
  890. err "No file '$ZIP_DUMP_LOCATION' found." >&2
  891. exit 1
  892. }
  893. #cmdline.spec:odoo:cmd:restart:run --service "$odoo_service" || exit 1
  894. msg_dbname=default
  895. [ -n "$opt_database" ] && msg_dbname="'$opt_database'"
  896. compose --no-hooks drop "$odoo_service" $opt_database || {
  897. err "Error dropping $msg_dbname database of service ${DARKYELLOW}$odoo_service${NORMAL}."
  898. exit 1
  899. }
  900. compose --no-hooks load "$odoo_service" $opt_database < "$ZIP_DUMP_LOCATION" || {
  901. err "Error restoring service ${DARKYELLOW}$odoo_service${NORMAL} to $msg_dbname database."
  902. exit 1
  903. }
  904. info "Successfully restored ${DARKYELLOW}$odoo_service${NORMAL} to $msg_dbname database."
  905. ## Restart odoo, ensure there is no bugs lingering on it.
  906. cmdline.spec:odoo:cmd:restart:run --service "$odoo_service" || exit 1
  907. }
  908. cmdline.spec.gnu dump
  909. cmdline.spec:odoo:cmd:dump:run() {
  910. : :posarg: DUMP_ZIPFILE 'Target path to store odoo dump zip file.'
  911. : :optval: --database,-d 'Target database (default if not specified)'
  912. : :optval: --service,-s "The service (defaults to 'odoo')"
  913. odoo_service="${opt_service:-odoo}"
  914. msg_dbname=default
  915. [ -n "$opt_database" ] && msg_dbname="'$opt_database'"
  916. compose --no-hooks save "$odoo_service" $opt_database > "$DUMP_ZIPFILE" || {
  917. err "Error dumping ${DARKYELLOW}$odoo_service${NORMAL}'s $msg_dbname database to '$DUMP_ZIPFILE'."
  918. exit 1
  919. }
  920. info "Successfully dumped ${DARKYELLOW}$odoo_service${NORMAL}'s $msg_dbname database to '$DUMP_ZIPFILE'."
  921. }
  922. cmdline.spec.gnu drop
  923. cmdline.spec:odoo:cmd:drop:run() {
  924. : :optval: --database,-d 'Target database (default if not specified)'
  925. : :optval: --service,-s "The service (defaults to 'odoo')"
  926. odoo_service="${opt_service:-odoo}"
  927. msg_dbname=default
  928. [ -n "$opt_database" ] && msg_dbname="'$opt_database'"
  929. compose --no-hooks drop "$odoo_service" $opt_database || {
  930. err "Error dropping ${DARKYELLOW}$odoo_service${NORMAL}'s $msg_dbname database."
  931. exit 1
  932. }
  933. info "Successfully dropped ${DARKYELLOW}$odoo_service${NORMAL}'s $msg_dbname database."
  934. }
  935. cmdline.spec.gnu set-cyclos-url
  936. cmdline.spec:odoo:cmd:set-cyclos-url:run() {
  937. : :optval: --database,-d "Target database ('odoo' if not specified)"
  938. : :optval: --service,-s "The cyclos service name (defaults to 'cyclos')"
  939. local URL
  940. dbname=${opt_database:-odoo}
  941. cyclos_service="${opt_service:-cyclos}"
  942. project_name=$(compose:project_name) || exit 1
  943. URL=$(compose:get_url "${project_name}" "${cyclos_service}") || exit 1
  944. echo "UPDATE res_company SET cyclos_server_url = '$URL/api' WHERE id=1;" |
  945. compose:psql "$project_name" "$dbname" || {
  946. err "Failed to set cyclos url value in '$dbname' database."
  947. exit 1
  948. }
  949. }
  950. cmdline.spec.gnu cyclos
  951. cmdline.spec::cmd:cyclos:run() {
  952. :
  953. }
  954. cmdline.spec:cyclos:cmd:dump:run() {
  955. : :posarg: DUMP_GZFILE 'Target path to store odoo dump gz file.'
  956. : :optval: --database,-d "Target database ('cyclos' if not specified)"
  957. : :optval: --service,-s "The cyclos service name (defaults to 'cyclos')"
  958. cyclos_service="${opt_service:-cyclos}"
  959. cyclos_database="${opt_database:-cyclos}"
  960. project_name=$(compose:project_name) || exit 1
  961. container_id=$(compose:service:container_one "$project_name" "${cyclos_service}") || exit 1
  962. Wrap -d "stop ${DARKYELLOW}${cyclos_service}${NORMAL}'s container" -- \
  963. docker stop "$container_id" || exit 1
  964. Wrap -d "Dump postgres database '${cyclos_database}'." -- \
  965. postgres:dump "${project_name}" "$cyclos_database" "$DUMP_GZFILE" || exit 1
  966. Wrap -d "start ${DARKYELLOW}${cyclos_service}${NORMAL}'s container" -- \
  967. docker start "${container_id}" || exit 1
  968. }
  969. cmdline.spec.gnu restore
  970. cmdline.spec:cyclos:cmd:restore:run() {
  971. : :posarg: GZ_DUMP_LOCATION 'Source cyclos dump file to restore
  972. (can be a local file or an url)'
  973. : :optval: --service,-s "The service (defaults to 'cyclos')"
  974. : :optval: --database,-d 'Target database (default if not specified)'
  975. local out
  976. cyclos_service="${opt_service:-cyclos}"
  977. cyclos_database="${opt_database:-cyclos}"
  978. project_name=$(compose:project_name) || exit 1
  979. url=$(compose:get_url "${project_name}" "${cyclos_service}") || return 1
  980. container_id=$(compose:service:container_one "$project_name" "${cyclos_service}") || exit 1
  981. if [[ "$GZ_DUMP_LOCATION" == "http://"* ]] ||
  982. [[ "$GZ_DUMP_LOCATION" == "https://"* ]]; then
  983. settmpdir GZ_TMP_LOCATION
  984. tmp_location="$GZ_TMP_LOCATION/dump.gz"
  985. Wrap -d "get '$GZ_DUMP_LOCATION'" <<EOF || exit 1
  986. ## Note that curll version before 7.76.0 do not have
  987. curl -k -s -L "$GZ_DUMP_LOCATION" --fail \\
  988. > "$tmp_location" || {
  989. echo "Error fetching ressource. Is url correct ?" >&2
  990. exit 1
  991. }
  992. if [[ "\$(dd if="$tmp_location" count=2 bs=1 2>/dev/null |
  993. hexdump -v -e "/1 \"%02x\"")" != "1f8b" ]]; then
  994. err "Download doesn't seem to be a gzip file."
  995. dd if="$tmp_location" count=1 bs=256 | hd | prefix " ${GRAY}|${NORMAL} " >&2
  996. exit 1
  997. fi
  998. EOF
  999. GZ_DUMP_LOCATION="$tmp_location"
  1000. fi
  1001. [ -e "$GZ_DUMP_LOCATION" ] || {
  1002. err "No file '$GZ_DUMP_LOCATION' found." >&2
  1003. exit 1
  1004. }
  1005. Wrap -d "stop ${DARKYELLOW}${cyclos_service}${NORMAL}'s container" -- \
  1006. docker stop "$container_id" || exit 1
  1007. ## XXXvlab: making the assumption that the postgres username should
  1008. ## be the same as the cyclos service selected (which is the default,
  1009. ## but not always the case).
  1010. Wrap -d "restore postgres database '${cyclos_database}'." -- \
  1011. postgres:restore "$project_name" "$GZ_DUMP_LOCATION" "${cyclos_service}@${cyclos_database}" || exit 1
  1012. ## ensure that the database is not locked
  1013. ## XXXvlab: 70 is uid of user postgres, this avoids the docker bug
  1014. ## but introduce hardwritten value
  1015. Wrap -d "check and remove database lock if any" <<EOF || exit 1
  1016. echo "delete from database_lock;" | compose:psql "${project_name}" "${cyclos_database}"
  1017. EOF
  1018. Wrap -d "set root url to '$url'" -- \
  1019. cyclos:set_root_url "${project_name}" "${cyclos_database}" "${url}" || exit 1
  1020. Wrap -d "start ${DARKYELLOW}${cyclos_service}${NORMAL}'s container" -- \
  1021. docker start "${container_id}" || exit 1
  1022. }
  1023. cmdline.spec.gnu set-root-url
  1024. cmdline.spec:cyclos:cmd:set-root-url:run() {
  1025. : :optval: --database,-d "Target database ('cyclos' if not specified)"
  1026. : :optval: --service,-s "The cyclos service name (defaults to 'cyclos')"
  1027. local URL
  1028. cyclos_database=${opt_database:-cyclos}
  1029. cyclos_service="${opt_service:-cyclos}"
  1030. project_name=$(compose:project_name) || exit 1
  1031. url=$(compose:get_url "${project_name}" "${cyclos_service}") || exit 1
  1032. container_id=$(compose:service:container_one "${project_name}" "${cyclos_service}") || exit 1
  1033. Wrap -d "stop ${DARKYELLOW}${cyclos_service}${NORMAL}'s container" -- \
  1034. docker stop "$container_id" || exit 1
  1035. Wrap -d "set root url to '$url'" -- \
  1036. cyclos:set_root_url "${project_name}" "${cyclos_database}" "${url}" || exit 1
  1037. Wrap -d "start ${DARKYELLOW}${cyclos_service}${NORMAL}'s container" -- \
  1038. docker start "${container_id}" || exit 1
  1039. }
  1040. cmdline::parse "$@"