Page 1 of 1

Restart a service from domoticz

Posted: Monday 25 May 2020 9:16
by azonneveld
Hi,

I have a Unifi controller running on a pi. The unifi controller has a memory leak, which is not expected to be fixed soon.
So I installed domoticz on the same pi to monitor the memory usage.

When the memory usage gets very high, I would like to trigger a script, to restart the unifi service.
But it is not working. When I execute "sudo service unifi restart" using SSH the restart works.
Who can help me out?

Lua code, time based

Code: Select all


    local tNow = os.date("*t");
    local dayofyear = tNow.yday;
    local TimeInMinutes = tNow.min + tNow.hour * 60;

commandArray = {}

    mem = tonumber(otherdevices_svalues['Memory Usage'])
    if mem > 85 and TimeInMinutes == 1020 then   --restart at 1700 hrs
        commandArray[#commandArray + 1] = {['SendNotification']='Restarting Unifi Controller, memory: '..tostring(mem).."%"}
        os.execute ('(curl /bin/sleep 1 && //home/pi/domoticz/scripts/restart_unifi.sh > /dev/null)&') 
    end

return commandArray
SH script

Code: Select all

#!/bin/sh
sudo service unifi restart
exit 0

Re: Restart a service from domoticz

Posted: Monday 25 May 2020 12:45
by Egregius
Because you have low memory issues you install a overblown service like domoticz to detect that? Just for that?
Why not a simple bash script that you execute by cron?

Something like this should do:

Code: Select all

#!/bin/sh
ramusage=$(free | awk '/Mem/{printf("RAM Usage: %.2f\n"), $3/$2*100}'| awk '{print $3}')
if [ "$ramusage" > 80 ]; then
	sudo service unifi restart 
fi

Re: Restart a service from domoticz

Posted: Monday 25 May 2020 13:14
by azonneveld
Egregius wrote: Monday 25 May 2020 12:45 Because you have low memory issues you install a overblown service like domoticz to detect that? Just for that?
Actually it is a slave domoticz, also doing other things.

Is there a way to run a script from domoticz with root privileges?

Re: Restart a service from domoticz

Posted: Thursday 28 May 2020 17:31
by azonneveld
Egregius wrote: Monday 25 May 2020 12:45 Something like this should do:

Code: Select all

#!/bin/sh
ramusage=$(free | awk '/Mem/{printf("RAM Usage: %.2f\n"), $3/$2*100}'| awk '{print $3}')
if [ "$ramusage" > 80 ]; then
	sudo service unifi restart 
fi
With a little modification, I got the script working!
This script also sends a notification using telegram.

Code: Select all

#!/bin/sh
ramusage=$(free | awk '/Mem/{printf("RAM Usage: %.0f\n"), $3/$2*100}'| awk '{print $3}')
if [ "$ramusage" -gt 85 ]; then
  	TOKEN=<token>
  	CHAT_ID=<chat id>
  	MESSAGE="BASH: Restarting Unifi"
  	URL="https://api.telegram.org/bot$TOKEN/sendMessage"
  	curl -s -X POST $URL -d chat_id=$CHAT_ID -d text="$MESSAGE"
	sudo service unifi restart 
fi