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.

2230 lines
67 KiB

  1. #!/bin/bash
  2. . /etc/shlib >/dev/null 2>&1 || {
  3. echo "Error: you don't have kal-shlib-core installed."
  4. echo ""
  5. echo " You might want to add `deb.kalysto.org` deb repository, you'll need root access,"
  6. echo " so you might want to run these command after a \`sudo -i\` for instance..."
  7. echo ""
  8. echo " echo deb https://deb.kalysto.org no-dist kal-alpha kal-beta kal-main \\"
  9. echo " > /etc/apt/sources.list.d/kalysto.org.list"
  10. echo " wget -O - https://deb.kalysto.org/conf/public-key.gpg | apt-key add -"
  11. echo " apt-get update -o Dir::Etc::sourcelist=sources.list.d/kalysto.org.list \\"
  12. echo " -o Dir::Etc::sourceparts=- -o APT::Get::List-Cleanup=0"
  13. echo ""
  14. echo " Then install package kal-shlib-*:"
  15. echo ""
  16. echo " apt install kal-shlib-{common,cmdline,config,cache,docker,pretty}"
  17. echo ""
  18. exit 1
  19. } >&2
  20. include common
  21. include parse
  22. include cmdline
  23. include config
  24. include cache
  25. include fn
  26. include docker
  27. [[ "${BASH_SOURCE[0]}" != "${0}" ]] && SOURCED=true
  28. version=0.1
  29. desc='Install backup'
  30. help=""
  31. version_gt() { test "$(printf '%s\n' "$@" | sort -V | head -n 1)" != "$1"; }
  32. docker:running-container-projects() {
  33. :cache: scope=session
  34. docker ps --format '{{.Label "com.docker.compose.project"}}' | sort | uniq
  35. }
  36. decorator._mangle_fn docker:running-container-projects
  37. ssh:mk-private-key() {
  38. local host="$1" service_name="$2"
  39. (
  40. settmpdir VPS_TMPDIR
  41. ssh-keygen -t rsa -N "" -f "$VPS_TMPDIR/rsync_rsa" -C "$service_name@$host" >/dev/null
  42. cat "$VPS_TMPDIR/rsync_rsa"
  43. )
  44. }
  45. mailcow:has-images-running() {
  46. local images
  47. images=$(docker ps --format '{{.Image}}' | sort | uniq)
  48. [[ $'\n'"$images" == *$'\n'"mailcow/"* ]]
  49. }
  50. mailcow:has-container-project-mentionning-mailcow() {
  51. local projects
  52. projects=$(docker:running-container-projects) || return 1
  53. [[ $'\n'"$projects"$'\n' == *mailcow* ]]
  54. }
  55. mailcow:has-running-containers() {
  56. mailcow:has-images-running ||
  57. mailcow:has-container-project-mentionning-mailcow
  58. }
  59. mailcow:get-root() {
  60. :cache: scope=session
  61. local dir
  62. for dir in {/opt{,/apps},/root}/mailcow-dockerized; do
  63. [ -d "$dir" ] || continue
  64. [ -r "$dir/mailcow.conf" ] || continue
  65. echo "$dir"
  66. return 0
  67. done
  68. return 1
  69. }
  70. decorator._mangle_fn mailcow:get-root
  71. compose:get-compose-yml() {
  72. :cache: scope=session
  73. local path
  74. path=$(DEBUG=1 DRY_RUN=1 compose 2>&1 | egrep '^\s+-e HOST_COMPOSE_YML_FILE=' | cut -f 2- -d "=" | cut -f 1 -d " ")
  75. [ -e "$path" ] || return 1
  76. echo "$path"
  77. }
  78. decorator._mangle_fn compose:get-compose-yml
  79. export -f compose:get-compose-yml
  80. compose:has-container-project-myc() {
  81. local projects
  82. projects=$(docker:running-container-projects) || return 1
  83. [[ $'\n'"$projects"$'\n' == *$'\n'"myc"$'\n'* ]]
  84. }
  85. compose:file:value-change() {
  86. local key="$1" value="$2"
  87. local compose_yml
  88. if ! compose_yml=$(compose:get-compose-yml); then
  89. err "Couldn't locate your 'compose.yml' file."
  90. return 1
  91. fi
  92. yaml:file:value-change "$compose_yml" "$key" "$value" || return 1
  93. }
  94. export -f compose:file:value-change
  95. yaml:file:value-change() {
  96. local file="$1" key="$2" value="$3" first=1 count=0 diff=""
  97. (
  98. cd "${file%/*}"
  99. while read-0 hunk; do
  100. if [ -n "$first" ]; then
  101. diff+="$hunk"
  102. first=
  103. continue
  104. fi
  105. if [[ "$hunk" =~ $'\n'"+"[[:space:]]+"${key##*.}:" ]]; then
  106. ((count++))
  107. diff+="$hunk" >&2
  108. else
  109. :
  110. # echo "discarding:" >&2
  111. # e "$hunk" | prefix " | " >&2
  112. fi
  113. done < <(
  114. export DEBUG=
  115. settmpdir YQ_TEMP
  116. cp "${file}" "$YQ_TEMP/compose.yml" &&
  117. yq -i ".${key} = \"${value}\"" "$YQ_TEMP/compose.yml" &&
  118. sed -ri 's/^([^# ])/\n\0/g' "$YQ_TEMP/compose.yml" &&
  119. diff -u0 -Z "${file}" "$YQ_TEMP/compose.yml" |
  120. sed -r "s/^(@@.*)$/\x00\1/g;s%^(\+\+\+) [^\t]+%\1 ${file}%g"
  121. printf "\0"
  122. )
  123. if [[ "$count" == 0 ]]; then
  124. err "No change made to '$file'."
  125. return 1
  126. fi
  127. if [[ "$count" != 1 ]]; then
  128. err "compose file change request seems dubious and was refused:"
  129. e "$diff" | prefix " | " >&2
  130. return 1
  131. fi
  132. echo Applying: >&2
  133. e "$diff" | prefix " | " >&2
  134. patch <<<"$diff"
  135. ) || exit 1
  136. }
  137. export -f yaml:file:value-change
  138. type:is-mailcow() {
  139. mailcow:get-root >/dev/null ||
  140. mailcow:has-running-containers
  141. }
  142. type:is-compose() {
  143. compose:get-compose-yml >/dev/null &&
  144. compose:has-container-project-myc
  145. }
  146. vps:get-type() {
  147. :cache: scope=session
  148. local fn
  149. for fn in $(declare -F | cut -f 3 -d " " | egrep "^type:is-"); do
  150. "$fn" && {
  151. echo "${fn#type:is-}"
  152. return 0
  153. }
  154. done
  155. return 1
  156. }
  157. decorator._mangle_fn vps:get-type
  158. mirror-dir:sources() {
  159. :cache: scope=session
  160. if ! shyaml get-values default.sources < /etc/mirror-dir/config.yml; then
  161. err "Couldn't query 'default.sources' in '/etc/mirror-dir/config.yml'."
  162. return 1
  163. fi
  164. }
  165. decorator._mangle_fn mirror-dir:sources
  166. mirror-dir:check-add() {
  167. local elt="$1" sources
  168. sources=$(mirror-dir:sources) || return 1
  169. if [[ $'\n'"$sources"$'\n' == *$'\n'"$elt"$'\n'* ]]; then
  170. info "Volume $elt already in sources"
  171. else
  172. Elt "Adding directory $elt"
  173. sed -i "/sources:/a\ - \"${elt}\"" \
  174. /etc/mirror-dir/config.yml
  175. Feedback || return 1
  176. fi
  177. }
  178. mirror-dir:check-add-vol() {
  179. local elt="$1"
  180. mirror-dir:check-add "/var/lib/docker/volumes/*_${elt}-*/_data"
  181. }
  182. ## The first colon is to prevent auto-export of function from shlib
  183. : ; bash-bug-5() { { cat; } < <(e) >/dev/null; ! cat "$1"; } && bash-bug-5 <(e) 2>/dev/null &&
  184. export BASH_BUG_5=1 && unset -f bash_bug_5
  185. wrap() {
  186. local label="$1" code="$2"
  187. shift 2
  188. export VERBOSE=1
  189. interpreter=/bin/bash
  190. if [ -n "$BASH_BUG_5" ]; then
  191. (
  192. settmpdir tmpdir
  193. fname=${label##*/}
  194. e "$code" > "$tmpdir/$fname" &&
  195. chmod +x "$tmpdir/$fname" &&
  196. Wrap -vsd "$label" -- "$interpreter" "$tmpdir/$fname" "$@"
  197. )
  198. else
  199. Wrap -vsd "$label" -- "$interpreter" <(e "$code") "$@"
  200. fi
  201. }
  202. ping_check() {
  203. #global ignore_ping_check
  204. local host="$1"
  205. ip=$(getent ahosts "$host" | egrep "^[0-9]+\.[0-9]+\.[0-9]+\.[0-9]+\s+" |
  206. head -n 1 | cut -f 1 -d " ") || return 1
  207. my_ip=$(curl -s myip.kal.fr)
  208. if [ "$ip" != "$my_ip" ]; then
  209. if [ -n "$ignore_ping_check" ]; then
  210. warn "IP of '$host' ($ip) doesn't match mine ($my_ip). Ignoring due to ``--ignore-ping-check`` option."
  211. else
  212. err "IP of '$host' ($ip) doesn't match mine ($my_ip). Use ``--ignore-ping-check`` to ignore check."
  213. return 1
  214. fi
  215. fi
  216. }
  217. mailcow:install-backup() {
  218. local BACKUP_SERVER="$1" ignore_ping_check="$2" mailcow_root DOMAIN
  219. ## find installation
  220. mailcow_root=$(mailcow:get-root) || {
  221. err "Couldn't find a valid mailcow root directory."
  222. return 1
  223. }
  224. ## check ok
  225. DOMAIN=$(cat "$mailcow_root/.env" | grep ^MAILCOW_HOSTNAME= | cut -f 2 -d =) || {
  226. err "Couldn't find MAILCOW_HOSTNAME in file \"$mailcow_root/.env\"."
  227. return 1
  228. }
  229. ping_check "$DOMAIN" || return 1
  230. MYSQL_ROOT_PASSWORD=$(cat "$mailcow_root/.env" | grep ^DBROOT= | cut -f 2 -d =) || {
  231. err "Couldn't find DBROOT in file \"$mailcow_root/.env\"."
  232. return 1
  233. }
  234. if docker compose >/dev/null 2>&1; then
  235. MYSQL_CONTAINER=${MYSQL_CONTAINER:-mailcowdockerized-mysql-mailcow-1}
  236. else
  237. MYSQL_CONTAINER=${MYSQL_CONTAINER:-mailcowdockerized_mysql-mailcow_1}
  238. fi
  239. container_id=$(docker ps -f name="$MYSQL_CONTAINER" --format "{{.ID}}")
  240. if [ -z "$container_id" ]; then
  241. err "Couldn't find docker container named '$MYSQL_CONTAINER'."
  242. return 1
  243. fi
  244. export KEY_BACKUP_ID="mailcow"
  245. export MYSQL_ROOT_PASSWORD
  246. export MYSQL_CONTAINER
  247. export BACKUP_SERVER
  248. export DOMAIN
  249. wrap "Install rsync-backup on host" "
  250. cd /srv/charm-store/rsync-backup
  251. bash ./hooks/install.d/60-install.sh
  252. " || return 1
  253. wrap "Mysql dump install" "
  254. cd /srv/charm-store/mariadb
  255. bash ./hooks/install.d/60-backup.sh
  256. " || return 1
  257. ## Using https://github.com/mailcow/mailcow-dockerized/blob/master/helper-scripts/backup_and_restore.sh
  258. for elt in "vmail{,-attachments-vol}" crypt redis rspamd postfix; do
  259. mirror-dir:check-add-vol "$elt" || return 1
  260. done
  261. mirror-dir:check-add "$mailcow_root" || return 1
  262. mirror-dir:check-add "/var/backups/mysql" || return 1
  263. mirror-dir:check-add "/etc" || return 1
  264. dest="$BACKUP_SERVER"
  265. dest="${dest%/*}"
  266. ssh_options=()
  267. if [[ "$dest" == *":"* ]]; then
  268. port="${dest##*:}"
  269. dest="${dest%%:*}"
  270. ssh_options=(-p "$port")
  271. else
  272. port=""
  273. dest="${dest%%:*}"
  274. fi
  275. info "You can run this following command from an host having admin access to $dest:"
  276. echo " (Or send it to a backup admin of $dest)" >&2
  277. echo "ssh ${ssh_options[@]} myadmin@$dest ssh-key add '$(cat /var/lib/rsync/.ssh/id_rsa.pub)'"
  278. }
  279. compose:has_domain() {
  280. local compose_file="$1" host="$2" name conf relation relation_value domain server_aliases
  281. while read-0 name conf ; do
  282. name=$(e "$name" | shyaml get-value)
  283. if [[ "$name" =~ ^[a-zA-Z0-9-]+\.[a-zA-Z0-9-]+ ]]; then
  284. [ "$host" == "$name" ] && return 0
  285. fi
  286. rel=$(e "$conf" | shyaml -y get-value relations 2>/dev/null) || continue
  287. for relation in web-proxy publish-dir; do
  288. relation_value=$(e "$rel" | shyaml -y get-value "$relation" 2>/dev/null) || continue
  289. while read-0 label conf_relation; do
  290. domain=$(e "$conf_relation" | shyaml get-value "domain" 2>/dev/null) && {
  291. [ "$host" == "$domain" ] && return 0
  292. }
  293. server_aliases=$(e "$conf_relation" | shyaml get-values "server-aliases" 2>/dev/null) && {
  294. [[ $'\n'"$server_aliases" == *$'\n'"$host"$'\n'* ]] && return 0
  295. }
  296. done < <(e "$relation_value" | shyaml -y key-values-0)
  297. done
  298. done < <(shyaml -y key-values-0 < "$compose_file")
  299. return 1
  300. }
  301. compose:install-backup() {
  302. local BACKUP_SERVER="$1" service_name="$2" compose_file="$3" ignore_ping_check="$4" ignore_domain_check="$5"
  303. ## XXXvlab: far from perfect as it mimics and depends internal
  304. ## logic of current default way to get a domain in compose-core
  305. host=$(hostname)
  306. if ! compose:has_domain "$compose_file" "$host"; then
  307. if [ -n "$ignore_domain_check" ]; then
  308. warn "domain of '$host' not found in compose file '$compose_file'. Ignoring due to ``--ignore-domain-check`` option."
  309. else
  310. err "domain of '$host' not found in compose file '$compose_file'. Use ``--ignore-domain-check`` to ignore check."
  311. return 1
  312. fi
  313. fi
  314. ping_check "$host" || return 1
  315. if [ -e "/root/.ssh/rsync_rsa" ]; then
  316. warn "deleting private key in /root/.ssh/rsync_rsa, has we are not using it anymore."
  317. rm -fv /root/.ssh/rsync_rsa
  318. fi
  319. if [ -e "/root/.ssh/rsync_rsa.pub" ]; then
  320. warn "deleting public key in /root/.ssh/rsync_rsa.pub, has we are not using it anymore."
  321. rm -fv /root/.ssh/rsync_rsa.pub
  322. fi
  323. if service_cfg=$(cat "$compose_file" |
  324. shyaml get-value -y "$service_name" 2>/dev/null); then
  325. info "Entry for service ${DARKYELLOW}$service_name${NORMAL}" \
  326. "is already present in '$compose_file'."
  327. cfg=$(e "$service_cfg" | shyaml get-value -y options) || {
  328. err "No ${WHITE}options${NORMAL} in ${DARKYELLOW}$service_name${NORMAL}'s" \
  329. "entry in '$compose_file'."
  330. return 1
  331. }
  332. private_key=$(e "$cfg" | shyaml get-value private-key) || return 1
  333. target=$(e "$cfg" | shyaml get-value target) || return 1
  334. if [ "$target" != "$BACKUP_SERVER" ]; then
  335. err "Existing backup target '$target' is different" \
  336. "from specified '$BACKUP_SERVER'"
  337. return 1
  338. fi
  339. else
  340. private_key=$(ssh:mk-private-key "$host" "$service_name")
  341. cat <<EOF >> "$compose_file"
  342. $service_name:
  343. options:
  344. ident: $host
  345. target: $BACKUP_SERVER
  346. private-key: |
  347. $(e "$private_key" | sed -r 's/^/ /g')
  348. EOF
  349. fi
  350. dest="$BACKUP_SERVER"
  351. dest="${dest%/*}"
  352. ssh_options=()
  353. if [[ "$dest" == *":"* ]]; then
  354. port="${dest##*:}"
  355. dest="${dest%%:*}"
  356. ssh_options=(-p "$port")
  357. else
  358. port=""
  359. dest="${dest%%:*}"
  360. fi
  361. info "You can run this following command from an host having admin access to $dest:"
  362. echo " (Or send it to a backup admin of $dest)" >&2
  363. ## We remove ending label (label will be added or not in the
  364. ## private key, and thus here, depending on the version of
  365. ## openssh-client)
  366. public_key=$(ssh-keygen -y -f <(e "$private_key"$'\n') | sed -r 's/ [^ ]+@[^ ]+$//')
  367. echo "ssh ${ssh_options[@]} myadmin@$dest ssh-key add '$public_key compose@$host'"
  368. }
  369. backup-action() {
  370. local action="$1"
  371. shift
  372. vps_type=$(vps:get-type) || {
  373. err "Failed to get type of installation."
  374. return 1
  375. }
  376. if ! fn.exists "${vps_type}:${action}"; then
  377. err "type '${vps_type}' has no ${vps_type}:${action} implemented yet."
  378. return 1
  379. fi
  380. "${vps_type}:${action}" "$@"
  381. }
  382. compose:get_default_backup_host_ident() {
  383. local service_name="$1" ## Optional
  384. local compose_file service_cfg cfg target
  385. compose_file=$(compose:get-compose-yml)
  386. service_name="${service_name:-rsync-backup}"
  387. if ! service_cfg=$(cat "$compose_file" |
  388. shyaml get-value -y "$service_name" 2>/dev/null); then
  389. err "No service named '$service_name' found in 'compose.yml'."
  390. return 1
  391. fi
  392. cfg=$(e "$service_cfg" | shyaml get-value -y options) || {
  393. err "No ${WHITE}options${NORMAL} in ${DARKYELLOW}$service_name${NORMAL}'s" \
  394. "entry in '$compose_file'."
  395. return 1
  396. }
  397. if ! target=$(e "$cfg" | shyaml get-value target); then
  398. err "No ${WHITE}options.target${NORMAL} in ${DARKYELLOW}$service_name${NORMAL}'s" \
  399. "entry in '$compose_file'."
  400. fi
  401. if ! target=$(e "$cfg" | shyaml get-value target); then
  402. err "No ${WHITE}options.target${NORMAL} in ${DARKYELLOW}$service_name${NORMAL}'s" \
  403. "entry in '$compose_file'."
  404. fi
  405. if ! ident=$(e "$cfg" | shyaml get-value ident); then
  406. err "No ${WHITE}options.ident${NORMAL} in ${DARKYELLOW}$service_name${NORMAL}'s" \
  407. "entry in '$compose_file'."
  408. fi
  409. echo "$target $ident"
  410. }
  411. mailcow:get_default_backup_host_ident() {
  412. local content cron_line ident found dest cmd_line
  413. if ! [ -e "/etc/cron.d/mirror-dir" ]; then
  414. err "No '/etc/cron.d/mirror-dir' found."
  415. return 1
  416. fi
  417. content=$(cat /etc/cron.d/mirror-dir) || {
  418. err "Can't read '/etc/cron.d/mirror-dir'."
  419. return 1
  420. }
  421. if ! cron_line=$(e "$content" | grep "mirror-dir backup"); then
  422. err "Can't find 'mirror-dir backup' line in '/etc/cron.d/mirror-dir'."
  423. return 1
  424. fi
  425. cron_line=${cron_line%|*}
  426. cmd_line=(${cron_line#*root})
  427. found=
  428. dest=
  429. for arg in "${cmd_line[@]}"; do
  430. [ -n "$found" ] && {
  431. dest="$arg"
  432. break
  433. }
  434. [ "$arg" == "-d" ] && {
  435. found=1
  436. }
  437. done
  438. if ! [[ "$dest" =~ ^[\'\"a-zA-Z0-9:/.-]+$ ]]; then
  439. err "Can't find valid destination in 'mirror-dir backup' arguments from '/etc/cron.d/mirror-dir'."
  440. return 1
  441. fi
  442. if [[ "$dest" == \"*\" ]] || [[ "$dest" == \'*\' ]]; then
  443. ## unquoting, the eval should be safe because of previous check
  444. dest=$(eval e "$dest")
  445. fi
  446. if [ -z "$dest" ]; then
  447. err "Can't find destination in 'mirror-dir backup' arguments from '/etc/cron.d/mirror-dir'."
  448. return 1
  449. fi
  450. ## looking for ident
  451. found=
  452. ident=
  453. for arg in "${cmd_line[@]}"; do
  454. [ -n "$found" ] && {
  455. ident="$arg"
  456. break
  457. }
  458. [ "$arg" == "-h" ] && {
  459. found=1
  460. }
  461. done
  462. if ! [[ "$ident" =~ ^[\'\"a-zA-Z0-9.-]+$ ]]; then
  463. err "Can't find valid identifier in 'mirror-dir backup' arguments from '/etc/cron.d/mirror-dir'."
  464. return 1
  465. fi
  466. if [[ "$ident" == \"*\" ]] || [[ "$ident" == \'*\' ]]; then
  467. ## unquoting, the eval should be safe because of previous check
  468. ident=$(eval e "$ident")
  469. fi
  470. if [ -z "$ident" ]; then
  471. err "Can't find destination in 'mirror-dir backup' arguments from '/etc/cron.d/mirror-dir'."
  472. return 1
  473. fi
  474. echo "$dest $ident"
  475. }
  476. compose:service:containers() {
  477. local project="$1" service="$2"
  478. docker ps \
  479. --filter label="com.docker.compose.project=$project" \
  480. --filter label="compose.master-service=$service" \
  481. --format="{{.ID}}"
  482. }
  483. export -f compose:service:containers
  484. compose:service:container_one() {
  485. local project="$1" service="$2" container_id
  486. {
  487. read-0a container_id || {
  488. err "service ${DARKYELLOW}$service${NORMAL} has no running container."
  489. return 1
  490. }
  491. if read-0a _; then
  492. err "service ${DARKYELLOW}$service${NORMAL} has more than one running container."
  493. return 1
  494. fi
  495. } < <(compose:service:containers "$project" "$service")
  496. echo "$container_id"
  497. }
  498. export -f compose:service:container_one
  499. compose:service:container_first() {
  500. local project="$1" service="$2" container_id
  501. {
  502. read-0a container_id || {
  503. err "service ${DARKYELLOW}$service${NORMAL} has no running container."
  504. return 1
  505. }
  506. if read-0a _; then
  507. warn "service ${DARKYELLOW}$service${NORMAL} has more than one running container."
  508. fi
  509. } < <(compose:service:containers "$project" "$service")
  510. echo "$container_id"
  511. }
  512. export -f compose:service:container_first
  513. docker:running_containers() {
  514. :cache: scope=session
  515. docker ps --format="{{.ID}}"
  516. }
  517. decorator._mangle_fn docker:running_containers
  518. export -f docker:running_containers
  519. compose:project:containers() {
  520. local project="$1" opts
  521. opts+=(--filter label="com.docker.compose.project=$project")
  522. docker ps "${opts[@]}" \
  523. --format="{{.ID}}"
  524. }
  525. export -f compose:project:containers
  526. compose:charm:containers() {
  527. local project="$1" charm="$2"
  528. docker ps \
  529. --filter label="com.docker.compose.project=$project" \
  530. --filter label="compose.charm=$charm" \
  531. --format="{{.ID}}"
  532. }
  533. export -f compose:charm:containers
  534. compose:charm:container_one() {
  535. local project="$1" charm="$2" container_id
  536. {
  537. read-0a container_id || {
  538. err "charm ${DARKPINK}$charm${NORMAL} has no running container in project '$project'."
  539. return 1
  540. }
  541. if read-0a _; then
  542. err "charm ${DARKPINK}$charm${NORMAL} has more than one running container."
  543. return 1
  544. fi
  545. } < <(compose:charm:containers "$project" "$charm")
  546. echo "$container_id"
  547. }
  548. export -f compose:charm:container_one
  549. compose:charm:container_first() {
  550. local project="$1" charm="$2" container_id
  551. {
  552. read-0a container_id || {
  553. warn "charm ${DARKYELLOW}$charm${NORMAL} has no running container in project '$project'."
  554. }
  555. if read-0a _; then
  556. warn "charm ${DARKYELLOW}$charm${NORMAL} has more than one running container."
  557. fi
  558. } < <(compose:charm:containers "$project" "$charm")
  559. echo "$container_id"
  560. }
  561. export -f compose:charm:container_first
  562. compose:get_url() {
  563. local project_name="$1" service="$2" data_file network ip
  564. data_file="/var/lib/compose/relations/${project_name}/${service}-frontend/web-proxy/data"
  565. if [ -e "$data_file" ]; then
  566. (
  567. set -o pipefail
  568. cat "$data_file" | shyaml get-value url
  569. )
  570. else
  571. ## Assume there are no frontend relation here, the url is direct IP
  572. container_id=$(compose:service:container_one "${project_name}" "${service}") || return 1
  573. network_ip=$(docker:container:network_ip_one "${container_id}") || return 1
  574. IFS=":" read -r network ip <<<"$network_ip"
  575. tcp_port=
  576. for port in $(docker:exposed_ports "$container_id"); do
  577. IFS="/" read port type <<<"$port"
  578. [ "$type" == "tcp" ] || continue
  579. tcp_port="$port"
  580. break
  581. done
  582. echo -n "http://$ip"
  583. [ -n "$tcp_port" ] && echo ":$tcp_port"
  584. fi || {
  585. err "Failed querying ${service} to frontend relation to get url."
  586. return 1
  587. }
  588. }
  589. export -f compose:get_url
  590. compose:container:service() {
  591. local container="$1" service
  592. if ! service=$(docker:container:label "$container" "compose.service"); then
  593. err "Failed to get service name from container ${container}."
  594. return 1
  595. fi
  596. if [ -z "$service" ]; then
  597. err "No service found for container ${container}."
  598. return 1
  599. fi
  600. echo "$service"
  601. }
  602. export -f compose:container:service
  603. compose:psql() {
  604. local project_name="$1" dbname="$2" container_id
  605. shift 2
  606. container_id=$(compose:charm:container_one "$project_name" "postgres") || return 1
  607. docker exec -i "${container_id}" psql -U postgres "$dbname" "$@"
  608. }
  609. export -f compose:psql
  610. compose:mongo() {
  611. local project_name="$1" dbname="$2" container_id
  612. container_id=$(compose:charm:container_one "$project_name" "mongo") || return 1
  613. docker exec -i "${container_id}" mongo --quiet "$dbname"
  614. }
  615. export -f compose:mongo
  616. compose:pgm() {
  617. local project_name="$1" container_network_ip container_ip container_network
  618. shift
  619. container_id=$(compose:charm:container_one "$project_name" "postgres") || return 1
  620. service_name=$(compose:container:service "$container_id") || return 1
  621. image_id=$(docker:container:image "$container_id") || return 1
  622. container_network_ip=$(docker:container:network_ip_one "$container_id") || return 1
  623. IFS=":" read -r container_network container_ip <<<"$container_network_ip"
  624. pgpass="/srv/datastore/data/${service_name}/var/lib/postgresql/data/pgpass"
  625. local final_pgm_docker_run_opts+=(
  626. -u 0 -e prefix_pg_local_command=" "
  627. --network "${container_network}"
  628. -e PGHOST="$container_ip"
  629. -e PGUSER=postgres
  630. -v "$pgpass:/root/.pgpass"
  631. "${pgm_docker_run_opts[@]}"
  632. )
  633. cmd=(docker run --rm \
  634. "${final_pgm_docker_run_opts[@]}" \
  635. "${image_id}" pgm "$@"
  636. )
  637. echo "${cmd[@]}"
  638. "${cmd[@]}"
  639. }
  640. export -f compose:pgm
  641. postgres:dump() {
  642. local project_name="$1" src="$2" dst="$3"
  643. (
  644. settmpdir PGM_TMP_LOCATION
  645. pgm_docker_run_opts=('-v' "${PGM_TMP_LOCATION}:/tmp/dump")
  646. compose:pgm "$project_name" cp -f "$src" "/tmp/dump/dump.gz" &&
  647. mv "$PGM_TMP_LOCATION/dump.gz" "$dst"
  648. ) || return 1
  649. }
  650. export -f postgres:dump
  651. postgres:restore() {
  652. local project_name="$1" src="$2" dst="$3"
  653. full_src_path=$(readlink -e "$src") || exit 1
  654. (
  655. pgm_docker_run_opts=('-v' "${full_src_path}:/tmp/dump.gz")
  656. compose:pgm "$project_name" cp -f "/tmp/dump.gz" "$dst"
  657. ) || return 1
  658. }
  659. export -f postgres:restore
  660. odoo:get_public_user_id() {
  661. local project_name="$1" dbname="$2"
  662. echo "select res_id from ir_model_data where model = 'res.users' and name = 'public_user';" |
  663. compose:psql "$project_name" "$dbname" -qAt
  664. }
  665. cyclos:set_root_url() {
  666. local project_name="$1" dbname="$2" url="$3"
  667. echo "UPDATE configurations SET root_url = '$url';" |
  668. compose:psql "$project_name" "$dbname" || {
  669. err "Failed to set cyclos url value in '$dbname' database."
  670. return 1
  671. }
  672. }
  673. export -f cyclos:set_root_url
  674. cyclos:unlock() {
  675. local project_name="$1" dbname="$2"
  676. echo "delete from database_lock;" |
  677. compose:psql "${project_name}" "${dbname}"
  678. }
  679. export -f cyclos:unlock
  680. rocketchat:drop-indexes() {
  681. local project_name="$1" dbname="$2"
  682. echo "db.users.dropIndexes()" |
  683. compose:mongo "${project_name}" "${dbname}"
  684. }
  685. export -f rocketchat:drop-indexes
  686. compose:project_name() {
  687. if [ -z "$PROJECT_NAME" ]; then
  688. PROJECT_NAME=$(compose --get-project-name) || {
  689. err "Couldn't get project name."
  690. return 1
  691. }
  692. if [ -z "$PROJECT_NAME" -o "$PROJECT_NAME" == "orphan" ]; then
  693. err "Couldn't get project name, probably because 'compose.yml' wasn't found."
  694. echo " Please ensure to either configure a global 'compose.yml' or run this command" >&2
  695. echo " in a compose project (with 'compose.yml' on the top level directory)." >&2
  696. return 1
  697. fi
  698. export PROJECT_NAME
  699. fi
  700. echo "$PROJECT_NAME"
  701. }
  702. export -f compose:project_name
  703. compose:get_cron_docker_cmd() {
  704. local cron_line cmd_line docker_cmd
  705. project_name=$(compose:project_name) || return 1
  706. if ! cron_line=$(docker exec "${project_name}"_cron_1 cat /etc/cron.d/rsync-backup | grep "\* \* \*"); then
  707. err "Can't find cron_line in cron container."
  708. echo " Have you forgotten to run 'compose up' ?" >&2
  709. return 1
  710. fi
  711. cron_line=${cron_line%|*}
  712. cron_line=${cron_line%"2>&1"*}
  713. cmd_line="${cron_line#*root}"
  714. eval "args=($cmd_line)"
  715. ## should be last argument
  716. docker_cmd=$(echo ${args[@]: -1})
  717. if ! [[ "$docker_cmd" == "docker run --rm -e "* ]]; then
  718. echo "docker command found should start with 'docker run'." >&2
  719. echo "Here's command:" >&2
  720. echo " $docker_cmd" >&2
  721. return 1
  722. fi
  723. e "$docker_cmd"
  724. }
  725. compose:recover-target() {
  726. local backup_host="$1" ident="$2" src="$3" dst="$4" service_name="${5:-rsync-backup}" project_name
  727. project_name=$(compose:project_name) || return 1
  728. docker_image="${project_name}_${service_name}"
  729. if ! docker_has_image "$docker_image"; then
  730. compose build "${service_name}" || {
  731. err "Couldn't find nor build image for service '$service_name'."
  732. return 1
  733. }
  734. fi
  735. dst="${dst%/}" ## remove final slash
  736. ssh_options=(-o StrictHostKeyChecking=no)
  737. if [[ "$backup_host" == *":"* ]]; then
  738. port="${backup_host##*:}"
  739. backup_host="${backup_host%%:*}"
  740. ssh_options+=(-p "$port")
  741. else
  742. port=""
  743. backup_host="${backup_host%%:*}"
  744. fi
  745. rsync_opts=(
  746. -e "ssh ${ssh_options[*]} -i /var/lib/rsync/.ssh/id_rsa -l rsync"
  747. -azvArH --delete --delete-excluded
  748. --partial --partial-dir .rsync-partial
  749. --numeric-ids
  750. )
  751. if [ "$DRY_RUN" ]; then
  752. rsync_opts+=("-n")
  753. fi
  754. cmd=(
  755. docker run --rm --entrypoint rsync \
  756. -v "/srv/datastore/config/${service_name}/var/lib/rsync":/var/lib/rsync \
  757. -v "${dst%/*}":/mnt/dest \
  758. "$docker_image" \
  759. "${rsync_opts[@]}" "$backup_host":"/var/mirror/$ident/$src" "/mnt/dest/${dst##*/}"
  760. )
  761. echo "${WHITE}Launching: ${NORMAL} ${cmd[@]}"
  762. "${cmd[@]}"
  763. }
  764. mailcow:recover-target() {
  765. local backup_host="$1" ident="$2" src="$3" dst="$4"
  766. dst="${dst%/}" ## remove final slash
  767. ssh_options=(-o StrictHostKeyChecking=no)
  768. if [[ "$backup_host" == *":"* ]]; then
  769. port="${backup_host##*:}"
  770. backup_host="${backup_host%%:*}"
  771. ssh_options+=(-p "$port")
  772. else
  773. port=""
  774. backup_host="${backup_host%%:*}"
  775. fi
  776. rsync_opts=(
  777. -e "ssh ${ssh_options[*]} -i /var/lib/rsync/.ssh/id_rsa -l rsync"
  778. -azvArH --delete --delete-excluded
  779. --partial --partial-dir .rsync-partial
  780. --numeric-ids
  781. )
  782. if [ "$DRY_RUN" ]; then
  783. rsync_opts+=("-n")
  784. fi
  785. cmd=(
  786. rsync "${rsync_opts[@]}" "$backup_host":"/var/mirror/$ident/$src" "${dst}"
  787. )
  788. echo "${WHITE}Launching: ${NORMAL} ${cmd[@]}"
  789. "${cmd[@]}"
  790. }
  791. nextcloud:src:version() {
  792. local version
  793. if ! version=$(cat "/srv/datastore/data/${nextcloud_service}/var/www/html/version.php" 2>/dev/null); then
  794. err "Can't find version.php file to get last version installed."
  795. exit 1
  796. fi
  797. version=$(e "$version" | grep 'VersionString =' | cut -f 3 -d ' ' | cut -f 2 -d "'")
  798. if [ -z "$version" ]; then
  799. err "Can't figure out version from version.php content."
  800. exit 1
  801. fi
  802. echo "$version"
  803. }
  804. container:health:check-fix:container-aliveness() {
  805. local container_id="$1"
  806. timeout 5s docker inspect "$container_id" >/dev/null 2>&1
  807. errlvl=$?
  808. if [ "$errlvl" == 124 ]; then
  809. service_name=$(docker ps --filter id="$container_id" --format '{{.Label "com.docker.compose.service"}}')
  810. container_name=($(docker ps --filter id="$container_id" --format '{{.Names}}'))
  811. pid=$(ps ax -o pid,command -ww | grep docker-containerd-shim |
  812. grep "/$container_id" |
  813. sed -r 's/^ *//g' |
  814. cut -f 1 -d " ")
  815. if [ -z "$pid" ]; then
  816. err "container ${DARKCYAN}${container_name[0]}${NORMAL} for ${DARKYELLOW}$service_name${NORMAL} doesn't answer to 'inspect' command. Can't find its PID neither."
  817. return 1
  818. fi
  819. echo "container ${DARKCYAN}${container_name[0]}${NORMAL} for ${DARKYELLOW}$service_name${NORMAL} doesn't answer to 'inspect' command (pid: $pid)."
  820. Wrap -d "kill pid $pid and restart" <<EOF
  821. kill "$pid"
  822. sleep 2
  823. docker restart "$container_id"
  824. EOF
  825. fi
  826. return $errlvl
  827. }
  828. container:health:check-fix:no-matching-entries() {
  829. local container_id="$1"
  830. out=$(docker exec "$container_id" echo 2>&1)
  831. errlvl=$?
  832. [ "$errlvl" == 0 ] && return 0
  833. service_name=$(docker ps --filter id="$container_id" --format '{{.Label "com.docker.compose.service"}}')
  834. container_name=($(docker ps --filter id="$container_id" --format '{{.Names}}'))
  835. if [ "$errlvl" == 126 ] && [[ "$out" == *"no matching entries in passwd file"* ]]; then
  836. echo "container ${DARKCYAN}${container_name[0]}${NORMAL} for ${DARKYELLOW}$service_name${NORMAL} has ${DARKRED}no-matching-entries${NORMAL} bug." >&2
  837. Wrap -d "restarting container of ${DARKYELLOW}$service_name${NORMAL} twice" <<EOF
  838. docker restart "$container_id"
  839. sleep 2
  840. docker restart "$container_id"
  841. EOF
  842. return $errlvl
  843. fi
  844. warn "Unknown issue with ${DARKYELLOW}$service_name${NORMAL}'s container:"
  845. echo " ${WHITE}cmd:${NORMAL} docker exec -ti $container_id echo" >&2
  846. echo "$out" | prefix " ${DARKGRAY}|${NORMAL} " >&2
  847. echo " ${DARKGRAY}..${NORMAL} leaving this as-is."
  848. return $errlvl
  849. }
  850. docker:api() {
  851. local endpoint="$1"
  852. curl -sS --unix-socket /var/run/docker.sock "http://localhost$endpoint"
  853. }
  854. docker:containers:id() {
  855. docker:api /containers/json | jq -r ".[] | .Id"
  856. }
  857. docker:containers:names() {
  858. docker:api /containers/json | jq -r '.[] | .Names[0] | ltrimstr("/")'
  859. }
  860. docker:container:stats() {
  861. container="$1"
  862. docker:api "/containers/$container/stats?stream=false"
  863. }
  864. docker:containers:stats() {
  865. :cache: scope=session
  866. local jobs='' line container id_names sha names name data service project
  867. local DC="com.docker.compose"
  868. local PSF_values=(
  869. ".ID" ".Names" ".Label \"$DC.project\"" ".Label \"$DC.service\"" ".Image"
  870. )
  871. local PSF="$(printf "{{%s}} " "${PSF_values[@]}")"
  872. id_names=$(docker ps -a --format="$PSF") || return 1
  873. ## Create a docker container table from name/sha to service, project, image_name
  874. declare -A resolve
  875. while read-0a line; do
  876. sha=${line%% *}; line=${line#* }
  877. names=${line%% *}; line=${line#* }
  878. names=(${names//,/ })
  879. for name in "${names[@]}"; do
  880. resolve["$name"]="$line"
  881. done
  882. resolve["$sha"]="$line"
  883. done < <(printf "%s\n" "$id_names")
  884. declare -A data
  885. while read-0a line; do
  886. name=${line%% *}; line=${line#* }
  887. ts=${line%% *}; line=${line#* }
  888. resolved="${resolve["$name"]}"
  889. project=${resolved%% *}; resolved=${resolved#* }
  890. service=${resolved%% *}; resolved=${resolved#* }
  891. image_name="$resolved"
  892. if [ -z "$service" ]; then
  893. project="@"
  894. service=$(docker inspect "$image_name" | jq -r '.[0].RepoTags[0]')
  895. service=${service//\//_}
  896. fi
  897. if [ -n "${data["$project/$service"]}" ]; then
  898. previous=(${data["$project/$service"]})
  899. previous=(${previous[@]:1})
  900. current=($line)
  901. sum=()
  902. i=0; max=${#previous[@]}
  903. while (( i < max )); do
  904. sum+=($((${previous[$i]} + ${current[$i]})))
  905. ((i++))
  906. done
  907. data["$project/$service"]="$ts ${sum[*]}"
  908. else
  909. data["$project/$service"]="$ts $line"
  910. fi
  911. done < <(
  912. for container in "$@"; do
  913. (
  914. docker:container:stats "${container}" |
  915. jq -r '
  916. (.name | ltrimstr("/"))
  917. + " " + (.read | sub("\\.[0-9]+Z"; "Z") | fromdate | tostring)
  918. + " " + (.memory_stats.usage | tostring)
  919. + " " + (.memory_stats.stats.inactive_file | tostring)
  920. + " " + ((.memory_stats.usage - .memory_stats.stats.inactive_file) | tostring)
  921. + " " + (.memory_stats.limit | tostring)
  922. + " " + (.networks.eth0.rx_bytes | tostring)
  923. + " " + (.networks.eth0.rx_packets | tostring)
  924. + " " + (.networks.eth0.rx_errors | tostring)
  925. + " " + (.networks.eth0.rx_dropped | tostring)
  926. + " " + (.networks.eth0.tx_bytes | tostring)
  927. + " " + (.networks.eth0.tx_packets | tostring)
  928. + " " + (.networks.eth0.tx_errors | tostring)
  929. + " " + (.networks.eth0.tx_dropped | tostring)
  930. '
  931. ) &
  932. jobs=1
  933. done
  934. [ -n "$jobs" ] && wait
  935. )
  936. for label in "${!data[@]}"; do
  937. echo "$label ${data[$label]}"
  938. done
  939. }
  940. decorator._mangle_fn docker:containers:stats
  941. export -f docker:containers:stats
  942. col:normalize:size() {
  943. local alignment=$1
  944. awk -v alignment="$alignment" '{
  945. # Store the entire line in the lines array.
  946. lines[NR] = $0;
  947. # Split the line into fields.
  948. split($0, fields);
  949. # Update max for each field.
  950. for (i = 1; i <= length(fields); i++) {
  951. if (length(fields[i]) > max[i]) {
  952. max[i] = length(fields[i]);
  953. }
  954. }
  955. }
  956. END {
  957. # Print lines with fields padded to max.
  958. for (i = 1; i <= NR; i++) {
  959. split(lines[i], fields);
  960. line = "";
  961. for (j = 1; j <= length(fields); j++) {
  962. # Get alignment for the current field.
  963. align = substr(alignment, j, 1);
  964. if (align != "+") {
  965. align = "-"; # Default to left alignment if not "+".
  966. }
  967. line = line sprintf("%" align max[j] "s ", fields[j]);
  968. }
  969. print line;
  970. }
  971. }'
  972. }
  973. rrd:create() {
  974. local prefix="$1"
  975. shift
  976. local label="$1" step="300" src_def
  977. shift
  978. if [ -z "$VAR_DIR" ]; then
  979. err "Unset \$VAR_DIR, can't create rrd graph"
  980. return 1
  981. fi
  982. mkdir -p "$VAR_DIR"
  983. if ! [ -d "$VAR_DIR" ]; then
  984. err "Invalid \$VAR_DIR: '$VAR_DIR' is not a directory"
  985. return 1
  986. fi
  987. if ! type -p rrdtool >/dev/null 2>&1; then
  988. apt-get install rrdtool -y --force-yes </dev/null
  989. if ! type -p rrdtool 2>/dev/null 2>&1; then
  990. err "Couldn't find nor install 'rrdtool'."
  991. return 1
  992. fi
  993. fi
  994. local RRD_PATH="$VAR_DIR/rrd"
  995. local RRD_FILE="$RRD_PATH/$prefix/$label.rrd"
  996. mkdir -p "${RRD_FILE%/*}"
  997. if [ -f "$RRD_FILE" ]; then
  998. err "File '$RRD_FILE' already exists, use a different label."
  999. return 1
  1000. fi
  1001. local rrd_ds_opts=()
  1002. for src_def in "$@"; do
  1003. IFS=":" read -r name type min max rra_types <<<"$src_def"
  1004. rra_types=${rra_types:-average,max,min}
  1005. rrd_ds_opts+=("DS:$name:$type:900:$min:$max")
  1006. done
  1007. local step=120
  1008. local times=( ## with steps 120 is 2mn datapoint
  1009. 2m:1w
  1010. 6m:3w
  1011. 30m:12w
  1012. 3h:1y
  1013. 1d:10y
  1014. 1w:2080w
  1015. )
  1016. rrd_rra_opts=()
  1017. for time in "${times[@]}"; do
  1018. rrd_rra_opts+=("RRA:"{AVERAGE,MIN,MAX}":0.5:$time")
  1019. done
  1020. cmd=(
  1021. rrdtool create "$RRD_FILE" \
  1022. --step "$step" \
  1023. "${rrd_ds_opts[@]}" \
  1024. "${rrd_rra_opts[@]}"
  1025. )
  1026. "${cmd[@]}" || {
  1027. err "Failed command: ${cmd[@]}"
  1028. return 1
  1029. }
  1030. }
  1031. rrd:update() {
  1032. local prefix="$1"
  1033. shift
  1034. while read-0a data; do
  1035. [ -z "$data" ] && continue
  1036. IFS="~" read -ra data <<<"${data// /\~}"
  1037. label="${data[0]}"
  1038. ts="${data[1]}"
  1039. for arg in "$@"; do
  1040. IFS="|" read -r name arg <<<"$arg"
  1041. rrd_label="${label}/${name}"
  1042. rrd_create_opt=()
  1043. rrd_update_opt="$ts"
  1044. for col_def in ${arg//,/ }; do
  1045. col=${col_def%%:*}; create_def=${col_def#*:}
  1046. rrd_update_opt="${rrd_update_opt}:${data[$col]}"
  1047. rrd_create_opt+=("$create_def")
  1048. done
  1049. local RRD_ROOT_PATH="$VAR_DIR/rrd"
  1050. local RRD_PATH="$RRD_ROOT_PATH/${prefix%/}"
  1051. local RRD_FILE="${RRD_PATH%/}/${rrd_label#/}.rrd"
  1052. if ! [ -f "$RRD_FILE" ]; then
  1053. info "Creating new RRD file '${RRD_FILE#$RRD_ROOT_PATH/}'"
  1054. if ! rrd:create "$prefix" "${rrd_label}" "${rrd_create_opt[@]}" </dev/null ; then
  1055. err "Couldn't create new RRD file ${rrd_label} with options: '${rrd_create_opt[*]}'"
  1056. return 1
  1057. fi
  1058. fi
  1059. rrdtool update "$RRD_FILE" "$rrd_update_opt" || {
  1060. err "update failed with options: '$rrd_update_opt'"
  1061. return 1
  1062. }
  1063. done
  1064. done
  1065. }
  1066. [ "$SOURCED" ] && return 0
  1067. ##
  1068. ## Command line processing
  1069. ##
  1070. cmdline.spec.gnu
  1071. cmdline.spec.reporting
  1072. cmdline.spec.gnu install
  1073. cmdline.spec::cmd:install:run() {
  1074. :
  1075. }
  1076. cmdline.spec.gnu get-type
  1077. cmdline.spec::cmd:get-type:run() {
  1078. vps:get-type
  1079. }
  1080. cmdline.spec:install:cmd:backup:run() {
  1081. : :posarg: BACKUP_SERVER 'Target backup server'
  1082. : :optfla: --ignore-domain-check \
  1083. "Allow to bypass the domain check in
  1084. compose file (only used in compose
  1085. installation)."
  1086. : :optfla: --ignore-ping-check "Allow to bypass the ping check of host."
  1087. local vps_type
  1088. vps_type=$(vps:get-type) || {
  1089. err "Failed to get type of installation."
  1090. return 1
  1091. }
  1092. if ! fn.exists "${vps_type}:install-backup"; then
  1093. err "type '${vps_type}' has no backup installation implemented yet."
  1094. return 1
  1095. fi
  1096. opts=()
  1097. [ "$opt_ignore_ping_check" ] &&
  1098. opts+=("--ignore-ping-check")
  1099. if [ "$vps_type" == "compose" ]; then
  1100. [ "$opt_ignore_domain_check" ] &&
  1101. opts+=("--ignore-domain-check")
  1102. fi
  1103. "cmdline.spec:install:cmd:${vps_type}-backup:run" "${opts[@]}" "$BACKUP_SERVER"
  1104. }
  1105. DEFAULT_BACKUP_SERVICE_NAME=rsync-backup
  1106. cmdline.spec.gnu compose-backup
  1107. cmdline.spec:install:cmd:compose-backup:run() {
  1108. : :posarg: BACKUP_SERVER 'Target backup server'
  1109. : :optval: --service-name,-s "YAML service name in compose
  1110. file to check for existence of key.
  1111. Defaults to '$DEFAULT_BACKUP_SERVICE_NAME'"
  1112. : :optval: --compose-file,-f "Compose file location. Defaults to
  1113. the value of '\$DEFAULT_COMPOSE_FILE'"
  1114. : :optfla: --ignore-domain-check \
  1115. "Allow to bypass the domain check in
  1116. compose file."
  1117. : :optfla: --ignore-ping-check "Allow to bypass the ping check of host."
  1118. local service_name compose_file
  1119. [ -e "/etc/compose/local.conf" ] && source /etc/compose/local.conf
  1120. compose_file=${opt_compose_file:-$DEFAULT_COMPOSE_FILE}
  1121. service_name=${opt_service_name:-$DEFAULT_BACKUP_SERVICE_NAME}
  1122. if ! [ -e "$compose_file" ]; then
  1123. err "Compose file not found in '$compose_file'."
  1124. return 1
  1125. fi
  1126. compose:install-backup "$BACKUP_SERVER" "$service_name" "$compose_file" \
  1127. "$opt_ignore_ping_check" "$opt_ignore_domain_check"
  1128. }
  1129. cmdline.spec:install:cmd:mailcow-backup:run() {
  1130. : :posarg: BACKUP_SERVER 'Target backup server'
  1131. : :optfla: --ignore-ping-check "Allow to bypass the ping check of host."
  1132. "mailcow:install-backup" "$BACKUP_SERVER" "$opt_ignore_ping_check"
  1133. }
  1134. cmdline.spec.gnu backup
  1135. cmdline.spec::cmd:backup:run() {
  1136. local vps_type
  1137. vps_type=$(vps:get-type) || {
  1138. err "Failed to get type of installation."
  1139. return 1
  1140. }
  1141. if ! fn.exists "cmdline.spec:backup:cmd:${vps_type}:run"; then
  1142. err "type '${vps_type}' has no backup process implemented yet."
  1143. return 1
  1144. fi
  1145. "cmdline.spec:backup:cmd:${vps_type}:run"
  1146. }
  1147. cmdline.spec:backup:cmd:mailcow:run() {
  1148. local cmd_line cron_line cmd
  1149. for f in mysql-backup mirror-dir; do
  1150. [ -e "/etc/cron.d/$f" ] || {
  1151. err "Can't find '/etc/cron.d/$f'."
  1152. echo " Have you forgotten to run 'vps install backup BACKUP_HOST' ?" >&2
  1153. return 1
  1154. }
  1155. if ! cron_line=$(cat "/etc/cron.d/$f" |
  1156. grep -v "^#" | grep "\* \* \*"); then
  1157. err "Can't find cron_line in '/etc/cron.d/$f'." \
  1158. "Have you modified it ?"
  1159. return 1
  1160. fi
  1161. cron_line=${cron_line%|*}
  1162. cmd_line=(${cron_line#*root})
  1163. if [ "$f" == "mirror-dir" ]; then
  1164. cmd=()
  1165. for arg in "${cmd_line[@]}"; do
  1166. [ "$arg" != "-q" ] && cmd+=("$arg")
  1167. done
  1168. else
  1169. cmd=("${cmd_line[@]}")
  1170. fi
  1171. code="${cmd[*]}"
  1172. echo "${WHITE}Launching:${NORMAL} ${code}"
  1173. {
  1174. {
  1175. (
  1176. ## Some commands are using colors that are already
  1177. ## set by this current program and will trickle
  1178. ## down unwantedly
  1179. ansi_color no
  1180. eval "${code}"
  1181. ) | sed -r "s/^/ ${GRAY}|${NORMAL} /g"
  1182. set_errlvl "${PIPESTATUS[0]}"
  1183. } 3>&1 1>&2 2>&3 | sed -r "s/^/ $DARKRED\!$NORMAL /g"
  1184. set_errlvl "${PIPESTATUS[0]}"
  1185. } 3>&1 1>&2 2>&3
  1186. if [ "$?" != "0" ]; then
  1187. err "Failed."
  1188. return 1
  1189. fi
  1190. done
  1191. info "Mysql backup and subsequent mirror-dir ${DARKGREEN}succeeded${NORMAL}."
  1192. }
  1193. set_errlvl() { return "${1:-1}"; }
  1194. cmdline.spec:backup:cmd:compose:run() {
  1195. local cron_line args
  1196. project_name=$(compose:project_name) || return 1
  1197. docker_cmd=$(compose:get_cron_docker_cmd) || return 1
  1198. echo "${WHITE}Launching:${NORMAL} docker exec -i "${project_name}_cron_1" $docker_cmd"
  1199. {
  1200. {
  1201. eval "docker exec -i \"${project_name}_cron_1\" $docker_cmd" | sed -r "s/^/ ${GRAY}|${NORMAL} /g"
  1202. set_errlvl "${PIPESTATUS[0]}"
  1203. } 3>&1 1>&2 2>&3 | sed -r "s/^/ $DARKRED\!$NORMAL /g"
  1204. set_errlvl "${PIPESTATUS[0]}"
  1205. } 3>&1 1>&2 2>&3
  1206. if [ "$?" != "0" ]; then
  1207. err "Failed."
  1208. return 1
  1209. fi
  1210. info "mirror-dir ${DARKGREEN}succeeded${NORMAL}."
  1211. }
  1212. cmdline.spec.gnu recover-target
  1213. cmdline.spec::cmd:recover-target:run() {
  1214. : :posarg: BACKUP_DIR 'Source directory on backup side'
  1215. : :posarg: HOST_DIR 'Target directory on host side'
  1216. : :optval: --backup-host,-B "The backup host"
  1217. : :optfla: --dry-run,-n "Don't do anything, instead tell what it
  1218. would do."
  1219. ## if no backup host take the one by default
  1220. backup_host="$opt_backup_host"
  1221. if [ -z "$backup_host" ]; then
  1222. backup_host_ident=$(backup-action get_default_backup_host_ident) || return 1
  1223. read -r backup_host ident <<<"$backup_host_ident"
  1224. fi
  1225. if [[ "$BACKUP_DIR" == /* ]]; then
  1226. err "BACKUP_DIR must be a relative path from the root of your backup."
  1227. return 1
  1228. fi
  1229. REAL_HOST_DIR=$(realpath "$HOST_DIR") || {
  1230. err "Can't find HOST_DIR '$HOST_DIR'."
  1231. return 1
  1232. }
  1233. export DRY_RUN="${opt_dry_run}"
  1234. backup-action recover-target "$backup_host" "$ident" "$BACKUP_DIR" "$REAL_HOST_DIR"
  1235. }
  1236. cmdline.spec.gnu odoo
  1237. cmdline.spec::cmd:odoo:run() {
  1238. :
  1239. }
  1240. cmdline.spec.gnu restart
  1241. cmdline.spec:odoo:cmd:restart:run() {
  1242. : :optval: --service,-s "The service (defaults to 'odoo')"
  1243. local out odoo_service
  1244. odoo_service="${opt_service:-odoo}"
  1245. project_name=$(compose:project_name) || return 1
  1246. if ! out=$(docker restart "${project_name}_${odoo_service}_1" 2>&1); then
  1247. if [[ "$out" == *"no matching entries in passwd file" ]]; then
  1248. warn "Catched docker bug. Restarting once more."
  1249. if ! out=$(docker restart "${project_name}_${odoo_service}_1"); then
  1250. err "Can't restart container ${project_name}_${odoo_service}_1 (restarted twice)."
  1251. echo " output:" >&2
  1252. echo "$out" | prefix " ${GRAY}|${NORMAL} " >&2
  1253. exit 1
  1254. fi
  1255. else
  1256. err "Couldn't restart container ${project_name}_${odoo_service}_1 (and no restart bug detected)."
  1257. exit 1
  1258. fi
  1259. fi
  1260. info "Container ${project_name}_${odoo_service}_1 was ${DARKGREEN}successfully${NORMAL} restarted."
  1261. }
  1262. cmdline.spec.gnu restore
  1263. cmdline.spec:odoo:cmd:restore:run() {
  1264. : :posarg: ZIP_DUMP_LOCATION 'Source odoo dump file to restore
  1265. (can be a local file or an url)'
  1266. : :optval: --service,-s "The service (defaults to 'odoo')"
  1267. : :optval: --database,-d 'Target database (default if not specified)'
  1268. local out
  1269. odoo_service="${opt_service:-odoo}"
  1270. if [[ "$ZIP_DUMP_LOCATION" == "http://"* ]] ||
  1271. [[ "$ZIP_DUMP_LOCATION" == "https://"* ]]; then
  1272. settmpdir ZIP_TMP_LOCATION
  1273. tmp_location="$ZIP_TMP_LOCATION/dump.zip"
  1274. curl -k -s -L "$ZIP_DUMP_LOCATION" > "$tmp_location" || {
  1275. err "Couldn't get '$ZIP_DUMP_LOCATION'."
  1276. exit 1
  1277. }
  1278. if [[ "$(dd if="$tmp_location" count=2 bs=1 2>/dev/null)" != "PK" ]]; then
  1279. err "Download doesn't seem to be a zip file."
  1280. dd if="$tmp_location" count=1 bs=256 | hd | prefix " ${GRAY}|${NORMAL} " >&2
  1281. exit 1
  1282. fi
  1283. info "Successfully downloaded '$ZIP_DUMP_LOCATION'"
  1284. echo " in '$tmp_location'." >&2
  1285. ZIP_DUMP_LOCATION="$tmp_location"
  1286. fi
  1287. [ -e "$ZIP_DUMP_LOCATION" ] || {
  1288. err "No file '$ZIP_DUMP_LOCATION' found." >&2
  1289. exit 1
  1290. }
  1291. #cmdline.spec:odoo:cmd:restart:run --service "$odoo_service" || exit 1
  1292. msg_dbname=default
  1293. [ -n "$opt_database" ] && msg_dbname="'$opt_database'"
  1294. compose --no-hooks drop "$odoo_service" $opt_database || {
  1295. err "Error dropping $msg_dbname database of service ${DARKYELLOW}$odoo_service${NORMAL}."
  1296. exit 1
  1297. }
  1298. compose --no-hooks load "$odoo_service" $opt_database < "$ZIP_DUMP_LOCATION" || {
  1299. err "Error restoring service ${DARKYELLOW}$odoo_service${NORMAL} to $msg_dbname database."
  1300. exit 1
  1301. }
  1302. info "Successfully restored ${DARKYELLOW}$odoo_service${NORMAL} to $msg_dbname database."
  1303. ## Restart odoo, ensure there is no bugs lingering on it.
  1304. cmdline.spec:odoo:cmd:restart:run --service "$odoo_service" || exit 1
  1305. }
  1306. cmdline.spec.gnu dump
  1307. cmdline.spec:odoo:cmd:dump:run() {
  1308. : :posarg: DUMP_ZIPFILE 'Target path to store odoo dump zip file.'
  1309. : :optval: --database,-d 'Target database (default if not specified)'
  1310. : :optval: --service,-s "The service (defaults to 'odoo')"
  1311. odoo_service="${opt_service:-odoo}"
  1312. msg_dbname=default
  1313. [ -n "$opt_database" ] && msg_dbname="'$opt_database'"
  1314. compose --no-hooks save "$odoo_service" $opt_database > "$DUMP_ZIPFILE" || {
  1315. err "Error dumping ${DARKYELLOW}$odoo_service${NORMAL}'s $msg_dbname database to '$DUMP_ZIPFILE'."
  1316. exit 1
  1317. }
  1318. info "Successfully dumped ${DARKYELLOW}$odoo_service${NORMAL}'s $msg_dbname database to '$DUMP_ZIPFILE'."
  1319. }
  1320. cmdline.spec.gnu drop
  1321. cmdline.spec:odoo:cmd:drop:run() {
  1322. : :optval: --database,-d 'Target database (default if not specified)'
  1323. : :optval: --service,-s "The service (defaults to 'odoo')"
  1324. odoo_service="${opt_service:-odoo}"
  1325. msg_dbname=default
  1326. [ -n "$opt_database" ] && msg_dbname="'$opt_database'"
  1327. compose --no-hooks drop "$odoo_service" $opt_database || {
  1328. err "Error dropping ${DARKYELLOW}$odoo_service${NORMAL}'s $msg_dbname database."
  1329. exit 1
  1330. }
  1331. info "Successfully dropped ${DARKYELLOW}$odoo_service${NORMAL}'s $msg_dbname database."
  1332. }
  1333. cmdline.spec.gnu set-cyclos-url
  1334. cmdline.spec:odoo:cmd:set-cyclos-url:run() {
  1335. : :optval: --database,-d "Target database ('odoo' if not specified)"
  1336. : :optval: --service,-s "The cyclos service name (defaults to 'cyclos')"
  1337. local URL
  1338. dbname=${opt_database:-odoo}
  1339. cyclos_service="${opt_service:-cyclos}"
  1340. project_name=$(compose:project_name) || exit 1
  1341. URL=$(compose:get_url "${project_name}" "${cyclos_service}") || exit 1
  1342. Wrap -d "set cyclos url to '$URL'" <<EOF || exit 1
  1343. echo "UPDATE res_company SET cyclos_server_url = '$URL/api' WHERE id=1;" |
  1344. compose:psql "$project_name" "$dbname" || {
  1345. err "Failed to set cyclos url value in '$dbname' database."
  1346. exit 1
  1347. }
  1348. EOF
  1349. }
  1350. cmdline.spec.gnu fix-sso
  1351. cmdline.spec:odoo:cmd:fix-sso:run() {
  1352. : :optval: --database,-d "Target database ('odoo' if not specified)"
  1353. local public_user_id project_name dbname
  1354. dbname=${opt_database:-odoo}
  1355. project_name=$(compose:project_name) || exit 1
  1356. public_user_id=$(odoo:get_public_user_id "${project_name}" "${dbname}") || exit 1
  1357. Wrap -d "fix website's object to 'public_user' (id=$public_user_id)" <<EOF || exit 1
  1358. echo "UPDATE website SET user_id = $public_user_id;" |
  1359. compose:psql "$project_name" "$dbname" || {
  1360. err "Failed to set website's object user_id to public user's id ($public_user_id) in '$dbname' database."
  1361. exit 1
  1362. }
  1363. EOF
  1364. }
  1365. cmdline.spec.gnu cyclos
  1366. cmdline.spec::cmd:cyclos:run() {
  1367. :
  1368. }
  1369. cmdline.spec:cyclos:cmd:dump:run() {
  1370. : :posarg: DUMP_GZFILE 'Target path to store odoo dump gz file.'
  1371. : :optval: --database,-d "Target database ('cyclos' if not specified)"
  1372. : :optval: --service,-s "The cyclos service name (defaults to 'cyclos')"
  1373. cyclos_service="${opt_service:-cyclos}"
  1374. cyclos_database="${opt_database:-cyclos}"
  1375. project_name=$(compose:project_name) || exit 1
  1376. container_id=$(compose:service:container_one "$project_name" "${cyclos_service}") || exit 1
  1377. Wrap -d "stop ${DARKYELLOW}${cyclos_service}${NORMAL}'s container" -- \
  1378. docker stop "$container_id" || exit 1
  1379. Wrap -d "Dump postgres database '${cyclos_database}'." -- \
  1380. postgres:dump "${project_name}" "$cyclos_database" "$DUMP_GZFILE" || exit 1
  1381. Wrap -d "start ${DARKYELLOW}${cyclos_service}${NORMAL}'s container" -- \
  1382. docker start "${container_id}" || exit 1
  1383. }
  1384. cmdline.spec.gnu restore
  1385. cmdline.spec:cyclos:cmd:restore:run() {
  1386. : :posarg: GZ_DUMP_LOCATION 'Source cyclos dump file to restore
  1387. (can be a local file or an url)'
  1388. : :optval: --service,-s "The service (defaults to 'cyclos')"
  1389. : :optval: --database,-d 'Target database (default if not specified)'
  1390. local out
  1391. cyclos_service="${opt_service:-cyclos}"
  1392. cyclos_database="${opt_database:-cyclos}"
  1393. project_name=$(compose:project_name) || exit 1
  1394. url=$(compose:get_url "${project_name}" "${cyclos_service}") || return 1
  1395. container_id=$(compose:service:container_one "$project_name" "${cyclos_service}") || exit 1
  1396. if [[ "$GZ_DUMP_LOCATION" == "http://"* ]] ||
  1397. [[ "$GZ_DUMP_LOCATION" == "https://"* ]]; then
  1398. settmpdir GZ_TMP_LOCATION
  1399. tmp_location="$GZ_TMP_LOCATION/dump.gz"
  1400. Wrap -d "get '$GZ_DUMP_LOCATION'" <<EOF || exit 1
  1401. ## Note that curll version before 7.76.0 do not have
  1402. curl -k -s -L "$GZ_DUMP_LOCATION" --fail \\
  1403. > "$tmp_location" || {
  1404. echo "Error fetching ressource. Is url correct ?" >&2
  1405. exit 1
  1406. }
  1407. if [[ "\$(dd if="$tmp_location" count=2 bs=1 2>/dev/null |
  1408. hexdump -v -e "/1 \"%02x\"")" != "1f8b" ]]; then
  1409. err "Download doesn't seem to be a gzip file."
  1410. dd if="$tmp_location" count=1 bs=256 | hd | prefix " ${GRAY}|${NORMAL} " >&2
  1411. exit 1
  1412. fi
  1413. EOF
  1414. GZ_DUMP_LOCATION="$tmp_location"
  1415. fi
  1416. [ -e "$GZ_DUMP_LOCATION" ] || {
  1417. err "No file '$GZ_DUMP_LOCATION' found." >&2
  1418. exit 1
  1419. }
  1420. Wrap -d "stop ${DARKYELLOW}${cyclos_service}${NORMAL}'s container" -- \
  1421. docker stop "$container_id" || exit 1
  1422. ## XXXvlab: making the assumption that the postgres username should
  1423. ## be the same as the cyclos service selected (which is the default,
  1424. ## but not always the case).
  1425. Wrap -d "restore postgres database '${cyclos_database}'." -- \
  1426. postgres:restore "$project_name" "$GZ_DUMP_LOCATION" "${cyclos_service}@${cyclos_database}" || exit 1
  1427. ## ensure that the database is not locked
  1428. Wrap -d "check and remove database lock if any" -- \
  1429. cyclos:unlock "${project_name}" "${cyclos_database}" || exit 1
  1430. Wrap -d "set root url to '$url'" -- \
  1431. cyclos:set_root_url "${project_name}" "${cyclos_database}" "${url}" || exit 1
  1432. Wrap -d "start ${DARKYELLOW}${cyclos_service}${NORMAL}'s container" -- \
  1433. docker start "${container_id}" || exit 1
  1434. }
  1435. cmdline.spec.gnu set-root-url
  1436. cmdline.spec:cyclos:cmd:set-root-url:run() {
  1437. : :optval: --database,-d "Target database ('cyclos' if not specified)"
  1438. : :optval: --service,-s "The cyclos service name (defaults to 'cyclos')"
  1439. local URL
  1440. cyclos_database=${opt_database:-cyclos}
  1441. cyclos_service="${opt_service:-cyclos}"
  1442. project_name=$(compose:project_name) || exit 1
  1443. url=$(compose:get_url "${project_name}" "${cyclos_service}") || exit 1
  1444. container_id=$(compose:service:container_one "${project_name}" "${cyclos_service}") || exit 1
  1445. Wrap -d "stop ${DARKYELLOW}${cyclos_service}${NORMAL}'s container" -- \
  1446. docker stop "$container_id" || exit 1
  1447. Wrap -d "set root url to '$url'" -- \
  1448. cyclos:set_root_url "${project_name}" "${cyclos_database}" "${url}" || exit 1
  1449. Wrap -d "start ${DARKYELLOW}${cyclos_service}${NORMAL}'s container" -- \
  1450. docker start "${container_id}" || exit 1
  1451. }
  1452. cmdline.spec.gnu unlock
  1453. cmdline.spec:cyclos:cmd:unlock:run() {
  1454. : :optval: --database,-d "Target database ('cyclos' if not specified)"
  1455. : :optval: --service,-s "The cyclos service name (defaults to 'cyclos')"
  1456. local URL
  1457. cyclos_database=${opt_database:-cyclos}
  1458. cyclos_service="${opt_service:-cyclos}"
  1459. project_name=$(compose:project_name) || exit 1
  1460. container_id=$(compose:service:container_one "${project_name}" "${cyclos_service}") || exit 1
  1461. Wrap -d "stop ${DARKYELLOW}${cyclos_service}${NORMAL}'s container" -- \
  1462. docker stop "$container_id" || exit 1
  1463. Wrap -d "check and remove database lock if any" -- \
  1464. cyclos:unlock "${project_name}" "${cyclos_database}" || exit 1
  1465. Wrap -d "start ${DARKYELLOW}${cyclos_service}${NORMAL}'s container" -- \
  1466. docker start "${container_id}" || exit 1
  1467. }
  1468. cmdline.spec.gnu rocketchat
  1469. cmdline.spec::cmd:rocketchat:run() {
  1470. :
  1471. }
  1472. cmdline.spec.gnu drop-indexes
  1473. cmdline.spec:rocketchat:cmd:drop-indexes:run() {
  1474. : :optval: --database,-d "Target database ('rocketchat' if not specified)"
  1475. : :optval: --service,-s "The rocketchat service name (defaults to 'rocketchat')"
  1476. local URL
  1477. rocketchat_database=${opt_database:-rocketchat}
  1478. rocketchat_service="${opt_service:-rocketchat}"
  1479. project_name=$(compose:project_name) || exit 1
  1480. container_id=$(compose:service:container_one "${project_name}" "${rocketchat_service}") || exit 1
  1481. Wrap -d "stop ${DARKYELLOW}${rocketchat_service}${NORMAL}'s container" -- \
  1482. docker stop "$container_id" || exit 1
  1483. errlvl=0
  1484. Wrap -d "drop indexes" -- \
  1485. rocketchat:drop-indexes "${project_name}" "${rocketchat_database}" || {
  1486. errlvl=1
  1487. errmsg="Failed to drop indexes"
  1488. }
  1489. Wrap -d "start ${DARKYELLOW}${rocketchat_service}${NORMAL}'s container" -- \
  1490. docker start "${container_id}" || exit 1
  1491. if [ "$errlvl" != 0 ]; then
  1492. err "$errmsg"
  1493. fi
  1494. exit "$errlvl"
  1495. }
  1496. cmdline.spec.gnu nextcloud
  1497. cmdline.spec::cmd:nextcloud:run() {
  1498. :
  1499. }
  1500. cmdline.spec.gnu upgrade
  1501. cmdline.spec:nextcloud:cmd:upgrade:run() {
  1502. : :posarg: [TARGET_VERSION] "Source cyclos dump file to restore"
  1503. : :optval: --service,-s "The nexcloud service name (defaults to 'nextcloud')"
  1504. local URL
  1505. nextcloud_service="${opt_service:-nextcloud}"
  1506. project_name=$(compose:project_name) || exit 1
  1507. containers=$(compose:service:containers "${project_name}" "${nextcloud_service}") || exit 1
  1508. container_stopped=()
  1509. if [ -n "$containers" ]; then
  1510. for container in $containers; do
  1511. Wrap -d "stop ${DARKYELLOW}${nextcloud_service}${NORMAL}'s container" -- \
  1512. docker stop "$container" || {
  1513. err "Failed to stop container '$container'."
  1514. exit 1
  1515. }
  1516. container_stopped+=("$container")
  1517. done
  1518. fi
  1519. before_version=$(nextcloud:src:version) || exit 1
  1520. ## -q to remove the display of ``compose`` related information
  1521. ## like relation resolution.
  1522. ## --no-hint to remove the final hint about modifying your
  1523. ## ``compose.yml``.
  1524. compose -q upgrade "$nextcloud_service" --no-hint
  1525. errlvl="$?"
  1526. after_version=$(nextcloud:src:version)
  1527. if [ "$after_version" != "$before_version" ]; then
  1528. desc="update \`compose.yml\` to set ${DARKYELLOW}$nextcloud_service${NORMAL}'s "
  1529. desc+="docker image to actual code version ${WHITE}${after_version}${NORMAL}"
  1530. Wrap -d "$desc" -- \
  1531. compose:file:value-change \
  1532. "${nextcloud_service}.docker-compose.image" \
  1533. "docker.0k.io/nextcloud:${after_version}-myc" || exit 1
  1534. fi
  1535. if [ "$errlvl" == 0 ]; then
  1536. echo "${WHITE}Launching final compose${NORMAL}"
  1537. compose up || exit 1
  1538. fi
  1539. exit "$errlvl"
  1540. }
  1541. cmdline.spec.gnu check-fix
  1542. cmdline.spec::cmd:check-fix:run() {
  1543. : :posarg: [SERVICES...] "Optional service to check"
  1544. : :optval: --check,-c "Specify a check or a list of checks separated by commas"
  1545. : :optfla: --silent,-s "Don't ouput anything if everything goes well"
  1546. local project_name service_name containers container check
  1547. all_checks=$(declare -F |
  1548. egrep '^declare -fx? container:health:check-fix:[^ ]+$' |
  1549. cut -f 4 -d ":")
  1550. checks=(${opt_check//,/ })
  1551. for check in "${checks[@]}"; do
  1552. fn.exists container:health:check-fix:$check || {
  1553. err "check '$check' not found."
  1554. return 1
  1555. }
  1556. done
  1557. if [ "${#checks[*]}" == 0 ]; then
  1558. checks=($all_checks)
  1559. fi
  1560. ## XXXvlab: could make it parallel
  1561. project_name=$(compose:project_name) || exit 1
  1562. containers=($(compose:project:containers "${project_name}")) || exit 1
  1563. found=
  1564. for container in "${containers[@]}"; do
  1565. service_name=$(docker ps --filter id="$container" --format '{{.Label "com.docker.compose.service"}}')
  1566. if [ "${#SERVICES[@]}" -gt 0 ]; then
  1567. [[ " ${SERVICES[*]} " == *" $service_name "* ]] || continue
  1568. fi
  1569. found=1
  1570. one_bad=
  1571. for check in "${checks[@]}"; do
  1572. if ! container:health:check-fix:"$check" "$container"; then
  1573. one_bad=1
  1574. fi
  1575. done
  1576. if [ -z "$opt_silent" ] && [ -z "$one_bad" ]; then
  1577. Elt "containers have been checked for ${DARKYELLOW}$service_name${NORMAL}"
  1578. Feedback
  1579. fi
  1580. done
  1581. if [ -z "$found" ]; then
  1582. if [ -z "$opt_silent" ]; then
  1583. if [ "${#SERVICES[@]}" -gt 0 ]; then
  1584. warn "No container for given services found in current project '$project_name'."
  1585. else
  1586. warn "No container found for current project '$project_name'."
  1587. fi
  1588. fi
  1589. return 1
  1590. fi
  1591. }
  1592. awk:require() {
  1593. local require_at_least="$1" version already_installed
  1594. while true; do
  1595. if ! version=$(awk --version 2>/dev/null); then
  1596. version=""
  1597. else
  1598. version=${version%%,*}
  1599. version=${version##* }
  1600. fi
  1601. if [ -z "$version" ] || version_gt "$require_at_least" "$version"; then
  1602. if [ -z "$already_installed" ]; then
  1603. if [ -z "$version" ]; then
  1604. info "No 'gawk' available, probably using a clone. Installing 'gawk'..."
  1605. else
  1606. info "Found gawk version '$version'. Updating 'gawk'..."
  1607. fi
  1608. apt-get install gawk -y </dev/null || {
  1609. err "Failed to install 'gawk'."
  1610. return 1
  1611. }
  1612. already_installed=true
  1613. else
  1614. if [ -z "$version" ]; then
  1615. err "No 'gawk' available even after having installed one"
  1616. else
  1617. err "'gawk' version '$version' is lower than required" \
  1618. "'$require_at_least' even after updating 'gawk'."
  1619. fi
  1620. return 1
  1621. fi
  1622. continue
  1623. fi
  1624. return 0
  1625. done
  1626. }
  1627. cmdline.spec.gnu stats
  1628. cmdline.spec::cmd:stats:run() {
  1629. : :optval: --format,-f "Either 'silent', 'raw', or 'pretty', default is pretty."
  1630. : :optfla: --silent,-s "Shorthand for '--format silent'"
  1631. : :optval: --resource,-r 'resource(s) separated with a comma'
  1632. local project_name service_name containers container check
  1633. if [[ -n "${opt_silent}" ]]; then
  1634. if [[ -n "${opt_format}" ]]; then
  1635. err "'--silent' conflict with option '--format'."
  1636. return 1
  1637. fi
  1638. opt_format=s
  1639. fi
  1640. opt_format="${opt_format:-pretty}"
  1641. case "${opt_format}" in
  1642. raw|r)
  1643. opt_format="raw"
  1644. :
  1645. ;;
  1646. silent|s)
  1647. opt_format="silent"
  1648. ;;
  1649. pretty|p)
  1650. opt_format="pretty"
  1651. awk:require 4.1.4 || return 1
  1652. ;;
  1653. *)
  1654. err "Invalid value '$opt_format' for option --format"
  1655. echo " use either 'raw' (shorthand 'r'), 'silent' (shorthand 's') or pretty (shorthand 'p')." >&2
  1656. return 1
  1657. esac
  1658. local resources=(c.{memory,network} load_avg)
  1659. if [ -n "${opt_resource}" ]; then
  1660. resources=(${opt_resource//,/ })
  1661. fi
  1662. local not_found=()
  1663. for resource in "${resources[@]}"; do
  1664. if ! fn.exists "stats:$resource"; then
  1665. not_found+=("$resource")
  1666. fi
  1667. done
  1668. if [[ "${#not_found[@]}" -gt 0 ]]; then
  1669. not_found_msg=$(printf "%s, " "${not_found[@]}")
  1670. not_found_msg=${not_found_msg%, }
  1671. err "Unsupported resource(s) provided: ${not_found_msg}"
  1672. echo " resource must be one-of:" >&2
  1673. declare -F | egrep -- '-fx? stats:[a-zA-Z0-9_.]+$' | cut -f 3- -d " " | cut -f 2- -d ":" | prefix " - " >&2
  1674. return 1
  1675. fi
  1676. :state-dir:
  1677. for resource in "${resources[@]}"; do
  1678. [ "$opt_format" == "pretty" ] && echo "${WHITE}$resource${NORMAL}:"
  1679. stats:"$resource" "$opt_format" 2>&1 | prefix " "
  1680. set_errlvl "${PIPESTATUS[0]}" || return 1
  1681. done
  1682. }
  1683. stats:c.memory() {
  1684. local format="$1"
  1685. local out
  1686. container_to_check=($(docker:running_containers)) || exit 1
  1687. out=$(docker:containers:stats "${container_to_check[@]}")
  1688. printf "%s\n" "$out" | rrd:update "containers" "memory|3:usage:GAUGE:U:U,4:inactive:GAUGE:U:U" || {
  1689. return 1
  1690. }
  1691. case "${format:-p}" in
  1692. raw|r)
  1693. printf "%s\n" "$out" | cut -f 1-5 -d " "
  1694. ;;
  1695. pretty|p)
  1696. awk:require 4.1.4 || return 1
  1697. {
  1698. echo "container" "__total____" "buffered____" "resident____"
  1699. printf "%s\n" "$out" |
  1700. awk '
  1701. {
  1702. offset = strftime("%z", $2);
  1703. print $1, substr($0, index($0,$3));
  1704. }' | cut -f 1-4 -d " " |
  1705. numfmt --field 2-4 --to=iec-i --format=%8.1fB |
  1706. sed -r 's/(\.[0-9])([A-Z]?iB)/\1:\2/g' |
  1707. sort
  1708. } | col:normalize:size -+++ |
  1709. sed -r 's/(\.[0-9]):([A-Z]?iB)/\1 \2/g' |
  1710. header:make
  1711. ;;
  1712. esac
  1713. }
  1714. stats:c.network() {
  1715. local format="$1"
  1716. local out
  1717. container_to_check=($(docker:running_containers)) || exit 1
  1718. out=$(docker:containers:stats "${container_to_check[@]}")
  1719. cols=(
  1720. {rx,tx}_{bytes,packets,errors,dropped}
  1721. )
  1722. idx=5 ## starting column idx for next fields
  1723. defs=()
  1724. for col in "${cols[@]}"; do
  1725. defs+=("$((idx++)):${col}:COUNTER:U:U")
  1726. done
  1727. OLDIFS="$IFS"
  1728. IFS="," defs="${defs[*]}"
  1729. IFS="$OLDIFS"
  1730. printf "%s\n" "$out" |
  1731. rrd:update "containers" \
  1732. "network|${defs}" || {
  1733. return 1
  1734. }
  1735. case "${format:-p}" in
  1736. raw|r)
  1737. printf "%s\n" "$out" | cut -f 1,2,7- -d " "
  1738. ;;
  1739. pretty|p)
  1740. awk:require 4.1.4 || return 1
  1741. {
  1742. echo "container" "_" "_" "_" "RX" "_" "_" "_" "TX"
  1743. echo "_" "__bytes____" "__packets" "__errors" "__dropped" "__bytes____" "__packets" "__errors" "__dropped"
  1744. printf "%s\n" "$out" |
  1745. awk '
  1746. {
  1747. offset = strftime("%z", $2);
  1748. print $1, substr($0, index($0,$7));
  1749. }' |
  1750. numfmt --field 2,6 --to=iec-i --format=%8.1fB |
  1751. numfmt --field 3,4,5,7,8,9 --to=si --format=%8.1f |
  1752. sed -r 's/(\.[0-9])([A-Z]?(iB|B)?)/\1:\2/g' |
  1753. sort
  1754. } | col:normalize:size -++++++++ |
  1755. sed -r '
  1756. s/(\.[0-9]):([A-Z]?iB)/\1 \2/g;
  1757. s/(\.[0-9]):([KMGTPE])/\1 \2/g;
  1758. s/ ([0-9]+)\.0:B/\1 /g;
  1759. s/ ([0-9]+)\.0:/\1 /g;
  1760. ' |
  1761. header:make 2
  1762. ;;
  1763. esac
  1764. }
  1765. header:make() {
  1766. local nb_line="${1:-1}"
  1767. local line
  1768. while ((nb_line-- > 0)); do
  1769. read-0a line
  1770. echo "${GRAY}$(printf "%s" "$line" | sed -r 's/_/ /g')${NORMAL}"
  1771. done
  1772. cat
  1773. }
  1774. stats:load_avg() {
  1775. local format="$1"
  1776. local out
  1777. out=$(host:sys:load_avg)
  1778. printf "%s\n" "$out" | rrd:update "" "load_avg|2:load_avg_1:GAUGE:U:U,3:load_avg_5:GAUGE:U:U,4:load_avg_15:GAUGE:U:U" || {
  1779. return 1
  1780. }
  1781. case "${format:-p}" in
  1782. raw|r)
  1783. printf "%s\n" "$out" | cut -f 2-5 -d " "
  1784. ;;
  1785. pretty|p)
  1786. {
  1787. echo "___1m" "___5m" "__15m"
  1788. printf "%s\n" "$out" | cut -f 3-5 -d " "
  1789. } | col:normalize:size +++ | header:make
  1790. ;;
  1791. esac
  1792. }
  1793. host:sys:load_avg() {
  1794. local uptime
  1795. uptime="$(uptime)"
  1796. uptime=${uptime##*: }
  1797. uptime=${uptime//,/}
  1798. printf "%s " "" "$(date +%s)" "$uptime"
  1799. }
  1800. cmdline::parse "$@"