_common.sh 26 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735
  1. #!/bin/bash
  2. #=================================================
  3. # PERSONAL HELPERS
  4. #=================================================
  5. #=================================================
  6. # BACKUP
  7. #=================================================
  8. HUMAN_SIZE () { # Transforme une taille en Ko en une taille lisible pour un humain
  9. human=$(numfmt --to=iec --from-unit=1K $1)
  10. echo $human
  11. }
  12. CHECK_SIZE () { # Vérifie avant chaque backup que l'espace est suffisant
  13. file_to_analyse=$1
  14. backup_size=$(du --summarize "$file_to_analyse" | cut -f1)
  15. free_space=$(df --output=avail "/home/yunohost.backup" | sed 1d)
  16. if [ $free_space -le $backup_size ]
  17. then
  18. ynh_print_err "Espace insuffisant pour sauvegarder $file_to_analyse."
  19. ynh_print_err "Espace disponible: $(HUMAN_SIZE $free_space)"
  20. ynh_die "Espace nécessaire: $(HUMAN_SIZE $backup_size)"
  21. fi
  22. }
  23. #=================================================
  24. # PACKAGE CHECK BYPASSING...
  25. #=================================================
  26. IS_PACKAGE_CHECK () {
  27. if [ ${PACKAGE_CHECK_EXEC:-0} -eq 1 ]
  28. then
  29. return 0
  30. else
  31. return 1
  32. fi
  33. }
  34. #=================================================
  35. # FUTUR OFFICIAL HELPERS
  36. #=================================================
  37. # Install or update the main directory yunohost.multimedia
  38. #
  39. # usage: ynh_multimedia_build_main_dir
  40. ynh_multimedia_build_main_dir () {
  41. local ynh_media_release="v1.2"
  42. local checksum="806a827ba1902d6911095602a9221181"
  43. # Download yunohost.multimedia scripts
  44. wget -nv https://github.com/YunoHost-Apps/yunohost.multimedia/archive/${ynh_media_release}.tar.gz
  45. # Check the control sum
  46. echo "${checksum} ${ynh_media_release}.tar.gz" | md5sum -c --status \
  47. || ynh_die "Corrupt source"
  48. # Check if the package acl is installed. Or install it.
  49. ynh_package_is_installed 'acl' \
  50. || ynh_package_install acl
  51. # Extract
  52. mkdir yunohost.multimedia-master
  53. tar -xf ${ynh_media_release}.tar.gz -C yunohost.multimedia-master --strip-components 1
  54. ./yunohost.multimedia-master/script/ynh_media_build.sh
  55. }
  56. # Add a directory in yunohost.multimedia
  57. # This "directory" will be a symbolic link to a existing directory.
  58. #
  59. # usage: ynh_multimedia_addfolder "Source directory" "Destination directory"
  60. #
  61. # | arg: -s, --source_dir= - Source directory - The real directory which contains your medias.
  62. # | arg: -d, --dest_dir= - Destination directory - The name and the place of the symbolic link, relative to "/home/yunohost.multimedia"
  63. ynh_multimedia_addfolder () {
  64. # Declare an array to define the options of this helper.
  65. declare -Ar args_array=( [s]=source_dir= [d]=dest_dir= )
  66. local source_dir
  67. local dest_dir
  68. # Manage arguments with getopts
  69. ynh_handle_getopts_args "$@"
  70. ./yunohost.multimedia-master/script/ynh_media_addfolder.sh --source="$source_dir" --dest="$dest_dir"
  71. }
  72. # Move a directory in yunohost.multimedia, and replace by a symbolic link
  73. #
  74. # usage: ynh_multimedia_movefolder "Source directory" "Destination directory"
  75. #
  76. # | arg: -s, --source_dir= - Source directory - The real directory which contains your medias.
  77. # It will be moved to "Destination directory"
  78. # A symbolic link will replace it.
  79. # | arg: -d, --dest_dir= - Destination directory - The new name and place of the directory, relative to "/home/yunohost.multimedia"
  80. ynh_multimedia_movefolder () {
  81. # Declare an array to define the options of this helper.
  82. declare -Ar args_array=( [s]=source_dir= [d]=dest_dir= )
  83. local source_dir
  84. local dest_dir
  85. # Manage arguments with getopts
  86. ynh_handle_getopts_args "$@"
  87. ./yunohost.multimedia-master/script/ynh_media_addfolder.sh --inv --source="$source_dir" --dest="$dest_dir"
  88. }
  89. # Allow an user to have an write authorisation in multimedia directories
  90. #
  91. # usage: ynh_multimedia_addaccess user_name
  92. #
  93. # | arg: -u, --user_name= - The name of the user which gain this access.
  94. ynh_multimedia_addaccess () {
  95. # Declare an array to define the options of this helper.
  96. declare -Ar args_array=( [u]=user_name=)
  97. local user_name
  98. # Manage arguments with getopts
  99. ynh_handle_getopts_args "$@"
  100. groupadd -f multimedia
  101. usermod -a -G multimedia $user_name
  102. }
  103. #=================================================
  104. # EXPERIMENTAL HELPERS
  105. #=================================================
  106. # Send an email to inform the administrator
  107. #
  108. # usage: ynh_send_readme_to_admin --app_message=app_message [--recipients=recipients] [--type=type]
  109. # | arg: -m --app_message= - The file with the content to send to the administrator.
  110. # | arg: -r, --recipients= - The recipients of this email. Use spaces to separate multiples recipients. - default: root
  111. # example: "root admin@domain"
  112. # If you give the name of a YunoHost user, ynh_send_readme_to_admin will find its email adress for you
  113. # example: "root admin@domain user1 user2"
  114. # | arg: -t, --type= - Type of mail, could be 'backup', 'change_url', 'install', 'remove', 'restore', 'upgrade'
  115. ynh_send_readme_to_admin() {
  116. # Declare an array to define the options of this helper.
  117. declare -Ar args_array=( [m]=app_message= [r]=recipients= [t]=type= )
  118. local app_message
  119. local recipients
  120. local type
  121. # Manage arguments with getopts
  122. ynh_handle_getopts_args "$@"
  123. app_message="${app_message:-}"
  124. recipients="${recipients:-root}"
  125. type="${type:-install}"
  126. # Get the value of admin_mail_html
  127. admin_mail_html=$(ynh_app_setting_get $app admin_mail_html)
  128. admin_mail_html="${admin_mail_html:-0}"
  129. # Retrieve the email of users
  130. find_mails () {
  131. local list_mails="$1"
  132. local mail
  133. local recipients=" "
  134. # Read each mail in argument
  135. for mail in $list_mails
  136. do
  137. # Keep root or a real email address as it is
  138. if [ "$mail" = "root" ] || echo "$mail" | grep --quiet "@"
  139. then
  140. recipients="$recipients $mail"
  141. else
  142. # But replace an user name without a domain after by its email
  143. if mail=$(ynh_user_get_info "$mail" "mail" 2> /dev/null)
  144. then
  145. recipients="$recipients $mail"
  146. fi
  147. fi
  148. done
  149. echo "$recipients"
  150. }
  151. recipients=$(find_mails "$recipients")
  152. # Subject base
  153. local mail_subject="☁️🆈🅽🅷☁️: \`$app\`"
  154. # Adapt the subject according to the type of mail required.
  155. if [ "$type" = "backup" ]; then
  156. mail_subject="$mail_subject has just been backup."
  157. elif [ "$type" = "change_url" ]; then
  158. mail_subject="$mail_subject has just been moved to a new URL!"
  159. elif [ "$type" = "remove" ]; then
  160. mail_subject="$mail_subject has just been removed!"
  161. elif [ "$type" = "restore" ]; then
  162. mail_subject="$mail_subject has just been restored!"
  163. elif [ "$type" = "upgrade" ]; then
  164. mail_subject="$mail_subject has just been upgraded!"
  165. else # install
  166. mail_subject="$mail_subject has just been installed!"
  167. fi
  168. local mail_message="This is an automated message from your beloved YunoHost server.
  169. Specific information for the application $app.
  170. $(if [ -n "$app_message" ]
  171. then
  172. cat "$app_message"
  173. else
  174. echo "...No specific information..."
  175. fi)
  176. ---
  177. Automatic diagnosis data from YunoHost
  178. __PRE_TAG1__$(yunohost tools diagnosis | grep -B 100 "services:" | sed '/services:/d')__PRE_TAG2__"
  179. # Store the message into a file for further modifications.
  180. echo "$mail_message" > mail_to_send
  181. # If a html email is required. Apply html tags to the message.
  182. if [ "$admin_mail_html" -eq 1 ]
  183. then
  184. # Insert 'br' tags at each ending of lines.
  185. ynh_replace_string "$" "<br>" mail_to_send
  186. # Insert starting HTML tags
  187. sed --in-place '1s@^@<!DOCTYPE html>\n<html>\n<head></head>\n<body>\n@' mail_to_send
  188. # Keep tabulations
  189. ynh_replace_string " " "\&#160;\&#160;" mail_to_send
  190. ynh_replace_string "\t" "\&#160;\&#160;" mail_to_send
  191. # Insert url links tags
  192. ynh_replace_string "__URL_TAG1__\(.*\)__URL_TAG2__\(.*\)__URL_TAG3__" "<a href=\"\2\">\1</a>" mail_to_send
  193. # Insert pre tags
  194. ynh_replace_string "__PRE_TAG1__" "<pre>" mail_to_send
  195. ynh_replace_string "__PRE_TAG2__" "<\pre>" mail_to_send
  196. # Insert finishing HTML tags
  197. echo -e "\n</body>\n</html>" >> mail_to_send
  198. # Otherwise, remove tags to keep a plain text.
  199. else
  200. # Remove URL tags
  201. ynh_replace_string "__URL_TAG[1,3]__" "" mail_to_send
  202. ynh_replace_string "__URL_TAG2__" ": " mail_to_send
  203. # Remove PRE tags
  204. ynh_replace_string "__PRE_TAG[1-2]__" "" mail_to_send
  205. fi
  206. # Define binary to use for mail command
  207. if [ -e /usr/bin/bsd-mailx ]
  208. then
  209. local mail_bin=/usr/bin/bsd-mailx
  210. else
  211. local mail_bin=/usr/bin/mail.mailutils
  212. fi
  213. if [ "$admin_mail_html" -eq 1 ]
  214. then
  215. content_type="text/html"
  216. else
  217. content_type="text/plain"
  218. fi
  219. # Send the email to the recipients
  220. cat mail_to_send | $mail_bin -a "Content-Type: $content_type; charset=UTF-8" -s "$mail_subject" "$recipients"
  221. }
  222. #=================================================
  223. ynh_debian_release () {
  224. lsb_release --codename --short
  225. }
  226. is_stretch () {
  227. if [ "$(ynh_debian_release)" == "stretch" ]
  228. then
  229. return 0
  230. else
  231. return 1
  232. fi
  233. }
  234. is_jessie () {
  235. if [ "$(ynh_debian_release)" == "jessie" ]
  236. then
  237. return 0
  238. else
  239. return 1
  240. fi
  241. }
  242. #=================================================
  243. ynh_maintenance_mode_ON () {
  244. # Load value of $path_url and $domain from the config if their not set
  245. if [ -z $path_url ]; then
  246. path_url=$(ynh_app_setting_get $app path)
  247. fi
  248. if [ -z $domain ]; then
  249. domain=$(ynh_app_setting_get $app domain)
  250. fi
  251. mkdir -p /var/www/html/
  252. # Create an html to serve as maintenance notice
  253. echo "<!DOCTYPE html>
  254. <html>
  255. <head>
  256. <meta http-equiv="refresh" content="3">
  257. <title>Your app $app is currently under maintenance!</title>
  258. <style>
  259. body {
  260. width: 70em;
  261. margin: 0 auto;
  262. }
  263. </style>
  264. </head>
  265. <body>
  266. <h1>Your app $app is currently under maintenance!</h1>
  267. <p>This app has been put under maintenance by your administrator at $(date)</p>
  268. <p>Please wait until the maintenance operation is done. This page will be reloaded as soon as your app will be back.</p>
  269. </body>
  270. </html>" > "/var/www/html/maintenance.$app.html"
  271. # Create a new nginx config file to redirect all access to the app to the maintenance notice instead.
  272. echo "# All request to the app will be redirected to ${path_url}_maintenance and fall on the maintenance notice
  273. rewrite ^${path_url}/(.*)$ ${path_url}_maintenance/? redirect;
  274. # Use another location, to not be in conflict with the original config file
  275. location ${path_url}_maintenance/ {
  276. alias /var/www/html/ ;
  277. try_files maintenance.$app.html =503;
  278. # Include SSOWAT user panel.
  279. include conf.d/yunohost_panel.conf.inc;
  280. }" > "/etc/nginx/conf.d/$domain.d/maintenance.$app.conf"
  281. # The current config file will redirect all requests to the root of the app.
  282. # To keep the full path, we can use the following rewrite rule:
  283. # rewrite ^${path_url}/(.*)$ ${path_url}_maintenance/\$1? redirect;
  284. # The difference will be in the $1 at the end, which keep the following queries.
  285. # But, if it works perfectly for a html request, there's an issue with any php files.
  286. # This files are treated as simple files, and will be downloaded by the browser.
  287. # 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.
  288. systemctl reload nginx
  289. }
  290. ynh_maintenance_mode_OFF () {
  291. # Load value of $path_url and $domain from the config if their not set
  292. if [ -z $path_url ]; then
  293. path_url=$(ynh_app_setting_get $app path)
  294. fi
  295. if [ -z $domain ]; then
  296. domain=$(ynh_app_setting_get $app domain)
  297. fi
  298. # Rewrite the nginx config file to redirect from ${path_url}_maintenance to the real url of the app.
  299. echo "rewrite ^${path_url}_maintenance/(.*)$ ${path_url}/\$1 redirect;" > "/etc/nginx/conf.d/$domain.d/maintenance.$app.conf"
  300. systemctl reload nginx
  301. # Sleep 4 seconds to let the browser reload the pages and redirect the user to the app.
  302. sleep 4
  303. # Then remove the temporary files used for the maintenance.
  304. rm "/var/www/html/maintenance.$app.html"
  305. rm "/etc/nginx/conf.d/$domain.d/maintenance.$app.conf"
  306. systemctl reload nginx
  307. }
  308. #=================================================
  309. # Create a changelog for an app after an upgrade from the file CHANGELOG.md.
  310. #
  311. # usage: ynh_app_changelog [--format=markdown/html/plain] [--output=changelog_file] --changelog=changelog_source]
  312. # | arg: -f --format= - Format in which the changelog will be printed
  313. # markdown: Default format.
  314. # html: Turn urls into html format.
  315. # plain: Plain text changelog
  316. # | arg: -o --output= - Output file for the changelog file (Default ./changelog)
  317. # | arg: -c --changelog= - CHANGELOG.md source (Default ../CHANGELOG.md)
  318. #
  319. # The changelog is printed into the file ./changelog and ./changelog_lite
  320. ynh_app_changelog () {
  321. # Declare an array to define the options of this helper.
  322. local legacy_args=foc
  323. declare -Ar args_array=( [f]=format= [o]=output= [c]=changelog= )
  324. local format
  325. local output
  326. local changelog
  327. # Manage arguments with getopts
  328. ynh_handle_getopts_args "$@"
  329. format=${format:-markdown}
  330. output=${output:-changelog}
  331. changelog=${changelog:-../CHANGELOG.md}
  332. local original_changelog="$changelog"
  333. local temp_changelog="changelog_temp"
  334. local final_changelog="$output"
  335. if [ ! -n "$original_changelog" ]
  336. then
  337. echo "No changelog available..." > "$final_changelog"
  338. echo "No changelog available..." > "${final_changelog}_lite"
  339. return 0
  340. fi
  341. local current_version=$(ynh_read_manifest --manifest="/etc/yunohost/apps/$YNH_APP_INSTANCE_NAME/manifest.json" --manifest_key="version")
  342. local update_version=$(ynh_read_manifest --manifest="../manifest.json" --manifest_key="version")
  343. # Get the line of the version to update to into the changelog
  344. local update_version_line=$(grep --max-count=1 --line-number "^## \[$update_version" "$original_changelog" | cut -d':' -f1)
  345. # If there's no entry for this version yet into the changelog
  346. # Get the first available version
  347. if [ -z "$update_version_line" ]
  348. then
  349. update_version_line=$(grep --max-count=1 --line-number "^##" "$original_changelog" | cut -d':' -f1)
  350. fi
  351. # Get the length of the complete changelog.
  352. local changelog_length=$(wc --lines "$original_changelog" | awk '{print $1}')
  353. # Cut the file before the version to update to.
  354. tail --lines=$(( $changelog_length - $update_version_line + 1 )) "$original_changelog" > "$temp_changelog"
  355. # Get the length of the troncated changelog.
  356. changelog_length=$(wc --lines "$temp_changelog" | awk '{print $1}')
  357. # Get the line of the current version into the changelog
  358. # Keep only the last line found
  359. local current_version_line=$(grep --line-number "^## \[$current_version" "$temp_changelog" | cut -d':' -f1 | tail --lines=1)
  360. # If there's no entry for this version into the changelog
  361. # Get the last available version
  362. if [ -z "$current_version_line" ]
  363. then
  364. current_version_line=$(grep --line-number "^##" "$original_changelog" | cut -d':' -f1 | tail --lines=1)
  365. fi
  366. # Cut the file before the current version.
  367. # Then grep the previous version into the changelog to get the line number of the previous version
  368. local previous_version_line=$(tail --lines=$(( $changelog_length - $current_version_line )) \
  369. "$temp_changelog" | grep --max-count=1 --line-number "^## " | cut -d':' -f1)
  370. # If there's no previous version into the changelog
  371. # Go until the end of the changelog
  372. if [ -z "$previous_version_line" ]
  373. then
  374. previous_version_line=$changelog_length
  375. fi
  376. # Cut the file after the previous version to keep only the changelog between the current version and the version to update to.
  377. head --lines=$(( $current_version_line + $previous_version_line - 1 )) "$temp_changelog" | tee "$final_changelog"
  378. if [ "$format" = "html" ]
  379. then
  380. # Replace markdown links by html links
  381. ynh_replace_string --match_string="\[\(.*\)\](\(.*\)))" --replace_string="<a href=\"\2\">\1</a>)" --target_file="$final_changelog"
  382. ynh_replace_string --match_string="\[\(.*\)\](\(.*\))" --replace_string="<a href=\"\2\">\1</a>" --target_file="$final_changelog"
  383. elif [ "$format" = "plain" ]
  384. then
  385. # Change title format.
  386. ynh_replace_string --match_string="^##.*\[\(.*\)\](\(.*\)) - \(.*\)$" --replace_string="## \1 (\3) - \2" --target_file="$final_changelog"
  387. # Change modifications lines format.
  388. ynh_replace_string --match_string="^\([-*]\).*\[\(.*\)\]\(.*\)" --replace_string="\1 \2 \3" --target_file="$final_changelog"
  389. fi
  390. # else markdown. As the file is already in markdown, nothing to do.
  391. # Keep only important changes into the changelog
  392. # Remove all minor changes
  393. sed '/^-/d' "$final_changelog" > "${final_changelog}_lite"
  394. # Remove all blank lines (to keep a clear workspace)
  395. sed --in-place '/^$/d' "${final_changelog}_lite"
  396. # Add a blank line at the end
  397. echo "" >> "${final_changelog}_lite"
  398. # Clean titles if there's no significative changes
  399. local line
  400. local previous_line=""
  401. while read line <&3
  402. do
  403. if [ -n "$previous_line" ]
  404. then
  405. # Remove the line if it's a title or a blank line, and the previous one was a title as well.
  406. if ( [ "${line:0:1}" = "#" ] || [ ${#line} -eq 0 ] ) && [ "${previous_line:0:1}" = "#" ]
  407. then
  408. ynh_replace_special_string --match_string="${previous_line//[/.}" --replace_string="" --target_file="${final_changelog}_lite"
  409. fi
  410. fi
  411. previous_line="$line"
  412. done 3< "${final_changelog}_lite"
  413. # Remove all blank lines again
  414. sed --in-place '/^$/d' "${final_changelog}_lite"
  415. # Restore changelog format with blank lines
  416. ynh_replace_string --match_string="^##.*" --replace_string="\n\n&\n" --target_file="${final_changelog}_lite"
  417. # Remove the 2 first blank lines
  418. sed --in-place '1,2d' "${final_changelog}_lite"
  419. # Add a blank line at the end
  420. echo "" >> "${final_changelog}_lite"
  421. # If changelog are empty, add an info
  422. if [ $(wc --words "$final_changelog" | awk '{print $1}') -eq 0 ]
  423. then
  424. echo "No changes from the changelog..." > "$final_changelog"
  425. fi
  426. if [ $(wc --words "${final_changelog}_lite" | awk '{print $1}') -eq 0 ]
  427. then
  428. echo "No significative changes from the changelog..." > "${final_changelog}_lite"
  429. fi
  430. }
  431. #=================================================
  432. # Check the amount of available RAM
  433. #
  434. # usage: ynh_check_ram [--required=RAM required in Mb] [--no_swap|--only_swap] [--free_ram]
  435. # | arg: -r, --required= - Amount of RAM required in Mb. The helper will return 0 is there's enough RAM, or 1 otherwise.
  436. # If --required isn't set, the helper will print the amount of RAM, in Mb.
  437. # | arg: -s, --no_swap - Ignore swap
  438. # | arg: -o, --only_swap - Ignore real RAM, consider only swap.
  439. # | arg: -f, --free_ram - Count only free RAM, not the total amount of RAM available.
  440. ynh_check_ram () {
  441. # Declare an array to define the options of this helper.
  442. declare -Ar args_array=( [r]=required= [s]=no_swap [o]=only_swap [f]=free_ram )
  443. local required
  444. local no_swap
  445. local only_swap
  446. # Manage arguments with getopts
  447. ynh_handle_getopts_args "$@"
  448. required=${required:-}
  449. no_swap=${no_swap:-0}
  450. only_swap=${only_swap:-0}
  451. local total_ram=$(vmstat --stats --unit M | grep "total memory" | awk '{print $1}')
  452. local total_swap=$(vmstat --stats --unit M | grep "total swap" | awk '{print $1}')
  453. local total_ram_swap=$(( total_ram + total_swap ))
  454. local free_ram=$(vmstat --stats --unit M | grep "free memory" | awk '{print $1}')
  455. local free_swap=$(vmstat --stats --unit M | grep "free swap" | awk '{print $1}')
  456. local free_ram_swap=$(( free_ram + free_swap ))
  457. # Use the total amount of ram
  458. local ram=$total_ram_swap
  459. if [ $free_ram -eq 1 ]
  460. then
  461. # Use the total amount of free ram
  462. ram=$free_ram_swap
  463. if [ $no_swap -eq 1 ]
  464. then
  465. # Use only the amount of free ram
  466. ram=$free_ram
  467. elif [ $only_swap -eq 1 ]
  468. then
  469. # Use only the amount of free swap
  470. ram=$free_swap
  471. fi
  472. else
  473. if [ $no_swap -eq 1 ]
  474. then
  475. # Use only the amount of free ram
  476. ram=$total_ram
  477. elif [ $only_swap -eq 1 ]
  478. then
  479. # Use only the amount of free swap
  480. ram=$total_swap
  481. fi
  482. fi
  483. if [ -n "$required" ]
  484. then
  485. # Return 1 if the amount of ram isn't enough.
  486. if [ $ram -lt $required ]
  487. then
  488. return 1
  489. else
  490. return 0
  491. fi
  492. # If no RAM is required, return the amount of available ram.
  493. else
  494. echo $ram
  495. fi
  496. }
  497. #=================================================
  498. # Define the values to configure php-fpm
  499. #
  500. # usage: ynh_get_scalable_phpfpm --usage=usage --footprint=footprint [--print]
  501. # | arg: -f, --footprint - Memory footprint of the service (low/medium/high).
  502. # low - Less than 20Mb of ram by pool.
  503. # medium - Between 20Mb and 40Mb of ram by pool.
  504. # high - More than 40Mb of ram by pool.
  505. # Or specify exactly the footprint, the load of the service as Mb by pool instead of having a standard value.
  506. # To have this value, use the following command and stress the service.
  507. # watch -n0.5 ps -o user,cmd,%cpu,rss -u APP
  508. #
  509. # | arg: -u, --usage - Expected usage of the service (low/medium/high).
  510. # low - Personal usage, behind the sso.
  511. # medium - Low usage, few people or/and publicly accessible.
  512. # high - High usage, frequently visited website.
  513. #
  514. # | arg: -p, --print - Print the result
  515. #
  516. #
  517. #
  518. # The footprint of the service will be used to defined the maximum footprint we can allow, which is half the maximum RAM.
  519. # So it will be used to defined 'pm.max_children'
  520. # A lower value for the footprint will allow more children for 'pm.max_children'. And so for
  521. # 'pm.start_servers', 'pm.min_spare_servers' and 'pm.max_spare_servers' which are defined from the
  522. # value of 'pm.max_children'
  523. # NOTE: 'pm.max_children' can't exceed 4 times the number of processor's cores.
  524. #
  525. # The usage value will defined the way php will handle the children for the pool.
  526. # A value set as 'low' will set the process manager to 'ondemand'. Children will start only if the
  527. # service is used, otherwise no child will stay alive. This config gives the lower footprint when the
  528. # service is idle. But will use more proc since it has to start a child as soon it's used.
  529. # Set as 'medium', the process manager will be at dynamic. If the service is idle, a number of children
  530. # equal to pm.min_spare_servers will stay alive. So the service can be quick to answer to any request.
  531. # The number of children can grow if needed. The footprint can stay low if the service is idle, but
  532. # not null. The impact on the proc is a little bit less than 'ondemand' as there's always a few
  533. # children already available.
  534. # Set as 'high', the process manager will be set at 'static'. There will be always as many children as
  535. # 'pm.max_children', the footprint is important (but will be set as maximum a quarter of the maximum
  536. # RAM) but the impact on the proc is lower. The service will be quick to answer as there's always many
  537. # children ready to answer.
  538. ynh_get_scalable_phpfpm () {
  539. local legacy_args=ufp
  540. # Declare an array to define the options of this helper.
  541. declare -Ar args_array=( [u]=usage= [f]=footprint= [p]=print )
  542. local usage
  543. local footprint
  544. local print
  545. # Manage arguments with getopts
  546. ynh_handle_getopts_args "$@"
  547. # Set all characters as lowercase
  548. footprint=${footprint,,}
  549. usage=${usage,,}
  550. print=${print:-0}
  551. if [ "$footprint" = "low" ]
  552. then
  553. footprint=20
  554. elif [ "$footprint" = "medium" ]
  555. then
  556. footprint=35
  557. elif [ "$footprint" = "high" ]
  558. then
  559. footprint=50
  560. fi
  561. # Define the way the process manager handle child processes.
  562. if [ "$usage" = "low" ]
  563. then
  564. php_pm=ondemand
  565. elif [ "$usage" = "medium" ]
  566. then
  567. php_pm=dynamic
  568. elif [ "$usage" = "high" ]
  569. then
  570. php_pm=static
  571. else
  572. ynh_die --message="Does not recognize '$usage' as an usage value."
  573. fi
  574. # Get the total of RAM available, except swap.
  575. local max_ram=$(ynh_check_ram --no_swap)
  576. less0() {
  577. # Do not allow value below 1
  578. if [ $1 -le 0 ]
  579. then
  580. echo 1
  581. else
  582. echo $1
  583. fi
  584. }
  585. # Define pm.max_children
  586. # The value of pm.max_children is the total amount of ram divide by 2 and divide again by the footprint of a pool for this app.
  587. # So if php-fpm start the maximum of children, it won't exceed half of the ram.
  588. php_max_children=$(( $max_ram / 2 / $footprint ))
  589. # If process manager is set as static, use half less children.
  590. # Used as static, there's always as many children as the value of pm.max_children
  591. if [ "$php_pm" = "static" ]
  592. then
  593. php_max_children=$(( $php_max_children / 2 ))
  594. fi
  595. php_max_children=$(less0 $php_max_children)
  596. # To not overload the proc, limit the number of children to 4 times the number of cores.
  597. local core_number=$(nproc)
  598. local max_proc=$(( $core_number * 4 ))
  599. if [ $php_max_children -gt $max_proc ]
  600. then
  601. php_max_children=$max_proc
  602. fi
  603. if [ "$php_pm" = "dynamic" ]
  604. then
  605. # Define pm.start_servers, pm.min_spare_servers and pm.max_spare_servers for a dynamic process manager
  606. php_min_spare_servers=$(( $php_max_children / 8 ))
  607. php_min_spare_servers=$(less0 $php_min_spare_servers)
  608. php_max_spare_servers=$(( $php_max_children / 2 ))
  609. php_max_spare_servers=$(less0 $php_max_spare_servers)
  610. php_start_servers=$(( $php_min_spare_servers + ( $php_max_spare_servers - $php_min_spare_servers ) /2 ))
  611. php_start_servers=$(less0 $php_start_servers)
  612. else
  613. php_min_spare_servers=0
  614. php_max_spare_servers=0
  615. php_start_servers=0
  616. fi
  617. if [ $print -eq 1 ]
  618. then
  619. ynh_debug --message="Footprint=${footprint}Mb by pool."
  620. ynh_debug --message="Process manager=$php_pm"
  621. ynh_debug --message="Max RAM=${max_ram}Mb"
  622. if [ "$php_pm" != "static" ]; then
  623. ynh_debug --message="\nMax estimated footprint=$(( $php_max_children * $footprint ))"
  624. ynh_debug --message="Min estimated footprint=$(( $php_min_spare_servers * $footprint ))"
  625. fi
  626. if [ "$php_pm" = "dynamic" ]; then
  627. ynh_debug --message="Estimated average footprint=$(( $php_max_spare_servers * $footprint ))"
  628. elif [ "$php_pm" = "static" ]; then
  629. ynh_debug --message="Estimated footprint=$(( $php_max_children * $footprint ))"
  630. fi
  631. ynh_debug --message="\nRaw php-fpm values:"
  632. ynh_debug --message="pm.max_children = $php_max_children"
  633. if [ "$php_pm" = "dynamic" ]; then
  634. ynh_debug --message="pm.start_servers = $php_start_servers"
  635. ynh_debug --message="pm.min_spare_servers = $php_min_spare_servers"
  636. ynh_debug --message="pm.max_spare_servers = $php_max_spare_servers"
  637. fi
  638. fi
  639. }