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.

1727 lines
52 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. export -f compose:get-compose-yml
  63. compose:has-container-project-myc() {
  64. local projects
  65. projects=$(docker:running-container-projects) || return 1
  66. [[ $'\n'"$projects"$'\n' == *$'\n'"myc"$'\n'* ]]
  67. }
  68. compose:file:value-change() {
  69. local key="$1" value="$2"
  70. yaml:file:value-change "$(compose:get-compose-yml)" "$key" "$value" || exit 1
  71. }
  72. export -f compose:file:value-change
  73. yaml:file:value-change() {
  74. local file="$1" key="$2" value="$3" first=1 count=0 diff=""
  75. (
  76. cd "${file%/*}"
  77. while read-0 hunk; do
  78. if [ -n "$first" ]; then
  79. diff+="$hunk"
  80. first=
  81. continue
  82. fi
  83. if [[ "$hunk" =~ $'\n'"+"[[:space:]]+"${key##*.}:" ]]; then
  84. ((count++))
  85. diff+="$hunk" >&2
  86. else
  87. :
  88. # echo "discarding:" >&2
  89. # e "$hunk" | prefix " | " >&2
  90. fi
  91. done < <(
  92. export DEBUG=
  93. settmpdir YQ_TEMP
  94. cp "${file}" "$YQ_TEMP/compose.yml" &&
  95. yq -i ".${key} = \"${value}\"" "$YQ_TEMP/compose.yml" &&
  96. sed -ri 's/^([^# ])/\n\0/g' "$YQ_TEMP/compose.yml" &&
  97. diff -u0 -Z "${file}" "$YQ_TEMP/compose.yml" |
  98. sed -r "s/^(@@.*)$/\x00\1/g;s%^(\+\+\+) [^\t]+%\1 ${file}%g"
  99. printf "\0"
  100. )
  101. if [[ "$count" == 0 ]]; then
  102. err "No change made to '$file'."
  103. return 1
  104. fi
  105. if [[ "$count" != 1 ]]; then
  106. err "compose file change request seems dubious and was refused:"
  107. e "$diff" | prefix " | " >&2
  108. return 1
  109. fi
  110. echo Applying: >&2
  111. e "$diff" | prefix " | " >&2
  112. patch <<<"$diff"
  113. ) || exit 1
  114. }
  115. export -f yaml:file:value-change
  116. type:is-mailcow() {
  117. mailcow:get-root >/dev/null ||
  118. mailcow:has-running-containers
  119. }
  120. type:is-compose() {
  121. compose:get-compose-yml >/dev/null &&
  122. compose:has-container-project-myc
  123. }
  124. vps:get-type() {
  125. :cache: scope=session
  126. local fn
  127. for fn in $(declare -F | cut -f 3 -d " " | egrep "^type:is-"); do
  128. "$fn" && {
  129. echo "${fn#type:is-}"
  130. return 0
  131. }
  132. done
  133. return 1
  134. }
  135. decorator._mangle_fn vps:get-type
  136. mirror-dir:sources() {
  137. :cache: scope=session
  138. if ! shyaml get-values default.sources < /etc/mirror-dir/config.yml; then
  139. err "Couldn't query 'default.sources' in '/etc/mirror-dir/config.yml'."
  140. return 1
  141. fi
  142. }
  143. decorator._mangle_fn mirror-dir:sources
  144. mirror-dir:check-add() {
  145. local elt="$1" sources
  146. sources=$(mirror-dir:sources) || return 1
  147. if [[ $'\n'"$sources"$'\n' == *$'\n'"$elt"$'\n'* ]]; then
  148. info "Volume $elt already in sources"
  149. else
  150. Elt "Adding directory $elt"
  151. sed -i "/sources:/a\ - \"${elt}\"" \
  152. /etc/mirror-dir/config.yml
  153. Feedback || return 1
  154. fi
  155. }
  156. mirror-dir:check-add-vol() {
  157. local elt="$1"
  158. mirror-dir:check-add "/var/lib/docker/volumes/*_${elt}-*/_data"
  159. }
  160. ## The first colon is to prevent auto-export of function from shlib
  161. : ; bash-bug-5() { { cat; } < <(e) >/dev/null; ! cat "$1"; } && bash-bug-5 <(e) 2>/dev/null &&
  162. export BASH_BUG_5=1 && unset -f bash_bug_5
  163. wrap() {
  164. local label="$1" code="$2"
  165. shift 2
  166. export VERBOSE=1
  167. interpreter=/bin/bash
  168. if [ -n "$BASH_BUG_5" ]; then
  169. (
  170. settmpdir tmpdir
  171. fname=${label##*/}
  172. e "$code" > "$tmpdir/$fname" &&
  173. chmod +x "$tmpdir/$fname" &&
  174. Wrap -vsd "$label" -- "$interpreter" "$tmpdir/$fname" "$@"
  175. )
  176. else
  177. Wrap -vsd "$label" -- "$interpreter" <(e "$code") "$@"
  178. fi
  179. }
  180. ping_check() {
  181. #global ignore_ping_check
  182. local host="$1"
  183. ip=$(getent ahosts "$host" | egrep "^[0-9]+\.[0-9]+\.[0-9]+\.[0-9]+\s+" |
  184. head -n 1 | cut -f 1 -d " ") || return 1
  185. my_ip=$(curl -s myip.kal.fr)
  186. if [ "$ip" != "$my_ip" ]; then
  187. if [ -n "$ignore_ping_check" ]; then
  188. warn "IP of '$host' ($ip) doesn't match mine ($my_ip). Ignoring due to ``--ignore-ping-check`` option."
  189. else
  190. err "IP of '$host' ($ip) doesn't match mine ($my_ip). Use ``--ignore-ping-check`` to ignore check."
  191. return 1
  192. fi
  193. fi
  194. }
  195. mailcow:install-backup() {
  196. local BACKUP_SERVER="$1" ignore_ping_check="$2" mailcow_root DOMAIN
  197. ## find installation
  198. mailcow_root=$(mailcow:get-root) || {
  199. err "Couldn't find a valid mailcow root directory."
  200. return 1
  201. }
  202. ## check ok
  203. DOMAIN=$(cat "$mailcow_root/.env" | grep ^MAILCOW_HOSTNAME= | cut -f 2 -d =) || {
  204. err "Couldn't find MAILCOW_HOSTNAME in file \"$mailcow_root/.env\"."
  205. return 1
  206. }
  207. ping_check "$DOMAIN" || return 1
  208. MYSQL_ROOT_PASSWORD=$(cat "$mailcow_root/.env" | grep ^DBROOT= | cut -f 2 -d =) || {
  209. err "Couldn't find DBROOT in file \"$mailcow_root/.env\"."
  210. return 1
  211. }
  212. MYSQL_CONTAINER=${MYSQL_CONTAINER:-mailcowdockerized_mysql-mailcow_1}
  213. container_id=$(docker ps -f name="$MYSQL_CONTAINER" --format "{{.ID}}")
  214. if [ -z "$container_id" ]; then
  215. err "Couldn't find docker container named '$MYSQL_CONTAINER'."
  216. return 1
  217. fi
  218. export KEY_BACKUP_ID="mailcow"
  219. export MYSQL_ROOT_PASSWORD
  220. export MYSQL_CONTAINER
  221. export BACKUP_SERVER
  222. export DOMAIN
  223. wrap "Install rsync-backup on host" "
  224. cd /srv/charm-store/rsync-backup
  225. bash ./hooks/install.d/60-install.sh
  226. " || return 1
  227. wrap "Mysql dump install" "
  228. cd /srv/charm-store/mariadb
  229. bash ./hooks/install.d/60-backup.sh
  230. " || return 1
  231. ## Using https://github.com/mailcow/mailcow-dockerized/blob/master/helper-scripts/backup_and_restore.sh
  232. for elt in "vmail{,-attachments-vol}" crypt redis rspamd postfix; do
  233. mirror-dir:check-add-vol "$elt" || return 1
  234. done
  235. mirror-dir:check-add "$mailcow_root" || return 1
  236. mirror-dir:check-add "/var/backups/mysql" || return 1
  237. mirror-dir:check-add "/etc" || return 1
  238. dest="$BACKUP_SERVER"
  239. dest="${dest%/*}"
  240. ssh_options=()
  241. if [[ "$dest" == *":"* ]]; then
  242. port="${dest##*:}"
  243. dest="${dest%%:*}"
  244. ssh_options=(-p "$port")
  245. else
  246. port=""
  247. dest="${dest%%:*}"
  248. fi
  249. info "You can run this following command from an host having admin access to $dest:"
  250. echo " (Or send it to a backup admin of $dest)" >&2
  251. echo "ssh ${ssh_options[@]} myadmin@$dest ssh-key add '$(cat /var/lib/rsync/.ssh/id_rsa.pub)'"
  252. }
  253. compose:has_domain() {
  254. local compose_file="$1" host="$2" name conf relation relation_value domain server_aliases
  255. while read-0 name conf ; do
  256. name=$(e "$name" | shyaml get-value)
  257. if [[ "$name" =~ ^[a-zA-Z0-9-]+\.[a-zA-Z0-9-]+ ]]; then
  258. [ "$host" == "$name" ] && return 0
  259. fi
  260. rel=$(e "$conf" | shyaml -y get-value relations 2>/dev/null) || continue
  261. for relation in web-proxy publish-dir; do
  262. relation_value=$(e "$rel" | shyaml -y get-value "$relation" 2>/dev/null) || continue
  263. while read-0 label conf_relation; do
  264. domain=$(e "$conf_relation" | shyaml get-value "domain" 2>/dev/null) && {
  265. [ "$host" == "$domain" ] && return 0
  266. }
  267. server_aliases=$(e "$conf_relation" | shyaml get-values "server-aliases" 2>/dev/null) && {
  268. [[ $'\n'"$server_aliases" == *$'\n'"$host"$'\n'* ]] && return 0
  269. }
  270. done < <(e "$relation_value" | shyaml -y key-values-0)
  271. done
  272. done < <(shyaml -y key-values-0 < "$compose_file")
  273. return 1
  274. }
  275. compose:install-backup() {
  276. local BACKUP_SERVER="$1" service_name="$2" compose_file="$3" ignore_ping_check="$4" ignore_domain_check="$5"
  277. ## XXXvlab: far from perfect as it mimics and depends internal
  278. ## logic of current default way to get a domain in compose-core
  279. host=$(hostname)
  280. if ! compose:has_domain "$compose_file" "$host"; then
  281. if [ -n "$ignore_domain_check" ]; then
  282. warn "domain of '$host' not found in compose file '$compose_file'. Ignoring due to ``--ignore-domain-check`` option."
  283. else
  284. err "domain of '$host' not found in compose file '$compose_file'. Use ``--ignore-domain-check`` to ignore check."
  285. return 1
  286. fi
  287. fi
  288. ping_check "$host" || return 1
  289. if [ -e "/root/.ssh/rsync_rsa" ]; then
  290. warn "deleting private key in /root/.ssh/rsync_rsa, has we are not using it anymore."
  291. rm -fv /root/.ssh/rsync_rsa
  292. fi
  293. if [ -e "/root/.ssh/rsync_rsa.pub" ]; then
  294. warn "deleting public key in /root/.ssh/rsync_rsa.pub, has we are not using it anymore."
  295. rm -fv /root/.ssh/rsync_rsa.pub
  296. fi
  297. if service_cfg=$(cat "$compose_file" |
  298. shyaml get-value -y "$service_name" 2>/dev/null); then
  299. info "Entry for service ${DARKYELLOW}$service_name${NORMAL}" \
  300. "is already present in '$compose_file'."
  301. cfg=$(e "$service_cfg" | shyaml get-value -y options) || {
  302. err "No ${WHITE}options${NORMAL} in ${DARKYELLOW}$service_name${NORMAL}'s" \
  303. "entry in '$compose_file'."
  304. return 1
  305. }
  306. private_key=$(e "$cfg" | shyaml get-value private-key) || return 1
  307. target=$(e "$cfg" | shyaml get-value target) || return 1
  308. if [ "$target" != "$BACKUP_SERVER" ]; then
  309. err "Existing backup target '$target' is different" \
  310. "from specified '$BACKUP_SERVER'"
  311. return 1
  312. fi
  313. else
  314. private_key=$(ssh:mk-private-key "$host" "$service_name")
  315. cat <<EOF >> "$compose_file"
  316. $service_name:
  317. options:
  318. ident: $host
  319. target: $BACKUP_SERVER
  320. private-key: |
  321. $(e "$private_key" | sed -r 's/^/ /g')
  322. EOF
  323. fi
  324. dest="$BACKUP_SERVER"
  325. dest="${dest%/*}"
  326. ssh_options=()
  327. if [[ "$dest" == *":"* ]]; then
  328. port="${dest##*:}"
  329. dest="${dest%%:*}"
  330. ssh_options=(-p "$port")
  331. else
  332. port=""
  333. dest="${dest%%:*}"
  334. fi
  335. info "You can run this following command from an host having admin access to $dest:"
  336. echo " (Or send it to a backup admin of $dest)" >&2
  337. ## We remove ending label (label will be added or not in the
  338. ## private key, and thus here, depending on the version of
  339. ## openssh-client)
  340. public_key=$(ssh-keygen -y -f <(e "$private_key"$'\n') | sed -r 's/ [^ ]+@[^ ]+$//')
  341. echo "ssh ${ssh_options[@]} myadmin@$dest ssh-key add '$public_key compose@$host'"
  342. }
  343. backup-action() {
  344. local action="$1"
  345. shift
  346. vps_type=$(vps:get-type) || {
  347. err "Failed to get type of installation."
  348. return 1
  349. }
  350. if ! fn.exists "${vps_type}:${action}"; then
  351. err "type '${vps_type}' has no ${vps_type}:${action} implemented yet."
  352. return 1
  353. fi
  354. "${vps_type}:${action}" "$@"
  355. }
  356. compose:get_default_backup_host_ident() {
  357. local service_name="$1" ## Optional
  358. local compose_file service_cfg cfg target
  359. compose_file=$(compose:get-compose-yml)
  360. service_name="${service_name:-rsync-backup}"
  361. if ! service_cfg=$(cat "$compose_file" |
  362. shyaml get-value -y "$service_name" 2>/dev/null); then
  363. err "No service named '$service_name' found in 'compose.yml'."
  364. return 1
  365. fi
  366. cfg=$(e "$service_cfg" | shyaml get-value -y options) || {
  367. err "No ${WHITE}options${NORMAL} in ${DARKYELLOW}$service_name${NORMAL}'s" \
  368. "entry in '$compose_file'."
  369. return 1
  370. }
  371. if ! target=$(e "$cfg" | shyaml get-value target); then
  372. err "No ${WHITE}options.target${NORMAL} in ${DARKYELLOW}$service_name${NORMAL}'s" \
  373. "entry in '$compose_file'."
  374. fi
  375. if ! target=$(e "$cfg" | shyaml get-value target); then
  376. err "No ${WHITE}options.target${NORMAL} in ${DARKYELLOW}$service_name${NORMAL}'s" \
  377. "entry in '$compose_file'."
  378. fi
  379. if ! ident=$(e "$cfg" | shyaml get-value ident); then
  380. err "No ${WHITE}options.ident${NORMAL} in ${DARKYELLOW}$service_name${NORMAL}'s" \
  381. "entry in '$compose_file'."
  382. fi
  383. echo "$target $ident"
  384. }
  385. mailcow:get_default_backup_host_ident() {
  386. local content cron_line ident found dest cmd_line
  387. if ! [ -e "/etc/cron.d/mirror-dir" ]; then
  388. err "No '/etc/cron.d/mirror-dir' found."
  389. return 1
  390. fi
  391. content=$(cat /etc/cron.d/mirror-dir) || {
  392. err "Can't read '/etc/cron.d/mirror-dir'."
  393. return 1
  394. }
  395. if ! cron_line=$(e "$content" | grep "mirror-dir backup"); then
  396. err "Can't find 'mirror-dir backup' line in '/etc/cron.d/mirror-dir'."
  397. return 1
  398. fi
  399. cron_line=${cron_line%|*}
  400. cmd_line=(${cron_line#*root})
  401. found=
  402. dest=
  403. for arg in "${cmd_line[@]}"; do
  404. [ -n "$found" ] && {
  405. dest="$arg"
  406. break
  407. }
  408. [ "$arg" == "-d" ] && {
  409. found=1
  410. }
  411. done
  412. if ! [[ "$dest" =~ ^[\'\"a-zA-Z0-9:/.-]+$ ]]; then
  413. err "Can't find valid destination in 'mirror-dir backup' arguments from '/etc/cron.d/mirror-dir'."
  414. return 1
  415. fi
  416. if [[ "$dest" == \"*\" ]] || [[ "$dest" == \'*\' ]]; then
  417. ## unquoting, the eval should be safe because of previous check
  418. dest=$(eval e "$dest")
  419. fi
  420. if [ -z "$dest" ]; then
  421. err "Can't find destination in 'mirror-dir backup' arguments from '/etc/cron.d/mirror-dir'."
  422. return 1
  423. fi
  424. ## looking for ident
  425. found=
  426. ident=
  427. for arg in "${cmd_line[@]}"; do
  428. [ -n "$found" ] && {
  429. ident="$arg"
  430. break
  431. }
  432. [ "$arg" == "-h" ] && {
  433. found=1
  434. }
  435. done
  436. if ! [[ "$ident" =~ ^[\'\"a-zA-Z0-9.-]+$ ]]; then
  437. err "Can't find valid identifier in 'mirror-dir backup' arguments from '/etc/cron.d/mirror-dir'."
  438. return 1
  439. fi
  440. if [[ "$ident" == \"*\" ]] || [[ "$ident" == \'*\' ]]; then
  441. ## unquoting, the eval should be safe because of previous check
  442. ident=$(eval e "$ident")
  443. fi
  444. if [ -z "$ident" ]; then
  445. err "Can't find destination in 'mirror-dir backup' arguments from '/etc/cron.d/mirror-dir'."
  446. return 1
  447. fi
  448. echo "$dest $ident"
  449. }
  450. compose:service:containers() {
  451. local project="$1" service="$2"
  452. docker ps \
  453. --filter label="com.docker.compose.project=$project" \
  454. --filter label="compose.master-service=$service" \
  455. --format="{{.ID}}"
  456. }
  457. export -f compose:service:containers
  458. compose:service:container_one() {
  459. local project="$1" service="$2" container_id
  460. {
  461. read-0a container_id || {
  462. err "service ${DARKYELLOW}$service${NORMAL} has no running container."
  463. return 1
  464. }
  465. if read-0a _; then
  466. err "service ${DARKYELLOW}$service${NORMAL} has more than one running container."
  467. return 1
  468. fi
  469. } < <(compose:service:containers "$project" "$service")
  470. echo "$container_id"
  471. }
  472. export -f compose:service:container_one
  473. compose:service:container_first() {
  474. local project="$1" service="$2" container_id
  475. {
  476. read-0a container_id || {
  477. err "service ${DARKYELLOW}$service${NORMAL} has no running container."
  478. return 1
  479. }
  480. if read-0a _; then
  481. warn "service ${DARKYELLOW}$service${NORMAL} has more than one running container."
  482. fi
  483. } < <(compose:service:containers "$project" "$service")
  484. echo "$container_id"
  485. }
  486. export -f compose:service:container_first
  487. compose:project:containers() {
  488. local project="$1" opts
  489. opts+=(--filter label="com.docker.compose.project=$project")
  490. docker ps "${opts[@]}" \
  491. --format="{{.ID}}"
  492. }
  493. export -f compose:project:containers
  494. compose:charm:containers() {
  495. local project="$1" charm="$2"
  496. docker ps \
  497. --filter label="com.docker.compose.project=$project" \
  498. --filter label="compose.charm=$charm" \
  499. --format="{{.ID}}"
  500. }
  501. export -f compose:charm:containers
  502. compose:charm:container_one() {
  503. local project="$1" charm="$2" container_id
  504. {
  505. read-0a container_id || {
  506. err "charm ${DARKPINK}$charm${NORMAL} has no running container in project '$project'."
  507. return 1
  508. }
  509. if read-0a _; then
  510. err "charm ${DARKPINK}$charm${NORMAL} has more than one running container."
  511. return 1
  512. fi
  513. } < <(compose:charm:containers "$project" "$charm")
  514. echo "$container_id"
  515. }
  516. export -f compose:charm:container_one
  517. compose:charm:container_first() {
  518. local project="$1" charm="$2" container_id
  519. {
  520. read-0a container_id || {
  521. warn "charm ${DARKYELLOW}$charm${NORMAL} has no running container in project '$project'."
  522. }
  523. if read-0a _; then
  524. warn "charm ${DARKYELLOW}$charm${NORMAL} has more than one running container."
  525. fi
  526. } < <(compose:charm:containers "$project" "$charm")
  527. echo "$container_id"
  528. }
  529. export -f compose:charm:container_first
  530. compose:get_url() {
  531. local project_name="$1" service="$2" data_file network ip
  532. data_file="/var/lib/compose/relations/${project_name}/${service}-frontend/web-proxy/data"
  533. if [ -e "$data_file" ]; then
  534. (
  535. set -o pipefail
  536. cat "$data_file" | shyaml get-value url
  537. )
  538. else
  539. ## Assume there are no frontend relation here, the url is direct IP
  540. container_id=$(compose:service:container_one "${project_name}" "${service}") || return 1
  541. network_ip=$(docker:container:network_ip_one "${container_id}") || return 1
  542. IFS=":" read -r network ip <<<"$network_ip"
  543. tcp_port=
  544. for port in $(docker:exposed_ports "$container_id"); do
  545. IFS="/" read port type <<<"$port"
  546. [ "$type" == "tcp" ] || continue
  547. tcp_port="$port"
  548. break
  549. done
  550. echo -n "http://$ip"
  551. [ -n "$tcp_port" ] && echo ":$tcp_port"
  552. fi || {
  553. err "Failed querying ${service} to frontend relation to get url."
  554. return 1
  555. }
  556. }
  557. export -f compose:get_url
  558. compose:container:service() {
  559. local container="$1" service
  560. if ! service=$(docker:container:label "$container" "compose.service"); then
  561. err "Failed to get service name from container ${container}."
  562. return 1
  563. fi
  564. if [ -z "$service" ]; then
  565. err "No service found for container ${container}."
  566. return 1
  567. fi
  568. echo "$service"
  569. }
  570. export -f compose:container:service
  571. compose:psql() {
  572. local project_name="$1" dbname="$2" container_id
  573. shift 2
  574. container_id=$(compose:charm:container_one "$project_name" "postgres") || return 1
  575. docker exec -i "${container_id}" psql -U postgres "$dbname" "$@"
  576. }
  577. export -f compose:psql
  578. compose:mongo() {
  579. local project_name="$1" dbname="$2" container_id
  580. container_id=$(compose:charm:container_one "$project_name" "mongo") || return 1
  581. docker exec -i "${container_id}" mongo --quiet "$dbname"
  582. }
  583. export -f compose:mongo
  584. compose:pgm() {
  585. local project_name="$1" container_network_ip container_ip container_network
  586. shift
  587. container_id=$(compose:charm:container_one "$project_name" "postgres") || return 1
  588. service_name=$(compose:container:service "$container_id") || return 1
  589. image_id=$(docker:container:image "$container_id") || return 1
  590. container_network_ip=$(docker:container:network_ip_one "$container_id") || return 1
  591. IFS=":" read -r container_network container_ip <<<"$container_network_ip"
  592. pgpass="/srv/datastore/data/${service_name}/var/lib/postgresql/data/pgpass"
  593. local final_pgm_docker_run_opts+=(
  594. -u 0 -e prefix_pg_local_command=" "
  595. --network "${container_network}"
  596. -e PGHOST="$container_ip"
  597. -e PGUSER=postgres
  598. -v "$pgpass:/root/.pgpass"
  599. "${pgm_docker_run_opts[@]}"
  600. )
  601. cmd=(docker run --rm \
  602. "${final_pgm_docker_run_opts[@]}" \
  603. "${image_id}" pgm "$@"
  604. )
  605. echo "${cmd[@]}"
  606. "${cmd[@]}"
  607. }
  608. export -f compose:pgm
  609. postgres:dump() {
  610. local project_name="$1" src="$2" dst="$3"
  611. (
  612. settmpdir PGM_TMP_LOCATION
  613. pgm_docker_run_opts=('-v' "${PGM_TMP_LOCATION}:/tmp/dump")
  614. compose:pgm "$project_name" cp -f "$src" "/tmp/dump/dump.gz" &&
  615. mv "$PGM_TMP_LOCATION/dump.gz" "$dst"
  616. ) || return 1
  617. }
  618. export -f postgres:dump
  619. postgres:restore() {
  620. local project_name="$1" src="$2" dst="$3"
  621. full_src_path=$(readlink -e "$src") || exit 1
  622. (
  623. pgm_docker_run_opts=('-v' "${full_src_path}:/tmp/dump.gz")
  624. compose:pgm "$project_name" cp -f "/tmp/dump.gz" "$dst"
  625. ) || return 1
  626. }
  627. export -f postgres:restore
  628. odoo:get_public_user_id() {
  629. local project_name="$1" dbname="$2"
  630. echo "select res_id from ir_model_data where model = 'res.users' and name = 'public_user';" |
  631. compose:psql "$project_name" "$dbname" -qAt
  632. }
  633. cyclos:set_root_url() {
  634. local project_name="$1" dbname="$2" url="$3"
  635. echo "UPDATE configurations SET root_url = '$url';" |
  636. compose:psql "$project_name" "$dbname" || {
  637. err "Failed to set cyclos url value in '$dbname' database."
  638. return 1
  639. }
  640. }
  641. export -f cyclos:set_root_url
  642. cyclos:unlock() {
  643. local project_name="$1" dbname="$2"
  644. echo "delete from database_lock;" |
  645. compose:psql "${project_name}" "${dbname}"
  646. }
  647. export -f cyclos:unlock
  648. rocketchat:drop-indexes() {
  649. local project_name="$1" dbname="$2"
  650. echo "db.users.dropIndexes()" |
  651. compose:mongo "${project_name}" "${dbname}"
  652. }
  653. export -f rocketchat:drop-indexes
  654. compose:project_name() {
  655. if [ -z "$PROJECT_NAME" ]; then
  656. PROJECT_NAME=$(compose --get-project-name) || {
  657. err "Couldn't get project name."
  658. return 1
  659. }
  660. if [ -z "$PROJECT_NAME" -o "$PROJECT_NAME" == "orphan" ]; then
  661. err "Couldn't get project name, probably because 'compose.yml' wasn't found."
  662. echo " Please ensure to either configure a global 'compose.yml' or run this command" >&2
  663. echo " in a compose project (with 'compose.yml' on the top level directory)." >&2
  664. return 1
  665. fi
  666. export PROJECT_NAME
  667. fi
  668. echo "$PROJECT_NAME"
  669. }
  670. export -f compose:project_name
  671. compose:get_cron_docker_cmd() {
  672. local cron_line cmd_line docker_cmd
  673. project_name=$(compose:project_name) || return 1
  674. if ! cron_line=$(docker exec "${project_name}"_cron_1 cat /etc/cron.d/rsync-backup | grep "\* \* \*"); then
  675. err "Can't find cron_line in cron container."
  676. echo " Have you forgotten to run 'compose up' ?" >&2
  677. return 1
  678. fi
  679. cron_line=${cron_line%|*}
  680. cron_line=${cron_line%"2>&1"*}
  681. cmd_line="${cron_line#*root}"
  682. eval "args=($cmd_line)"
  683. ## should be last argument
  684. docker_cmd=$(echo ${args[@]: -1})
  685. if ! [[ "$docker_cmd" == "docker run --rm -e "* ]]; then
  686. echo "docker command found should start with 'docker run'." >&2
  687. echo "Here's command:" >&2
  688. echo " $docker_cmd" >&2
  689. return 1
  690. fi
  691. e "$docker_cmd"
  692. }
  693. compose:recover-target() {
  694. local backup_host="$1" ident="$2" src="$3" dst="$4" service_name="${5:-rsync-backup}" project_name
  695. project_name=$(compose:project_name) || return 1
  696. docker_image="${project_name}_${service_name}"
  697. if ! docker_has_image "$docker_image"; then
  698. compose build "${service_name}" || {
  699. err "Couldn't find nor build image for service '$service_name'."
  700. return 1
  701. }
  702. fi
  703. dst="${dst%/}" ## remove final slash
  704. ssh_options=(-o StrictHostKeyChecking=no)
  705. if [[ "$backup_host" == *":"* ]]; then
  706. port="${backup_host##*:}"
  707. backup_host="${backup_host%%:*}"
  708. ssh_options+=(-p "$port")
  709. else
  710. port=""
  711. backup_host="${backup_host%%:*}"
  712. fi
  713. rsync_opts=(
  714. -e "ssh ${ssh_options[*]} -i /var/lib/rsync/.ssh/id_rsa -l rsync"
  715. -azvArH --delete --delete-excluded
  716. --partial --partial-dir .rsync-partial
  717. --numeric-ids
  718. )
  719. if [ "$DRY_RUN" ]; then
  720. rsync_opts+=("-n")
  721. fi
  722. cmd=(
  723. docker run --rm --entrypoint rsync \
  724. -v "/srv/datastore/config/${service_name}/var/lib/rsync":/var/lib/rsync \
  725. -v "${dst%/*}":/mnt/dest \
  726. "$docker_image" \
  727. "${rsync_opts[@]}" "$backup_host":"/var/mirror/$ident/$src" "/mnt/dest/${dst##*/}"
  728. )
  729. echo "${WHITE}Launching: ${NORMAL} ${cmd[@]}"
  730. "${cmd[@]}"
  731. }
  732. mailcow:recover-target() {
  733. local backup_host="$1" ident="$2" src="$3" dst="$4"
  734. dst="${dst%/}" ## remove final slash
  735. ssh_options=(-o StrictHostKeyChecking=no)
  736. if [[ "$backup_host" == *":"* ]]; then
  737. port="${backup_host##*:}"
  738. backup_host="${backup_host%%:*}"
  739. ssh_options+=(-p "$port")
  740. else
  741. port=""
  742. backup_host="${backup_host%%:*}"
  743. fi
  744. rsync_opts=(
  745. -e "ssh ${ssh_options[*]} -i /var/lib/rsync/.ssh/id_rsa -l rsync"
  746. -azvArH --delete --delete-excluded
  747. --partial --partial-dir .rsync-partial
  748. --numeric-ids
  749. )
  750. if [ "$DRY_RUN" ]; then
  751. rsync_opts+=("-n")
  752. fi
  753. cmd=(
  754. rsync "${rsync_opts[@]}" "$backup_host":"/var/mirror/$ident/$src" "${dst}"
  755. )
  756. echo "${WHITE}Launching: ${NORMAL} ${cmd[@]}"
  757. "${cmd[@]}"
  758. }
  759. nextcloud:src:version() {
  760. local version
  761. if ! version=$(cat "/srv/datastore/data/${nextcloud_service}/var/www/html/version.php" 2>/dev/null); then
  762. err "Can't find version.php file to get last version installed."
  763. exit 1
  764. fi
  765. version=$(e "$version" | grep 'VersionString =' | cut -f 3 -d ' ' | cut -f 2 -d "'")
  766. if [ -z "$version" ]; then
  767. err "Can't figure out version from version.php content."
  768. exit 1
  769. fi
  770. echo "$version"
  771. }
  772. container:health:check-fix:container-aliveness() {
  773. local container_id="$1"
  774. timeout 5s docker inspect "$container_id" >/dev/null 2>&1
  775. errlvl=$?
  776. if [ "$errlvl" == 124 ]; then
  777. service_name=$(docker ps --filter id="$container_id" --format '{{.Label "com.docker.compose.service"}}')
  778. container_name=($(docker ps --filter id="$container_id" --format '{{.Names}}'))
  779. pid=$(ps ax -o pid,command -ww | grep docker-containerd-shim |
  780. grep "/$container_id" |
  781. sed -r 's/^ *//g' |
  782. cut -f 1 -d " ")
  783. if [ -z "$pid" ]; then
  784. err "container ${DARKCYAN}${container_name[0]}${NORMAL} for ${DARKYELLOW}$service_name${NORMAL} doesn't answer to 'inspect' command. Can't find its PID neither."
  785. return 1
  786. fi
  787. echo "container ${DARKCYAN}${container_name[0]}${NORMAL} for ${DARKYELLOW}$service_name${NORMAL} doesn't answer to 'inspect' command (pid: $pid)."
  788. Wrap -d "kill pid $pid and restart" <<EOF
  789. kill "$pid"
  790. sleep 2
  791. docker restart "$container_id"
  792. EOF
  793. fi
  794. return $errlvl
  795. }
  796. container:health:check-fix:no-matching-entries() {
  797. local container_id="$1"
  798. out=$(docker exec "$container_id" echo 2>&1)
  799. errlvl=$?
  800. [ "$errlvl" == 0 ] && return 0
  801. service_name=$(docker ps --filter id="$container_id" --format '{{.Label "com.docker.compose.service"}}')
  802. container_name=($(docker ps --filter id="$container_id" --format '{{.Names}}'))
  803. if [ "$errlvl" == 126 ] && [[ "$out" == *"no matching entries in passwd file"* ]]; then
  804. echo "container ${DARKCYAN}${container_name[0]}${NORMAL} for ${DARKYELLOW}$service_name${NORMAL} has ${DARKRED}no-matching-entries${NORMAL} bug." >&2
  805. Wrap -d "restarting container of ${DARKYELLOW}$service_name${NORMAL} twice" <<EOF
  806. docker restart "$container_id"
  807. sleep 2
  808. docker restart "$container_id"
  809. EOF
  810. return $errlvl
  811. fi
  812. warn "Unknown issue with ${DARKYELLOW}$service_name${NORMAL}'s container:"
  813. echo " ${WHITE}cmd:${NORMAL} docker exec -ti $container_id echo" >&2
  814. echo "$out" | prefix " ${DARKGRAY}|${NORMAL} " >&2
  815. echo " ${DARKGRAY}..${NORMAL} leaving this as-is."
  816. return $errlvl
  817. }
  818. [ "$SOURCED" ] && return 0
  819. ##
  820. ## Command line processing
  821. ##
  822. cmdline.spec.gnu
  823. cmdline.spec.reporting
  824. cmdline.spec.gnu install
  825. cmdline.spec::cmd:install:run() {
  826. :
  827. }
  828. cmdline.spec.gnu get-type
  829. cmdline.spec::cmd:get-type:run() {
  830. vps:get-type
  831. }
  832. cmdline.spec:install:cmd:backup:run() {
  833. : :posarg: BACKUP_SERVER 'Target backup server'
  834. : :optfla: --ignore-domain-check \
  835. "Allow to bypass the domain check in
  836. compose file (only used in compose
  837. installation)."
  838. : :optfla: --ignore-ping-check "Allow to bypass the ping check of host."
  839. local vps_type
  840. vps_type=$(vps:get-type) || {
  841. err "Failed to get type of installation."
  842. return 1
  843. }
  844. if ! fn.exists "${vps_type}:install-backup"; then
  845. err "type '${vps_type}' has no backup installation implemented yet."
  846. return 1
  847. fi
  848. opts=()
  849. [ "$opt_ignore_ping_check" ] &&
  850. opts+=("--ignore-ping-check")
  851. if [ "$vps_type" == "compose" ]; then
  852. [ "$opt_ignore_domain_check" ] &&
  853. opts+=("--ignore-domain-check")
  854. fi
  855. "cmdline.spec:install:cmd:${vps_type}-backup:run" "${opts[@]}" "$BACKUP_SERVER"
  856. }
  857. DEFAULT_BACKUP_SERVICE_NAME=rsync-backup
  858. cmdline.spec.gnu compose-backup
  859. cmdline.spec:install:cmd:compose-backup:run() {
  860. : :posarg: BACKUP_SERVER 'Target backup server'
  861. : :optval: --service-name,-s "YAML service name in compose
  862. file to check for existence of key.
  863. Defaults to '$DEFAULT_BACKUP_SERVICE_NAME'"
  864. : :optval: --compose-file,-f "Compose file location. Defaults to
  865. the value of '\$DEFAULT_COMPOSE_FILE'"
  866. : :optfla: --ignore-domain-check \
  867. "Allow to bypass the domain check in
  868. compose file."
  869. : :optfla: --ignore-ping-check "Allow to bypass the ping check of host."
  870. local service_name compose_file
  871. [ -e "/etc/compose/local.conf" ] && source /etc/compose/local.conf
  872. compose_file=${opt_compose_file:-$DEFAULT_COMPOSE_FILE}
  873. service_name=${opt_service_name:-$DEFAULT_BACKUP_SERVICE_NAME}
  874. if ! [ -e "$compose_file" ]; then
  875. err "Compose file not found in '$compose_file'."
  876. return 1
  877. fi
  878. compose:install-backup "$BACKUP_SERVER" "$service_name" "$compose_file" \
  879. "$opt_ignore_ping_check" "$opt_ignore_domain_check"
  880. }
  881. cmdline.spec:install:cmd:mailcow-backup:run() {
  882. : :posarg: BACKUP_SERVER 'Target backup server'
  883. : :optfla: --ignore-ping-check "Allow to bypass the ping check of host."
  884. "mailcow:install-backup" "$BACKUP_SERVER" "$opt_ignore_ping_check"
  885. }
  886. cmdline.spec.gnu backup
  887. cmdline.spec::cmd:backup:run() {
  888. local vps_type
  889. vps_type=$(vps:get-type) || {
  890. err "Failed to get type of installation."
  891. return 1
  892. }
  893. if ! fn.exists "cmdline.spec:backup:cmd:${vps_type}:run"; then
  894. err "type '${vps_type}' has no backup process implemented yet."
  895. return 1
  896. fi
  897. "cmdline.spec:backup:cmd:${vps_type}:run"
  898. }
  899. cmdline.spec:backup:cmd:mailcow:run() {
  900. local cmd_line cron_line cmd
  901. for f in mysql-backup mirror-dir; do
  902. [ -e "/etc/cron.d/$f" ] || {
  903. err "Can't find '/etc/cron.d/$f'."
  904. echo " Have you forgotten to run 'vps install backup BACKUP_HOST' ?" >&2
  905. return 1
  906. }
  907. if ! cron_line=$(cat "/etc/cron.d/$f" |
  908. grep -v "^#" | grep "\* \* \*"); then
  909. err "Can't find cron_line in '/etc/cron.d/$f'." \
  910. "Have you modified it ?"
  911. return 1
  912. fi
  913. cron_line=${cron_line%|*}
  914. cmd_line=(${cron_line#*root})
  915. if [ "$f" == "mirror-dir" ]; then
  916. cmd=()
  917. for arg in "${cmd_line[@]}"; do
  918. [ "$arg" != "-q" ] && cmd+=("$arg")
  919. done
  920. else
  921. cmd=("${cmd_line[@]}")
  922. fi
  923. code="${cmd[*]}"
  924. echo "${WHITE}Launching:${NORMAL} ${code}"
  925. {
  926. {
  927. (
  928. ## Some commands are using colors that are already
  929. ## set by this current program and will trickle
  930. ## down unwantedly
  931. ansi_color no
  932. eval "${code}"
  933. ) | sed -r "s/^/ ${GRAY}|${NORMAL} /g"
  934. set_errlvl "${PIPESTATUS[0]}"
  935. } 3>&1 1>&2 2>&3 | sed -r "s/^/ $DARKRED\!$NORMAL /g"
  936. set_errlvl "${PIPESTATUS[0]}"
  937. } 3>&1 1>&2 2>&3
  938. if [ "$?" != "0" ]; then
  939. err "Failed."
  940. return 1
  941. fi
  942. done
  943. info "Mysql backup and subsequent mirror-dir ${DARKGREEN}succeeded${NORMAL}."
  944. }
  945. set_errlvl() { return "${1:-1}"; }
  946. cmdline.spec:backup:cmd:compose:run() {
  947. local cron_line args
  948. project_name=$(compose:project_name) || return 1
  949. docker_cmd=$(compose:get_cron_docker_cmd) || return 1
  950. echo "${WHITE}Launching:${NORMAL} docker exec -i "${project_name}_cron_1" $docker_cmd"
  951. {
  952. {
  953. eval "docker exec -i \"${project_name}_cron_1\" $docker_cmd" | sed -r "s/^/ ${GRAY}|${NORMAL} /g"
  954. set_errlvl "${PIPESTATUS[0]}"
  955. } 3>&1 1>&2 2>&3 | sed -r "s/^/ $DARKRED\!$NORMAL /g"
  956. set_errlvl "${PIPESTATUS[0]}"
  957. } 3>&1 1>&2 2>&3
  958. if [ "$?" != "0" ]; then
  959. err "Failed."
  960. return 1
  961. fi
  962. info "mirror-dir ${DARKGREEN}succeeded${NORMAL}."
  963. }
  964. cmdline.spec.gnu recover-target
  965. cmdline.spec::cmd:recover-target:run() {
  966. : :posarg: BACKUP_DIR 'Source directory on backup side'
  967. : :posarg: HOST_DIR 'Target directory on host side'
  968. : :optval: --backup-host,-B "The backup host"
  969. : :optfla: --dry-run,-n "Don't do anything, instead tell what it
  970. would do."
  971. ## if no backup host take the one by default
  972. backup_host="$opt_backup_host"
  973. if [ -z "$backup_host" ]; then
  974. backup_host_ident=$(backup-action get_default_backup_host_ident) || return 1
  975. read -r backup_host ident <<<"$backup_host_ident"
  976. fi
  977. if [[ "$BACKUP_DIR" == /* ]]; then
  978. err "BACKUP_DIR must be a relative path from the root of your backup."
  979. return 1
  980. fi
  981. REAL_HOST_DIR=$(realpath "$HOST_DIR") || {
  982. err "Can't find HOST_DIR '$HOST_DIR'."
  983. return 1
  984. }
  985. export DRY_RUN="${opt_dry_run}"
  986. backup-action recover-target "$backup_host" "$ident" "$BACKUP_DIR" "$REAL_HOST_DIR"
  987. }
  988. cmdline.spec.gnu odoo
  989. cmdline.spec::cmd:odoo:run() {
  990. :
  991. }
  992. cmdline.spec.gnu restart
  993. cmdline.spec:odoo:cmd:restart:run() {
  994. : :optval: --service,-s "The service (defaults to 'odoo')"
  995. local out odoo_service
  996. odoo_service="${opt_service:-odoo}"
  997. project_name=$(compose:project_name) || return 1
  998. if ! out=$(docker restart "${project_name}_${odoo_service}_1" 2>&1); then
  999. if [[ "$out" == *"no matching entries in passwd file" ]]; then
  1000. warn "Catched docker bug. Restarting once more."
  1001. if ! out=$(docker restart "${project_name}_${odoo_service}_1"); then
  1002. err "Can't restart container ${project_name}_${odoo_service}_1 (restarted twice)."
  1003. echo " output:" >&2
  1004. echo "$out" | prefix " ${GRAY}|${NORMAL} " >&2
  1005. exit 1
  1006. fi
  1007. else
  1008. err "Couldn't restart container ${project_name}_${odoo_service}_1 (and no restart bug detected)."
  1009. exit 1
  1010. fi
  1011. fi
  1012. info "Container ${project_name}_${odoo_service}_1 was ${DARKGREEN}successfully${NORMAL} restarted."
  1013. }
  1014. cmdline.spec.gnu restore
  1015. cmdline.spec:odoo:cmd:restore:run() {
  1016. : :posarg: ZIP_DUMP_LOCATION 'Source odoo dump file to restore
  1017. (can be a local file or an url)'
  1018. : :optval: --service,-s "The service (defaults to 'odoo')"
  1019. : :optval: --database,-d 'Target database (default if not specified)'
  1020. local out
  1021. odoo_service="${opt_service:-odoo}"
  1022. if [[ "$ZIP_DUMP_LOCATION" == "http://"* ]] ||
  1023. [[ "$ZIP_DUMP_LOCATION" == "https://"* ]]; then
  1024. settmpdir ZIP_TMP_LOCATION
  1025. tmp_location="$ZIP_TMP_LOCATION/dump.zip"
  1026. curl -k -s -L "$ZIP_DUMP_LOCATION" > "$tmp_location" || {
  1027. err "Couldn't get '$ZIP_DUMP_LOCATION'."
  1028. exit 1
  1029. }
  1030. if [[ "$(dd if="$tmp_location" count=2 bs=1 2>/dev/null)" != "PK" ]]; then
  1031. err "Download doesn't seem to be a zip file."
  1032. dd if="$tmp_location" count=1 bs=256 | hd | prefix " ${GRAY}|${NORMAL} " >&2
  1033. exit 1
  1034. fi
  1035. info "Successfully downloaded '$ZIP_DUMP_LOCATION'"
  1036. echo " in '$tmp_location'." >&2
  1037. ZIP_DUMP_LOCATION="$tmp_location"
  1038. fi
  1039. [ -e "$ZIP_DUMP_LOCATION" ] || {
  1040. err "No file '$ZIP_DUMP_LOCATION' found." >&2
  1041. exit 1
  1042. }
  1043. #cmdline.spec:odoo:cmd:restart:run --service "$odoo_service" || exit 1
  1044. msg_dbname=default
  1045. [ -n "$opt_database" ] && msg_dbname="'$opt_database'"
  1046. compose --no-hooks drop "$odoo_service" $opt_database || {
  1047. err "Error dropping $msg_dbname database of service ${DARKYELLOW}$odoo_service${NORMAL}."
  1048. exit 1
  1049. }
  1050. compose --no-hooks load "$odoo_service" $opt_database < "$ZIP_DUMP_LOCATION" || {
  1051. err "Error restoring service ${DARKYELLOW}$odoo_service${NORMAL} to $msg_dbname database."
  1052. exit 1
  1053. }
  1054. info "Successfully restored ${DARKYELLOW}$odoo_service${NORMAL} to $msg_dbname database."
  1055. ## Restart odoo, ensure there is no bugs lingering on it.
  1056. cmdline.spec:odoo:cmd:restart:run --service "$odoo_service" || exit 1
  1057. }
  1058. cmdline.spec.gnu dump
  1059. cmdline.spec:odoo:cmd:dump:run() {
  1060. : :posarg: DUMP_ZIPFILE 'Target path to store odoo dump zip file.'
  1061. : :optval: --database,-d 'Target database (default if not specified)'
  1062. : :optval: --service,-s "The service (defaults to 'odoo')"
  1063. odoo_service="${opt_service:-odoo}"
  1064. msg_dbname=default
  1065. [ -n "$opt_database" ] && msg_dbname="'$opt_database'"
  1066. compose --no-hooks save "$odoo_service" $opt_database > "$DUMP_ZIPFILE" || {
  1067. err "Error dumping ${DARKYELLOW}$odoo_service${NORMAL}'s $msg_dbname database to '$DUMP_ZIPFILE'."
  1068. exit 1
  1069. }
  1070. info "Successfully dumped ${DARKYELLOW}$odoo_service${NORMAL}'s $msg_dbname database to '$DUMP_ZIPFILE'."
  1071. }
  1072. cmdline.spec.gnu drop
  1073. cmdline.spec:odoo:cmd:drop:run() {
  1074. : :optval: --database,-d 'Target database (default if not specified)'
  1075. : :optval: --service,-s "The service (defaults to 'odoo')"
  1076. odoo_service="${opt_service:-odoo}"
  1077. msg_dbname=default
  1078. [ -n "$opt_database" ] && msg_dbname="'$opt_database'"
  1079. compose --no-hooks drop "$odoo_service" $opt_database || {
  1080. err "Error dropping ${DARKYELLOW}$odoo_service${NORMAL}'s $msg_dbname database."
  1081. exit 1
  1082. }
  1083. info "Successfully dropped ${DARKYELLOW}$odoo_service${NORMAL}'s $msg_dbname database."
  1084. }
  1085. cmdline.spec.gnu set-cyclos-url
  1086. cmdline.spec:odoo:cmd:set-cyclos-url:run() {
  1087. : :optval: --database,-d "Target database ('odoo' if not specified)"
  1088. : :optval: --service,-s "The cyclos service name (defaults to 'cyclos')"
  1089. local URL
  1090. dbname=${opt_database:-odoo}
  1091. cyclos_service="${opt_service:-cyclos}"
  1092. project_name=$(compose:project_name) || exit 1
  1093. URL=$(compose:get_url "${project_name}" "${cyclos_service}") || exit 1
  1094. Wrap -d "set cyclos url to '$URL'" <<EOF || exit 1
  1095. echo "UPDATE res_company SET cyclos_server_url = '$URL/api' WHERE id=1;" |
  1096. compose:psql "$project_name" "$dbname" || {
  1097. err "Failed to set cyclos url value in '$dbname' database."
  1098. exit 1
  1099. }
  1100. EOF
  1101. }
  1102. cmdline.spec.gnu fix-sso
  1103. cmdline.spec:odoo:cmd:fix-sso:run() {
  1104. : :optval: --database,-d "Target database ('odoo' if not specified)"
  1105. local public_user_id project_name dbname
  1106. dbname=${opt_database:-odoo}
  1107. project_name=$(compose:project_name) || exit 1
  1108. public_user_id=$(odoo:get_public_user_id "${project_name}" "${dbname}") || exit 1
  1109. Wrap -d "fix website's object to 'public_user' (id=$public_user_id)" <<EOF || exit 1
  1110. echo "UPDATE website SET user_id = $public_user_id;" |
  1111. compose:psql "$project_name" "$dbname" || {
  1112. err "Failed to set website's object user_id to public user's id ($public_user_id) in '$dbname' database."
  1113. exit 1
  1114. }
  1115. EOF
  1116. }
  1117. cmdline.spec.gnu cyclos
  1118. cmdline.spec::cmd:cyclos:run() {
  1119. :
  1120. }
  1121. cmdline.spec:cyclos:cmd:dump:run() {
  1122. : :posarg: DUMP_GZFILE 'Target path to store odoo dump gz file.'
  1123. : :optval: --database,-d "Target database ('cyclos' if not specified)"
  1124. : :optval: --service,-s "The cyclos service name (defaults to 'cyclos')"
  1125. cyclos_service="${opt_service:-cyclos}"
  1126. cyclos_database="${opt_database:-cyclos}"
  1127. project_name=$(compose:project_name) || exit 1
  1128. container_id=$(compose:service:container_one "$project_name" "${cyclos_service}") || exit 1
  1129. Wrap -d "stop ${DARKYELLOW}${cyclos_service}${NORMAL}'s container" -- \
  1130. docker stop "$container_id" || exit 1
  1131. Wrap -d "Dump postgres database '${cyclos_database}'." -- \
  1132. postgres:dump "${project_name}" "$cyclos_database" "$DUMP_GZFILE" || exit 1
  1133. Wrap -d "start ${DARKYELLOW}${cyclos_service}${NORMAL}'s container" -- \
  1134. docker start "${container_id}" || exit 1
  1135. }
  1136. cmdline.spec.gnu restore
  1137. cmdline.spec:cyclos:cmd:restore:run() {
  1138. : :posarg: GZ_DUMP_LOCATION 'Source cyclos dump file to restore
  1139. (can be a local file or an url)'
  1140. : :optval: --service,-s "The service (defaults to 'cyclos')"
  1141. : :optval: --database,-d 'Target database (default if not specified)'
  1142. local out
  1143. cyclos_service="${opt_service:-cyclos}"
  1144. cyclos_database="${opt_database:-cyclos}"
  1145. project_name=$(compose:project_name) || exit 1
  1146. url=$(compose:get_url "${project_name}" "${cyclos_service}") || return 1
  1147. container_id=$(compose:service:container_one "$project_name" "${cyclos_service}") || exit 1
  1148. if [[ "$GZ_DUMP_LOCATION" == "http://"* ]] ||
  1149. [[ "$GZ_DUMP_LOCATION" == "https://"* ]]; then
  1150. settmpdir GZ_TMP_LOCATION
  1151. tmp_location="$GZ_TMP_LOCATION/dump.gz"
  1152. Wrap -d "get '$GZ_DUMP_LOCATION'" <<EOF || exit 1
  1153. ## Note that curll version before 7.76.0 do not have
  1154. curl -k -s -L "$GZ_DUMP_LOCATION" --fail \\
  1155. > "$tmp_location" || {
  1156. echo "Error fetching ressource. Is url correct ?" >&2
  1157. exit 1
  1158. }
  1159. if [[ "\$(dd if="$tmp_location" count=2 bs=1 2>/dev/null |
  1160. hexdump -v -e "/1 \"%02x\"")" != "1f8b" ]]; then
  1161. err "Download doesn't seem to be a gzip file."
  1162. dd if="$tmp_location" count=1 bs=256 | hd | prefix " ${GRAY}|${NORMAL} " >&2
  1163. exit 1
  1164. fi
  1165. EOF
  1166. GZ_DUMP_LOCATION="$tmp_location"
  1167. fi
  1168. [ -e "$GZ_DUMP_LOCATION" ] || {
  1169. err "No file '$GZ_DUMP_LOCATION' found." >&2
  1170. exit 1
  1171. }
  1172. Wrap -d "stop ${DARKYELLOW}${cyclos_service}${NORMAL}'s container" -- \
  1173. docker stop "$container_id" || exit 1
  1174. ## XXXvlab: making the assumption that the postgres username should
  1175. ## be the same as the cyclos service selected (which is the default,
  1176. ## but not always the case).
  1177. Wrap -d "restore postgres database '${cyclos_database}'." -- \
  1178. postgres:restore "$project_name" "$GZ_DUMP_LOCATION" "${cyclos_service}@${cyclos_database}" || exit 1
  1179. ## ensure that the database is not locked
  1180. Wrap -d "check and remove database lock if any" -- \
  1181. cyclos:unlock "${project_name}" "${cyclos_database}" || exit 1
  1182. Wrap -d "set root url to '$url'" -- \
  1183. cyclos:set_root_url "${project_name}" "${cyclos_database}" "${url}" || exit 1
  1184. Wrap -d "start ${DARKYELLOW}${cyclos_service}${NORMAL}'s container" -- \
  1185. docker start "${container_id}" || exit 1
  1186. }
  1187. cmdline.spec.gnu set-root-url
  1188. cmdline.spec:cyclos:cmd:set-root-url:run() {
  1189. : :optval: --database,-d "Target database ('cyclos' if not specified)"
  1190. : :optval: --service,-s "The cyclos service name (defaults to 'cyclos')"
  1191. local URL
  1192. cyclos_database=${opt_database:-cyclos}
  1193. cyclos_service="${opt_service:-cyclos}"
  1194. project_name=$(compose:project_name) || exit 1
  1195. url=$(compose:get_url "${project_name}" "${cyclos_service}") || exit 1
  1196. container_id=$(compose:service:container_one "${project_name}" "${cyclos_service}") || exit 1
  1197. Wrap -d "stop ${DARKYELLOW}${cyclos_service}${NORMAL}'s container" -- \
  1198. docker stop "$container_id" || exit 1
  1199. Wrap -d "set root url to '$url'" -- \
  1200. cyclos:set_root_url "${project_name}" "${cyclos_database}" "${url}" || exit 1
  1201. Wrap -d "start ${DARKYELLOW}${cyclos_service}${NORMAL}'s container" -- \
  1202. docker start "${container_id}" || exit 1
  1203. }
  1204. cmdline.spec.gnu unlock
  1205. cmdline.spec:cyclos:cmd:unlock:run() {
  1206. : :optval: --database,-d "Target database ('cyclos' if not specified)"
  1207. : :optval: --service,-s "The cyclos service name (defaults to 'cyclos')"
  1208. local URL
  1209. cyclos_database=${opt_database:-cyclos}
  1210. cyclos_service="${opt_service:-cyclos}"
  1211. project_name=$(compose:project_name) || exit 1
  1212. container_id=$(compose:service:container_one "${project_name}" "${cyclos_service}") || exit 1
  1213. Wrap -d "stop ${DARKYELLOW}${cyclos_service}${NORMAL}'s container" -- \
  1214. docker stop "$container_id" || exit 1
  1215. Wrap -d "check and remove database lock if any" -- \
  1216. cyclos:unlock "${project_name}" "${cyclos_database}" || exit 1
  1217. Wrap -d "start ${DARKYELLOW}${cyclos_service}${NORMAL}'s container" -- \
  1218. docker start "${container_id}" || exit 1
  1219. }
  1220. cmdline.spec.gnu rocketchat
  1221. cmdline.spec::cmd:rocketchat:run() {
  1222. :
  1223. }
  1224. cmdline.spec.gnu drop-indexes
  1225. cmdline.spec:rocketchat:cmd:drop-indexes:run() {
  1226. : :optval: --database,-d "Target database ('rocketchat' if not specified)"
  1227. : :optval: --service,-s "The rocketchat service name (defaults to 'rocketchat')"
  1228. local URL
  1229. rocketchat_database=${opt_database:-rocketchat}
  1230. rocketchat_service="${opt_service:-rocketchat}"
  1231. project_name=$(compose:project_name) || exit 1
  1232. container_id=$(compose:service:container_one "${project_name}" "${rocketchat_service}") || exit 1
  1233. Wrap -d "stop ${DARKYELLOW}${rocketchat_service}${NORMAL}'s container" -- \
  1234. docker stop "$container_id" || exit 1
  1235. errlvl=0
  1236. Wrap -d "drop indexes" -- \
  1237. rocketchat:drop-indexes "${project_name}" "${rocketchat_database}" || {
  1238. errlvl=1
  1239. errmsg="Failed to drop indexes"
  1240. }
  1241. Wrap -d "start ${DARKYELLOW}${rocketchat_service}${NORMAL}'s container" -- \
  1242. docker start "${container_id}" || exit 1
  1243. if [ "$errlvl" != 0 ]; then
  1244. err "$errmsg"
  1245. fi
  1246. exit "$errlvl"
  1247. }
  1248. cmdline.spec.gnu nextcloud
  1249. cmdline.spec::cmd:nextcloud:run() {
  1250. :
  1251. }
  1252. cmdline.spec.gnu upgrade
  1253. cmdline.spec:nextcloud:cmd:upgrade:run() {
  1254. : :posarg: [TARGET_VERSION] "Source cyclos dump file to restore"
  1255. : :optval: --service,-s "The nexcloud service name (defaults to 'nextcloud')"
  1256. local URL
  1257. nextcloud_service="${opt_service:-nextcloud}"
  1258. project_name=$(compose:project_name) || exit 1
  1259. containers=$(compose:service:containers "${project_name}" "${nextcloud_service}") || exit 1
  1260. container_stopped=()
  1261. if [ -n "$containers" ]; then
  1262. for container in $containers; do
  1263. Wrap -d "stop ${DARKYELLOW}${nextcloud_service}${NORMAL}'s container" -- \
  1264. docker stop "$container" || {
  1265. err "Failed to stop container '$container'."
  1266. exit 1
  1267. }
  1268. container_stopped+=("$container")
  1269. done
  1270. fi
  1271. before_version=$(nextcloud:src:version) || exit 1
  1272. ## -q to remove the display of ``compose`` related information
  1273. ## like relation resolution.
  1274. ## --no-hint to remove the final hint about modifying your
  1275. ## ``compose.yml``.
  1276. compose -q upgrade "$nextcloud_service" --no-hint
  1277. errlvl="$?"
  1278. after_version=$(nextcloud:src:version)
  1279. if [ "$after_version" != "$before_version" ]; then
  1280. desc="update \`compose.yml\` to set ${DARKYELLOW}$nextcloud_service${NORMAL}'s "
  1281. desc+="docker image to actual code version ${WHITE}${after_version}${NORMAL}"
  1282. Wrap -d "$desc" -- \
  1283. compose:file:value-change \
  1284. "${nextcloud_service}.docker-compose.image" \
  1285. "docker.0k.io/nextcloud:${after_version}-myc" || exit 1
  1286. fi
  1287. if [ "$errlvl" == 0 ]; then
  1288. echo "${WHITE}Launching final compose${NORMAL}"
  1289. compose up || exit 1
  1290. fi
  1291. exit "$errlvl"
  1292. }
  1293. cmdline.spec.gnu check-fix
  1294. cmdline.spec::cmd:check-fix:run() {
  1295. : :posarg: [SERVICES...] "Optional service to check"
  1296. : :optval: --check,-c "Specify a check or a list of checks separated by commas"
  1297. : :optfla: --silent,-s "Don't ouput anything if everything goes well"
  1298. local project_name service_name containers container check
  1299. all_checks=$(declare -F |
  1300. egrep '^declare -fx? container:health:check-fix:[^ ]+$' |
  1301. cut -f 4 -d ":")
  1302. checks=(${opt_check//,/ })
  1303. for check in "${checks[@]}"; do
  1304. fn.exists container:health:check-fix:$check || {
  1305. err "check '$check' not found."
  1306. return 1
  1307. }
  1308. done
  1309. if [ "${#checks[*]}" == 0 ]; then
  1310. checks=($all_checks)
  1311. fi
  1312. ## XXXvlab: could make it parallel
  1313. project_name=$(compose:project_name) || exit 1
  1314. containers=($(compose:project:containers "${project_name}")) || exit 1
  1315. found=
  1316. for container in "${containers[@]}"; do
  1317. service_name=$(docker ps --filter id="$container" --format '{{.Label "com.docker.compose.service"}}')
  1318. if [ "${#SERVICES[@]}" -gt 0 ]; then
  1319. [[ " ${SERVICES[*]} " == *" $service_name "* ]] || continue
  1320. fi
  1321. found=1
  1322. one_bad=
  1323. for check in "${checks[@]}"; do
  1324. if ! container:health:check-fix:"$check" "$container"; then
  1325. one_bad=1
  1326. fi
  1327. done
  1328. if [ -z "$opt_silent" ] && [ -z "$one_bad" ]; then
  1329. Elt "containers have been checked for ${DARKYELLOW}$service_name${NORMAL}"
  1330. Feedback
  1331. fi
  1332. done
  1333. if [ -z "$found" ]; then
  1334. if [ -z "$opt_silent" ]; then
  1335. if [ "${#SERVICES[@]}" -gt 0 ]; then
  1336. warn "No container for given services found in current project '$project_name'."
  1337. else
  1338. warn "No container found for current project '$project_name'."
  1339. fi
  1340. fi
  1341. return 1
  1342. fi
  1343. }
  1344. cmdline::parse "$@"