_common.sh 18 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575
  1. #!/bin/bash
  2. #=================================================
  3. # BACKUP
  4. #=================================================
  5. HUMAN_SIZE () { # Transforme une taille en Ko en une taille lisible pour un humain
  6. human=$(numfmt --to=iec --from-unit=1K $1)
  7. echo $human
  8. }
  9. CHECK_SIZE () { # Vérifie avant chaque backup que l'espace est suffisant
  10. file_to_analyse=$1
  11. backup_size=$(du --summarize "$file_to_analyse" | cut -f1)
  12. free_space=$(df --output=avail "/home/yunohost.backup" | sed 1d)
  13. if [ $free_space -le $backup_size ]
  14. then
  15. ynh_print_err "Espace insuffisant pour sauvegarder $file_to_analyse."
  16. ynh_print_err "Espace disponible: $(HUMAN_SIZE $free_space)"
  17. ynh_die "Espace nécessaire: $(HUMAN_SIZE $backup_size)"
  18. fi
  19. }
  20. #=================================================
  21. # PACKAGE CHECK BYPASSING...
  22. #=================================================
  23. IS_PACKAGE_CHECK () { # Détermine une exécution en conteneur (Non testé)
  24. return $(uname -n | grep -c 'pchecker_lxc')
  25. }
  26. #=================================================
  27. # EXPERIMENTAL HELPERS
  28. #=================================================
  29. # Start or restart a service and follow its booting
  30. #
  31. # usage: ynh_check_starting "Line to match" [Log file] [Timeout] [Service name]
  32. #
  33. # | arg: Line to match - The line to find in the log to attest the service have finished to boot.
  34. # | arg: Log file - The log file to watch; specify "systemd" to read systemd journal for specified service
  35. # /var/log/$app/$app.log will be used if no other log is defined.
  36. # | arg: Timeout - The maximum time to wait before ending the watching. Defaut 300 seconds.
  37. # | arg: Service name
  38. ynh_check_starting () {
  39. local line_to_match="$1"
  40. local app_log="${2:-/var/log/$service_name/$service_name.log}"
  41. local timeout=${3:-300}
  42. local service_name="${4:-$app}"
  43. echo "Starting of $service_name" >&2
  44. systemctl stop $service_name
  45. local templog="$(mktemp)"
  46. # Following the starting of the app in its log
  47. if [ "$app_log" == "systemd" ] ; then
  48. # Read the systemd journal
  49. journalctl -u $service_name -f --since=-45 > "$templog" &
  50. else
  51. # Read the specified log file
  52. tail -F -n0 "$app_log" > "$templog" &
  53. fi
  54. # Get the PID of the last command
  55. local pid_tail=$!
  56. systemctl start $service_name
  57. local i=0
  58. for i in `seq 1 $timeout`
  59. do
  60. # Read the log until the sentence is found, which means the app finished starting. Or run until the timeout.
  61. if grep --quiet "$line_to_match" "$templog"
  62. then
  63. echo "The service $service_name has correctly started." >&2
  64. break
  65. fi
  66. echo -n "." >&2
  67. sleep 1
  68. done
  69. if [ $i -eq $timeout ]
  70. then
  71. echo "The service $service_name didn't fully start before the timeout." >&2
  72. fi
  73. echo ""
  74. ynh_clean_check_starting
  75. }
  76. # Clean temporary process and file used by ynh_check_starting
  77. # (usually used in ynh_clean_setup scripts)
  78. #
  79. # usage: ynh_clean_check_starting
  80. ynh_clean_check_starting () {
  81. # Stop the execution of tail.
  82. kill -s 15 $pid_tail 2>&1
  83. ynh_secure_remove "$templog" 2>&1
  84. }
  85. #=================================================
  86. ynh_print_log () {
  87. echo "${1}"
  88. }
  89. # Print an info on stdout
  90. #
  91. # usage: ynh_print_info "Text to print"
  92. # | arg: text - The text to print
  93. ynh_print_info () {
  94. ynh_print_log "[INFO] ${1}"
  95. }
  96. # Print a warning on stderr
  97. #
  98. # usage: ynh_print_warn "Text to print"
  99. # | arg: text - The text to print
  100. ynh_print_warn () {
  101. ynh_print_log "[WARN] ${1}" >&2
  102. }
  103. # Print a error on stderr
  104. #
  105. # usage: ynh_print_err "Text to print"
  106. # | arg: text - The text to print
  107. ynh_print_err () {
  108. ynh_print_log "[ERR] ${1}" >&2
  109. }
  110. # Execute a command and print the result as an error
  111. #
  112. # usage: ynh_exec_err command to execute
  113. # usage: ynh_exec_err "command to execute | following command"
  114. # In case of use of pipes, you have to use double quotes. Otherwise, this helper will be executed with the first command, then be send to the next pipe.
  115. #
  116. # | arg: command - command to execute
  117. ynh_exec_err () {
  118. ynh_print_err "$(eval $@)"
  119. }
  120. # Execute a command and print the result as a warning
  121. #
  122. # usage: ynh_exec_warn command to execute
  123. # usage: ynh_exec_warn "command to execute | following command"
  124. # In case of use of pipes, you have to use double quotes. Otherwise, this helper will be executed with the first command, then be send to the next pipe.
  125. #
  126. # | arg: command - command to execute
  127. ynh_exec_warn () {
  128. ynh_print_warn "$(eval $@)"
  129. }
  130. # Execute a command and force the result to be printed on stdout
  131. #
  132. # usage: ynh_exec_warn_less command to execute
  133. # usage: ynh_exec_warn_less "command to execute | following command"
  134. # In case of use of pipes, you have to use double quotes. Otherwise, this helper will be executed with the first command, then be send to the next pipe.
  135. #
  136. # | arg: command - command to execute
  137. ynh_exec_warn_less () {
  138. eval $@ 2>&1
  139. }
  140. # Execute a command and redirect stdout in /dev/null
  141. #
  142. # usage: ynh_exec_quiet command to execute
  143. # usage: ynh_exec_quiet "command to execute | following command"
  144. # In case of use of pipes, you have to use double quotes. Otherwise, this helper will be executed with the first command, then be send to the next pipe.
  145. #
  146. # | arg: command - command to execute
  147. ynh_exec_quiet () {
  148. eval $@ > /dev/null
  149. }
  150. # Execute a command and redirect stdout and stderr in /dev/null
  151. #
  152. # usage: ynh_exec_fully_quiet command to execute
  153. # usage: ynh_exec_fully_quiet "command to execute | following command"
  154. # In case of use of pipes, you have to use double quotes. Otherwise, this helper will be executed with the first command, then be send to the next pipe.
  155. #
  156. # | arg: command - command to execute
  157. ynh_exec_fully_quiet () {
  158. eval $@ > /dev/null 2>&1
  159. }
  160. # Remove any logs for all the following commands.
  161. #
  162. # usage: ynh_print_OFF
  163. # WARNING: You should be careful with this helper, and never forgot to use ynh_print_ON as soon as possible to restore the logging.
  164. ynh_print_OFF () {
  165. set +x
  166. }
  167. # Restore the logging after ynh_print_OFF
  168. #
  169. # usage: ynh_print_ON
  170. ynh_print_ON () {
  171. set -x
  172. # Print an echo only for the log, to be able to know that ynh_print_ON has been called.
  173. echo ynh_print_ON > /dev/null
  174. }
  175. #=================================================
  176. # Install or update the main directory yunohost.multimedia
  177. #
  178. # usage: ynh_multimedia_build_main_dir
  179. ynh_multimedia_build_main_dir () {
  180. local ynh_media_release="v1.0"
  181. local checksum="4852c8607db820ad51f348da0dcf0c88"
  182. # Download yunohost.multimedia scripts
  183. wget -nv https://github.com/YunoHost-Apps/yunohost.multimedia/archive/${ynh_media_release}.tar.gz
  184. # Check the control sum
  185. echo "${checksum} ${ynh_media_release}.tar.gz" | md5sum -c --status \
  186. || ynh_die "Corrupt source"
  187. # Extract
  188. mkdir yunohost.multimedia-master
  189. tar -xf ${ynh_media_release}.tar.gz -C yunohost.multimedia-master --strip-components 1
  190. ./yunohost.multimedia-master/script/ynh_media_build.sh
  191. }
  192. # Add a directory in yunohost.multimedia
  193. # This "directory" will be a symbolic link to a existing directory.
  194. #
  195. # usage: ynh_multimedia_addfolder "Source directory" "Destination directory"
  196. #
  197. # | arg: Source directory - The real directory which contains your medias.
  198. # | arg: Destination directory - The name and the place of the symbolic link, relative to "/home/yunohost.multimedia"
  199. ynh_multimedia_addfolder () {
  200. local source_dir="$1"
  201. local dest_dir="$2"
  202. ./yunohost.multimedia-master/script/ynh_media_addfolder.sh --source="$source_dir" --dest="$dest_dir"
  203. }
  204. # Move a directory in yunohost.multimedia, and replace by a symbolic link
  205. #
  206. # usage: ynh_multimedia_movefolder "Source directory" "Destination directory"
  207. #
  208. # | arg: Source directory - The real directory which contains your medias.
  209. # It will be moved to "Destination directory"
  210. # A symbolic link will replace it.
  211. # | arg: Destination directory - The new name and place of the directory, relative to "/home/yunohost.multimedia"
  212. ynh_multimedia_movefolder () {
  213. local source_dir="$1"
  214. local dest_dir="$2"
  215. ./yunohost.multimedia-master/script/ynh_media_addfolder.sh --inv --source="$source_dir" --dest="$dest_dir"
  216. }
  217. # Allow an user to have an write authorisation in multimedia directories
  218. #
  219. # usage: ynh_multimedia_addaccess user_name
  220. #
  221. # | arg: user_name - The name of the user which gain this access.
  222. ynh_multimedia_addaccess () {
  223. local user_name=$1
  224. groupadd -f multimedia
  225. usermod -a -G multimedia $user_name
  226. }
  227. #=================================================
  228. # Create a dedicated fail2ban config (jail and filter conf files)
  229. #
  230. # usage: ynh_add_fail2ban_config log_file filter [max_retry [ports]]
  231. # | arg: log_file - Log file to be checked by fail2ban
  232. # | arg: failregex - Failregex to be looked for by fail2ban
  233. # | arg: max_retry - Maximum number of retries allowed before banning IP address - default: 3
  234. # | arg: ports - Ports blocked for a banned IP address - default: http,https
  235. ynh_add_fail2ban_config () {
  236. # Process parameters
  237. logpath=$1
  238. failregex=$2
  239. max_retry=${3:-3}
  240. ports=${4:-http,https}
  241. test -n "$logpath" || ynh_die "ynh_add_fail2ban_config expects a logfile path as first argument and received nothing."
  242. test -n "$failregex" || ynh_die "ynh_add_fail2ban_config expects a failure regex as second argument and received nothing."
  243. finalfail2banjailconf="/etc/fail2ban/jail.d/$app.conf"
  244. finalfail2banfilterconf="/etc/fail2ban/filter.d/$app.conf"
  245. ynh_backup_if_checksum_is_different "$finalfail2banjailconf" 1
  246. ynh_backup_if_checksum_is_different "$finalfail2banfilterconf" 1
  247. sudo tee $finalfail2banjailconf <<EOF
  248. [$app]
  249. enabled = true
  250. port = $ports
  251. filter = $app
  252. logpath = $logpath
  253. maxretry = $max_retry
  254. EOF
  255. sudo tee $finalfail2banfilterconf <<EOF
  256. [INCLUDES]
  257. before = common.conf
  258. [Definition]
  259. failregex = $failregex
  260. ignoreregex =
  261. EOF
  262. ynh_store_file_checksum "$finalfail2banjailconf"
  263. ynh_store_file_checksum "$finalfail2banfilterconf"
  264. systemctl reload fail2ban
  265. local fail2ban_error="$(journalctl -u fail2ban | tail -n50 | grep "WARNING.*$app.*")"
  266. if [ -n "$fail2ban_error" ]
  267. then
  268. echo "[ERR] Fail2ban failed to load the jail for $app" >&2
  269. echo "WARNING${fail2ban_error#*WARNING}" >&2
  270. fi
  271. }
  272. # Remove the dedicated fail2ban config (jail and filter conf files)
  273. #
  274. # usage: ynh_remove_fail2ban_config
  275. ynh_remove_fail2ban_config () {
  276. ynh_secure_remove "/etc/fail2ban/jail.d/$app.conf"
  277. ynh_secure_remove "/etc/fail2ban/filter.d/$app.conf"
  278. systemctl reload fail2ban
  279. }
  280. #=================================================
  281. # Read the value of a key in a ynh manifest file
  282. #
  283. # usage: ynh_read_manifest manifest key
  284. # | arg: manifest - Path of the manifest to read
  285. # | arg: key - Name of the key to find
  286. ynh_read_manifest () {
  287. manifest="$1"
  288. key="$2"
  289. python3 -c "import sys, json;print(json.load(open('$manifest', encoding='utf-8'))['$key'])"
  290. }
  291. # Read the upstream version from the manifest
  292. # The version number in the manifest is defined by <upstreamversion>~ynh<packageversion>
  293. # For example : 4.3-2~ynh3
  294. # This include the number before ~ynh
  295. # In the last example it return 4.3-2
  296. #
  297. # usage: ynh_app_upstream_version
  298. ynh_app_upstream_version () {
  299. manifest_path="../manifest.json"
  300. if [ ! -e "$manifest_path" ]; then
  301. manifest_path="../settings/manifest.json" # Into the restore script, the manifest is not at the same place
  302. fi
  303. version_key=$(ynh_read_manifest "$manifest_path" "version")
  304. echo "${version_key/~ynh*/}"
  305. }
  306. # Read package version from the manifest
  307. # The version number in the manifest is defined by <upstreamversion>~ynh<packageversion>
  308. # For example : 4.3-2~ynh3
  309. # This include the number after ~ynh
  310. # In the last example it return 3
  311. #
  312. # usage: ynh_app_package_version
  313. ynh_app_package_version () {
  314. manifest_path="../manifest.json"
  315. if [ ! -e "$manifest_path" ]; then
  316. manifest_path="../settings/manifest.json" # Into the restore script, the manifest is not at the same place
  317. fi
  318. version_key=$(ynh_read_manifest "$manifest_path" "version")
  319. echo "${version_key/*~ynh/}"
  320. }
  321. # Exit without error if the package is up to date
  322. #
  323. # This helper should be used to avoid an upgrade of a package
  324. # when it's not needed.
  325. #
  326. # To force an upgrade, even if the package is up to date,
  327. # you have to set the variable YNH_FORCE_UPGRADE before.
  328. # example: sudo YNH_FORCE_UPGRADE=1 yunohost app upgrade MyApp
  329. #
  330. # usage: ynh_abort_if_up_to_date
  331. ynh_abort_if_up_to_date () {
  332. local force_upgrade=${YNH_FORCE_UPGRADE:-0}
  333. local package_check=${PACKAGE_CHECK_EXEC:-0}
  334. local version=$(ynh_read_manifest "/etc/yunohost/apps/$YNH_APP_INSTANCE_NAME/manifest.json" "version" || echo 1.0)
  335. local last_version=$(ynh_read_manifest "../manifest.json" "version" || echo 1.0)
  336. if [ "$version" = "$last_version" ]
  337. then
  338. if [ "$force_upgrade" != "0" ]
  339. then
  340. echo "Upgrade forced by YNH_FORCE_UPGRADE." >&2
  341. unset YNH_FORCE_UPGRADE
  342. elif [ "$package_check" != "0" ]
  343. then
  344. echo "Upgrade forced for package check." >&2
  345. else
  346. ynh_die "Up-to-date, nothing to do" 0
  347. fi
  348. fi
  349. }
  350. #=================================================
  351. # Send an email to inform the administrator
  352. #
  353. # usage: ynh_send_readme_to_admin app_message [recipients]
  354. # | arg: app_message - The message to send to the administrator.
  355. # | arg: recipients - The recipients of this email. Use spaces to separate multiples recipients. - default: root
  356. # example: "root admin@domain"
  357. # If you give the name of a YunoHost user, ynh_send_readme_to_admin will find its email adress for you
  358. # example: "root admin@domain user1 user2"
  359. ynh_send_readme_to_admin() {
  360. local app_message="${1:-...No specific information...}"
  361. local recipients="${2:-root}"
  362. # Retrieve the email of users
  363. find_mails () {
  364. local list_mails="$1"
  365. local mail
  366. local recipients=" "
  367. # Read each mail in argument
  368. for mail in $list_mails
  369. do
  370. # Keep root or a real email address as it is
  371. if [ "$mail" = "root" ] || echo "$mail" | grep --quiet "@"
  372. then
  373. recipients="$recipients $mail"
  374. else
  375. # But replace an user name without a domain after by its email
  376. if mail=$(ynh_user_get_info "$mail" "mail" 2> /dev/null)
  377. then
  378. recipients="$recipients $mail"
  379. fi
  380. fi
  381. done
  382. echo "$recipients"
  383. }
  384. recipients=$(find_mails "$recipients")
  385. local mail_subject="☁️🆈🅽🅷☁️: \`$app\` was just installed!"
  386. local mail_message="This is an automated message from your beloved YunoHost server.
  387. Specific information for the application $app.
  388. $app_message
  389. ---
  390. Automatic diagnosis data from YunoHost
  391. $(yunohost tools diagnosis | grep -B 100 "services:" | sed '/services:/d')"
  392. # Define binary to use for mail command
  393. if [ -e /usr/bin/bsd-mailx ]
  394. then
  395. local mail_bin=/usr/bin/bsd-mailx
  396. else
  397. local mail_bin=/usr/bin/mail.mailutils
  398. fi
  399. # Send the email to the recipients
  400. echo "$mail_message" | $mail_bin -a "Content-Type: text/plain; charset=UTF-8" -s "$mail_subject" "$recipients"
  401. }
  402. #=================================================
  403. # Reload (or other actions) a service and print a log in case of failure.
  404. #
  405. # usage: ynh_system_reload service_name [action]
  406. # | arg: service_name - Name of the service to reload
  407. # | arg: action - Action to perform with systemctl. Default: reload
  408. ynh_system_reload () {
  409. local service_name=$1
  410. local action=${2:-reload}
  411. # Reload, restart or start and print the log if the service fail to start or reload
  412. systemctl $action $service_name || ( journalctl --lines=20 -u $service_name >&2 && false)
  413. }
  414. #=================================================
  415. ynh_debian_release () {
  416. lsb_release --codename --short
  417. }
  418. is_stretch () {
  419. if [ "$(ynh_debian_release)" == "stretch" ]
  420. then
  421. return 0
  422. else
  423. return 1
  424. fi
  425. }
  426. is_jessie () {
  427. if [ "$(ynh_debian_release)" == "jessie" ]
  428. then
  429. return 0
  430. else
  431. return 1
  432. fi
  433. }
  434. #=================================================
  435. # Delete a file checksum from the app settings
  436. #
  437. # $app should be defined when calling this helper
  438. #
  439. # usage: ynh_remove_file_checksum file
  440. # | arg: file - The file for which the checksum will be deleted
  441. ynh_delete_file_checksum () {
  442. local checksum_setting_name=checksum_${1//[\/ ]/_} # Replace all '/' and ' ' by '_'
  443. ynh_app_setting_delete $app $checksum_setting_name
  444. }
  445. #=================================================
  446. ynh_maintenance_mode_ON () {
  447. # Create an html to serve as maintenance notice
  448. echo "<!DOCTYPE html>
  449. <html>
  450. <head>
  451. <meta http-equiv="refresh" content="3">
  452. <title>Your app $app is currently under maintenance!</title>
  453. <style>
  454. body {
  455. width: 70em;
  456. margin: 0 auto;
  457. }
  458. </style>
  459. </head>
  460. <body>
  461. <h1>Your app $app is currently under maintenance!</h1>
  462. <p>This app has been put under maintenance by your administrator at $(date)</p>
  463. <p>Please wait until the maintenance operation is done. This page will be reloaded as soon as your app will be back.</p>
  464. </body>
  465. </html>" > "/var/www/html/maintenance.$app.html"
  466. # Create a new nginx config file to redirect all access to the app to the maintenance notice instead.
  467. echo "# All request to the app will be redirected to ${path_url}_maintenance and fall on the maintenance notice
  468. rewrite ^${path_url}/(.*)$ ${path_url}_maintenance/? redirect;
  469. # Use another location, to not be in conflict with the original config file
  470. location ${path_url}_maintenance/ {
  471. alias /var/www/html/ ;
  472. try_files maintenance.$app.html =503;
  473. # Include SSOWAT user panel.
  474. include conf.d/yunohost_panel.conf.inc;
  475. }" > "/etc/nginx/conf.d/$domain.d/maintenance.$app.conf"
  476. # The current config file will redirect all requests to the root of the app.
  477. # To keep the full path, we can use the following rewrite rule:
  478. # rewrite ^${path_url}/(.*)$ ${path_url}_maintenance/\$1? redirect;
  479. # The difference will be in the $1 at the end, which keep the following queries.
  480. # But, if it works perfectly for a html request, there's an issue with any php files.
  481. # This files are treated as simple files, and will be downloaded by the browser.
  482. # Would be really be nice to be able to fix that issue. So that, when the page is reloaded after the maintenance, the user will be redirected to the real page he was.
  483. systemctl reload nginx
  484. }
  485. ynh_maintenance_mode_OFF () {
  486. # Rewrite the nginx config file to redirect from ${path_url}_maintenance to the real url of the app.
  487. echo "rewrite ^${path_url}_maintenance/(.*)$ ${path_url}/\$1 redirect;" > "/etc/nginx/conf.d/$domain.d/maintenance.$app.conf"
  488. systemctl reload nginx
  489. # Sleep 4 seconds to let the browser reload the pages and redirect the user to the app.
  490. sleep 4
  491. # Then remove the temporary files used for the maintenance.
  492. rm "/var/www/html/maintenance.$app.html"
  493. rm "/etc/nginx/conf.d/$domain.d/maintenance.$app.conf"
  494. systemctl reload nginx
  495. }