Update to use Server module updates and store CpuUsage stats instead of just load

pull/3833/head
Isaac Connor 2024-02-20 13:13:27 -05:00
parent 93ef297c24
commit 68e2b19440
2 changed files with 43 additions and 50 deletions

View File

@ -65,6 +65,7 @@ use constant MAX_CONNECT_DELAY => 40;
@EXTRA_PERL_LIB@
use ZoneMinder;
use ZoneMinder::Server;
use POSIX;
use Socket;
use IO::Handle;
@ -155,12 +156,15 @@ socket(CLIENT, PF_UNIX, SOCK_STREAM, 0) or Fatal("Can't open socket: $!");
my $saddr = sockaddr_un(SOCK_FILE);
my $server_up = connect(CLIENT, $saddr);
if ( !$server_up ) {
if ( $Config{ZM_SERVER_ID} ) {
if (!$server_up) {
my $server = new ZoneMinder::Server($Config{ZM_SERVER_ID});
if ($server->Id()) {
use Sys::MemInfo qw(totalmem freemem totalswap freeswap);
use ZoneMinder::Server qw(CpuLoad);
if ( ! defined $dbh->do(q{UPDATE Servers SET Status=?,TotalMem=?,FreeMem=?,TotalSwap=?,FreeSwap=? WHERE Id=?}, undef,
'NotRunning', &totalmem, &freemem, &totalswap, &freeswap, $Config{ZM_SERVER_ID} ) ) {
my ($user_percent, $nice_percent, $sys_percent, $idle_percent, $usage_percent) = $server->CpuUsage();
if ($_=$server->save({Status=>'NotRunning',
TotalMem=>&totalmem, FreeMem=>&freemem, TotalSwap=>&totalswap, FreeSwap=>&freeswap,
CpuUserPercent=>$user_percent, CpuNicePercent=>$nice_percent, CpuSysPercent=>$sys_percent, CpuIdlePercent=>$idle_percent, CpuUsagePercent=>$usage_percent,
})) {
Error('Failed Updating status of Server record to Not Running for Id='.$Config{ZM_SERVER_ID}.': '.$dbh->errstr());
}
}
@ -237,7 +241,7 @@ use Socket;
use IO::Handle;
use Time::HiRes qw(usleep);
use Sys::MemInfo qw(totalmem freemem totalswap freeswap);
use ZoneMinder::Server qw(CpuLoad);
use ZoneMinder::Server;
#use Data::Dumper;
use constant KILL_DELAY => 30; # seconds to wait between sending TERM and sending KILL
@ -304,9 +308,11 @@ sub run {
my $timeout = 1;
my $secs_count = 0;
my $server = new ZoneMinder::Server($Config{ZM_SERVER_ID});
while ( !$zm_terminate ) {
if ( $Config{ZM_SERVER_ID} ) {
if ($server->Id()) {
if ( ! ( $secs_count % 60 ) ) {
while ( (!$zm_terminate) and !($dbh and $dbh->ping()) ) {
Warning("Not connected to db ($dbh)".($dbh?' ping('.$dbh->ping().')':''). ($DBI::errstr?" errstr($DBI::errstr)":'').' Reconnecting');
@ -315,11 +321,13 @@ sub run {
}
last if $zm_terminate;
my @cpuload = CpuLoad();
Debug("Updating Server record @cpuload");
if ( ! defined $dbh->do('UPDATE Servers SET Status=?,CpuLoad=?,TotalMem=?,FreeMem=?,TotalSwap=?,FreeSwap=? WHERE Id=?', undef,
'Running', $cpuload[0], &totalmem, &freemem, &totalswap, &freeswap, $Config{ZM_SERVER_ID} ) ) {
Error("Failed Updating status of Server record for Id=$Config{ZM_SERVER_ID} :".$dbh->errstr());
my @cpuload = ZoneMinder::Server::CpuLoad();
my ($user_percent, $nice_percent, $sys_percent, $idle_percent, $usage_percent) = $server->CpuUsage();
if ($_=$server->save({Status=>'Running',
TotalMem=>&totalmem, FreeMem=>&freemem, TotalSwap=>&totalswap, FreeSwap=>&freeswap, CpuLoad=>$cpuload[0],
CpuUserPercent=>$user_percent, CpuNicePercent=>$nice_percent, CpuSysPercent=>$sys_percent, CpuIdlePercent=>$idle_percent, CpuUsagePercent=>$usage_percent
})) {
Error('Failed Updating status of Server record to Not Running for Id='.$Config{ZM_SERVER_ID}.': '.$dbh->errstr());
}
}
$secs_count += 1;
@ -384,14 +392,12 @@ sub run {
reaper() if %pids_to_reap;
} # end while
dPrint(ZoneMinder::Logger::INFO, 'Server exiting at '
.strftime('%y/%m/%d %H:%M:%S', localtime())
."\n"
);
if ( $Config{ZM_SERVER_ID} ) {
dPrint(ZoneMinder::Logger::INFO, 'Server exiting at '.strftime('%y/%m/%d %H:%M:%S', localtime())."\n");
if ($Config{ZM_SERVER_ID}) {
$dbh = zmDbConnect() if ! ($dbh and $dbh->ping());
if ( ! defined $dbh->do(q{UPDATE Servers SET Status='NotRunning' WHERE Id=?}, undef, $Config{ZM_SERVER_ID}) ) {
Error("Failed Updating status of Server record for Id=$Config{ZM_SERVER_ID}".$dbh->errstr());
my $server = new ZoneMinder::Server($Config{ZM_SERVER_ID});
if ($_=$server->save({Status=>'NotRunning'})) {
Error('Failed Updating status of Server record to Not Running for Id='.$Config{ZM_SERVER_ID}.': '.$dbh->errstr());
}
}
shutdownAll();

View File

@ -21,7 +21,7 @@ use constant START_DELAY => 30; # To give everything else time to start
use ZoneMinder;
use DBI;
use Sys::MemInfo qw(totalmem freemem totalswap freeswap);
use ZoneMinder::Server qw(CpuLoad);
use ZoneMinder::Server;
$| = 1;
@ -43,6 +43,7 @@ Info('Stats Daemon starting in '.START_DELAY.' seconds');
sleep(START_DELAY);
my $dbh = zmDbConnect();
my $server = new ZoneMinder::Server($Config{ZM_SERVER_ID});
while (!$zm_terminate) {
while ( ! ( $dbh and $dbh->ping() ) ) {
@ -53,34 +54,18 @@ while (!$zm_terminate) {
}
}
my @cpuload = CpuLoad();
if ( $Config{ZM_SERVER_ID} and ! defined $dbh->do('UPDATE Servers SET Status=?,CpuLoad=?,TotalMem=?,FreeMem=?,TotalSwap=?,FreeSwap=? WHERE Id=?', undef,
'Running', $cpuload[0], &totalmem, &freemem, &totalswap, &freeswap, $Config{ZM_SERVER_ID} ) ) {
Error("Failed Updating status of Server record for Id=$Config{ZM_SERVER_ID} :".$dbh->errstr());
}
# Get CPU utilization percentages
my $top_output = `top -b -n 1 | grep -i "^%Cpu(s)" | awk '{print \$2, \$4}'`;
my ($user_utilization, $system_utilization) = split(/ /, $top_output);
$user_utilization =~ s/[^\d\.]//g;
$system_utilization =~ s/[^\d\.]//g;
if (!$user_utilization) {
Warning("Failed getting user_utilization from $top_output");
$user_utilization = 0;
}
if (!$system_utilization) {
Warning("Failed getting user_utilization from $top_output");
$system_utilization = 0;
}
my @cpuload = $server->CpuLoad();
my ($user_percent, $nice_percent, $sys_percent, $idle_percent, $usage_percent) = $server->CpuUsage();
zmDbDo('INSERT INTO Server_Stats (ServerId, TimeStamp, CpuLoad, CpuUserPercent, CpuSystemPercent, TotalMem, FreeMem, TotalSwap, FreeSwap) VALUES (?,NOW(),?,?,?,?,?,?,?)',
$Config{ZM_SERVER_ID},
$cpuload[0], $user_utilization, $system_utilization,
$cpuload[0], $user_percent, $sys_percent,
&totalmem, &freemem, &totalswap, &freeswap);
my $rows = zmDbDo('DELETE FROM `Server_Stats` WHERE `TimeStamp` < now() - interval 1 DAY LIMIT 100');
Debug("Deleted $rows Server Stats table entries by time");
{
my $rows = zmDbDo('DELETE FROM `Server_Stats` WHERE `TimeStamp` < now() - interval 1 DAY LIMIT 100');
Debug("Deleted $rows Server Stats table entries by time");
}
# Clear out statuses for Monitors that have been set to None but for some reason didn't update the db
zmDbDo('DELETE FROM Monitor_Status WHERE MonitorId IN (SELECT Id FROM Monitors WHERE Capturing=\'None\')');
@ -114,18 +99,20 @@ while (!$zm_terminate) {
}
my $rows;
do {
$rows = zmDbDo('DELETE FROM `Logs` WHERE `TimeKey` < unix_timestamp(now() - interval '.$Config{ZM_LOG_DATABASE_LIMIT}.') LIMIT 100');
$rows = zmDbDo('DELETE low_priority FROM `Logs` WHERE `TimeKey` < unix_timestamp(now() - interval '.$Config{ZM_LOG_DATABASE_LIMIT}.') LIMIT 100');
Debug("Deleted $rows log table entries by time") if $rows;
} while ($rows and ($rows == 100) and !$zm_terminate);
}
} # end if ZM_LOG_DATABASE_LIMIT
my $rows;
do {
# Delete any sessions that are more than a week old. Limiting to 100 because mysql sucks
$rows = zmDbDo('DELETE FROM Sessions WHERE access < ? LIMIT 100', time - $Config{ZM_COOKIE_LIFETIME});
Debug("Deleted $rows sessions") if $rows;
} while ($rows and ($rows == 100) and !$zm_terminate);
{
my $rows;
do {
# Delete any sessions that are more than a week old. Limiting to 100 because mysql sucks
$rows = zmDbDo('DELETE FROM Sessions WHERE access < ? LIMIT 100', time - $Config{ZM_COOKIE_LIFETIME});
Debug("Deleted $rows sessions") if $rows;
} while ($rows and ($rows == 100) and !$zm_terminate);
}
sleep($Config{ZM_STATS_UPDATE_INTERVAL});
} # end while (!$zm_terminate)