Merge branch 'storageareas' of github.com:connortechnology/ZoneMinder into storageareas

This commit is contained in:
Isaac Connor 2018-02-17 12:25:42 -05:00
commit e634e0addc
9 changed files with 241 additions and 188 deletions

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, @_ );
fetch()->logPrint(FATAL, @_);
if ( $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

@ -620,9 +620,12 @@ FROM Frames WHERE EventId=?';
$res = $selectUnclosedEventsSth->execute()
or Fatal( "Can't execute: ".$selectUnclosedEventsSth->errstr() );
while( my $event = $selectUnclosedEventsSth->fetchrow_hashref() ) {
aud_print( "Found open event '$event->{Id}'" );
aud_print( "Found open event '$event->{Id}' at $$event{StartTime}" );
if ( confirm( 'close', 'closing' ) ) {
$res = $selectFrameDataSth->execute( $event->{Id} ) or Fatal( "Can't execute: ".$selectFrameDataSth->errstr() );
if ( ! ( $res = $selectFrameDataSth->execute($event->{Id}) ) ) {
Error( "Can't execute: $selectFrameDataSql:".$selectFrameDataSth->errstr() );
next;
}
my $frame = $selectFrameDataSth->fetchrow_hashref();
if ( $frame ) {
$res = $updateUnclosedEventsSth->execute(
@ -643,12 +646,13 @@ FROM Frames WHERE EventId=?';
$frame->{MaxScore},
RECOVER_TEXT,
$event->{Id}
) or Fatal( "Can't execute: ".$updateUnclosedEventsSth->errstr() );
) or Error( "Can't execute: ".$updateUnclosedEventsSth->errstr() );
} else {
Error('SHOULD DELETE');
} # end if has frame data
}
} # end while unclosed event
Debug("Done closing open events.");
# Now delete any old image files
if ( my @old_files = grep { -M > $max_image_age } <$image_path/*.{jpg,gif,wbmp}> ) {
@ -709,14 +713,6 @@ FROM Frames WHERE EventId=?';
UPDATE Monitors SET
TotalEvents=(SELECT COUNT(Id) FROM Events WHERE MonitorId=Monitors.Id),
TotalEventDiskSpace=(SELECT SUM(DiskSpace) FROM Events WHERE MonitorId=Monitors.Id AND DiskSpace IS NOT NULL),
HourEvents=(SELECT COUNT(Id) FROM Events WHERE MonitorId=Monitors.Id AND StartTime > DATE_SUB( NOW(), INTERVAL 1 hour) ),
HourEventDiskSpace=(SELECT SUM(DiskSpace) FROM Events WHERE MonitorId=Monitors.Id AND StartTime > DATE_SUB(NOW(), INTERVAL 1 hour) AND DiskSpace IS NOT NULL),
DayEvents=(SELECT COUNT(Id) FROM Events WHERE MonitorId=Monitors.Id AND StartTime > DATE_SUB(NOW(), INTERVAL 1 day)),
DayEventDiskSpace=(SELECT SUM(DiskSpace) FROM Events WHERE MonitorId=Monitors.Id AND StartTime > DATE_SUB(NOW(), INTERVAL 1 day) AND DiskSpace IS NOT NULL),
WeekEvents=(SELECT COUNT(Id) FROM Events WHERE MonitorId=Monitors.Id AND StartTime > DATE_SUB(NOW(), INTERVAL 1 week)),
WeekEventDiskSpace=(SELECT SUM(DiskSpace) FROM Events WHERE MonitorId=Monitors.Id AND StartTime > DATE_SUB(NOW(), INTERVAL 1 week) AND DiskSpace IS NOT NULL),
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)
`;

View File

@ -109,7 +109,6 @@ FfmpegCamera::FfmpegCamera( int p_id, const std::string &p_path, const std::stri
frameCount = 0;
startTime = 0;
mCanCapture = false;
mOpenStart = 0;
videoStore = NULL;
video_last_pts = 0;
have_video_keyframe = false;
@ -161,7 +160,7 @@ void FfmpegCamera::Terminate() {
int FfmpegCamera::PrimeCapture() {
if ( mCanCapture ) {
Info( "Priming capture from %s", mPath.c_str() );
Info( "Priming capture from %s, CLosing", mPath.c_str() );
CloseFfmpeg();
}
mVideoStreamId = -1;
@ -200,12 +199,15 @@ int FfmpegCamera::Capture( Image &image ) {
(avResult == -110)
) {
Info( "av_read_frame returned \"%s\". Reopening stream.", errbuf );
ReopenFfmpeg();
if ( ReopenFfmpeg() < 0 ) {
// OpenFfmpeg will do enough logging.
return -1;
}
continue;
}
Error( "Unable to read packet from stream %d: error %d \"%s\".", packet.stream_index, avResult, errbuf );
return( -1 );
return -1;
}
int keyframe = packet.flags & AV_PKT_FLAG_KEY;
@ -321,7 +323,6 @@ int FfmpegCamera::OpenFfmpeg() {
int ret;
mOpenStart = time(NULL);
have_video_keyframe = false;
// Open the input, not necessarily a file
@ -364,12 +365,21 @@ int FfmpegCamera::OpenFfmpeg() {
#endif
{
Error("Unable to open input %s due to: %s", mPath.c_str(), strerror(errno));
#if !LIBAVFORMAT_VERSION_CHECK(53, 17, 0, 25, 0)
av_close_input_file( mFormatContext );
#else
avformat_close_input( &mFormatContext );
#endif
mFormatContext = NULL;
av_dict_free(&opts);
return -1;
}
AVDictionaryEntry *e=NULL;
while ( (e = av_dict_get(opts, "", e, AV_DICT_IGNORE_SUFFIX)) != NULL ) {
Warning( "Option %s not recognized by ffmpeg", e->key);
}
av_dict_free(&opts);
Debug(1, "Opened input");
@ -517,6 +527,7 @@ int FfmpegCamera::OpenFfmpeg() {
Warning( "Option %s not recognized by ffmpeg", e->key);
}
Error( "Unable to open codec for video stream from %s", mPath.c_str() );
av_dict_free(&opts);
return -1;
} else {
@ -524,6 +535,7 @@ int FfmpegCamera::OpenFfmpeg() {
if ( (e = av_dict_get(opts, "", e, AV_DICT_IGNORE_SUFFIX)) != NULL ) {
Warning( "Option %s not recognized by ffmpeg", e->key);
}
av_dict_free(&opts);
}
}
@ -698,12 +710,16 @@ int FfmpegCamera::CaptureAndRecord( Image &image, timeval recording, char* event
// Check for Connection failure.
(ret == -110)
) {
Info( "av_read_frame returned \"%s\". Reopening stream.", errbuf);
ReopenFfmpeg();
Info( "av_read_frame returned \"%s\". Reopening stream.", errbuf);
if ( ReopenFfmpeg() < 0 ) {
// OpenFfmpeg will do enough logging.
return -1;
}
continue;
}
Error( "Unable to read packet from stream %d: error %d \"%s\".", packet.stream_index, ret, errbuf );
return( -1 );
return -1;
}
int keyframe = packet.flags & AV_PKT_FLAG_KEY;

View File

@ -128,7 +128,7 @@ void Logger::initialise( const std::string &id, const Options &options ) {
char *envPtr;
if ( !id.empty() )
this->id( id );
this->id(id);
std::string tempLogFile;
@ -151,14 +151,17 @@ void Logger::initialise( const std::string &id, const Options &options ) {
if ( options.mTerminalLevel != NOOPT )
tempTerminalLevel = options.mTerminalLevel;
if ( options.mDatabaseLevel != NOOPT )
tempDatabaseLevel = options.mDatabaseLevel;
else
tempDatabaseLevel = config.log_level_database >= DEBUG1 ? DEBUG9 : config.log_level_database;
if ( options.mFileLevel != NOOPT )
tempFileLevel = options.mFileLevel;
else
tempFileLevel = config.log_level_file >= DEBUG1 ? DEBUG9 : config.log_level_file;
if ( options.mSyslogLevel != NOOPT )
tempSyslogLevel = options.mSyslogLevel;
else
@ -363,13 +366,12 @@ Logger::Level Logger::databaseLevel( Logger::Level databaseLevel ) {
Logger::Level Logger::fileLevel( Logger::Level fileLevel ) {
if ( fileLevel > NOOPT ) {
fileLevel = limit(fileLevel);
if ( mFileLevel != fileLevel ) {
if ( mFileLevel > NOLOG )
closeFile();
mFileLevel = fileLevel;
if ( mFileLevel > NOLOG )
openFile();
}
// Always close, because we may have changed file names
if ( mFileLevel > NOLOG )
closeFile();
mFileLevel = fileLevel;
if ( mFileLevel > NOLOG )
openFile();
}
return( mFileLevel );
}
@ -402,9 +404,13 @@ void Logger::logFile( const std::string &logFile ) {
}
void Logger::openFile() {
if ( mLogFile.size() && (mLogFileFP = fopen( mLogFile.c_str() ,"a" )) == (FILE *)NULL ) {
if ( mLogFile.size() ) {
if ( (mLogFileFP = fopen(mLogFile.c_str() ,"a")) == (FILE *)NULL ) {
mFileLevel = NOLOG;
Fatal( "fopen() for %s, error = %s", mLogFile.c_str(), strerror(errno) );
}
} else {
puts("Called Logger::openFile() without a filename");
}
}
@ -524,6 +530,8 @@ void Logger::logPrint( bool hex, const char * const filepath, const int line, co
} else {
puts("Logging to file, but file not open\n");
}
} else {
puts("Not logging to file because level <= mFileLevel");
}
*syslogEnd = '\0';
if ( level <= mDatabaseLevel ) {

View File

@ -1,7 +1,12 @@
<?php
if ($_REQUEST['entity'] == 'navBar') {
ajaxResponse(getNavBarHtml('reload'));
return;
$data = array();
if ( ZM_OPT_USE_AUTH && ZM_AUTH_RELAY == 'hashed' ) {
$data['auth'] = generateAuthHash( ZM_AUTH_HASH_IPS );
}
$data['message'] = getNavBarHtml('reload');
ajaxResponse($data);
return;
}
$statusData = array(

View File

@ -151,7 +151,9 @@ function generateAuthHash( $useRemoteAddr ) {
if ( ZM_OPT_USE_AUTH and ZM_AUTH_RELAY == 'hashed' and isset($_SESSION['username']) and $_SESSION['passwordHash'] ) {
# regenerate a hash at half the liftetime of a hash, an hour is 3600 so half is 1800
$time = time();
if ( ( ! isset($_SESSION['AuthHash']) ) or ( $_SESSION['AuthHashGeneratedAt'] < ( $time - ( ZM_AUTH_HASH_TTL * 1800 ) ) ) ) {
$mintime = $time - ( ZM_AUTH_HASH_TTL * 1800 );
if ( ( !isset($_SESSION['AuthHash']) ) or ( $_SESSION['AuthHashGeneratedAt'] < $mintime ) ) {
# Don't both regenerating Auth Hash if an hour hasn't gone by yet
$local_time = localtime();
$authKey = '';
@ -160,6 +162,7 @@ function generateAuthHash( $useRemoteAddr ) {
} else {
$authKey = ZM_AUTH_HASH_SECRET.$_SESSION['username'].$_SESSION['passwordHash'].$local_time[2].$local_time[3].$local_time[4].$local_time[5];
}
#Logger::Debug("Generated using hour:".$local_time[2] . ' mday:' . $local_time[3] . ' month:'.$local_time[4] . ' year: ' . $local_time[5] );
$auth = md5( $authKey );
if ( session_status() == PHP_SESSION_NONE ) {
$backTrace = debug_backtrace();
@ -171,7 +174,7 @@ function generateAuthHash( $useRemoteAddr ) {
$_SESSION['AuthHashGeneratedAt'] = $time;
#Logger::Debug("Generated new auth $auth at " . $_SESSION['AuthHashGeneratedAt']. " using $authKey" );
#} else {
#Logger::Debug( "Using cached auth " . $_SESSION['AuthHash'] ." beacuse " . $_SESSION['AuthHashGeneratedAt'] . ' < '. $time . ' - ' . ZM_AUTH_HASH_TTL . ' * 1800 = '.( $time - (ZM_AUTH_HASH_TTL * 1800) ));
#Logger::Debug("Using cached auth " . $_SESSION['AuthHash'] ." beacuse generatedat:" . $_SESSION['AuthHashGeneratedAt'] . ' < now:'. $time . ' - ' . ZM_AUTH_HASH_TTL . ' * 1800 = '. $mintime);
} # end if AuthHash is not cached
return $_SESSION['AuthHash'];
} else {

View File

@ -182,18 +182,27 @@ function refreshParentWindow() {
}
}
if (currentView !='none') {
if ( currentView != 'none' ) {
$j.ajaxSetup ({timeout: AJAX_TIMEOUT }); //sets timeout for all getJSON.
$j(document).ready(function() {
if ($j('.navbar').length) setInterval(getNavBar, navBarRefresh)
if ($j('.navbar').length) {
setInterval(getNavBar, navBarRefresh);
}
});
function getNavBar () {
function getNavBar() {
$j.getJSON(thisUrl + '?view=request&request=status&entity=navBar', setNavBar);
}
function setNavBar (data) {
function setNavBar(data) {
console.log(data);
if ( data.auth ) {
if ( data.auth != auth_hash ) {
// Update authentication token.
auth_hash = data.auth;
}
}
$j('#reload').replaceWith(data.message);
}
}

View File

@ -45,10 +45,14 @@ function evaluateLoadTimes() {
} // end evaluateLoadTimes()
// time is seconds since epoch
function SetImageSource( monId, time ) {
function getImageSource( monId, time ) {
if ( liveMode == 1 ) {
return monitorImageObject[monId].src.replace(/rand=\d+/i, 'rand='+Math.floor((Math.random() * 1000000) ));
var new_url = monitorImageObject[monId].src.replace(/rand=\d+/i, 'rand='+Math.floor((Math.random() * 1000000) ));
if ( auth_hash ) {
// update auth hash
new_url = new_url.replace(/auth=[a-z0-9]+/i, 'auth='+auth_hash);
}
return new_url;
}
for ( var i=0, eIdlength = eId.length; i < eIdlength; i++ ) {
@ -395,7 +399,7 @@ function redrawScreen() {
function outputUpdate(time) {
drawSliderOnGraph(time);
for ( var i=0; i < numMonitors; i++ ) {
loadImage2Monitor(monitorPtr[i],SetImageSource(monitorPtr[i],time));
loadImage2Monitor(monitorPtr[i],getImageSource(monitorPtr[i],time));
}
currentTimeSecs = time;
}
@ -706,12 +710,26 @@ function showOneMonitor(monId) {
createPopup(url, 'zmWatch', 'watch', monitorWidth[monId], monitorHeight[monId] );
} else {
for ( var i=0, len=eId.length; i<len; i++ ) {
if ( eMonId[i] == monId && currentTimeSecs >= eStartSecs[i] && currentTimeSecs <= eEndSecs[i] ) {
if ( eMonId[i] != monId )
continue;
if ( currentTimeSecs >= eStartSecs[i] && currentTimeSecs <= eEndSecs[i] ) {
url="?view=event&eid=" + eId[i] + '&fid=' + parseInt(Math.max(1, Math.min(eventFrames[i], eventFrames[i] * (currentTimeSecs - eStartSecs[i]) / (eEndSecs[i] - eStartSecs[i] + 1) ) ));
break;
} else if ( currentTimeSecs <= eStartSecs[i] ) {
if ( i ) {
// Didn't find an exact event, so go with the one before.
url="?view=event&eid=" + eId[i] + '&fid=' + parseInt(Math.max(1, Math.min(eventFrames[i], eventFrames[i] * (currentTimeSecs - eStartSecs[i]) / (eEndSecs[i] - eStartSecs[i] + 1) ) ));
}
break;
}
}
createPopup(url, 'zmEvent', 'event', monitorWidth[monId], monitorHeight[monId]);
if ( url ) {
createPopup(url, 'zmEvent', 'event', monitorWidth[monId], monitorHeight[monId]);
} else {
url="?view=watch&mid=" + monId.toString();
createPopup(url, 'zmWatch', 'watch', monitorWidth[monId], monitorHeight[monId] );
}
}
}

View File

@ -199,6 +199,7 @@ if ( isset($minTime) && isset($maxTime) ) {
$frameSql .= " AND TimeStamp > '" . $minTime . "' AND TimeStamp < '" . $maxTime . "'";
}
$frameSql .= ' GROUP BY E.Id, E.MonitorId, F.TimeStamp, F.Delta ORDER BY E.MonitorId, F.TimeStamp ASC';
$eventsSql .= ' ORDER BY E.Id ASC';
$monitors = array();
foreach( $displayMonitors as $row ) {