|
|
@@ -6,10 +6,71 @@
|
|
|
|
|
|
use strict;
|
|
|
use JSON::PP;
|
|
|
+use HTTP::Daemon;
|
|
|
+use HTTP::Status;
|
|
|
|
|
|
# location of vnstat binary
|
|
|
my $vnstat_cmd = '/usr/bin/vnstat';
|
|
|
|
|
|
+# Create an HTTP::Daemon instance listening on port 9955
|
|
|
+my $d = HTTP::Daemon->new(
|
|
|
+ LocalAddr => 'localhost',
|
|
|
+ LocalPort => 9955,
|
|
|
+) || die "Cannot create HTTP::Daemon instance: $!";
|
|
|
+
|
|
|
+print "HTTP server listening on ", $d->url, "\n";
|
|
|
+
|
|
|
+# Enter an event loop to handle incoming requests
|
|
|
+while (my $c = $d->accept) {
|
|
|
+ while (my $r = $c->get_request) {
|
|
|
+ if ($r->method eq 'GET') {
|
|
|
+ my $response_text = generate_response();
|
|
|
+ $c->send_response(HTTP::Response->new(RC_OK, undef, undef, $response_text));
|
|
|
+ } else {
|
|
|
+ $c->send_error(RC_FORBIDDEN);
|
|
|
+ }
|
|
|
+ }
|
|
|
+ $c->close;
|
|
|
+ undef($c);
|
|
|
+}
|
|
|
+
|
|
|
+sub generate_response {
|
|
|
+ my $response = "Content-Type: text/plain\n\n";
|
|
|
+
|
|
|
+ my $json_data = `$vnstat_cmd --json s 1`;
|
|
|
+
|
|
|
+ my $data = "";
|
|
|
+ eval { $data = decode_json($json_data) };
|
|
|
+ if ($@) {
|
|
|
+ $response .= "# Error: Invalid command output: $json_data\n";
|
|
|
+ return $response;
|
|
|
+ }
|
|
|
+
|
|
|
+ if (not defined $data->{'vnstatversion'}) {
|
|
|
+ $response .= "# Error: Expected content from command output missing\n";
|
|
|
+ return $response;
|
|
|
+ }
|
|
|
+
|
|
|
+ if (not defined $data->{'interfaces'}[0]) {
|
|
|
+ $response .= "# Error: No interfaces found in command output\n";
|
|
|
+ return $response;
|
|
|
+ }
|
|
|
+
|
|
|
+ if (not defined $data->{'interfaces'}[0]{'created'}{'timestamp'}) {
|
|
|
+ $response .= "# Error: Incompatible vnStat version used\n";
|
|
|
+ return $response;
|
|
|
+ }
|
|
|
+
|
|
|
+ $response .= "# vnStat version: ".$data->{'vnstatversion'}."\n";
|
|
|
+
|
|
|
+ $response .= print_totals($data);
|
|
|
+
|
|
|
+ foreach my $data_resolution ( @data_resolutions ) {
|
|
|
+ $response .= print_data_resolution($data_resolution, $data);
|
|
|
+ }
|
|
|
+
|
|
|
+ return $response;
|
|
|
+}
|
|
|
|
|
|
################
|
|
|
|