Page 1 of 1

A script to calculate Average CPU Load

Posted: Fri Apr 18, 2008 6:16 pm
by rgraham
# Name : Average CPU Load
# Set up the scheduler to run this at a 1 second intervals (Sample Rate)
# Set info logs to echo to Terminal in System Logging

:local cpuload 0
:global cpuarray
:local arraylen 0
:local arraypos 0
:local arraytot 0
:global avgcpuload 0
:global highavgcpuload

# arraysize is the number of cpu-Load samples to keep
# Experiment with this value to incease or decrease the number of samples
# The greater the value the longer the time that the cpu-load average is calculated for.
:local arraysize 5

# Get cpu-load samples, limit cpuarray to array size
:set cpuload [/system resource get cpu-load]
:set cpuarray ( [:toarray $cpuload] + $cpuarray )
:set cpuarray [:pick $cpuarray 0 $arraysize]

# add up all values in array
:set arraypos 0
:set arraylen [:len $cpuarray]
:while ($arraypos < $arraylen) do={
:set arraytot ($arraytot + [:pick $cpuarray $arraypos] );
:set arraypos ($arraypos +1)}

# divide sum of array values by the number of values in cpuarray
:set avgcpuload ($arraytot / [:len $cpuarray])
:if ([:len $highavgcpuload] = 0) do={:set highavgcpuload $avgcpuload}
:if ([$highavgcpuload] < [$avgcpuload]) do={:set highavgcpuload $avgcpuload}

# Display results in Terminal window
:log info ("CPU Load Captures:")
:log info $cpuarray
:log info ("Array Total: $arraytot")
:log info ("Array size: $arraysize")
:log info ("CPU Load - Avg: $avgcpuload High: $highavgcpuload")

Re: A script to calculate Average CPU Load

Posted: Fri Apr 25, 2008 7:31 am
by thavinci
[admin@oldPPPOES] /system script> run cpuload
Script Error: cannot add time interval to nothing
[admin@oldPPPOES] /system script>
Unfortunately didn't work here, but havent really had a look at it yet.
Wan't to use this script and modify it to accomadate for bugs in latest ROS that causes 100% cpu usage and lockup.
Want this script to monitor and when cpu usage = 100 over so many samples, reboot router.
Till MT sorts issues out.



Advise?


Thank You for script!

Re: A script to calculate Average CPU Load

Posted: Mon Apr 28, 2008 12:43 am
by thavinci
Solved it, my stupidity....
Also modified it to accommodate mikrotik bugs.
The following modification monitors router for 20 seconds.
If in 20 seconds the router's cpu usage stays at 100%, it will reboot it.

In scheduler create job that starts on start-up and runs at one second intervals...

Add code:
# Name : Average CPU Load
# Set up the scheduler to run this at a 1 second intervals (Sample Rate)
# Set info logs to echo to Terminal in System Logging

:local cpuload 0
:global cpuarray
:local arraylen 0
:local arraypos 0
:local arraytot 0
:global avgcpuload 0
:global highavgcpuload

# arraysize is the number of cpu-Load samples to keep
# Experiment with this value to incease or decrease the number of samples
# The greater the value the longer the time that the cpu-load average is calculated for.
:local arraysize 20

# Get cpu-load samples, limit cpuarray to array size
:set cpuload [/system resource get cpu-load]
:set cpuarray ( [:toarray $cpuload] + $cpuarray )
:set cpuarray [:pick $cpuarray 0 $arraysize]

# add up all values in array
:set arraypos 0
:set arraylen [:len $cpuarray]
:while ($arraypos < $arraylen) do={
:set arraytot ($arraytot + [:pick $cpuarray $arraypos] );
:set arraypos ($arraypos +1)}

# divide sum of array values by the number of values in cpuarray
:set avgcpuload ($arraytot / [:len $cpuarray])
:if ([:len $highavgcpuload] = 0) do={:set highavgcpuload $avgcpuload}
:if ([$highavgcpuload] < [$avgcpuload]) do={:set highavgcpuload $avgcpuload}

# Display results in Terminal window
:log info ("CPU Load Captures:")
:log info $cpuarray
:log info ("Array Total: $arraytot")
:log info ("Array size: $arraysize")
:log info ("CPU Load - Avg: $avgcpuload High: $highavgcpuload")

:if ($avgcpuload >= 100)  do={ /system reboot; }

Re: A script to calculate Average CPU Load

Posted: Sat Apr 24, 2010 6:50 am
by mrzero
thanks but it doesn't run and when running in terminal to see the error it said:
Script Error: cannot add time interval to nothing
i wish replying fast as i need this script badly.
thanks

Re: A script to calculate Average CPU Load

Posted: Thu Jul 08, 2010 5:55 pm
by psamsig
This should work:
# Name : Average CPU Load
# Set up the scheduler to run this at a 1 second intervals (Sample Rate)
# Set info logs to echo to Terminal in System Logging
#
# maxsamples is the number of cpu-Load samples to keep
# Experiment with this value to incease or decrease the number of samples
# The greater the value the longer the time that the cpu-load average is calculated for.
:local maxsamples 20

# Get cpu-load samples, limit cpuarray to array size
:global cpuarray
:set cpuarray ([/system resource get cpu-load] , [:pick $cpuarray 0 ($maxsamples - 1)])

# add up all values in array
:local arraytot 0
:foreach o in=$cpuarray do={:set arraytot ($arraytot + $o)};

# divide sum of array values by the number of values in cpuarray
:local arraysize [:len $cpuarray]
:local avgcpuload ($arraytot / $arraysize)

# Display results in Terminal window
:log info ("CPU Load Captures:")
:log info $cpuarray
:log info ("Array Total: $arraytot")
:log info ("Array size: $arraysize of $maxsamples")
:global highavgcpuload
:if ([:len $highavgcpuload] = 0 || $highavgcpuload < $avgcpuload) do={:set highavgcpuload $avgcpuload}
:log info ("CPU Load - Avg: $avgcpuload High: $highavgcpuload")

#reboot if all samples show highload
:if ($arraysize = $maxsamples && $avgcpuload >= 100)  do={ /system reboot; }

Re: A script to calculate Average CPU Load

Posted: Sun May 15, 2011 6:26 pm
by jwelebd
But I need to log which profile is using higher cpu. Or which profile is going more than 30% to 50%

Re: A script to calculate Average CPU Load

Posted: Sun May 15, 2011 11:50 pm
by dssmiktik
$avgcpuload >= 100
I should hope CPU (or average value) would never be higher than 100! :lol:

Re: A script to calculate Average CPU Load

Posted: Sat Dec 03, 2011 6:49 am
by xunil76
we have some RB750 units out in the field (NOT RB750G) that are completely inadequate for the number of people logging in via Hotspot where they are installed, and it is causing the units to max out at 100% CPU usage. these customers are constantly calling us because they cannot login as a result, and we have to login to the units remotely via telnet to issue a reboot command, because Winbox always times out before the login process can complete, or it just sits there indefinitely and never times out, but also never does anything.

we usually have to reboot these units at least once a day, but usually 2 - 3 times a day, depending on how many people are logging in on any given night. when we do have to telnet in and reboot, it tends to take between 5 - 15 minutes for us to be able to get logged in successfully, and for the reboot command to actually register on the unit and cause the reboot to take place. this gets very tiresome for us, and is not good for our customers because they are (understandably) getting very frustrated having to call us all the time. a reboot does resolve the issue, and it normally takes a while for the CPU to max out at 100% again.

i already know that the units need to be upgraded, and we are in the process of trying to have our client do just that (another company owns/runs the equipment, and we do the billing, tech suppot & system health monitoring for them), but it takes time for them to get approval for the cost of replacing them, as well as scheduling a tech to go out & install the replacement equipment, and we need a temporary solution in the meantime so that we are not constantly having to waste a lot of time manually rebooting these things.

i tried the scripts in this thread, but the line below (unless i'm interpreting it incorrectly) leads me to believe that i am supposed to set up a "/system logging" entry that sets "info" to have an action of "echo".
# Set info logs to echo to Terminal in System Logging
however, when i do this (even right after rebooting the unit & it is not running at 100% anymore), the info logging action actually causes the CPU to max out at 100%, which basically defeats the purpose of the script, and if left in place, would actually cause the system to reboot every 5 minutes (i set the scheduler interval to 10 seconds, and the "arraysize" to 30), instead of only when the system is actually maxing out at 100% on its own and we manually reboot it.

is there any other script that would allow the system to reboot itself after 5 minutes of 100% CPU load, which does not actually cause the unit to max out at 100% CPU load?

Re: A script to calculate Average CPU Load

Posted: Sat Dec 03, 2011 7:43 pm
by psamsig
You don't need any logging for it to do it's main purpose, rebooting on high load, you can even remove all lines starting with ':log'

Re: A script to calculate Average CPU Load

Posted: Thu Dec 29, 2011 2:30 am
by n21roadie
I have modified the above script to suit my requirements but would ask as I am new to this if I have it correctly coded for the following task;
Every 15mins scheduler runs the script =RebootOnHighCPU if the system resources are less 5% then it will for 20 seconds compare CPU load and if greater than 100% (this if by chance the script coincided with a momentary CPU high load?) it will send a email and then auto-reboot the router, on the email it will detail the name of the router the time it was rebooted, If the system resource is more than 5% free cancel the rest of the script so not to run a un-necessary task, am i correct with this.
/system scheduler
add comment="" disabled=no interval=15m name=RebootOnHighCPU on-event="/system script run RebootOnHighCPU" policy=ftp,reboot,read,write,policy,test,winbox,password,sniff,sensitive start-date=jan/01/1970 start-time=startup
/system script
add name=RebootOnHighCPU
Code for script
:global datum [/system clock get date];
:global time [/system clock get time];
:local percentfree ((100 * [/system resource get free-memory]) / [/system resource get total-memory])
/system resource
:if ($percentfree < 5) do={:local maxsamples 20
:global cpuarray
:set cpuarray ([/system resource get cpu-load] , [:pick $cpuarray 0 ($maxsamples - 1)])
:local arraytot 0
:foreach o in=$cpuarray do={:set arraytot ($arraytot + $o)};
:local arraysize [:len $cpuarray]
:local avgcpuload ($arraytot / $arraysize)
:log info ("CPU Load Captures:")
:log info $cpuarray
:log info ("Array Total: $arraytot")
:log info ("Array size: $arraysize of $maxsamples")
:global highavgcpuload
:if ([:len $highavgcpuload] = 0 || $highavgcpuload < $avgcpuload) do={:set highavgcpuload $avgcpuload}
:log info ("CPU Load - Avg: $avgcpuload High: $highavgcpuload")
:if ($arraysize = $maxsamples && $avgcpuload >= 100)  
}
  /tool e-mail send server=000.000.000.000 to="xxxxxxx@hotmail.com" subject=[/system identity get name] from="xxxxxxx@nospam.com" body=(" on $datum at $time the memory on this repeater got to ", [/system resource get free-memory])
  /system reboot;
};

Re: A script to calculate Average CPU Load

Posted: Thu Dec 29, 2011 7:11 pm
by n21roadie
Discovered my script just auto reboots on running so i edited, now hopefully it will work correctly but at present i don't have a router with high CPU load.

Strange request (normally users would be seeking advice to reduce CPU load)but any suggestions how to simulate high CPU load to test this script?


:global datum [/system clock get date];
:global time [/system clock get time];
{:local maxsamples 20
:global cpuarray
:set cpuarray ([/system resource get cpu-load] , [:pick $cpuarray 0 ($maxsamples - 1)])
:local arraytot 0
:foreach o in=$cpuarray do={:set arraytot ($arraytot + $o)};
:local arraysize [:len $cpuarray]
:local avgcpuload ($arraytot / $arraysize)
:log info ("CPU Load Captures:")
:log info $cpuarray
:log info ("Array Total: $arraytot")
:log info ("Array size: $arraysize of $maxsamples")
:global highavgcpuload
:if ([:len $highavgcpuload] = 0 || $highavgcpuload < $avgcpuload) do={:set highavgcpuload $avgcpuload}
:log info ("CPU Load - Avg: $avgcpuload High: $highavgcpuload")
:if ($arraysize = $maxsamples && $avgcpuload >= 100) 
}
 /tool e-mail send server=000.000.000.000 to="xxxxxxx@hotmail.com" subject=[/system identity get name] from="xxxxxxx@nospam.com" body=(" on $datum at $time the memory on this repeater got to ", [/system resource get free-memory])
  /system reboot;
};

Re: A script to calculate Average CPU Load

Posted: Fri Dec 30, 2011 1:21 am
by THG
Strange request (normally users would be seeking advice to reduce CPU load)but any suggestions how to simulate high CPU load to test this script?
TCP Bandwidth Test to localhost (127.0.0.1). If you have a firewall rule that drops everything to input chain, disable it before you run the test.

Re: A script to calculate Average CPU Load

Posted: Fri Dec 30, 2011 2:58 am
by n21roadie
Strange request (normally users would be seeking advice to reduce CPU load)but any suggestions how to simulate high CPU load to test this script?
TCP Bandwidth Test to localhost (127.0.0.1). If you have a firewall rule that drops everything to input chain, disable it before you run the test.
Thank you, I modified the script again and tried 20 samples but it appeared like the CPU running @100% could not run the task and gave a incorrect average so the router would not reboot so i dropped the maxsample to 5 and then with 100% load it reboots
:global datum [/system clock get date];
:global time [/system clock get time];
:local maxsamples 5
:global cpuarray
:set cpuarray ([/system resource get cpu-load] , [:pick $cpuarray 0 ($maxsamples - 1)])
:local arraytot 0
:foreach o in=$cpuarray do={:set arraytot ($arraytot + $o)};
:local arraysize [:len $cpuarray]
:local avgcpuload ($arraytot / $arraysize)
:log info ("CPU Load Captures:")
:log info $cpuarray
:log info ("Array Total: $arraytot")
:log info ("Array size: $arraysize of $maxsamples")
:global highavgcpuload
:if ([:len $highavgcpuload] = 0 || $highavgcpuload < $avgcpuload) do={:set highavgcpuload $avgcpuload}
:log info ("CPU Load - Avg: $avgcpuload High: $highavgcpuload")
:if ($arraysize = $maxsamples && $avgcpuload >= 100) do={ 
/tool e-mail send server=000.000.000.000 to="xxxxxxx@hotmail.com" subject=[/system identity get name] from="xxxxxxx@nospam.com" body=[/system identity get name] ," At $time the CPU Load on this router was running at 100%")
  /system reboot;
};

Re: A script to calculate Average CPU Load

Posted: Wed Jun 13, 2012 11:52 am
by n21roadie
Tried the script on a CPE OS v5.17 which is setup as pppoe client and in testing, I noticed from the log file it will not run the 5 samples with CPU running @100% but just 1 and maybe 2 which is not enough for calculation, also I note the log is full of pppoe dial-out attempts before and after the 1 or 2 cpu samples , I disabled pppoe client but dial out logging continues.

Re: A script to calculate Average CPU Load

Posted: Thu Aug 17, 2017 7:23 pm
by orfi
i have to install that script on a newer machine with 36 cores , and is not working. any ideea ?

Re: A script to calculate Average CPU Load

Posted: Thu Aug 17, 2017 8:36 pm
by IntrusDave
This is the Observer effect as known in physics. Just running a script to monitor the load will increase the load and therefore make the results invalid. The more complicated the script, the higher the load, and the weaker the cpu, the higher the load.

A better way to do this would be a use fetch and send an http post with the current CPU load to a server every 60 seconds, then let the server do the work.

Re: A script to calculate Average CPU Load

Posted: Thu Aug 17, 2017 11:40 pm
by n21roadie
This is the Observer effect as known in physics. Just running a script to monitor the load will increase the load and therefore make the results invalid. The more complicated the script, the higher the load, and the weaker the cpu, the higher the load.

A better way to do this would be a use fetch and send an http post with the current CPU load to a server every 60 seconds, then let the server do the work.
I totally agree !

Re: A script to calculate Average CPU Load

Posted: Sun Dec 31, 2017 8:28 pm
by EIKA
Hi all!

Looks like this syntax isn't valid for ROS 6.41 anymore. Could you please suggest how to correct it?
:foreach o in=$cpuarray do={:set arraytot ($arraytot + $o)};

Re: A script to calculate Average CPU Load

Posted: Sun Dec 31, 2017 10:11 pm
by n21roadie
Hi all!

Looks like this syntax isn't valid for ROS 6.41 anymore. Could you please suggest how to correct it?
:foreach o in=$cpuarray do={:set arraytot ($arraytot + $o)};
I gave up a long time ago trying to use a script to calculate CPU load as it was only accurate during low CPU load, higher CPU load gave inaccurate results or the script did not run ?

Re: A script to calculate Average CPU Load

Posted: Mon Jan 01, 2018 2:34 pm
by EIKA
It could be. But what with syntax? Can you fix it? I am intened to set it up fo 90% or something. 100% is not a good idea, because script can't be run in the most of cases.