0

This is the first time I'm using cron. I want to restart the apacher in my server if the amount of available memory goes less than 500 mb. To do so I wrote the following script:

restart_if_memory_full.sh (in /var/www/myapp/)

#!/bin/bash

mem=$(free -m | awk '/Mem:/{print $4}')
(( mem <= 500 )) && (sudo service apache2 restart)

Then I did it executable by running (sudo chmod +x restart_if_memory_full.sh) and added the following line to the cron by (sudo crontab -e) (Note I did not use .sh extension as recommended)

* * * * * /var/www/myapp/restart_if_memory_full 

Now, I check the output by (grep CRON /var/log/syslog) and see this:

Nov 11 11:13:01 mardy2 CRON[31963]: (root) CMD (/var/www/myapp/restart_if_memory_full)
Nov 11 11:13:01 mardy2 CRON[31962]: (CRON) info (No MTA installed, discarding output)

However, when I check the memory usage by htop, it doesn't decrease and therefore I realized apache server was not restarted. So, how can I make this script runnable ?

zwlayer
  • 145

1 Answers1

0

Rather than doing a check every minute, I'd suggest running an endless script checking for your memory threshold and make it a systemd-service:

#!/bin/bash
#memory_check.sh
while [[ "free -m | awk '/Mem:/{print $4}'" -lt  500 ]] ; do
  sleep 5
done

#service called e.g. mem_check.service
[Unit]
Description=continuously monitors memory
After=apache2

[Service] ExecStart=/path/to/memory_check.sh Restart=on-failure #let's give apache some time: RestartSec=10s


Then add a restart dependeny to your apache2.service in the [Unit] section with:

PartOf=mem_check.service

The PartOf= dependency forwards the restart of mem_check to apache2.

PartOf=

Configures dependencies similar to Requires=, but limited to stopping and restarting of units. When systemd stops or restarts the units listed here, the action is propagated to this unit. Note that this is a one-way dependency — changes to this unit do not affect the listed units.

When PartOf=b.service is used on a.service, this dependency will show as ConsistsOf=a.service in property listing of b.service. ConsistsOf= dependency cannot be specified directly.

(from https://www.freedesktop.org/software/systemd/man/systemd.unit.html)

FelixJN
  • 2,358