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.

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