contrib/collection3: Update bin/json.cgi to use the JSON module.
authorFlorian Forster <octo@noris.net>
Fri, 13 Mar 2009 14:42:30 +0000 (15:42 +0100)
committerFlorian Forster <octo@noris.net>
Fri, 13 Mar 2009 14:42:30 +0000 (15:42 +0100)
contrib/collection3/bin/json.cgi

index c2af61c..99e2703 100755 (executable)
@@ -24,6 +24,7 @@ use FindBin ('$RealBin');
 use CGI (':cgi');
 use CGI::Carp ('fatalsToBrowser');
 use URI::Escape ('uri_escape');
+use JSON ('objToJson');
 
 use Data::Dumper;
 
@@ -33,6 +34,7 @@ use Collectd::Graph::Common (qw(get_all_hosts get_files_for_host type_to_module_
 use Collectd::Graph::Type ();
 
 our $Debug = param ('debug') ? 1 : 0;
+our $ServerName = 'collect.noris.net';
 
 gc_read_config ("$RealBin/../etc/collection.conf");
 
@@ -45,11 +47,11 @@ else
   print "Content-Type: application/json; charset=utf-8\n\n";
 }
 
-print "{\n";
-
+my $obj = {};
 my @hosts = get_all_hosts ();
 for (my $i = 0; $i < @hosts; $i++)
 {
+  my $host_obj = {};
   my $host = $hosts[$i];
   my $files = get_files_for_host ($host);
   my %graphs = ();
@@ -75,46 +77,31 @@ for (my $i = 0; $i < @hosts; $i++)
     $graphs{$type}->addFiles ($file);
   } # for (@$files)
 
-  print qq(  "$host":\n  {\n);
+  #print qq(  ") . objToJson ({ foo => 123 }) . qq(":\n  {\n);
 
   @graphs = keys %graphs;
   for (my $j = 0; $j < @graphs; $j++)
   {
     my $type = $graphs[$j];
     my $graphs_num = $graphs{$type}->getGraphsNum ();
-    my @args = ();
 
-    for (my $k = 0; $k < $graphs_num; $k++)
+    if (!defined ($host_obj->{$type}))
     {
-      my $args = $graphs{$type}->getGraphArgs ($k);
-      my $url = 'http://' . $ENV{'SERVER_NAME'} . "/cgi-bin/graph.cgi?" . $args;
-      push (@args, $url);
+      $host_obj->{$type} = [];
     }
 
-    print qq(    "$type": [ )
-    . join (', ', map { qq("$_") } (@args));
-
-    if ($j == (@graphs - 1))
-    {
-      print qq( ]\n);
-    }
-    else
+    for (my $k = 0; $k < $graphs_num; $k++)
     {
-      print qq( ],\n);
+      my $args = $graphs{$type}->getGraphArgs ($k);
+      my $url = "http://$ServerName/cgi-bin/collection3/bin/graph.cgi?" . $args;
+      push (@{$host_obj->{$type}}, $url);
     }
   } # for (keys %graphs)
 
-  if ($i == (@hosts - 1))
-  {
-    print qq(  }\n);
-  }
-  else
-  {
-    print qq(  },\n\n);
-  }
+  $obj->{$host} = $host_obj;
 } # for (my $i = 0; $i < @hosts; $i++)
 
-print "}\n";
+print STDOUT objToJson ($obj, { pretty => 1, indent => 2 });
 
 exit (0);