Merge branch 'storageareas' into zma_to_thread

pull/3122/head
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 ; 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 // delimiter //
DROP TRIGGER IF EXISTS Events_Day_delete_trigger// DROP TRIGGER IF EXISTS Events_Day_delete_trigger//
CREATE TRIGGER Events_Day_delete_trigger BEFORE DELETE ON Events_Day 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// DROP TRIGGER IF EXISTS Events_Week_delete_trigger//
CREATE TRIGGER Events_Week_delete_trigger BEFORE DELETE ON Events_Week CREATE TRIGGER Events_Week_delete_trigger BEFORE DELETE ON Events_Week
FOR EACH ROW BEGIN FOR EACH ROW BEGIN
@ -112,20 +88,6 @@ FOR EACH ROW
END; 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// DROP TRIGGER IF EXISTS Events_Month_delete_trigger//
CREATE TRIGGER Events_Month_delete_trigger BEFORE DELETE ON Events_Month CREATE TRIGGER Events_Month_delete_trigger BEFORE DELETE ON Events_Month
FOR EACH ROW BEGIN FOR EACH ROW BEGIN
@ -136,7 +98,6 @@ FOR EACH ROW BEGIN
END; END;
// //
DROP TRIGGER IF EXISTS Events_Month_update_trigger; DROP TRIGGER IF EXISTS Events_Month_update_trigger;
CREATE TRIGGER Events_Month_update_trigger AFTER UPDATE ON Events_Month CREATE TRIGGER Events_Month_update_trigger AFTER UPDATE ON Events_Month
FOR EACH ROW FOR EACH ROW
@ -155,23 +116,7 @@ FOR EACH ROW
END; 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; drop procedure if exists update_storage_stats;
delimiter //
create procedure update_storage_stats(IN StorageId smallint(5), IN space BIGINT) create procedure update_storage_stats(IN StorageId smallint(5), IN space BIGINT)
sql security invoker sql security invoker
@ -227,7 +172,7 @@ BEGIN
WHERE Id=OLD.MonitorId; WHERE Id=OLD.MonitorId;
END IF; END IF;
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; UPDATE Events_Archived SET DiskSpace=NEW.DiskSpace WHERE EventId=NEW.Id;
END IF; 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_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); INSERT INTO Events_Month (EventId,MonitorId,StartTime,DiskSpace) VALUES (NEW.Id,NEW.MonitorId,NEW.StartTime,0);
UPDATE Monitors SET UPDATE Monitors SET
HourEvents = COALESCE(DayEvents,0)+1, HourEvents = COALESCE(HourEvents,0)+1,
DayEvents = COALESCE(DayEvents,0)+1, DayEvents = COALESCE(DayEvents,0)+1,
WeekEvents = COALESCE(DayEvents,0)+1, WeekEvents = COALESCE(WeekEvents,0)+1,
MonthEvents = COALESCE(DayEvents,0)+1, MonthEvents = COALESCE(MonthEvents,0)+1,
TotalEvents = COALESCE(TotalEvents,0)+1 TotalEvents = COALESCE(TotalEvents,0)+1
WHERE Id=NEW.MonitorId; WHERE Id=NEW.MonitorId;
END; END;

View File

@ -756,18 +756,18 @@ CREATE TABLE `Monitors` (
`WebColour` varchar(32) NOT NULL default 'red', `WebColour` varchar(32) NOT NULL default 'red',
`Exif` tinyint(1) unsigned NOT NULL default '0', `Exif` tinyint(1) unsigned NOT NULL default '0',
`Sequence` smallint(5) unsigned default NULL, `Sequence` smallint(5) unsigned default NULL,
`TotalEvents` int(10) unsigned, `TotalEvents` int(10) default NULL,
`TotalEventDiskSpace` bigint unsigned, `TotalEventDiskSpace` bigint default NULL,
`HourEvents` int(10) unsigned, `HourEvents` int(10) default NULL,
`HourEventDiskSpace` bigint unsigned, `HourEventDiskSpace` bigint default NULL,
`DayEvents` int(10) unsigned, `DayEvents` int(10) default NULL,
`DayEventDiskSpace` bigint unsigned, `DayEventDiskSpace` bigint default NULL,
`WeekEvents` int(10) unsigned, `WeekEvents` int(10) default NULL,
`WeekEventDiskSpace` bigint unsigned, `WeekEventDiskSpace` bigint default NULL,
`MonthEvents` int(10) unsigned, `MonthEvents` int(10) default NULL,
`MonthEventDiskSpace` bigint unsigned, `MonthEventDiskSpace` bigint default NULL,
`ArchivedEvents` int(10) unsigned, `ArchivedEvents` int(10) default NULL,
`ArchivedEventDiskSpace` bigint unsigned, `ArchivedEventDiskSpace` bigint default NULL,
`ZoneCount` TINYINT NOT NULL DEFAULT 0, `ZoneCount` TINYINT NOT NULL DEFAULT 0,
PRIMARY KEY (`Id`) PRIMARY KEY (`Id`)
) ENGINE=@ZM_MYSQL_ENGINE@; ) 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"} }' ); 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. -- 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 triggers.sql
=======
source @ZM_PATH_DATA@/db/triggers.sql
>>>>>>> storageareas
-- --
-- Apply the initial configuration -- 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)), 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), 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), 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; WHERE Id=OLD.MonitorId;
END IF; END IF;
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; UPDATE Events_Archived SET DiskSpace=NEW.DiskSpace WHERE EventId=NEW.Id;
END IF; 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_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); INSERT INTO Events_Month (EventId,MonitorId,StartTime,DiskSpace) VALUES (NEW.Id,NEW.MonitorId,NEW.StartTime,0);
UPDATE Monitors SET UPDATE Monitors SET
HourEvents = COALESCE(DayEvents,0)+1, HourEvents = COALESCE(HourEvents,0)+1,
DayEvents = COALESCE(DayEvents,0)+1, DayEvents = COALESCE(DayEvents,0)+1,
WeekEvents = COALESCE(DayEvents,0)+1, WeekEvents = COALESCE(WeekEvents,0)+1,
MonthEvents = COALESCE(DayEvents,0)+1, MonthEvents = COALESCE(MonthEvents,0)+1,
TotalEvents = COALESCE(TotalEvents,0)+1 TotalEvents = COALESCE(TotalEvents,0)+1
WHERE Id=NEW.MonitorId; WHERE Id=NEW.MonitorId;
END; END;
@ -260,3 +260,17 @@ FOR EACH ROW
// //
DELIMITER ; 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 } # end sub delete_files
sub Storage { sub Storage {
if ( @_ > 1 ) {
$_[0]{Storage} = $_[1];
}
if ( ! $_[0]{Storage} ) { if ( ! $_[0]{Storage} ) {
$_[0]{Storage} = new ZoneMinder::Storage( $_[0]{StorageId} ); $_[0]{Storage} = new ZoneMinder::Storage( $_[0]{StorageId} );
} }
@ -487,7 +490,7 @@ sub MoveTo {
return "Event has already been moved by someone else."; return "Event has already been moved by someone else.";
} }
my $OldStorage = $self->Storage(); my $OldStorage = $self->Storage(undef);
my ( $OldPath ) = ( $self->Path() =~ /^(.*)$/ ); # De-taint my ( $OldPath ) = ( $self->Path() =~ /^(.*)$/ ); # De-taint
$$self{Storage} = $NewStorage; $$self{Storage} = $NewStorage;
@ -535,6 +538,7 @@ sub MoveTo {
for my $file (@files) { for my $file (@files) {
next if $file =~ /^\./; next if $file =~ /^\./;
( $file ) = ( $file =~ /^(.*)$/ ); # De-taint ( $file ) = ( $file =~ /^(.*)$/ ); # De-taint
Debug("Moving file $file to $NewPath");
if ( ! File::Copy::copy( $file, $NewPath ) ) { if ( ! File::Copy::copy( $file, $NewPath ) ) {
$error .= "Copy failed: for $file to $NewPath: $!"; $error .= "Copy failed: for $file to $NewPath: $!";
last; last;

View File

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

View File

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

View File

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

View File

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

View File

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

View File

@ -58,7 +58,7 @@ public:
class Options { class Options {
public: public:
int mTermLevel; int mTerminalLevel;
int mDatabaseLevel; int mDatabaseLevel;
int mFileLevel; int mFileLevel;
int mSyslogLevel; int mSyslogLevel;
@ -67,8 +67,8 @@ public:
std::string mLogFile; std::string mLogFile;
public: public:
Options( Level termLevel=NOOPT, Level databaseLevel=NOOPT, Level fileLevel=NOOPT, Level syslogLevel=NOOPT, const std::string &logPath=".", const std::string &logFile="" ) : Options( Level terminalLevel=NOOPT, Level databaseLevel=NOOPT, Level fileLevel=NOOPT, Level syslogLevel=NOOPT, const std::string &logPath=".", const std::string &logFile="" ) :
mTermLevel( termLevel ), mTerminalLevel( terminalLevel ),
mDatabaseLevel( databaseLevel ), mDatabaseLevel( databaseLevel ),
mFileLevel( fileLevel ), mFileLevel( fileLevel ),
mSyslogLevel( syslogLevel ), mSyslogLevel( syslogLevel ),
@ -93,7 +93,7 @@ private:
std::string mIdArgs; std::string mIdArgs;
Level mLevel; // Level that is currently in operation 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 mDatabaseLevel; // Maximum level output via database
Level mFileLevel; // Maximum level output via file Level mFileLevel; // Maximum level output via file
Level mSyslogLevel; // Maximum level output via syslog Level mSyslogLevel; // Maximum level output via syslog
@ -104,7 +104,7 @@ private:
std::string mLogFile; std::string mLogFile;
FILE *mLogFileFP; FILE *mLogFileFP;
bool mHasTerm; bool mHasTerminal;
bool mFlush; bool mFlush;
private: private:
@ -114,10 +114,8 @@ public:
friend void logInit( const char *name, const Options &options ); friend void logInit( const char *name, const Options &options );
friend void logTerm(); friend void logTerm();
static Logger *fetch() static Logger *fetch() {
{ if ( !smInstance ) {
if ( !smInstance )
{
smInstance = new Logger(); smInstance = new Logger();
Options options; Options options;
smInstance->initialise( "undef", options ); smInstance->initialise( "undef", options );
@ -134,8 +132,7 @@ public:
void terminate(); void terminate();
private: private:
int limit( int level ) int limit( int level ) {
{
if ( level > DEBUG9 ) if ( level > DEBUG9 )
return( DEBUG9 ); return( DEBUG9 );
if ( level < NOLOG ) if ( level < NOLOG )
@ -151,15 +148,13 @@ private:
void loadEnv(); void loadEnv();
public: public:
const std::string &id() const const std::string &id() const {
{
return( mId ); return( mId );
} }
const std::string &id( const std::string &id ); const std::string &id( const std::string &id );
Level level() const Level level() const {
{
return( mLevel ); return( mLevel );
} }
Level level( Level=NOOPT ); Level level( Level=NOOPT );
@ -168,7 +163,7 @@ public:
return( mEffectiveLevel >= DEBUG1 ); return( mEffectiveLevel >= DEBUG1 );
} }
Level termLevel( Level=NOOPT ); Level terminalLevel( Level=NOOPT );
Level databaseLevel( Level=NOOPT ); Level databaseLevel( Level=NOOPT );
Level fileLevel( Level=NOOPT ); Level fileLevel( Level=NOOPT );
Level syslogLevel( 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 ) { 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; $frame = null;
} else { } else {
# Load the frame with the highest score to use as a thumbnail # 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'} ) )) ) { 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'} ); 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. // FIXME: What if somehow the db frame was lost or score was changed? Should probably try another search for any frame.
return( false ); return false;
} }
} }
if ( ZM_WEB_LIST_THUMB_WIDTH ) { if ( ZM_WEB_LIST_THUMB_WIDTH ) {
@ -234,34 +237,20 @@ class Event {
Fatal( "No thumbnail width or height specified, please check in Options->Web" ); Fatal( "No thumbnail width or height specified, please check in Options->Web" );
} }
$eventPath = $this->Path(); $imageData = $this->getImageSrc($frame, $scale, false, $overwrite);
if ( file_exists( $eventPath.'/snapshot.jpg' ) ) { if ( ! $imageData ) {
$frame = 'snapshot'; return false;
$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'];
} }
$thumbData['Width'] = (int)$thumbWidth; $thumbData['Width'] = (int)$thumbWidth;
$thumbData['Height'] = (int)$thumbHeight; $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 } // end function createListThumbnail
// frame is an array representing the db row for a frame. // frame is an array representing the db row for a frame.
function getImageSrc( $frame, $scale=SCALE_BASE, $captureOnly=false, $overwrite=false ) { function getImageSrc($frame, $scale=SCALE_BASE, $captureOnly=false, $overwrite=false) {
$Storage = new Storage( isset($this->{'StorageId'}) ? $this->{'StorageId'} : NULL ); $Storage = new Storage(isset($this->{'StorageId'}) ? $this->{'StorageId'} : NULL);
$Event = $this; $Event = $this;
$eventPath = $Event->Path(); $eventPath = $Event->Path();
@ -271,10 +260,11 @@ class Event {
$frame = array( 'FrameId'=>$frame, 'Type'=>'' ); $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 # No frame specified, so look for a snapshot to use
$captImage = 'snapshot.jpg'; $captImage = 'snapshot.jpg';
Logger::Debug("Frame not specified, using snapshot"); Logger::Debug("Frame not specified, using snapshot");
$frame = array('FrameId'=>'snapshot', 'Type'=>'');
} else { } else {
$captImage = sprintf( '%0'.ZM_EVENT_IMAGE_DIGITS.'d-analyze.jpg', $frame['FrameId'] ); $captImage = sprintf( '%0'.ZM_EVENT_IMAGE_DIGITS.'d-analyze.jpg', $frame['FrameId'] );
if ( ! file_exists( $eventPath.'/'.$captImage ) ) { if ( ! file_exists( $eventPath.'/'.$captImage ) ) {
@ -371,9 +361,10 @@ class Event {
'imageClass' => $alarmFrame?'alarm':'normal', 'imageClass' => $alarmFrame?'alarm':'normal',
'isAnalImage' => $isAnalImage, 'isAnalImage' => $isAnalImage,
'hasAnalImage' => $hasAnalImage, 'hasAnalImage' => $hasAnalImage,
'FrameId' => $frame['FrameId'],
); );
return( $imageData ); return $imageData;
} }
public static function find_all( $parameters = null, $options = null ) { public static function find_all( $parameters = null, $options = null ) {

View File

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

View File

@ -200,16 +200,11 @@ while ( $event_row = dbFetchNext( $results ) ) {
} }
if ( ZM_WEB_LIST_THUMBS ) { if ( ZM_WEB_LIST_THUMBS ) {
if ( $thumbData = $event->createListThumbnail() ) { if ( $thumbData = $event->createListThumbnail() ) {
#Logger::Debug(print_r($thumbData,true));
?> ?>
<td class="colThumbnail"> <td class="colThumbnail">
<?php <?php
if ( ( $event->SaveJPEGs() == 0 ) and file_exists($event->Path().'/snapshot.jpg') ) { $imgSrc = $thumbData['url'];
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'];
}
$streamSrc = $event->getStreamSrc( array( 'mode'=>'jpeg', 'scale'=>$scale, 'maxfps'=>ZM_WEB_VIDEO_MAXFPS, 'replay'=>'single') ); $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.'\';"/>'; $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.'\';"/>';