/
zmtelemetry.pl.in
420 lines (361 loc) · 12.7 KB
/
zmtelemetry.pl.in
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
#!@PERL_EXECUTABLE@ -wT
#
# ==========================================================================
#
# ZoneMinder Telemetry Upload Script, $Date$, $Revision$
# Copyright (C) 2001-2008 Philip Coombes
#
# This program is free software; you can redistribute it and/or
# modify it under the terms of the GNU General Public License
# as published by the Free Software Foundation; either version 2
# of the License, or (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program; if not, write to the Free Software
# Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
#
# ==========================================================================
use strict;
use bytes;
use utf8;
@EXTRA_PERL_LIB@
use ZoneMinder;
use DBI;
use Getopt::Long;
use autouse 'Pod::Usage'=>qw(pod2usage);
use LWP::UserAgent;
use Sys::MemInfo qw(totalmem);
use Sys::CPU qw(cpu_count);
use POSIX qw(strftime uname);
use JSON::MaybeXS;
use Encode;
$ENV{PATH} = '/bin:/usr/bin:/usr/local/bin';
$ENV{SHELL} = '/bin/sh' if exists $ENV{SHELL};
delete @ENV{qw(IFS CDPATH ENV BASH_ENV)};
# Setting these as constants for now.
my $help = 0;
my $force = 0;
my $show = 0;
# Interval between version checks
my $interval;
my $version;
GetOptions(
force => \$force,
help => \$help,
show => \$show,
interval => \$interval,
version => \$version
);
if ($version) {
print(ZoneMinder::Base::ZM_VERSION . "\n");
exit(0);
}
if ($help) {
pod2usage(-exitstatus => -1);
}
if ($show) {
my %telemetry;
my $dbh = zmDbConnect();
collectData($dbh, \%telemetry);
my $result = jsonEncode(\%telemetry);
print($result);
exit(0);
}
if (!defined $interval) {
$interval = eval($Config{ZM_TELEMETRY_INTERVAL});
}
if (!($Config{ZM_TELEMETRY_DATA} or $force)) {
print("ZoneMinder Telemetry Agent not enabled. Exiting.\n");
exit(0);
}
print('ZoneMinder Telemetry Agent starting at '.strftime('%y/%m/%d %H:%M:%S', localtime())."\n");
my $lastCheck = $Config{ZM_TELEMETRY_LAST_UPLOAD};
while (1) {
my $now = time();
my $since_last_check = $now - $lastCheck;
Debug("Last Check time (now($now) - lastCheck($lastCheck)) = $since_last_check > interval($interval) or force($force)");
if ($since_last_check < 0) {
Warning('Seconds since last check is negative! Which means that lastCheck is in the future!');
sleep($interval);
next;
}
if ((($since_last_check) > $interval) or $force) {
print "Collecting data to send to ZoneMinder Telemetry server.\n";
my $dbh = zmDbConnect();
if ($dbh) {
# Build the telemetry hash
# We should keep *BSD systems in mind when calling system commands
my %telemetry;
collectData($dbh, \%telemetry);
my $result = jsonEncode(\%telemetry);
if (sendData($result)) {
ZoneMinder::Database::zmDbDo('UPDATE Config SET Value=? WHERE Name=?',
$now, 'ZM_TELEMETRY_LAST_UPLOAD');
$Config{ZM_TELEMETRY_LAST_UPLOAD} = $now;
}
zmDbDisconnect();
} else {
Error('Failed to open database. Sleeping.');
}
} elsif (-t STDIN) {
print "ZoneMinder Telemetry Agent sleeping for $interval seconds because ($now-$lastCheck=$since_last_check > $interval\n";
}
$lastCheck = $now;
sleep($interval);
} # end while
print 'ZoneMinder Telemetry Agent exiting at '.strftime('%y/%m/%d %H:%M:%S', localtime())."\n";
exit(0);
###############
# SUBROUTINES #
###############
# collect data to send
sub collectData {
my $dbh = shift;
my $telemetry = shift;
$telemetry->{uuid} = getUUID($dbh);
@$telemetry{qw(city region country latitude longitude)} = getGeo();
$telemetry->{timestamp} = strftime('%Y-%m-%dT%H:%M:%S%z', localtime());
$telemetry->{monitor_count} = countQuery($dbh, 'Monitors');
$telemetry->{event_count} = countQuery($dbh, 'Events');
$telemetry->{architecture} = runSysCmd($Config{ZM_PATH_UNAME}.' -p');
@$telemetry{qw(kernel distro version)} = getDistro();
$telemetry->{zm_version} = ZoneMinder::Base::ZM_VERSION;
$telemetry->{system_memory} = totalmem();
$telemetry->{processor_count} = cpu_count();
$telemetry->{use_event_server} = $Config{ZM_OPT_USE_EVENTNOTIFICATION};
$telemetry->{monitors} = getMonitorRef($dbh);
}
# Find, verify, then run the supplied system command
sub runSysCmd {
my $msg = shift;
my @arguments = split(/ /, $msg);
chomp($arguments[0]);
my $path = qx( which $arguments[0] );
my $status = $? >> 8;
my $result = '';
if (!$path || $status) {
Warning("Cannot find the $arguments[0] executable.");
return $result;
}
chomp($path);
$arguments[0] = $path;
my $cmd = join(' ', @arguments);
($cmd) = $cmd =~ /(.*)/; # detaint
$result = qx( $cmd );
chomp($result);
return $result;
}
# Upload message data to ZoneMinder telemetry server
sub sendData {
my $msg = shift;
my $ua = LWP::UserAgent->new;
my $server_endpoint = $Config{ZM_TELEMETRY_SERVER_ENDPOINT};
if ($Config{ZM_UPDATE_CHECK_PROXY}) {
$ua->proxy('https', $Config{ZM_UPDATE_CHECK_PROXY});
}
Debug("Posting telemetry data to: $server_endpoint");
# set custom HTTP request header fields
my $req = HTTP::Request->new(POST => $server_endpoint);
$req->header('content-type' => 'application/x-www-form-urlencoded');
$req->header('content-length' => length($msg));
$req->header('connection' => 'Close');
$req->content(encode('UTF-8', $msg));
my $resp = $ua->request($req);
my $resp_msg = $resp->decoded_content;
my $resp_code = $resp->code;
if ($resp->is_success) {
Info('Telemetry data uploaded successfully.');
Debug("Telemetry server upload success response message: $resp_msg");
} else {
Warning("Telemetry server returned HTTP POST error code: $resp_code");
Debug("Telemetry server upload failure response message: $resp_msg");
}
return $resp->is_success;
}
# Retrieves the UUID from the database. Creates a new UUID if one does not exist.
sub getUUID {
my $dbh = shift;
my $uuid = '';
# Verify the current UUID is valid and not nil
if (
($Config{ZM_TELEMETRY_UUID} =~ /([0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12})/i)
&&
($Config{ZM_TELEMETRY_UUID} ne '00000000-0000-0000-0000-000000000000' )
) {
$uuid = $Config{ZM_TELEMETRY_UUID};
} else {
my $sql = 'SELECT uuid()';
my $sth = $dbh->prepare_cached( $sql ) or die( "Can't prepare '$sql': ".$dbh->errstr() );
my $res = $sth->execute() or die( "Can't execute: ".$sth->errstr() );
$uuid = $Config{ZM_TELEMETRY_UUID} = $sth->fetchrow_array();
$sth->finish();
zmDbDo('UPDATE Config SET Value=? WHERE Name=?', $uuid, 'ZM_TELEMETRY_UUID');
}
return $uuid;
}
# Retrieve this server's general location information from a GeoIP database
sub getGeo {
my $unknown = 'Unknown';
my $endpoint = 'https://ipinfo.io/geo';
my $ua = LWP::UserAgent->new;
my $req = HTTP::Request->new(GET => $endpoint);
my $resp = $ua->request($req);
my $resp_msg = $resp->decoded_content;
my $resp_code = $resp->code;
if ($resp->is_success) {
my $content = decode_json($resp_msg);
(my $latitude, my $longitude) = split /,/, $content->{loc};
return ($content->{city}, $content->{region}, $content->{country}, $latitude, $longitude);
} else {
Warning("Geoip data retrieval returned HTTP POST error code: $resp_code");
Debug("Geoip data retrieval failure response message: $resp_msg");
return ($unknown, $unknown, $unknown, $unknown, $unknown);
}
}
# As the name implies, just your average mysql count query
sub countQuery {
my $dbh = shift;
my $table = shift;
my $sql = "SELECT count(*) FROM `$table`";
my $sth = $dbh->prepare_cached($sql) or die "Can't prepare '$sql': ".$dbh->errstr();
my $res = $sth->execute() or die 'Can\'t execute: '.$sth->errstr();
my $count = $sth->fetchrow_array();
$sth->finish();
return $count
}
# Returns a reference to an array of hashes containing data from all monitors
sub getMonitorRef {
my $dbh = shift;
my $sql = 'SELECT `Id`,`Name`,`Type`,`Capturing`,`Analysing`,`Recording`,`Width`,`Height`,`Colours`,`MaxFPS`,`AlarmMaxFPS`,
(SELECT Name FROM Manufacturers WHERE Manufacturers.Id = ManufacturerId),
(SELECT Name FROM Models WHERE Models.Id = ModelId)
FROM `Monitors`';
my $sth = $dbh->prepare_cached( $sql ) or die( "Can't prepare '$sql': ".$dbh->errstr() );
my $res = $sth->execute() or die( "Can't execute: ".$sth->errstr() );
my $arrayref = $sth->fetchall_arrayref({});
return $arrayref;
}
sub getDistro {
my $kernel = '';
my $distro = '';
my $version = '';
my @uname = uname();
if ($uname[0] =~ /Linux/) {
Debug('Linux distro detected.');
($kernel, $distro, $version) = linuxDistro();
} elsif ($uname[0] =~ /.*BSD/) {
Debug('BSD distro detected.');
$kernel = $uname[3];
$distro = $uname[0];
$version = $uname[2];
} elsif ($uname[0] =~ /Darwin/) {
Debug('Mac OS distro detected.');
$kernel = $uname[3];
$distro = runSysCmd('sw_vers -productName');
$version = runSysCmd('sw_vers -productVersion');
} elsif ( $uname[0] =~ /SunOS|Solaris/ ) {
Debug('Sun Solaris detected.');
$kernel = $uname[3];
$distro = $uname[1];
$version = $uname[2];
} else {
Warning('ZoneMinder was unable to determine the host system. Please report.');
$kernel = 'Unknown';
$distro = 'Unknown';
$version = 'Unknown';
}
return ($kernel, $distro, $version);
}
sub linuxDistro {
my @uname = uname();
my $kernel = $uname[2];
my $distro = 'Unknown Linux Distro';
my $version = 'Unknown Linux Version';
my $found = 0;
# os-release is the standard for many new distros based on systemd
if (-f '/etc/os-release') {
open(my $RELFILE,'<','/etc/os-release') or die( "Can't Open file: $!\n" );
while (<$RELFILE>) {
if (/^NAME=(")?(.*)(?(1)\1|).*$/) {
$distro = $2;
$found = 1;
}
if (/^VERSION_ID=(")?(.*)(?(1)\1|).*$/) {
$version = $2;
$found = 1;
}
}
close $RELFILE;
# exists on many distros but does not always contain useful information, such as redhat
} elsif (-f '/etc/lsb-release') {
if (open(my $RELFILE,'<','/etc/lsb-release')) {
while (<$RELFILE>) {
if (/^DISTRIB_DESCRIPTION=(")?(.*)(?(1)\1|).*$/) {
$distro = $2;
$found = 1;
}
if (/^DISTRIB_RELEASE=(")?(.*)(?(1)\1|).*$/) {
$version = $2;
$found = 1;
}
}
close($RELFILE);
} else {
Error("Can't Open file /etc/lsb-release: $!\n");
}
}
# If all else fails, search through a list of known release files until we find one
if (!$found) {
my @releasefile = ('/etc/SuSE-release', '/etc/redhat-release', '/etc/redhat_version',
'/etc/fedora-release', '/etc/slackware-release', '/etc/slackware-version',
'/etc/debian_release', '/etc/debian_version', '/etc/mandrake-release',
'/etc/yellowdog-release', '/etc/gentoo-release');
foreach (@releasefile) {
if ( -f $_ ) {
open(my $RELFILE,'<',$_) or die( "Can't Open file: $!\n" );
while (<$RELFILE>) {
if ( /(.*).* (\d+\.?\d*) .*/ ) {
$distro = $1;
$version = $2;
$found = 1;
}
}
close $RELFILE;
last;
}
}
}
if (!$found) {
Warning('ZoneMinder was unable to determine Linux distro. Please report.');
}
return ($kernel, $distro, $version);
}
1;
__END__
=head1 NAME
zmtelemetry.pl - Send usage information to the ZoneMinder development team
=head1 SYNOPSIS
zmtelemetry.pl [--force] [--help] [--show] [--interval=seconds] [--version]
=head1 DESCRIPTION
This script collects usage information of the local system and sends it to the
ZoneMinder development team. This data will be used to determine things like
who and where our customers are, how big their systems are, the underlying
hardware and operating system, etc. This is being done for the sole purpoase of
creating a better product for our target audience. This script is intended to
be completely transparent to the end user, and can be disabled from the web
console under Options.
=head1 OPTIONS
--force Force the script to upload it's data instead of waiting
for the defined interval since last upload.
--help Display usage information
--show Displays telemetry data that is sent to zoneminder
--interval Override the default configured interval since last upload.
The value should be given in seconds, but can be an expression
such as 24*60*60.
--version Output the version of ZoneMinder.
=cut