_common.sh 18 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580
  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. # INFOS
  30. # n (Node version management) utilise la variable PATH pour stocker le path de la version de node à utiliser.
  31. # C'est ainsi qu'il change de version
  32. # ynh_install_nodejs installe la version de nodejs demandée en argument, avec n
  33. # ynh_use_nodejs active une version de nodejs dans le script courant
  34. # 3 variables sont mises à disposition, et 2 sont stockées dans la config de l'app
  35. # - nodejs_path: Le chemin absolu de cette version de node
  36. # Utilisé pour des appels directs à node.
  37. # - nodejs_version: Simplement le numéro de version de nodejs pour cette application
  38. # - nodejs_use_version: Un alias pour charger une version de node dans le shell courant.
  39. # Utilisé pour démarrer un service ou un script qui utilise node ou npm
  40. # Dans ce cas, c'est $PATH qui contient le chemin de la version de node. Il doit être propagé sur les autres shell si nécessaire.
  41. n_install_dir="/opt/node_n"
  42. node_version_path="/opt/node_n/n/versions/node"
  43. # N_PREFIX est le dossier de n, il doit être chargé dans les variables d'environnement pour n.
  44. export N_PREFIX="$n_install_dir"
  45. ynh_install_n () {
  46. echo "Installation of N - Node.js version management" >&2
  47. # Build an app.src for n
  48. mkdir -p "../conf"
  49. echo "SOURCE_URL=https://github.com/tj/n/archive/v2.1.7.tar.gz
  50. SOURCE_SUM=2ba3c9d4dd3c7e38885b37e02337906a1ee91febe6d5c9159d89a9050f2eea8f" > "../conf/n.src"
  51. # Download and extract n
  52. ynh_setup_source "$n_install_dir/git" n
  53. # Install n
  54. (cd "$n_install_dir/git"
  55. PREFIX=$N_PREFIX make install 2>&1)
  56. }
  57. ynh_use_nodejs () {
  58. nodejs_version=$(ynh_app_setting_get $app nodejs_version)
  59. load_n_path="[[ :$PATH: == *\":$n_install_dir/bin:\"* ]] || PATH=\"$n_install_dir/bin:$PATH\"; N_PREFIX="$n_install_dir""
  60. nodejs_use_version="$n_install_dir/bin/n -q $nodejs_version"
  61. # "Load" a version of node
  62. eval $load_n_path; $nodejs_use_version
  63. # Get the absolute path of this version of node
  64. nodejs_path="$(n bin $nodejs_version)"
  65. # Make an alias for node use
  66. ynh_node_exec="eval $load_n_path; n use $nodejs_version"
  67. }
  68. ynh_install_nodejs () {
  69. # Use n, https://github.com/tj/n to manage the nodejs versions
  70. nodejs_version="$1"
  71. local n_install_script="https://git.io/n-install"
  72. # Create $n_install_dir
  73. mkdir -p "$n_install_dir"
  74. # Load n path in PATH
  75. CLEAR_PATH="$n_install_dir/bin:$PATH"
  76. # Remove /usr/local/bin in PATH in case of node has already setup.
  77. PATH=$(echo $CLEAR_PATH | sed 's@/usr/local/bin:@@')
  78. # Move an existing node binary, to avoid to block n.
  79. test -x /usr/bin/node && mv /usr/bin/node /usr/bin/node_n
  80. test -x /usr/bin/npm && mv /usr/bin/npm /usr/bin/npm_n
  81. # If n is not previously setup, install it
  82. if ! test n --version > /dev/null 2>&1
  83. then
  84. ynh_install_n
  85. fi
  86. # Modify the default N_PREFIX in n script
  87. ynh_replace_string "^N_PREFIX=\${N_PREFIX-.*}$" "N_PREFIX=\${N_PREFIX-$N_PREFIX}" "$n_install_dir/bin/n"
  88. # Restore /usr/local/bin in PATH
  89. PATH=$CLEAR_PATH
  90. # And replace the old node binary.
  91. test -x /usr/bin/node_n && mv /usr/bin/node_n /usr/bin/node
  92. test -x /usr/bin/npm_n && mv /usr/bin/npm_n /usr/bin/npm
  93. # Install the requested version of nodejs
  94. n $nodejs_version
  95. # Find the last "real" version for this major version of node.
  96. real_nodejs_version=$(find $node_version_path/$nodejs_version* -maxdepth 0 | sort --version-sort | tail --lines=1)
  97. real_nodejs_version=$(basename $real_nodejs_version)
  98. # Create a symbolic link for this major version. If the file doesn't already exist
  99. if [ ! -e "$node_version_path/$nodejs_version" ]
  100. then
  101. ln --symbolic --force --no-target-directory $node_version_path/$real_nodejs_version $node_version_path/$nodejs_version
  102. fi
  103. # Store the ID of this app and the version of node requested for it
  104. echo "$YNH_APP_ID:$nodejs_version" | tee --append "$n_install_dir/ynh_app_version"
  105. # Store nodejs_version into the config of this app
  106. ynh_app_setting_set $app nodejs_version $nodejs_version
  107. # Build the update script and set the cronjob
  108. ynh_cron_upgrade_node
  109. ynh_use_nodejs
  110. }
  111. ynh_remove_nodejs () {
  112. ynh_use_nodejs
  113. # Remove the line for this app
  114. sed --in-place "/$YNH_APP_ID:$nodejs_version/d" "$n_install_dir/ynh_app_version"
  115. # If none another app uses this version of nodejs, remove it.
  116. if ! grep --quiet "$nodejs_version" "$n_install_dir/ynh_app_version"
  117. then
  118. n rm $nodejs_version
  119. fi
  120. # If none another app uses n, remove n
  121. if [ ! -s "$n_install_dir/ynh_app_version" ]
  122. then
  123. ynh_secure_remove "$n_install_dir"
  124. ynh_secure_remove "/usr/local/n"
  125. sed --in-place "/N_PREFIX/d" /root/.bashrc
  126. fi
  127. }
  128. ynh_cron_upgrade_node () {
  129. # Build the update script
  130. cat > "$n_install_dir/node_update.sh" << EOF
  131. #!/bin/bash
  132. version_path="$node_version_path"
  133. n_install_dir="$n_install_dir"
  134. # Log the date
  135. date
  136. # List all real installed version of node
  137. all_real_version="\$(find \$version_path/* -maxdepth 0 -type d | sed "s@\$version_path/@@g")"
  138. # Keep only the major version number of each line
  139. all_real_version=\$(echo "\$all_real_version" | sed 's/\..*\$//')
  140. # Remove double entries
  141. all_real_version=\$(echo "\$all_real_version" | sort --unique)
  142. # Read each major version
  143. while read version
  144. do
  145. echo "Update of the version \$version"
  146. sudo \$n_install_dir/bin/n \$version
  147. # Find the last "real" version for this major version of node.
  148. real_nodejs_version=\$(find \$version_path/\$version* -maxdepth 0 | sort --version-sort | tail --lines=1)
  149. real_nodejs_version=\$(basename \$real_nodejs_version)
  150. # Update the symbolic link for this version
  151. sudo ln --symbolic --force --no-target-directory \$version_path/\$real_nodejs_version \$version_path/\$version
  152. done <<< "\$(echo "\$all_real_version")"
  153. EOF
  154. chmod +x "$n_install_dir/node_update.sh"
  155. # Build the cronjob
  156. cat > "/etc/cron.daily/node_update" << EOF
  157. #!/bin/bash
  158. $n_install_dir/node_update.sh >> $n_install_dir/node_update.log
  159. EOF
  160. chmod +x "/etc/cron.daily/node_update"
  161. }
  162. #=================================================
  163. # Start or restart a service and follow its booting
  164. #
  165. # usage: ynh_check_starting "Line to match" [Log file] [Timeout]
  166. #
  167. # | arg: Line to match - The line to find in the log to attest the service have finished to boot.
  168. # | arg: Log file - The log file to watch
  169. # /var/log/$app/$app.log will be used if no other log is defined.
  170. # | arg: Timeout - The maximum time to wait before ending the watching. Defaut 300 seconds.
  171. ynh_check_starting () {
  172. local line_to_match="$1"
  173. local app_log="${2:-/var/log/$app/$app.log}"
  174. local timeout=${3:-300}
  175. ynh_clean_check_starting () {
  176. # Stop the execution of tail.
  177. kill -s 15 $pid_tail 2>&1
  178. ynh_secure_remove "$templog" 2>&1
  179. }
  180. echo "Starting of $app" >&2
  181. systemctl restart $app
  182. local templog="$(mktemp)"
  183. # Following the starting of the app in its log
  184. tail -f -n1 "$app_log" > "$templog" &
  185. # Get the PID of the tail command
  186. local pid_tail=$!
  187. local i=0
  188. for i in `seq 1 $timeout`
  189. do
  190. # Read the log until the sentence is found, that means the app finished to start. Or run until the timeout
  191. if grep --quiet "$line_to_match" "$templog"
  192. then
  193. echo "The service $app has correctly started." >&2
  194. break
  195. fi
  196. echo -n "." >&2
  197. sleep 1
  198. done
  199. if [ $i -eq $timeout ]
  200. then
  201. echo "The service $app didn't fully started before the timeout." >&2
  202. fi
  203. echo ""
  204. ynh_clean_check_starting
  205. }
  206. #=================================================
  207. ynh_print_log () {
  208. echo "${1}"
  209. }
  210. # Print an info on stdout
  211. #
  212. # usage: ynh_print_info "Text to print"
  213. # | arg: text - The text to print
  214. ynh_print_info () {
  215. ynh_print_log "[INFO] ${1}"
  216. }
  217. # Print a warning on stderr
  218. #
  219. # usage: ynh_print_warn "Text to print"
  220. # | arg: text - The text to print
  221. ynh_print_warn () {
  222. ynh_print_log "[WARN] ${1}" >&2
  223. }
  224. # Print a error on stderr
  225. #
  226. # usage: ynh_print_err "Text to print"
  227. # | arg: text - The text to print
  228. ynh_print_err () {
  229. ynh_print_log "[ERR] ${1}" >&2
  230. }
  231. # Execute a command and print the result as an error
  232. #
  233. # usage: ynh_exec_err command to execute
  234. # usage: ynh_exec_err "command to execute | following command"
  235. # 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.
  236. #
  237. # | arg: command - command to execute
  238. ynh_exec_err () {
  239. ynh_print_err "$(eval $@)"
  240. }
  241. # Execute a command and print the result as a warning
  242. #
  243. # usage: ynh_exec_warn command to execute
  244. # usage: ynh_exec_warn "command to execute | following command"
  245. # 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.
  246. #
  247. # | arg: command - command to execute
  248. ynh_exec_warn () {
  249. ynh_print_warn "$(eval $@)"
  250. }
  251. # Execute a command and force the result to be printed on stdout
  252. #
  253. # usage: ynh_exec_warn_less command to execute
  254. # usage: ynh_exec_warn_less "command to execute | following command"
  255. # 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.
  256. #
  257. # | arg: command - command to execute
  258. ynh_exec_warn_less () {
  259. eval $@ 2>&1
  260. }
  261. # Execute a command and redirect stdout in /dev/null
  262. #
  263. # usage: ynh_exec_quiet command to execute
  264. # usage: ynh_exec_quiet "command to execute | following command"
  265. # 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.
  266. #
  267. # | arg: command - command to execute
  268. ynh_exec_quiet () {
  269. eval $@ > /dev/null
  270. }
  271. # Execute a command and redirect stdout and stderr in /dev/null
  272. #
  273. # usage: ynh_exec_fully_quiet command to execute
  274. # usage: ynh_exec_fully_quiet "command to execute | following command"
  275. # 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.
  276. #
  277. # | arg: command - command to execute
  278. ynh_exec_fully_quiet () {
  279. eval $@ > /dev/null 2>&1
  280. }
  281. # Remove any logs for all the following commands.
  282. #
  283. # usage: ynh_print_OFF
  284. # WARNING: You should be careful with this helper, and never forgot to use ynh_print_ON as soon as possible to restore the logging.
  285. ynh_print_OFF () {
  286. set +x
  287. }
  288. # Restore the logging after ynh_print_OFF
  289. #
  290. # usage: ynh_print_ON
  291. ynh_print_ON () {
  292. set -x
  293. # Print an echo only for the log, to be able to know that ynh_print_ON has been called.
  294. echo ynh_print_ON > /dev/null
  295. }
  296. #=================================================
  297. # Install or update the main directory yunohost.multimedia
  298. #
  299. # usage: ynh_multimedia_build_main_dir
  300. ynh_multimedia_build_main_dir () {
  301. wget -nv https://github.com/YunoHost-Apps/yunohost.multimedia/archive/master.zip 2>&1
  302. unzip -q master.zip
  303. ./yunohost.multimedia-master/script/ynh_media_build.sh
  304. }
  305. # Add a directory in yunohost.multimedia
  306. # This "directory" will be a symbolic link to a existing directory.
  307. #
  308. # usage: ynh_multimedia_addfolder "Source directory" "Destination directory"
  309. #
  310. # | arg: Source directory - The real directory which contains your medias.
  311. # | arg: Destination directory - The name and the place of the symbolic link, relative to "/home/yunohost.multimedia"
  312. ynh_multimedia_addfolder () {
  313. local source_dir="$1"
  314. local dest_dir="$2"
  315. ./yunohost.multimedia-master/script/ynh_media_addfolder.sh --source="$source_dir" --dest="$dest_dir"
  316. }
  317. # Move a directory in yunohost.multimedia, and replace by a symbolic link
  318. #
  319. # usage: ynh_multimedia_movefolder "Source directory" "Destination directory"
  320. #
  321. # | arg: Source directory - The real directory which contains your medias.
  322. # It will be moved to "Destination directory"
  323. # A symbolic link will replace it.
  324. # | arg: Destination directory - The new name and place of the directory, relative to "/home/yunohost.multimedia"
  325. ynh_multimedia_movefolder () {
  326. local source_dir="$1"
  327. local dest_dir="$2"
  328. ./yunohost.multimedia-master/script/ynh_media_addfolder.sh --inv --source="$source_dir" --dest="$dest_dir"
  329. }
  330. # Allow an user to have an write authorisation in multimedia directories
  331. #
  332. # usage: ynh_multimedia_addaccess user_name
  333. #
  334. # | arg: user_name - The name of the user which gain this access.
  335. ynh_multimedia_addaccess () {
  336. local user_name=$1
  337. groupadd -f multimedia
  338. usermod -a -G multimedia $user_name
  339. }
  340. #=================================================
  341. # Create a dedicated fail2ban config (jail and filter conf files)
  342. #
  343. # usage: ynh_add_fail2ban_config log_file filter [max_retry [ports]]
  344. # | arg: log_file - Log file to be checked by fail2ban
  345. # | arg: failregex - Failregex to be looked for by fail2ban
  346. # | arg: max_retry - Maximum number of retries allowed before banning IP address - default: 3
  347. # | arg: ports - Ports blocked for a banned IP address - default: http,https
  348. ynh_add_fail2ban_config () {
  349. # Process parameters
  350. logpath=$1
  351. failregex=$2
  352. max_retry=${3:-3}
  353. ports=${4:-http,https}
  354. test -n "$logpath" || ynh_die "ynh_add_fail2ban_config expects a logfile path as first argument and received nothing."
  355. test -n "$failregex" || ynh_die "ynh_add_fail2ban_config expects a failure regex as second argument and received nothing."
  356. finalfail2banjailconf="/etc/fail2ban/jail.d/$app.conf"
  357. finalfail2banfilterconf="/etc/fail2ban/filter.d/$app.conf"
  358. ynh_backup_if_checksum_is_different "$finalfail2banjailconf" 1
  359. ynh_backup_if_checksum_is_different "$finalfail2banfilterconf" 1
  360. sudo tee $finalfail2banjailconf <<EOF
  361. [$app]
  362. enabled = true
  363. port = $ports
  364. filter = $app
  365. logpath = $logpath
  366. maxretry = $max_retry"
  367. EOF
  368. sudo tee $finalfail2banfilterconf <<EOF
  369. [INCLUDES]
  370. before = common.conf
  371. [Definition]
  372. failregex = $failregex
  373. ignoreregrex ="
  374. EOF
  375. ynh_store_file_checksum "$finalfail2banjailconf"
  376. ynh_store_file_checksum "$finalfail2banfilterconf"
  377. sudo systemctl restart fail2ban
  378. }
  379. # Remove the dedicated fail2ban config (jail and filter conf files)
  380. #
  381. # usage: ynh_remove_fail2ban_config
  382. ynh_remove_fail2ban_config () {
  383. ynh_secure_remove "/etc/fail2ban/jail.d/$app.conf"
  384. ynh_secure_remove "/etc/fail2ban/filter.d/$app.conf"
  385. sudo systemctl restart fail2ban
  386. }
  387. #=================================================
  388. # Read the value of a key in a ynh manifest file
  389. #
  390. # usage: ynh_read_manifest manifest key
  391. # | arg: manifest - Path of the manifest to read
  392. # | arg: key - Name of the key to find
  393. ynh_read_manifest () {
  394. manifest="$1"
  395. key="$2"
  396. python3 -c "import sys, json;print(json.load(open('$manifest'))['$key'])"
  397. }
  398. # Exit without error if the package is up to date
  399. #
  400. # This helper should be used to avoid an upgrade of a package
  401. # when it's not needed.
  402. #
  403. # To force an upgrade, even if the package is up to date,
  404. # you have to set the variable YNH_FORCE_UPGRADE before.
  405. # example: sudo YNH_FORCE_UPGRADE=1 yunohost app upgrade MyApp
  406. #
  407. # usage: ynh_abort_if_up_to_date
  408. ynh_abort_if_up_to_date () {
  409. local force_upgrade=${YNH_FORCE_UPGRADE:-0}
  410. local package_check=${PACKAGE_CHECK_EXEC:-0}
  411. local version=$(ynh_read_manifest "/etc/yunohost/apps/$YNH_APP_INSTANCE_NAME/manifest.json" "version" || echo 1.0)
  412. local last_version=$(ynh_read_manifest "../manifest.json" "version" || echo 1.0)
  413. if [ "$version" = "$last_version" ]
  414. then
  415. if [ "$force_upgrade" != "0" ]
  416. then
  417. echo "Upgrade forced by YNH_FORCE_UPGRADE." >&2
  418. unset YNH_FORCE_UPGRADE
  419. elif [ "$package_check" != "0" ]
  420. then
  421. echo "Upgrade forced for package check." >&2
  422. else
  423. ynh_die "Up-to-date, nothing to do" 0
  424. fi
  425. fi
  426. }
  427. #=================================================
  428. # Send an email to inform the administrator
  429. #
  430. # usage: ynh_send_readme_to_admin app_message [recipients]
  431. # | arg: app_message - The message to send to the administrator.
  432. # | arg: recipients - The recipients of this email. Use spaces to separate multiples recipients. - default: root
  433. # example: "root admin@domain"
  434. # If you give the name of a YunoHost user, ynh_send_readme_to_admin will find its email adress for you
  435. # example: "root admin@domain user1 user2"
  436. ynh_send_readme_to_admin() {
  437. local app_message="${1:-...No specific informations...}"
  438. local recipients="${2:-root}"
  439. # Retrieve the email of users
  440. find_mails () {
  441. local list_mails="$1"
  442. local mail
  443. local recipients=" "
  444. # Read each mail in argument
  445. for mail in $list_mails
  446. do
  447. # Keep root or a real email address as it is
  448. if [ "$mail" = "root" ] || echo "$mail" | grep --quiet "@"
  449. then
  450. recipients="$recipients $mail"
  451. else
  452. # But replace an user name without a domain after by its email
  453. if mail=$(ynh_user_get_info "$mail" "mail" 2> /dev/null)
  454. then
  455. recipients="$recipients $mail"
  456. fi
  457. fi
  458. done
  459. echo "$recipients"
  460. }
  461. recipients=$(find_mails "$recipients")
  462. local mail_subject="☁️🆈🅽🅷☁️: \`$app\` was just installed!"
  463. local mail_message="This is an automated message from your beloved YunoHost server.
  464. Specific informations for the application $app.
  465. $app_message
  466. ---
  467. Automatic diagnosis data from YunoHost
  468. $(yunohost tools diagnosis | grep -B 100 "services:" | sed '/services:/d')"
  469. # Send the email to the recipients
  470. echo "$mail_message" | mail -a "Content-Type: text/plain; charset=UTF-8" -s "$mail_subject" "$recipients"
  471. }
  472. #=================================================
  473. #============= FUTURE YUNOHOST HELPER ============
  474. #=================================================
  475. # Delete a file checksum from the app settings
  476. #
  477. # $app should be defined when calling this helper
  478. #
  479. # usage: ynh_remove_file_checksum file
  480. # | arg: file - The file for which the checksum will be deleted
  481. ynh_delete_file_checksum () {
  482. local checksum_setting_name=checksum_${1//[\/ ]/_} # Replace all '/' and ' ' by '_'
  483. ynh_app_setting_delete $app $checksum_setting_name
  484. }