Merge branch 'storageareas' into zma_to_thread

This commit is contained in:
Isaac Connor 2018-02-22 09:41:50 -05:00
commit 83785ac73f
17 changed files with 540 additions and 313 deletions

View File

@ -30,17 +30,6 @@ FOR EACH ROW
//
DELIMITER ;
DROP TABLE IF EXISTS `Events_Day`;
CREATE TABLE `Events_Day` (
`EventId` int(10) unsigned NOT NULL,
`MonitorId` int(10) unsigned NOT NULL,
`StartTime` datetime default NULL,
`DiskSpace` bigint unsigned default NULL,
PRIMARY KEY (`EventId`),
KEY `Events_Day_MonitorId_idx` (`MonitorId`),
KEY `Events_Day_StartTime_idx` (`StartTime`)
) ENGINE=@ZM_MYSQL_ENGINE@;
delimiter //
DROP TRIGGER IF EXISTS Events_Day_delete_trigger//
CREATE TRIGGER Events_Day_delete_trigger BEFORE DELETE ON Events_Day
@ -71,19 +60,6 @@ FOR EACH ROW
//
DELIMITER ;
DROP TABLE IF EXISTS `Events_Week`;
CREATE TABLE `Events_Week` (
`EventId` int(10) unsigned NOT NULL,
`MonitorId` int(10) unsigned NOT NULL,
`StartTime` datetime default NULL,
`DiskSpace` bigint unsigned default NULL,
PRIMARY KEY (`EventId`),
KEY `Events_Week_MonitorId_idx` (`MonitorId`),
KEY `Events_Week_StartTime_idx` (`StartTime`)
) ENGINE=@ZM_MYSQL_ENGINE@;
delimiter //
DROP TRIGGER IF EXISTS Events_Week_delete_trigger//
CREATE TRIGGER Events_Week_delete_trigger BEFORE DELETE ON Events_Week
FOR EACH ROW BEGIN
@ -112,20 +88,6 @@ FOR EACH ROW
END;
//
DELIMITER ;
DROP TABLE IF EXISTS `Events_Month`;
CREATE TABLE `Events_Month` (
`EventId` int(10) unsigned NOT NULL,
`MonitorId` int(10) unsigned NOT NULL,
`StartTime` datetime default NULL,
`DiskSpace` bigint unsigned default NULL,
PRIMARY KEY (`EventId`),
KEY `Events_Month_MonitorId_idx` (`MonitorId`),
KEY `Events_Month_StartTime_idx` (`StartTime`)
) ENGINE=@ZM_MYSQL_ENGINE@;
delimiter //
DROP TRIGGER IF EXISTS Events_Month_delete_trigger//
CREATE TRIGGER Events_Month_delete_trigger BEFORE DELETE ON Events_Month
FOR EACH ROW BEGIN
@ -136,7 +98,6 @@ FOR EACH ROW BEGIN
END;
//
DROP TRIGGER IF EXISTS Events_Month_update_trigger;
CREATE TRIGGER Events_Month_update_trigger AFTER UPDATE ON Events_Month
FOR EACH ROW
@ -155,23 +116,7 @@ FOR EACH ROW
END;
//
DELIMITER ;
DROP TABLE IF EXISTS `Events_Archived`;
CREATE TABLE `Events_Archived` (
`EventId` int(10) unsigned NOT NULL,
`MonitorId` int(10) unsigned NOT NULL,
`DiskSpace` bigint unsigned default NULL,
PRIMARY KEY (`EventId`),
KEY `Events_Archived_MonitorId_idx` (`MonitorId`)
) ENGINE=@ZM_MYSQL_ENGINE@;
drop procedure if exists update_storage_stats;
delimiter //
create procedure update_storage_stats(IN StorageId smallint(5), IN space BIGINT)
sql security invoker
@ -227,7 +172,7 @@ BEGIN
WHERE Id=OLD.MonitorId;
END IF;
END IF;
ELSE IF ( NEW.Archived AND diff ) THEN
ELSEIF ( NEW.Archived AND diff ) THEN
UPDATE Events_Archived SET DiskSpace=NEW.DiskSpace WHERE EventId=NEW.Id;
END IF;
@ -256,10 +201,10 @@ FOR EACH ROW
INSERT INTO Events_Week (EventId,MonitorId,StartTime,DiskSpace) VALUES (NEW.Id,NEW.MonitorId,NEW.StartTime,0);
INSERT INTO Events_Month (EventId,MonitorId,StartTime,DiskSpace) VALUES (NEW.Id,NEW.MonitorId,NEW.StartTime,0);
UPDATE Monitors SET
HourEvents = COALESCE(DayEvents,0)+1,
HourEvents = COALESCE(HourEvents,0)+1,
DayEvents = COALESCE(DayEvents,0)+1,
WeekEvents = COALESCE(DayEvents,0)+1,
MonthEvents = COALESCE(DayEvents,0)+1,
WeekEvents = COALESCE(WeekEvents,0)+1,
MonthEvents = COALESCE(MonthEvents,0)+1,
TotalEvents = COALESCE(TotalEvents,0)+1
WHERE Id=NEW.MonitorId;
END;

View File

@ -756,18 +756,18 @@ CREATE TABLE `Monitors` (
`WebColour` varchar(32) NOT NULL default 'red',
`Exif` tinyint(1) unsigned NOT NULL default '0',
`Sequence` smallint(5) unsigned default NULL,
`TotalEvents` int(10) unsigned,
`TotalEventDiskSpace` bigint unsigned,
`HourEvents` int(10) unsigned,
`HourEventDiskSpace` bigint unsigned,
`DayEvents` int(10) unsigned,
`DayEventDiskSpace` bigint unsigned,
`WeekEvents` int(10) unsigned,
`WeekEventDiskSpace` bigint unsigned,
`MonthEvents` int(10) unsigned,
`MonthEventDiskSpace` bigint unsigned,
`ArchivedEvents` int(10) unsigned,
`ArchivedEventDiskSpace` bigint unsigned,
`TotalEvents` int(10) default NULL,
`TotalEventDiskSpace` bigint default NULL,
`HourEvents` int(10) default NULL,
`HourEventDiskSpace` bigint default NULL,
`DayEvents` int(10) default NULL,
`DayEventDiskSpace` bigint default NULL,
`WeekEvents` int(10) default NULL,
`WeekEventDiskSpace` bigint default NULL,
`MonthEvents` int(10) default NULL,
`MonthEventDiskSpace` bigint default NULL,
`ArchivedEvents` int(10) default NULL,
`ArchivedEventDiskSpace` bigint default NULL,
`ZoneCount` TINYINT NOT NULL DEFAULT 0,
PRIMARY KEY (`Id`)
) ENGINE=@ZM_MYSQL_ENGINE@;
@ -1155,7 +1155,11 @@ INSERT INTO MontageLayouts (`Name`,`Positions`) VALUES ('4 Wide', '{ "default":{
INSERT INTO MontageLayouts (`Name`,`Positions`) VALUES ('5 Wide', '{ "default":{"float":"left", "width":"19%","left":"0px","right":"0px","top":"0px","bottom":"0px"} }' );
-- We generally don't alter triggers, we drop and re-create them, so let's keep them in a separate file that we can just source in update scripts.
<<<<<<< HEAD
source triggers.sql
=======
source @ZM_PATH_DATA@/db/triggers.sql
>>>>>>> storageareas
--
-- Apply the initial configuration
--

View File

@ -145,4 +145,4 @@ WeekEventDiskSpace=(SELECT SUM(DiskSpace) FROM Events WHERE MonitorId=Monitors.I
MonthEvents=(SELECT COUNT(Id) FROM Events WHERE MonitorId=Monitors.Id AND StartTime > DATE_SUB( NOW(), INTERVAL 1 month)),
MonthEventDiskSpace=(SELECT SUM(DiskSpace) FROM Events WHERE MonitorId=Monitors.Id AND StartTime > DATE_SUB(NOW(), INTERVAL 1 month) AND DiskSpace IS NOT NULL),
ArchivedEvents=(SELECT COUNT(Id) FROM Events WHERE MonitorId=Monitors.Id AND Archived=1),
ArchivedEventDiskSpace=(SELECT SUM(DiskSpace) FROM Events WHERE MonitorId=Monitors.Id AND Archived=1 AND DiskSpace IS NOT NULL)
ArchivedEventDiskSpace=(SELECT SUM(DiskSpace) FROM Events WHERE MonitorId=Monitors.Id AND Archived=1 AND DiskSpace IS NOT NULL);

View File

@ -176,7 +176,7 @@ BEGIN
WHERE Id=OLD.MonitorId;
END IF;
END IF;
ELSE IF ( NEW.Archived AND diff ) THEN
ELSEIF ( NEW.Archived AND diff ) THEN
UPDATE Events_Archived SET DiskSpace=NEW.DiskSpace WHERE EventId=NEW.Id;
END IF;
@ -205,10 +205,10 @@ FOR EACH ROW
INSERT INTO Events_Week (EventId,MonitorId,StartTime,DiskSpace) VALUES (NEW.Id,NEW.MonitorId,NEW.StartTime,0);
INSERT INTO Events_Month (EventId,MonitorId,StartTime,DiskSpace) VALUES (NEW.Id,NEW.MonitorId,NEW.StartTime,0);
UPDATE Monitors SET
HourEvents = COALESCE(DayEvents,0)+1,
HourEvents = COALESCE(HourEvents,0)+1,
DayEvents = COALESCE(DayEvents,0)+1,
WeekEvents = COALESCE(DayEvents,0)+1,
MonthEvents = COALESCE(DayEvents,0)+1,
WeekEvents = COALESCE(WeekEvents,0)+1,
MonthEvents = COALESCE(MonthEvents,0)+1,
TotalEvents = COALESCE(TotalEvents,0)+1
WHERE Id=NEW.MonitorId;
END;
@ -260,3 +260,17 @@ FOR EACH ROW
//
DELIMITER ;
UPDATE Monitors SET
TotalEvents=(SELECT COUNT(*) FROM Events WHERE MonitorId=Monitors.Id),
TotalEventDiskSpace=(SELECT SUM(DiskSpace) FROM Events WHERE MonitorId=Monitors.Id AND DiskSpace IS NOT NULL),
HourEvents=(SELECT COUNT(*) FROM Events_Hour WHERE MonitorId=Monitors.Id),
HourEventDiskSpace=(SELECT SUM(DiskSpace) FROM Events_Hour WHERE MonitorId=Monitors.Id AND DiskSpace IS NOT NULL),
DayEvents=(SELECT COUNT(*) FROM Events_Day WHERE MonitorId=Monitors.Id),
DayEventDiskSpace=(SELECT SUM(DiskSpace) FROM Events_Day WHERE MonitorId=Monitors.Id AND DiskSpace IS NOT NULL),
WeekEvents=(SELECT COUNT(Id) FROM Events_Week WHERE MonitorId=Monitors.Id),
WeekEventDiskSpace=(SELECT SUM(DiskSpace) FROM Events_Week WHERE MonitorId=Monitors.Id AND DiskSpace IS NOT NULL),
MonthEvents=(SELECT COUNT(Id) FROM Events_Month WHERE MonitorId=Monitors.Id),
MonthEventDiskSpace=(SELECT SUM(DiskSpace) FROM Events_Month WHERE MonitorId=Monitors.Id AND DiskSpace IS NOT NULL),
ArchivedEvents=(SELECT COUNT(Id) FROM Events_Archived WHERE MonitorId=Monitors.Id),
ArchivedEventDiskSpace=(SELECT SUM(DiskSpace) FROM Events_Archived WHERE MonitorId=Monitors.Id AND DiskSpace IS NOT NULL);

275
db/zm_update-1.31.39.sql Normal file
View File

@ -0,0 +1,275 @@
ALTER TABLE `Monitors` MODIFY `HourEvents` INT(10) DEFAULT NULL;
ALTER TABLE `Monitors` MODIFY `HourEventDiskSpace` BIGINT DEFAULT NULL;
ALTER TABLE `Monitors` MODIFY `DayEvents` INT(10) DEFAULT NULL;
ALTER TABLE `Monitors` MODIFY `DayEventDiskSpace` BIGINT DEFAULT NULL;
ALTER TABLE `Monitors` MODIFY `WeekEvents` INT(10) DEFAULT NULL;
ALTER TABLE `Monitors` MODIFY `WeekEventDiskSpace` BIGINT DEFAULT NULL;
ALTER TABLE `Monitors` MODIFY `MonthEvents` INT(10) DEFAULT NULL;
ALTER TABLE `Monitors` MODIFY `MonthEventDiskSpace` BIGINT DEFAULT NULL;
ALTER TABLE `Monitors` MODIFY `ArchivedEvents` INT(10) DEFAULT NULL;
ALTER TABLE `Monitors` MODIFY `ArchivedEventDiskSpace` BIGINT DEFAULT NULL;
ALTER TABLE `Monitors` MODIFY `TotalEvents` INT(10) DEFAULT NULL;
ALTER TABLE `Monitors` MODIFY `TotalEventDiskSpace` BIGINT DEFAULT NULL;
delimiter //
DROP TRIGGER IF EXISTS Events_Hour_delete_trigger//
CREATE TRIGGER Events_Hour_delete_trigger BEFORE DELETE ON Events_Hour
FOR EACH ROW BEGIN
UPDATE Monitors SET
HourEvents = COALESCE(HourEvents,1)-1,
HourEventDiskSpace=COALESCE(HourEventDiskSpace,0)-COALESCE(OLD.DiskSpace,0)
WHERE Id=OLD.MonitorId;
END;
//
DROP TRIGGER IF EXISTS Events_Hour_update_trigger//
CREATE TRIGGER Events_Hour_update_trigger AFTER UPDATE ON Events_Hour
FOR EACH ROW
BEGIN
declare diff BIGINT default 0;
set diff = COALESCE(NEW.DiskSpace,0) - COALESCE(OLD.DiskSpace,0);
IF ( diff ) THEN
IF ( NEW.MonitorID != OLD.MonitorID ) THEN
UPDATE Monitors SET HourEventDiskSpace=COALESCE(HourEventDiskSpace,0)-COALESCE(OLD.DiskSpace,0) WHERE Monitors.Id=OLD.MonitorId;
UPDATE Monitors SET HourEventDiskSpace=COALESCE(HourEventDiskSpace,0)-COALESCE(NEW.DiskSpace,0) WHERE Monitors.Id=NEW.MonitorId;
ELSE
UPDATE Monitors SET HourEventDiskSpace=COALESCE(HourEventDiskSpace,0)+diff WHERE Monitors.Id=NEW.MonitorId;
END IF;
END IF;
END;
//
DELIMITER ;
delimiter //
DROP TRIGGER IF EXISTS Events_Day_delete_trigger//
CREATE TRIGGER Events_Day_delete_trigger BEFORE DELETE ON Events_Day
FOR EACH ROW BEGIN
UPDATE Monitors SET
DayEvents = COALESCE(DayEvents,1)-1,
DayEventDiskSpace=COALESCE(DayEventDiskSpace,0)-COALESCE(OLD.DiskSpace,0)
WHERE Id=OLD.MonitorId;
END;
//
DROP TRIGGER IF EXISTS Events_Day_update_trigger;
CREATE TRIGGER Events_Day_update_trigger AFTER UPDATE ON Events_Day
FOR EACH ROW
BEGIN
declare diff BIGINT default 0;
set diff = COALESCE(NEW.DiskSpace,0) - COALESCE(OLD.DiskSpace,0);
IF ( diff ) THEN
IF ( NEW.MonitorID != OLD.MonitorID ) THEN
UPDATE Monitors SET DayEventDiskSpace=COALESCE(DayEventDiskSpace,0)-COALESCE(OLD.DiskSpace,0) WHERE Monitors.Id=OLD.MonitorId;
UPDATE Monitors SET DayEventDiskSpace=COALESCE(DayEventDiskSpace,0)+COALESCE(NEW.DiskSpace,0) WHERE Monitors.Id=NEW.MonitorId;
ELSE
UPDATE Monitors SET DayEventDiskSpace=COALESCE(DayEventDiskSpace,0)+diff WHERE Monitors.Id=NEW.MonitorId;
END IF;
END IF;
END;
//
delimiter //
DROP TRIGGER IF EXISTS Events_Week_delete_trigger//
CREATE TRIGGER Events_Week_delete_trigger BEFORE DELETE ON Events_Week
FOR EACH ROW BEGIN
UPDATE Monitors SET
WeekEvents = COALESCE(WeekEvents,1)-1,
WeekEventDiskSpace=COALESCE(WeekEventDiskSpace,0)-COALESCE(OLD.DiskSpace,0)
WHERE Id=OLD.MonitorId;
END;
//
DROP TRIGGER IF EXISTS Events_Week_update_trigger;
CREATE TRIGGER Events_Week_update_trigger AFTER UPDATE ON Events_Week
FOR EACH ROW
BEGIN
declare diff BIGINT default 0;
set diff = COALESCE(NEW.DiskSpace,0) - COALESCE(OLD.DiskSpace,0);
IF ( diff ) THEN
IF ( NEW.MonitorID != OLD.MonitorID ) THEN
UPDATE Monitors SET WeekEventDiskSpace=COALESCE(WeekEventDiskSpace,0)-COALESCE(OLD.DiskSpace,0) WHERE Monitors.Id=OLD.MonitorId;
UPDATE Monitors SET WeekEventDiskSpace=COALESCE(WeekEventDiskSpace,0)+COALESCE(NEW.DiskSpace,0) WHERE Monitors.Id=NEW.MonitorId;
ELSE
UPDATE Monitors SET WeekEventDiskSpace=COALESCE(WeekEventDiskSpace,0)+diff WHERE Monitors.Id=NEW.MonitorId;
END IF;
END IF;
END;
//
DELIMITER ;
delimiter //
DROP TRIGGER IF EXISTS Events_Month_delete_trigger//
CREATE TRIGGER Events_Month_delete_trigger BEFORE DELETE ON Events_Month
FOR EACH ROW BEGIN
UPDATE Monitors SET
MonthEvents = COALESCE(MonthEvents,1)-1,
MonthEventDiskSpace=COALESCE(MonthEventDiskSpace,0)-COALESCE(OLD.DiskSpace,0)
WHERE Id=OLD.MonitorId;
END;
//
DROP TRIGGER IF EXISTS Events_Month_update_trigger;
CREATE TRIGGER Events_Month_update_trigger AFTER UPDATE ON Events_Month
FOR EACH ROW
BEGIN
declare diff BIGINT default 0;
set diff = COALESCE(NEW.DiskSpace,0) - COALESCE(OLD.DiskSpace,0);
IF ( diff ) THEN
IF ( NEW.MonitorID != OLD.MonitorID ) THEN
UPDATE Monitors SET MonthEventDiskSpace=COALESCE(MonthEventDiskSpace,0)-COALESCE(OLD.DiskSpace) WHERE Monitors.Id=OLD.MonitorId;
UPDATE Monitors SET MonthEventDiskSpace=COALESCE(MonthEventDiskSpace,0)+COALESCE(NEW.DiskSpace) WHERE Monitors.Id=NEW.MonitorId;
ELSE
UPDATE Monitors SET MonthEventDiskSpace=COALESCE(MonthEventDiskSpace,0)+diff WHERE Monitors.Id=NEW.MonitorId;
END IF;
END IF;
END;
//
drop procedure if exists update_storage_stats;
create procedure update_storage_stats(IN StorageId smallint(5), IN space BIGINT)
sql security invoker
deterministic
begin
update Storage set DiskSpace = COALESCE(DiskSpace,0) + COALESCE(space,0) where Id = StorageId;
end;
//
drop trigger if exists event_update_trigger//
CREATE TRIGGER event_update_trigger AFTER UPDATE ON Events
FOR EACH ROW
BEGIN
declare diff BIGINT default 0;
set diff = COALESCE(NEW.DiskSpace,0) - COALESCE(OLD.DiskSpace,0);
IF ( NEW.StorageId = OLD.StorageID ) THEN
IF ( diff ) THEN
call update_storage_stats(OLD.StorageId, diff);
END IF;
ELSE
IF ( NEW.DiskSpace ) THEN
call update_storage_stats(NEW.StorageId, NEW.DiskSpace);
END IF;
IF ( OLD.DiskSpace ) THEN
call update_storage_stats(OLD.StorageId, -OLD.DiskSpace);
END IF;
END IF;
UPDATE Events_Hour SET DiskSpace=NEW.DiskSpace WHERE EventId=NEW.Id;
UPDATE Events_Day SET DiskSpace=NEW.DiskSpace WHERE EventId=NEW.Id;
UPDATE Events_Week SET DiskSpace=NEW.DiskSpace WHERE EventId=NEW.Id;
UPDATE Events_Month SET DiskSpace=NEW.DiskSpace WHERE EventId=NEW.Id;
IF ( NEW.Archived != OLD.Archived ) THEN
IF ( NEW.Archived ) THEN
INSERT INTO Events_Archived (EventId,MonitorId,DiskSpace) VALUES (NEW.Id,NEW.MonitorId,NEW.DiskSpace);
UPDATE Monitors SET ArchivedEvents = COALESCE(ArchivedEvents,0)+1, ArchivedEventDiskSpace = COALESCE(ArchivedEventDiskSpace,0) + COALESCE(NEW.DiskSpace,0) WHERE Id=NEW.MonitorId;
ELSEIF ( OLD.Archived ) THEN
DELETE FROM Events_Archived WHERE EventId=OLD.Id;
UPDATE Monitors SET ArchivedEvents = COALESCE(ArchivedEvents,0)-1, ArchivedEventDiskSpace = COALESCE(ArchivedEventDiskSpace,0) - COALESCE(OLD.DiskSpace,0) WHERE Id=OLD.MonitorId;
ELSE
IF ( OLD.DiskSpace != NEW.DiskSpace ) THEN
UPDATE Events_Archived SET DiskSpace=NEW.DiskSpace WHERE EventId=NEW.Id;
UPDATE Monitors SET
ArchivedEventDiskSpace = COALESCE(ArchivedEventDiskSpace,0) - COALESCE(OLD.DiskSpace,0) + COALESCE(NEW.DiskSpace,0)
WHERE Id=OLD.MonitorId;
END IF;
END IF;
ELSEIF ( NEW.Archived AND diff ) THEN
UPDATE Events_Archived SET DiskSpace=NEW.DiskSpace WHERE EventId=NEW.Id;
END IF;
IF ( diff ) THEN
UPDATE Monitors SET TotalEventDiskSpace = COALESCE(TotalEventDiskSpace,0) - COALESCE(OLD.DiskSpace,0) + COALESCE(NEW.DiskSpace,0) WHERE Id=OLD.MonitorId;
END IF;
END;
//
delimiter ;
DROP TRIGGER IF EXISTS event_insert_trigger;
delimiter //
/* The assumption is that when an Event is inserted, it has no size yet, so don't bother updating the DiskSpace, just the count.
* The DiskSpace will get update in the Event Update Trigger
*/
CREATE TRIGGER event_insert_trigger AFTER INSERT ON Events
FOR EACH ROW
BEGIN
INSERT INTO Events_Hour (EventId,MonitorId,StartTime,DiskSpace) VALUES (NEW.Id,NEW.MonitorId,NEW.StartTime,0);
INSERT INTO Events_Day (EventId,MonitorId,StartTime,DiskSpace) VALUES (NEW.Id,NEW.MonitorId,NEW.StartTime,0);
INSERT INTO Events_Week (EventId,MonitorId,StartTime,DiskSpace) VALUES (NEW.Id,NEW.MonitorId,NEW.StartTime,0);
INSERT INTO Events_Month (EventId,MonitorId,StartTime,DiskSpace) VALUES (NEW.Id,NEW.MonitorId,NEW.StartTime,0);
UPDATE Monitors SET
HourEvents = COALESCE(HourEvents,0)+1,
DayEvents = COALESCE(DayEvents,0)+1,
WeekEvents = COALESCE(WeekEvents,0)+1,
MonthEvents = COALESCE(MonthEvents,0)+1,
TotalEvents = COALESCE(TotalEvents,0)+1
WHERE Id=NEW.MonitorId;
END;
//
DROP TRIGGER IF EXISTS event_delete_trigger//
CREATE TRIGGER event_delete_trigger BEFORE DELETE ON Events
FOR EACH ROW
BEGIN
IF ( OLD.DiskSpace ) THEN
call update_storage_stats(OLD.StorageId, -OLD.DiskSpace);
END IF;
DELETE FROM Events_Hour WHERE EventId=OLD.Id;
DELETE FROM Events_Day WHERE EventId=OLD.Id;
DELETE FROM Events_Week WHERE EventId=OLD.Id;
DELETE FROM Events_Month WHERE EventId=OLD.Id;
IF ( OLD.Archived ) THEN
DELETE FROM Events_Archived WHERE EventId=OLD.Id;
UPDATE Monitors SET
ArchivedEvents = COALESCE(ArchivedEvents,1) - 1,
ArchivedEventDiskSpace = COALESCE(ArchivedEventDiskSpace,0) - COALESCE(OLD.DiskSpace,0),
TotalEvents = COALESCE(TotalEvents,1) - 1,
TotalEventDiskSpace = COALESCE(TotalEventDiskSpace,0) - COALESCE(OLD.DiskSpace,0)
WHERE Id=OLD.MonitorId;
ELSE
UPDATE Monitors SET
TotalEvents = COALESCE(TotalEvents,1)-1,
TotalEventDiskSpace=COALESCE(TotalEventDiskSpace,0)-COALESCE(OLD.DiskSpace,0)
WHERE Id=OLD.MonitorId;
END IF;
END;
//
DROP TRIGGER IF EXISTS Zone_Insert_Trigger//
CREATE TRIGGER Zone_Insert_Trigger AFTER INSERT ON Zones
FOR EACH ROW
BEGIN
UPDATE Monitors SET ZoneCount=(SELECT COUNT(*) FROM Zones WHERE MonitorId=NEW.MonitorId) WHERE Id=NEW.MonitorID;
END
//
DROP TRIGGER IF EXISTS Zone_Delete_Trigger//
CREATE TRIGGER Zone_Delete_Trigger AFTER DELETE ON Zones
FOR EACH ROW
BEGIN
UPDATE Monitors SET ZoneCount=(SELECT COUNT(*) FROM Zones WHERE MonitorId=OLD.MonitorId) WHERE Id=OLD.MonitorID;
END
//
DELIMITER ;

View File

@ -0,0 +1,6 @@
check process zmdc.pl with pidfile /run/zm/zm.pid
if failed unixsocket /run/zm/zmdc2.sock then restart
group zm
start program = "/bin/systemctl start zoneminder"
stop program = "/bin/systemctl stop zoneminder"
#if 4 restarts within 20 cycles then timeout

View File

@ -425,6 +425,9 @@ sub delete_files {
} # end sub delete_files
sub Storage {
if ( @_ > 1 ) {
$_[0]{Storage} = $_[1];
}
if ( ! $_[0]{Storage} ) {
$_[0]{Storage} = new ZoneMinder::Storage( $_[0]{StorageId} );
}
@ -487,7 +490,7 @@ sub MoveTo {
return "Event has already been moved by someone else.";
}
my $OldStorage = $self->Storage();
my $OldStorage = $self->Storage(undef);
my ( $OldPath ) = ( $self->Path() =~ /^(.*)$/ ); # De-taint
$$self{Storage} = $NewStorage;
@ -535,6 +538,7 @@ sub MoveTo {
for my $file (@files) {
next if $file =~ /^\./;
( $file ) = ( $file =~ /^(.*)$/ ); # De-taint
Debug("Moving file $file to $NewPath");
if ( ! File::Copy::copy( $file, $NewPath ) ) {
$error .= "Copy failed: for $file to $NewPath: $!";
last;

View File

@ -75,7 +75,7 @@ our %EXPORT_TAGS = (
push( @{$EXPORT_TAGS{all}}, @{$EXPORT_TAGS{$_}} ) foreach keys %EXPORT_TAGS;
our @EXPORT_OK = ( @{ $EXPORT_TAGS{'all'} } );
our @EXPORT_OK = ( @{ $EXPORT_TAGS{all} } );
our @EXPORT = qw();
@ -135,18 +135,19 @@ sub new {
$this->{initialised} = undef;
#$this->{id} = 'zmundef';
( $this->{id} ) = $0 =~ m|^(?:.*/)?([^/]+?)(?:\.[^/.]+)?$|;
$this->{idRoot} = $this->{id};
$this->{idArgs} = '';
$this->{level} = INFO;
# Detect if we are running in a terminal session, if so, default log level to INFO
$this->{hasTerm} = -t STDERR;
if ( $this->{hasTerm} ) {
$this->{termLevel} = INFO;
} else {
$this->{termLevel} = NOLOG;
}
if ( $this->{hasTerm} ) {
$this->{termLevel} = INFO;
} else {
$this->{termLevel} = NOLOG;
}
$this->{databaseLevel} = NOLOG;
$this->{fileLevel} = NOLOG;
$this->{syslogLevel} = NOLOG;
@ -156,7 +157,7 @@ if ( $this->{hasTerm} ) {
( $this->{fileName} = $0 ) =~ s|^.*/||;
$this->{logPath} = $Config{ZM_PATH_LOGS};
$this->{logFile} = $this->{logPath}.'/'.$this->{id}.".log";
$this->{logFile} = $this->{logPath}.'/'.$this->{id}.'.log';
$this->{trace} = 0;
@ -175,9 +176,9 @@ sub BEGIN {
ZM_LOG_LEVEL_FILE => 0,
ZM_LOG_LEVEL_SYSLOG => 0,
ZM_LOG_DEBUG => 0,
ZM_LOG_DEBUG_TARGET => "",
ZM_LOG_DEBUG_TARGET => '',
ZM_LOG_DEBUG_LEVEL => 1,
ZM_LOG_DEBUG_FILE => ""
ZM_LOG_DEBUG_FILE => ''
);
while ( my ( $name, $value ) = each( %dbgConfig ) ) {
*{$name} = sub { $value };
@ -196,13 +197,13 @@ sub initialise( @ ) {
my $this = shift;
my %options = @_;
$this->{id} = $options{id} if ( defined($options{id}) );
$this->{id} = $options{id} if defined($options{id});
$this->{logPath} = $options{logPath} if ( defined($options{logPath}) );
$this->{logPath} = $options{logPath} if defined($options{logPath});
my $tempLogFile;
$tempLogFile = $this->{logPath}.'/'.$this->{id}.".log";
$tempLogFile = $options{logFile} if ( defined($options{logFile}) );
$tempLogFile = $this->{logPath}.'/'.$this->{id}.'.log';
$tempLogFile = $options{logFile} if defined($options{logFile});
if ( my $logFile = $this->getTargettedEnv('LOG_FILE') ) {
$tempLogFile = $logFile;
}
@ -213,7 +214,7 @@ sub initialise( @ ) {
my $tempFileLevel = $this->{fileLevel};
my $tempSyslogLevel = $this->{syslogLevel};
$tempTermLevel = $options{termLevel} if ( defined($options{termLevel}) );
$tempTermLevel = $options{termLevel} if defined($options{termLevel});
if ( defined($options{databaseLevel}) ) {
$tempDatabaseLevel = $options{databaseLevel};
} else {
@ -230,16 +231,16 @@ sub initialise( @ ) {
$tempSyslogLevel = $Config{ZM_LOG_LEVEL_SYSLOG};
}
if ( defined($ENV{'LOG_PRINT'}) ) {
$tempTermLevel = $ENV{'LOG_PRINT'}? DEBUG : NOLOG;
if ( defined($ENV{LOG_PRINT}) ) {
$tempTermLevel = $ENV{LOG_PRINT}? DEBUG : NOLOG;
}
my $level;
$tempLevel = $level if ( defined($level = $this->getTargettedEnv('LOG_LEVEL')) );
$tempTermLevel = $level if ( defined($level = $this->getTargettedEnv('LOG_LEVEL_TERM')) );
$tempDatabaseLevel = $level if ( defined($level = $this->getTargettedEnv('LOG_LEVEL_DATABASE')) );
$tempFileLevel = $level if ( defined($level = $this->getTargettedEnv('LOG_LEVEL_FILE')) );
$tempSyslogLevel = $level if ( defined($level = $this->getTargettedEnv('LOG_LEVEL_SYSLOG')) );
$tempLevel = $level if defined($level = $this->getTargettedEnv('LOG_LEVEL'));
$tempTermLevel = $level if defined($level = $this->getTargettedEnv('LOG_LEVEL_TERM'));
$tempDatabaseLevel = $level if defined($level = $this->getTargettedEnv('LOG_LEVEL_DATABASE'));
$tempFileLevel = $level if defined($level = $this->getTargettedEnv('LOG_LEVEL_FILE'));
$tempSyslogLevel = $level if defined($level = $this->getTargettedEnv('LOG_LEVEL_SYSLOG'));
if ( $Config{ZM_LOG_DEBUG} ) {
foreach my $target ( split( /\|/, $Config{ZM_LOG_DEBUG_TARGET} ) ) {
@ -247,11 +248,11 @@ sub initialise( @ ) {
|| $target eq '_'.$this->{id}
|| $target eq $this->{idRoot}
|| $target eq '_'.$this->{idRoot}
|| $target eq ""
|| $target eq ''
) {
if ( $Config{ZM_LOG_DEBUG_LEVEL} > NOLOG ) {
$tempLevel = $this->limit( $Config{ZM_LOG_DEBUG_LEVEL} );
if ( $Config{ZM_LOG_DEBUG_FILE} ne "" ) {
if ( $Config{ZM_LOG_DEBUG_FILE} ne '' ) {
$tempLogFile = $Config{ZM_LOG_DEBUG_FILE};
$tempFileLevel = $tempLevel;
}
@ -269,9 +270,9 @@ sub initialise( @ ) {
$this->level( $tempLevel );
$this->{trace} = $options{trace} if ( defined($options{trace}) );
$this->{trace} = $options{trace} if defined($options{trace});
$this->{autoFlush} = $ENV{'LOG_FLUSH'}?1:0 if ( defined($ENV{'LOG_FLUSH'}) );
$this->{autoFlush} = $ENV{LOG_FLUSH}?1:0 if defined($ENV{LOG_FLUSH});
$this->{initialised} = !undef;
@ -303,28 +304,28 @@ sub reinitialise {
# Bit of a nasty hack to reopen connections to log files and the DB
my $syslogLevel = $this->syslogLevel();
$this->syslogLevel( NOLOG );
$this->syslogLevel( $syslogLevel ) if ( $syslogLevel > NOLOG );
$this->syslogLevel($syslogLevel) if $syslogLevel > NOLOG;
my $logfileLevel = $this->fileLevel();
$this->fileLevel( NOLOG );
$this->fileLevel( $logfileLevel ) if ( $logfileLevel > NOLOG );
$this->fileLevel(NOLOG);
$this->fileLevel($logfileLevel) if $logfileLevel > NOLOG;
my $databaseLevel = $this->databaseLevel();
$this->databaseLevel( NOLOG );
$this->databaseLevel( $databaseLevel ) if ( $databaseLevel > NOLOG );
$this->databaseLevel(NOLOG);
$this->databaseLevel($databaseLevel) if $databaseLevel > NOLOG;
my $screenLevel = $this->termLevel();
$this->termLevel( NOLOG );
$this->termLevel( $screenLevel ) if ( $screenLevel > NOLOG );
$this->termLevel(NOLOG);
$this->termLevel($screenLevel) if $screenLevel > NOLOG;
}
# Prevents undefined logging levels
sub limit {
my $this = shift;
my $level = shift;
return( DEBUG ) if ( $level > DEBUG );
return( NOLOG ) if ( $level < NOLOG );
return( $level );
return(DEBUG) if $level > DEBUG;
return(NOLOG) if $level < NOLOG;
return($level);
}
sub getTargettedEnv {
@ -332,32 +333,32 @@ sub getTargettedEnv {
my $name = shift;
my $envName = $name.'_'.$this->{id};
my $value;
$value = $ENV{$envName} if ( defined($ENV{$envName}) );
if ( !defined($value) && $this->{id} ne $this->{idRoot} ) {
$value = $ENV{$envName} if defined($ENV{$envName});
if ( !defined($value) and ($this->{id} ne $this->{idRoot}) ) {
$envName = $name.'_'.$this->{idRoot};
$value = $ENV{$envName} if ( defined($ENV{$envName}) );
$value = $ENV{$envName} if defined($ENV{$envName});
}
if ( !defined($value) ) {
$value = $ENV{$name} if ( defined($ENV{$name}) );
$value = $ENV{$name} if defined($ENV{$name});
}
if ( defined($value) ) {
( $value ) = $value =~ m/(.*)/;
}
return( $value );
return $value;
}
sub fetch {
if ( !$logger ) {
$logger = ZoneMinder::Logger->new();
$logger->initialise( 'syslogLevel'=>INFO, 'databaseLevel'=>INFO );
$logger->initialise( syslogLevel=>INFO, databaseLevel=>INFO );
}
return( $logger );
return $logger;
}
sub id {
my $this = shift;
my $id = shift;
if ( defined($id) && $this->{id} ne $id ) {
if ( defined($id) and ($this->{id} ne $id) ) {
# Remove whitespace
$id =~ s/\S//g;
# Replace non-alphanum with underscore
@ -371,37 +372,37 @@ sub id {
}
}
}
return( $this->{id} );
return $this->{id};
}
sub level {
my $this = shift;
my $level = shift;
if ( defined($level) ) {
$this->{level} = $this->limit( $level );
$this->{level} = $this->limit($level);
# effectiveLevel is the highest logging level used by any of the outputs.
$this->{effectiveLevel} = NOLOG;
$this->{effectiveLevel} = $this->{termLevel} if ( $this->{termLevel} > $this->{effectiveLevel} );
$this->{effectiveLevel} = $this->{databaseLevel} if ( $this->{databaseLevel} > $this->{effectiveLevel} );
$this->{effectiveLevel} = $this->{fileLevel} if ( $this->{fileLevel} > $this->{effectiveLevel} );
$this->{effectiveLevel} = $this->{syslogLevel} if ( $this->{syslogLevel} > $this->{effectiveLevel} );
$this->{effectiveLevel} = $this->{termLevel} if $this->{termLevel} > $this->{effectiveLevel};
$this->{effectiveLevel} = $this->{databaseLevel} if $this->{databaseLevel} > $this->{effectiveLevel};
$this->{effectiveLevel} = $this->{fileLevel} if $this->{fileLevel} > $this->{effectiveLevel};
$this->{effectiveLevel} = $this->{syslogLevel} if $this->{syslogLevel} > $this->{effectiveLevel};
# ICON: I am remarking this out because I don't see the point of having an effective level, if we are just going to set it to level.
#$this->{effectiveLevel} = $this->{level} if ( $this->{level} > $this->{effectiveLevel} );
}
return( $this->{level} );
return $this->{level};
}
sub debugOn {
my $this = shift;
return( $this->{effectiveLevel} >= DEBUG );
return $this->{effectiveLevel} >= DEBUG;
}
sub trace {
my $this = shift;
$this->{trace} = $_[0] if ( @_ );
return( $this->{trace} );
$this->{trace} = $_[0] if @_;
return $this->{trace};
}
sub termLevel {
@ -409,63 +410,62 @@ sub termLevel {
my $termLevel = shift;
if ( defined($termLevel) ) {
# What is the point of this next lint if we are just going to overwrite it with the next line? I propose we move it down one line or remove it altogether
$termLevel = NOLOG if ( !$this->{hasTerm} );
$termLevel = $this->limit( $termLevel );
$termLevel = NOLOG if !$this->{hasTerm};
$termLevel = $this->limit($termLevel);
if ( $this->{termLevel} != $termLevel ) {
$this->{termLevel} = $termLevel;
}
}
return( $this->{termLevel} );
return $this->{termLevel};
}
sub databaseLevel {
my $this = shift;
my $databaseLevel = shift;
if ( defined($databaseLevel) ) {
$databaseLevel = $this->limit( $databaseLevel );
$databaseLevel = $this->limit($databaseLevel);
if ( $this->{databaseLevel} != $databaseLevel ) {
if ( $databaseLevel > NOLOG && $this->{databaseLevel} <= NOLOG ) {
if ( $databaseLevel > NOLOG and $this->{databaseLevel} <= NOLOG ) {
if ( !$this->{dbh} ) {
my $socket;
my ( $host, $portOrSocket ) = ( $Config{ZM_DB_HOST} =~ /^([^:]+)(?::(.+))?$/ );
if ( defined($portOrSocket) ) {
if ( $portOrSocket =~ /^\// ) {
$socket = ";mysql_socket=".$portOrSocket;
$socket = ';mysql_socket='.$portOrSocket;
} else {
$socket = ";host=".$host.";port=".$portOrSocket;
$socket = ';host='.$host.';port='.$portOrSocket;
}
} else {
$socket = ";host=".$Config{ZM_DB_HOST};
$socket = ';host='.$Config{ZM_DB_HOST};
}
my $sslOptions = "";
my $sslOptions = '';
if ( $Config{ZM_DB_SSL_CA_CERT} ) {
$sslOptions = ';'.join(';',
"mysql_ssl=1",
"mysql_ssl_ca_file=".$Config{ZM_DB_SSL_CA_CERT},
"mysql_ssl_client_key=".$Config{ZM_DB_SSL_CLIENT_KEY},
"mysql_ssl_client_cert=".$Config{ZM_DB_SSL_CLIENT_CERT}
$sslOptions = join(';','',
'mysql_ssl=1',
'mysql_ssl_ca_file='.$Config{ZM_DB_SSL_CA_CERT},
'mysql_ssl_client_key='.$Config{ZM_DB_SSL_CLIENT_KEY},
'mysql_ssl_client_cert='.$Config{ZM_DB_SSL_CLIENT_CERT}
);
}
$this->{dbh} = DBI->connect( "DBI:mysql:database=".$Config{ZM_DB_NAME}
$this->{dbh} = DBI->connect( 'DBI:mysql:database='.$Config{ZM_DB_NAME}
.$socket.$sslOptions
, $Config{ZM_DB_USER}
, $Config{ZM_DB_PASS}
);
if ( !$this->{dbh} ) {
$databaseLevel = NOLOG;
Error( "Unable to write log entries to DB, can't connect to database '"
Error( 'Unable to write log entries to DB, can\'t connect to database '
.$Config{ZM_DB_NAME}
."' on host '"
.' on host '
.$Config{ZM_DB_HOST}
."'"
);
} else {
$this->{dbh}->{AutoCommit} = 1;
Fatal( "Can't set AutoCommit on in database connection" )
Fatal('Can\'t set AutoCommit on in database connection' )
unless( $this->{dbh}->{AutoCommit} );
$this->{dbh}->{mysql_auto_reconnect} = 1;
Fatal( "Can't set mysql_auto_reconnect on in database connection" )
Fatal('Can\'t set mysql_auto_reconnect on in database connection' )
unless( $this->{dbh}->{mysql_auto_reconnect} );
$this->{dbh}->trace( 0 );
}
@ -479,7 +479,7 @@ sub databaseLevel {
$this->{databaseLevel} = $databaseLevel;
}
}
return( $this->{databaseLevel} );
return $this->{databaseLevel};
}
sub fileLevel {
@ -487,13 +487,12 @@ sub fileLevel {
my $fileLevel = shift;
if ( defined($fileLevel) ) {
$fileLevel = $this->limit($fileLevel);
if ( $this->{fileLevel} != $fileLevel ) {
$this->closeFile() if ( $this->{fileLevel} > NOLOG );
$this->{fileLevel} = $fileLevel;
$this->openFile() if ( $this->{fileLevel} > NOLOG );
}
# The filename might have changed, so always close and re-open
$this->closeFile() if ( $this->{fileLevel} > NOLOG );
$this->{fileLevel} = $fileLevel;
$this->openFile() if ( $this->{fileLevel} > NOLOG );
}
return( $this->{fileLevel} );
return $this->{fileLevel};
}
sub syslogLevel {
@ -512,7 +511,7 @@ sub syslogLevel {
sub openSyslog {
my $this = shift;
openlog( $this->{id}, 'pid', "local1" );
openlog( $this->{id}, 'pid', 'local1' );
}
sub closeSyslog {
@ -532,27 +531,25 @@ sub logFile {
sub openFile {
my $this = shift;
if ( open( $LOGFILE, ">>", $this->{logFile} ) ) {
$LOGFILE->autoflush() if ( $this->{autoFlush} );
if ( open($LOGFILE, '>>', $this->{logFile}) ) {
$LOGFILE->autoflush() if $this->{autoFlush};
my $webUid = (getpwnam( $Config{ZM_WEB_USER} ))[2];
my $webGid = (getgrnam( $Config{ZM_WEB_GROUP} ))[2];
my $webUid = (getpwnam($Config{ZM_WEB_USER}))[2];
my $webGid = (getgrnam($Config{ZM_WEB_GROUP}))[2];
if ( $> == 0 ) {
chown( $webUid, $webGid, $this->{logFile} )
or Fatal( "Can't change permissions on log file '"
.$this->{logFile}."': $!"
)
or Fatal("Can't change permissions on log file $$this{logFile}: $!");
}
} else {
$this->fileLevel( NOLOG );
$this->termLevel( INFO );
Error( "Can't open log file '".$this->{logFile}."': $!" );
$this->fileLevel(NOLOG);
$this->termLevel(INFO);
Error("Can't open log file $$this{logFile}: $!");
}
}
sub closeFile {
my $this = shift;
close( $LOGFILE ) if ( fileno($LOGFILE) );
#my $this = shift;
close($LOGFILE) if fileno($LOGFILE);
}
sub logPrint {
@ -568,7 +565,7 @@ sub logPrint {
my ($seconds, $microseconds) = gettimeofday();
my $message = sprintf(
'%s.%06d %s[%d].%s [%s]'
, strftime( '%x %H:%M:%S' ,localtime( $seconds ) )
, strftime('%x %H:%M:%S', localtime($seconds))
, $microseconds
, $this->{id}
, $$
@ -576,42 +573,43 @@ sub logPrint {
, $string
);
if ( $this->{trace} ) {
$message = Carp::shortmess( $message );
$message = Carp::shortmess($message);
} else {
$message = $message."\n";
}
if ( $level <= $this->{syslogLevel} ) {
syslog( $priorities{$level}, $code." [%s]", $string );
syslog($priorities{$level}, $code.' [%s]', $string);
}
print( $LOGFILE $message ) if ( $level <= $this->{fileLevel} );
print($LOGFILE $message) if $level <= $this->{fileLevel};
if ( $level <= $this->{databaseLevel} ) {
my $sql = 'insert into Logs ( TimeKey, Component, Pid, Level, Code, Message, File, Line ) values ( ?, ?, ?, ?, ?, ?, ?, NULL )';
$this->{sth} = $this->{dbh}->prepare_cached( $sql );
my $sql = 'INSERT INTO Logs ( TimeKey, Component, Pid, Level, Code, Message, File, Line ) VALUES ( ?, ?, ?, ?, ?, ?, ?, NULL )';
$this->{sth} = $this->{dbh}->prepare_cached($sql);
if ( !$this->{sth} ) {
$this->{databaseLevel} = NOLOG;
Fatal( "Can't prepare log entry '$sql': ".$this->{dbh}->errstr() );
Error("Can't prepare log entry '$sql': ".$this->{dbh}->errstr());
} else {
my $res = $this->{sth}->execute($seconds+($microseconds/1000000.0)
, $this->{id}
, $$
, $level
, $code
, $string
, $this->{fileName}
);
if ( !$res ) {
$this->{databaseLevel} = NOLOG;
Error("Can't execute log entry '$sql': ".$this->{sth}->errstr());
}
}
my $res = $this->{sth}->execute( $seconds+($microseconds/1000000.0)
, $this->{id}
, $$
, $level
, $code
, $string
, $this->{fileName}
);
if ( !$res ) {
$this->{databaseLevel} = NOLOG;
Fatal( "Can't execute log entry '$sql': ".$this->{sth}->errstr() );
}
}
print( STDERR $message ) if ( $level <= $this->{termLevel} );
}
} # end if doing db logging
print(STDERR $message) if $level <= $this->{termLevel};
} # end if level < effectivelevel
}
sub logInit( ;@ ) {
my %options = @_ ? @_ : ();
$logger = ZoneMinder::Logger->new() if !$logger;
$logger->initialise( %options );
$logger->initialise(%options);
}
sub logReinit {
@ -619,14 +617,14 @@ sub logReinit {
}
sub logTerm {
return unless ( $logger );
return unless $logger;
$logger->terminate();
$logger = undef;
}
sub logHupHandler {
my $savedErrno = $!;
return unless( $logger );
return unless $logger;
fetch()->reinitialise();
logSetSignal();
$! = $savedErrno;
@ -641,88 +639,87 @@ sub logClearSignal {
}
sub logLevel {
return( fetch()->level( @_ ) );
return fetch()->level(@_);
}
sub logDebugging {
return( fetch()->debugOn() );
return fetch()->debugOn();
}
sub logTermLevel {
return( fetch()->termLevel( @_ ) );
return fetch()->termLevel(@_);
}
sub logDatabaseLevel {
return( fetch()->databaseLevel( @_ ) );
return fetch()->databaseLevel(@_);
}
sub logFileLevel {
return( fetch()->fileLevel( @_ ) );
return fetch()->fileLevel(@_);
}
sub logSyslogLevel {
return( fetch()->syslogLevel( @_ ) );
return fetch()->syslogLevel(@_);
}
sub Mark {
my $level = shift;
$level = DEBUG unless( defined($level) );
$level = DEBUG unless defined($level);
my $tag = 'Mark';
fetch()->logPrint( $level, $tag );
fetch()->logPrint($level, $tag);
}
sub Dump {
my $var = shift;
my $label = shift;
$label = 'VAR' unless( defined($label) );
fetch()->logPrint( DEBUG, Data::Dumper->Dump( [ $var ], [ $label ] ) );
$label = 'VAR' unless defined($label);
fetch()->logPrint(DEBUG, Data::Dumper->Dump([ $var ], [ $label ]));
}
sub debug {
my $log = shift;
$log->logPrint( DEBUG, @_ );
$log->logPrint(DEBUG, @_);
}
sub Debug( @ ) {
fetch()->logPrint( DEBUG, @_ );
fetch()->logPrint(DEBUG, @_);
}
sub Info( @ ) {
fetch()->logPrint( INFO, @_ );
fetch()->logPrint(INFO, @_);
}
sub info {
my $log = shift;
$log->logPrint( INFO, @_ );
$log->logPrint(INFO, @_);
}
sub Warning( @ ) {
fetch()->logPrint( WARNING, @_ );
fetch()->logPrint(WARNING, @_);
}
sub warn {
my $log = shift;
$log->logPrint( WARNING, @_ );
$log->logPrint(WARNING, @_);
}
sub Error( @ ) {
fetch()->logPrint( ERROR, @_ );
fetch()->logPrint(ERROR, @_);
}
sub error {
my $log = shift;
$log->logPrint( ERROR, @_ );
$log->logPrint(ERROR, @_);
}
sub Fatal( @ ) {
fetch()->logPrint( FATAL, @_ );
if ( $SIG{TERM} ne 'DEFAULT' ) {
fetch()->logPrint(FATAL, @_);
if ( $SIG{TERM} and ( $SIG{TERM} ne 'DEFAULT' ) ) {
$SIG{TERM}();
}
exit( -1 );
exit(-1);
}
sub Panic( @ ) {
fetch()->logPrint( PANIC, @_ );
confess( $_[0] );
fetch()->logPrint(PANIC, @_);
confess($_[0]);
}
1;
@ -741,10 +738,10 @@ logInit( 'myproc', DEBUG );
Debug( 'This is what is happening' );
Info( 'Something interesting is happening' );
Warning( "Something might be going wrong." );
Error( "Something has gone wrong!!" );
Fatal( "Something has gone badly wrong, gotta stop!!" );
Panic( "Something fundamental has gone wrong, die with stack trace );
Warning( 'Something might be going wrong.' );
Error( 'Something has gone wrong!!' );
Fatal( 'Something has gone badly wrong, gotta stop!!' );
Panic( 'Something fundamental has gone wrong, die with stack trace' );
=head1 DESCRIPTION

View File

@ -236,8 +236,8 @@ use Sys::MemInfo qw(totalmem freemem totalswap freeswap);
use Sys::CpuLoad;
#use Data::Dumper;
# We count 100 of these, so total timeout is this value *100.
use constant KILL_DELAY => 100*1000; # 1/10th of a second
# We count 10 of these, so total timeout is this value *10.
use constant KILL_DELAY => 1; # seconds
our %cmd_hash;
our %pid_hash;
@ -289,9 +289,8 @@ sub run {
if ( $Config{ZM_SERVER_ID} ) {
require ZoneMinder::Server;
dPrint( ZoneMinder::Logger::INFO, 'Loading Server record' );
$Server = new ZoneMinder::Server( $Config{ZM_SERVER_ID} );
dPrint( ZoneMinder::Logger::INFO, 'Loading Server record have ' . $$Server{Name} );
dPrint( ZoneMinder::Logger::INFO, 'Loading Server record have ' . $$Server{Name} );
}
while( 1 ) {
@ -300,7 +299,7 @@ sub run {
if ( ! ( $secs_count % 60 ) ) {
$dbh = zmDbConnect() if ! $dbh->ping();
my @cpuload = Sys::CpuLoad::load();
dPrint( ZoneMinder::Logger::INFO, 'Updating Server record' );
dPrint( ZoneMinder::Logger::DEBUG, 'Updating Server record' );
if ( ! defined $dbh->do(q{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());
@ -385,6 +384,7 @@ sub cPrint {
}
}
# I think the purpose of this is to echo the logs to the client process so it can then display them.
sub dPrint {
my $logLevel = shift;
if ( fileno(CLIENT) ) {
@ -523,7 +523,7 @@ sub kill_until_dead {
my $blockset = POSIX::SigSet->new(SIGCHLD);
sigprocmask(SIG_BLOCK, $blockset, $sigset ) or die "dying at block...\n";
while( $process and $$process{pid} and kill( 0, $$process{pid} ) ) {
if ( $count++ > 100 ) {
if ( $count++ > 10 ) {
dPrint( ZoneMinder::Logger::WARNING, "'$$process{command}' has not stopped at "
.strftime( '%y/%m/%d %H:%M:%S', localtime() )
.". Sending KILL to pid $$process{pid}\n"
@ -532,8 +532,9 @@ sub kill_until_dead {
last;
}
# THe purpose of the signal blocking is to simplify the concurrency
sigprocmask(SIG_UNBLOCK, $blockset) or die "dying at unblock...\n";
usleep( KILL_DELAY );
sleep( KILL_DELAY );
sigprocmask(SIG_BLOCK, $blockset, $sigset ) or die "dying at block...\n";
}
sigprocmask(SIG_UNBLOCK, $blockset) or die "dying at unblock...\n";

View File

@ -83,10 +83,10 @@ while( 1 ) {
$dbh = zmDbConnect();
}
$dbh->do('DELETE FROM Events_Hour WHERE StartTime < DATE_SUB(NOW(), INTERVAL 1 hour)');
$dbh->do('DELETE FROM Events_Day WHERE StartTime < DATE_SUB(NOW(), INTERVAL 1 day)');
$dbh->do('DELETE FROM Events_Week WHERE StartTime < DATE_SUB(NOW(), INTERVAL 1 week)');
$dbh->do('DELETE FROM Events_Month WHERE StartTime < DATE_SUB(NOW(), INTERVAL 1 month)');
$dbh->do('DELETE FROM Events_Hour WHERE StartTime < DATE_SUB(NOW(), INTERVAL 1 hour)') or Error($dbh->errstr());
$dbh->do('DELETE FROM Events_Day WHERE StartTime < DATE_SUB(NOW(), INTERVAL 1 day)') or Error($dbh->errstr());
$dbh->do('DELETE FROM Events_Week WHERE StartTime < DATE_SUB(NOW(), INTERVAL 1 week)') or Error($dbh->errstr());
$dbh->do('DELETE FROM Events_Month WHERE StartTime < DATE_SUB(NOW(), INTERVAL 1 month)') or Error($dbh->errstr());
sleep( $Config{ZM_STATS_UPDATE_INTERVAL} );
} # end while (1)

View File

@ -151,8 +151,7 @@ int FfmpegCamera::Capture( ZMPacket &zm_packet ) {
(ret == -110)
) {
Info( "av_read_frame returned \"%s\". Reopening stream.", av_make_error_string(ret).c_str() );
ReopenFfmpeg();
return 0;
return ReopenFfmpeg();
}
Error( "Unable to read packet from stream %d: error %d \"%s\".", packet.stream_index, ret, av_make_error_string(ret).c_str() );
return -1;

View File

@ -67,7 +67,7 @@ void Logger::usrHandler( int sig ) {
Logger::Logger() :
mLevel( INFO ),
mTermLevel( NOLOG ),
mTerminalLevel( NOLOG ),
mDatabaseLevel( NOLOG ),
mFileLevel( NOLOG ),
mSyslogLevel( NOLOG ),
@ -76,7 +76,7 @@ Logger::Logger() :
//mLogFile( mLogPath+"/"+mId+".log" ),
mDbConnected( false ),
mLogFileFP( NULL ),
mHasTerm( false ),
mHasTerminal( false ),
mFlush( false ) {
if ( smInstance ) {
@ -108,7 +108,7 @@ Logger::Logger() :
}
if ( fileno(stderr) && isatty(fileno(stderr)) )
mHasTerm = true;
mHasTerminal = true;
}
Logger::~Logger() {
@ -145,13 +145,13 @@ void Logger::initialise( const std::string &id, const Options &options ) {
}
Level tempLevel = INFO;
Level tempTermLevel = mTermLevel;
Level tempTerminalLevel = mTerminalLevel;
Level tempDatabaseLevel = mDatabaseLevel;
Level tempFileLevel = mFileLevel;
Level tempSyslogLevel = mSyslogLevel;
if ( options.mTermLevel != NOOPT )
tempTermLevel = options.mTermLevel;
if ( options.mTerminalLevel != NOOPT )
tempTerminalLevel = options.mTerminalLevel;
if ( options.mDatabaseLevel != NOOPT )
tempDatabaseLevel = options.mDatabaseLevel;
@ -170,13 +170,13 @@ void Logger::initialise( const std::string &id, const Options &options ) {
// Legacy
if ( (envPtr = getenv( "LOG_PRINT" )) )
tempTermLevel = atoi(envPtr) ? DEBUG9 : NOLOG;
tempTerminalLevel = atoi(envPtr) ? DEBUG9 : NOLOG;
if ( (envPtr = getTargettedEnv( "LOG_LEVEL" )) )
tempLevel = atoi(envPtr);
if ( (envPtr = getTargettedEnv( "LOG_LEVEL_TERM" )) )
tempTermLevel = atoi(envPtr);
tempTerminalLevel = atoi(envPtr);
if ( (envPtr = getTargettedEnv( "LOG_LEVEL_DATABASE" )) )
tempDatabaseLevel = atoi(envPtr);
if ( (envPtr = getTargettedEnv( "LOG_LEVEL_FILE" )) )
@ -202,7 +202,7 @@ void Logger::initialise( const std::string &id, const Options &options ) {
// if we don't have debug turned on, then the max effective log level is INFO
if ( tempSyslogLevel > INFO ) tempSyslogLevel = INFO;
if ( tempFileLevel > INFO ) tempFileLevel = INFO;
if ( tempTermLevel > INFO ) tempTermLevel = INFO;
if ( tempTerminalLevel > INFO ) tempTerminalLevel = INFO;
if ( tempDatabaseLevel > INFO ) tempDatabaseLevel = INFO;
if ( tempLevel > INFO ) tempLevel = INFO;
} // end if config.log_debug
@ -210,7 +210,7 @@ void Logger::initialise( const std::string &id, const Options &options ) {
logFile( tempLogFile );
termLevel( tempTermLevel );
terminalLevel( tempTerminalLevel );
databaseLevel( tempDatabaseLevel );
fileLevel( tempFileLevel );
syslogLevel( tempSyslogLevel );
@ -244,7 +244,7 @@ void Logger::initialise( const std::string &id, const Options &options ) {
Debug( 1, "LogOpts: level=%s/%s, screen=%s, database=%s, logfile=%s->%s, syslog=%s",
smCodes[mLevel].c_str(),
smCodes[mEffectiveLevel].c_str(),
smCodes[mTermLevel].c_str(),
smCodes[mTerminalLevel].c_str(),
smCodes[mDatabaseLevel].c_str(),
smCodes[mFileLevel].c_str(),
mLogFile.c_str(),
@ -323,8 +323,8 @@ Logger::Level Logger::level( Logger::Level level ) {
mLevel = level;
mEffectiveLevel = NOLOG;
if ( mTermLevel > mEffectiveLevel )
mEffectiveLevel = mTermLevel;
if ( mTerminalLevel > mEffectiveLevel )
mEffectiveLevel = mTerminalLevel;
if ( mDatabaseLevel > mEffectiveLevel )
mEffectiveLevel = mDatabaseLevel;
if ( mFileLevel > mEffectiveLevel )
@ -337,15 +337,15 @@ Logger::Level Logger::level( Logger::Level level ) {
return( mLevel );
}
Logger::Level Logger::termLevel( Logger::Level termLevel ) {
if ( termLevel > NOOPT ) {
if ( !mHasTerm )
termLevel = NOLOG;
termLevel = limit(termLevel);
if ( mTermLevel != termLevel )
mTermLevel = termLevel;
Logger::Level Logger::terminalLevel( Logger::Level terminalLevel ) {
if ( terminalLevel > NOOPT ) {
if ( !mHasTerminal )
terminalLevel = NOLOG;
terminalLevel = limit(terminalLevel);
if ( mTerminalLevel != terminalLevel )
mTerminalLevel = terminalLevel;
}
return( mTermLevel );
return( mTerminalLevel );
}
Logger::Level Logger::databaseLevel( Logger::Level databaseLevel ) {
@ -517,7 +517,7 @@ void Logger::logPrint( bool hex, const char * const filepath, const int line, co
char *syslogEnd = logPtr;
strncpy( logPtr, "]\n", sizeof(logString)-(logPtr-logString) );
if ( level <= mTermLevel ) {
if ( level <= mTerminalLevel ) {
puts( logString );
fflush( stdout );
}

View File

@ -58,7 +58,7 @@ public:
class Options {
public:
int mTermLevel;
int mTerminalLevel;
int mDatabaseLevel;
int mFileLevel;
int mSyslogLevel;
@ -67,8 +67,8 @@ public:
std::string mLogFile;
public:
Options( Level termLevel=NOOPT, Level databaseLevel=NOOPT, Level fileLevel=NOOPT, Level syslogLevel=NOOPT, const std::string &logPath=".", const std::string &logFile="" ) :
mTermLevel( termLevel ),
Options( Level terminalLevel=NOOPT, Level databaseLevel=NOOPT, Level fileLevel=NOOPT, Level syslogLevel=NOOPT, const std::string &logPath=".", const std::string &logFile="" ) :
mTerminalLevel( terminalLevel ),
mDatabaseLevel( databaseLevel ),
mFileLevel( fileLevel ),
mSyslogLevel( syslogLevel ),
@ -93,7 +93,7 @@ private:
std::string mIdArgs;
Level mLevel; // Level that is currently in operation
Level mTermLevel; // Maximum level output via terminal
Level mTerminalLevel; // Maximum level output via terminal
Level mDatabaseLevel; // Maximum level output via database
Level mFileLevel; // Maximum level output via file
Level mSyslogLevel; // Maximum level output via syslog
@ -104,7 +104,7 @@ private:
std::string mLogFile;
FILE *mLogFileFP;
bool mHasTerm;
bool mHasTerminal;
bool mFlush;
private:
@ -114,10 +114,8 @@ public:
friend void logInit( const char *name, const Options &options );
friend void logTerm();
static Logger *fetch()
{
if ( !smInstance )
{
static Logger *fetch() {
if ( !smInstance ) {
smInstance = new Logger();
Options options;
smInstance->initialise( "undef", options );
@ -134,8 +132,7 @@ public:
void terminate();
private:
int limit( int level )
{
int limit( int level ) {
if ( level > DEBUG9 )
return( DEBUG9 );
if ( level < NOLOG )
@ -151,15 +148,13 @@ private:
void loadEnv();
public:
const std::string &id() const
{
const std::string &id() const {
return( mId );
}
const std::string &id( const std::string &id );
Level level() const
{
Level level() const {
return( mLevel );
}
Level level( Level=NOOPT );
@ -168,7 +163,7 @@ public:
return( mEffectiveLevel >= DEBUG1 );
}
Level termLevel( Level=NOOPT );
Level terminalLevel( Level=NOOPT );
Level databaseLevel( Level=NOOPT );
Level fileLevel( Level=NOOPT );
Level syslogLevel( Level=NOOPT );

View File

@ -1 +1 @@
1.31.38
1.31.39

View File

@ -211,15 +211,18 @@ class Event {
}
function createListThumbnail( $overwrite=false ) {
if ( (!$this->SaveJPEGs()) and file_exists($this->Path().'/snapshot.jpg') ) {
# The idea here is that we don't really want to use the analysis jpeg as the thumbnail.
# The snapshot image will be generated during capturing
if ( file_exists($this->Path().'/snapshot.jpg') ) {
Logger::Debug("snapshot exists");
$frame = null;
} else {
# Load the frame with the highest score to use as a thumbnail
if ( !($frame = dbFetchOne( 'SELECT * FROM Frames WHERE EventId=? AND Score=? ORDER BY FrameId LIMIT 1', NULL, array( $this->{'Id'}, $this->{'MaxScore'} ) )) ) {
Error("Unable to find a Frame matching max score " . $this->{'MaxScore'} . ' for event ' . $this->{'Id'} );
// FIXME: What if somehow the db frame was lost or score was changed? Should probably try another search for any frame.
return( false );
}
# Load the frame with the highest score to use as a thumbnail
if ( !($frame = dbFetchOne( 'SELECT * FROM Frames WHERE EventId=? AND Score=? ORDER BY FrameId LIMIT 1', NULL, array( $this->{'Id'}, $this->{'MaxScore'} ) )) ) {
Error("Unable to find a Frame matching max score " . $this->{'MaxScore'} . ' for event ' . $this->{'Id'} );
// FIXME: What if somehow the db frame was lost or score was changed? Should probably try another search for any frame.
return false;
}
}
if ( ZM_WEB_LIST_THUMB_WIDTH ) {
@ -234,34 +237,20 @@ class Event {
Fatal( "No thumbnail width or height specified, please check in Options->Web" );
}
$eventPath = $this->Path();
if ( file_exists( $eventPath.'/snapshot.jpg' ) ) {
$frame = 'snapshot';
$thumbData = array('Path'=>$eventPath.'/snapshot.jpg');
} else {
# Load the frame with the highest score to use as a thumbnail
if ( !($frame = dbFetchOne( 'SELECT * FROM Frames WHERE EventId=? AND Score=? ORDER BY FrameId LIMIT 1', NULL, array( $this->{'Id'}, $this->{'MaxScore'} ) )) ) {
Error("Unable to find a Frame matching max score " . $this->{'MaxScore'} . ' for event ' . $this->{'Id'} );
// FIXME: What if somehow the db frame was lost or score was changed? Should probably try another search for any frame.
return( false );
}
$imageData = $this->getImageSrc( $frame, $scale, false, $overwrite );
if ( ! $imageData ) {
return ( false );
}
$thumbData = $frame;
$thumbData['Path'] = $imageData['thumbPath'];
$imageData = $this->getImageSrc($frame, $scale, false, $overwrite);
if ( ! $imageData ) {
return false;
}
$thumbData['Width'] = (int)$thumbWidth;
$thumbData['Height'] = (int)$thumbHeight;
$thumbData['url'] = '?view=image&amp;eid='.$this->Id().'&amp;fid='.$imageData['FrameId'].'&amp;width='.$thumbData['Width'].'&amp;height='.$thumbData['Height'];
return( $thumbData );
return $thumbData;
} // end function createListThumbnail
// frame is an array representing the db row for a frame.
function getImageSrc( $frame, $scale=SCALE_BASE, $captureOnly=false, $overwrite=false ) {
$Storage = new Storage( isset($this->{'StorageId'}) ? $this->{'StorageId'} : NULL );
function getImageSrc($frame, $scale=SCALE_BASE, $captureOnly=false, $overwrite=false) {
$Storage = new Storage(isset($this->{'StorageId'}) ? $this->{'StorageId'} : NULL);
$Event = $this;
$eventPath = $Event->Path();
@ -271,10 +260,11 @@ class Event {
$frame = array( 'FrameId'=>$frame, 'Type'=>'' );
}
if ( ( ! $frame ) and file_exists( $eventPath.'/snapshot.jpg' ) ) {
if ( ( ! $frame ) and file_exists($eventPath.'/snapshot.jpg') ) {
# No frame specified, so look for a snapshot to use
$captImage = 'snapshot.jpg';
Logger::Debug("Frame not specified, using snapshot");
$frame = array('FrameId'=>'snapshot', 'Type'=>'');
} else {
$captImage = sprintf( '%0'.ZM_EVENT_IMAGE_DIGITS.'d-analyze.jpg', $frame['FrameId'] );
if ( ! file_exists( $eventPath.'/'.$captImage ) ) {
@ -371,9 +361,10 @@ class Event {
'imageClass' => $alarmFrame?'alarm':'normal',
'isAnalImage' => $isAnalImage,
'hasAnalImage' => $hasAnalImage,
'FrameId' => $frame['FrameId'],
);
return( $imageData );
return $imageData;
}
public static function find_all( $parameters = null, $options = null ) {

View File

@ -195,6 +195,7 @@ if ( canView( 'Events' ) ) {
$_REQUEST['Id'] = dbInsertId();
}
if ( $action == 'execute' ) {
session_write_close();
executeFilter( $tempFilterName );
}

View File

@ -200,16 +200,11 @@ while ( $event_row = dbFetchNext( $results ) ) {
}
if ( ZM_WEB_LIST_THUMBS ) {
if ( $thumbData = $event->createListThumbnail() ) {
#Logger::Debug(print_r($thumbData,true));
?>
<td class="colThumbnail">
<?php
if ( ( $event->SaveJPEGs() == 0 ) and file_exists($event->Path().'/snapshot.jpg') ) {
Logger::Debug("Using snapshot" . $event->Path().'/snapshot.jpg' );
$imgSrc = '?view=image&amp;eid='.$event->Id().'&amp;fid=snapshot&amp;width='.$thumbData['Width'].'&amp;height='.$thumbData['Height'];
} else {
Logger::Debug("Not Using snapshot" . $event->Path().'/snapshot.jpg' );
$imgSrc = '?view=image&amp;eid='.$event->Id().'&amp;fid='.$thumbData['FrameId'].'&amp;width='.$thumbData['Width'].'&amp;height='.$thumbData['Height'];
}
$imgSrc = $thumbData['url'];
$streamSrc = $event->getStreamSrc( array( 'mode'=>'jpeg', 'scale'=>$scale, 'maxfps'=>ZM_WEB_VIDEO_MAXFPS, 'replay'=>'single') );
$imgHtml = '<img id="thumbnail'.$event->id().'" src="'.$imgSrc.'" alt="'. validHtmlStr('Event '.$event->Id()) .'" style="width:'. validInt($thumbData['Width']) .'px;height:'. validInt($thumbData['Height']).'px;" onmouseover="this.src=\''.$streamSrc.'\';" onmouseout="this.src=\''.$imgSrc.'\';"/>';