Code

Added additional graphs
[gosa.git] / gosa-core / plugins / generic / statistics / class_statistics.inc
1 <?php
3 class statistics extends plugin
4 {
5     var $plHeadline = 'Statistics';
6     var $plDescription = 'GOsa usage statistics';
7     var $plShortIcon = 'statistics.png';
8     var $plIcon = 'plugin.png';
9     
10     var $rpcHandle = NULL;
11     var $rpcConfigured = FALSE;
13     var $graphID_1 = 0;
14     var $graphID_2 = 0;
15     var $graphID_3 = 0;
16     var $graphID_4 = 0;
17     var $graphID_5 = 0;
19     var $graph1DatePicker1 = 0;
20     var $graph1DatePicker2 = 0;
22     var $unsbmittedFiles = array();
24     function __construct($config)
25     {
26         plugin::plugin($config, NULL);
28         // Init start and stop times for graph 1
29         $this->graph1DatePicker1 = date('d.m.Y', time() - 7 * 24 * 60 *60);
30         $this->graph1DatePicker2 = date('d.m.Y', time());
32         // First try to retrieve values via RPC
33         $this->rpcConfigured = FALSE;
34         if ($this->config->get_cfg_value("core","gosaRpcServer") != ""){
35             $this->rpcConfigured = TRUE;
36             $this->rpcHandle = $this->config->getRpcHandle(
37                     "http://10.3.64.59:4000",
38                     "65717fe6-9e3e-11df-b010-5452005f1250",
39                     "WyukwauWoid2",
40                     TRUE);
41         }
43         // Get list of unsubmitted files.
44         $this->unsbmittedFiles = $this->getUnsubmittedStatistics();
46         // Collect category translations
47         $this->catTranslations = array();
48         foreach($this->config->configRegistry->getListOfPlugins() as $plugin => $data){
49             if(isset($data['plCategory'])){
50                 foreach($data['plCategory'] as $id => $name){
51                     if(!is_numeric($id)){
52                         $this->catTranslations[$id] = $name['description'];
53                     }
54                 }
55             }
56         }
57     }
59     /*! \brief      Returns a list local stored statistic files
60         @param      Array   A list of filenames and dates.
61      */ 
62     function getLocalStatisticsFiles()
63     {
64         
65         $res = stats::getLocalStatFiles();
66         $tmp = array();
67         if(count($res)){
68             foreach($res as $file){
69                 $date = strtotime($file);
70                 if($date){
71                     $tmp[$file] = $date;
72                 }
73             }
74         }
75         return($tmp);
76     }
78    
79     /*! \brief      Returns a list of not transmitted stat files (except files for the current day)
80      *  @return     Array   A list of unsubmitted statistic files.
81      */ 
82     function getUnsubmittedStatistics()
83     {
84         $available = $this->getLocalStatisticsFiles();
85         $alreadyTransmitted = $this->getStatisticsDatesFromServer();
86         $unsubmitted = array_intersect($available,$alreadyTransmitted);
88         // Exclude statistic collection from today, they are still active and cannot be submitted.
89         $curDate =  date('Y-m-d');
90         if(isset($unsubmitted)) unset($unsubmitted[$curDate]);
92         return($unsubmitted);  
93     }
96     /*! \brief      Request a list of dates for which the server can return statistics.
97         @param      Array   A list of dates    $ret=[iso-str] = timestamp
98      */ 
99     function getStatisticsDatesFromServer()
100     {
101         $res = $this->rpcHandle->getInstanceStatDates();
102         $dates = array();
103         if(!$this->rpcHandle->success()){
104             msg_dialog::display(_("Error"),msgPool::rpcError($this->rpcHandle->get_error()),ERROR_DIALOG);
105         }else{
106             foreach($res as $date){
107                 $dates[$date] = strtotime($date);
108             }
109         }
110         return($dates);
111     }
114     function execute()
115     {
116         if(isset($_POST['graph1DatePicker1'])) $this->graph1DatePicker1 = get_post('graph1DatePicker1');
117         if(isset($_POST['graph1DatePicker2'])) $this->graph1DatePicker2 = get_post('graph1DatePicker2');
119         $smarty = get_smarty();
120         $smarty->assign('graph1DatePicker1', $this->graph1DatePicker1);
121         $smarty->assign('graph1DatePicker2', $this->graph1DatePicker2);
123         // Do not render anything if we are not prepared to send and receive data via rpc.
124         $smarty->assign("rpcConfigured", $this->rpcConfigured);
125         $smarty->assign("validRpcHandle", TRUE);
126         if(!$this->rpcConfigured || !$this->rpcHandle){
127             $smarty->assign("validRpcHandle", FALSE);
128             return($smarty->fetch(get_template_path('statistics.tpl', TRUE)));
129         }
131         // Send stats 
132         if(isset($_POST['transmitStatistics'])){
133             $this->unsbmittedFiles = $this->getUnsubmittedStatistics();
134             foreach($this->unsbmittedFiles as $filename => $date){
135                 $tmp = stats::dumpTables($filename);
136                 $dump = array();
137                 foreach($tmp as $entry){
138                     $dump[] = array_values($entry);
139                 }
140                 $res = $this->rpcHandle->updateInstanceStatus($dump);
141                 if(!$this->rpcHandle->success()){
142                     msg_dialog::display(_("Error"),msgPool::rpcError($this->rpcHandle->get_error()),ERROR_DIALOG);
143                 }else{
144                     stats::removeStatsFile($filename);
145                     echo "Inserted ".$res." entries for date ".date('d.m.Y', $date)."<br>";
146                 }
147             }
148             $this->unsbmittedFiles = $this->getUnsubmittedStatistics();
149         }
151         // Transmit daily statistics to GOsa-Server
152         if(isset($_POST['receiveStatistics'])){
154             // First try to retrieve values via RPC
155             if ($this->config->get_cfg_value("core","gosaRpcServer") != ""){
157                 $start = strtotime($this->graph1DatePicker1);
158                 $stop  = strtotime($this->graph1DatePicker2);
160                 // Request statistics now
161                 $res = $this->rpcHandle->getInstanceStats($start,$stop);
162                 if(!$this->rpcHandle->success()){
163                     msg_dialog::display(_("Error"),msgPool::rpcError($this->rpcHandle->get_error()),ERROR_DIALOG);
164                 }
166                 if($res && $this->rpcHandle->success()){
168                     // Include pChart 
169                     new pChartInclude();
171                     // Get most used categories, but only eight at once.
172                     if(count($res['actionsPerCategory'])){
174                         // --------
175                         // Generate PIE chart of most used categories
176                         // --------
178                         arsort($res['actionsPerCategory']);
180                         $mostUsedCategories = array_slice($res['actionsPerCategory'],0,8);
182                         // Dataset definition   
183                         $DataSet = new pData;  
184                         $this->graphID_1 = preg_replace("/[^0-9]/","",microtime(TRUE));
186                         $values = array_values($mostUsedCategories);
188                         $keys = array_keys($mostUsedCategories);
189                         foreach($keys as $id => $cat){
190                             $keys[$id] = $this->getCategoryTranslation($cat);
191                         }
193                         $DataSet->AddPoint($values,"Serie1");  
194                         $DataSet->AddAllSeries();  
195                         $DataSet->AddPoint($keys,"Serie2");  
196                         $DataSet->SetAbsciseLabelSerie("Serie2");  
198                         // Initialise the graph  
199                         $Test = new pChart(500,200);  
200                         $Test->setFontProperties("./themes/default/fonts/LiberationSans-Regular.ttf",10);  
203                         $Test->drawPieGraph($DataSet->GetData(),$DataSet->GetDataDescription(),150,90,110,PIE_PERCENTAGE,TRUE,50,20,5);  
204                         $Test->drawPieLegend(310,15,$DataSet->GetData(),$DataSet->GetDataDescription(),200,255,200);  
206                         $file = '/tmp/graph_'.$this->graphID_1;
207                         $Test->Render($file);
208                         session::set('statistics::graphFile'.$this->graphID_1,$file);
209                     }
211                     // --------
212                     // Generate combined line and car chart of plugin usage, ldap execution time and errors 
213                     // --------
215                     // Generate new and unique graph id
216                     $this->graphID_2 = preg_replace("/[^0-9]/","",microtime(TRUE));
218                     // Prepare transmitted data, sort it by date and collect 
219                     //  transmitted timestamps to be able to print the x-Axis labels.
220                     $dataArray = array();
221                     $dates = array();
222                     $DataSet2 = new pData;  
223                     $max = 1;
224                     $seriesNumber = 0;
225                     foreach($res['actionsPerInterval'] as $category => $entriesPerDate){
227                         // Collect data per category and store used timestamps
228                         foreach($entriesPerDate as $dateStr => $count){
229                             $date = strtotime($dateStr);
230                             $dates[$date]=$date;
232                             // Do not append empty data                            
233                             if(empty($category)) continue;
234                             if($count) $count = ($count);
235                             $dataArray[$category][$date] = $count;
236                         }
237                       
238  
239                         // Do not append empty data 
240                         if(empty($category)) continue;
242                         // Sort results. 
243                         ksort($dataArray[$category]);
245                         // Add results to our data set.
246                         $DataSet2->AddPoint($dataArray[$category], $category);
247                         $DataSet2->SetSerieName($this->getCategoryTranslation($category), $category);
248                         $Test->setLabel($DataSet->GetData(),$DataSet->GetDataDescription(),"Serie1",0,"Daily incomes");  
249                         $DataSet2->AddSerie($category);
250                         $seriesNumber++;
252                         // Detect maximum value, to adjust the Y-Axis
253                         $tmpMax = max($dataArray[$category]);
254                         if($tmpMax > $max) $max = $tmpMax;
255                     }
256                     ksort($dates);
258                     // Prepare date strings for X-Axis, only print a given number of 
259                     //  of labels to keep the axis readable.
260                     $Xam = 5; // Number of labels
261                     $cnt = 0;
262                     $dateSeries = array();
263                     foreach($dates as $stamp){
264                         if((count($dates) <= $Xam) || ($cnt % (floor(count($dates) / $Xam )) == 0)){
265                             $dateSeries[$stamp] = date('d.m.Y',$stamp);
266                         }else{
267                             $dateSeries[$stamp] = ' ';
268                         }
269                         $cnt ++;    
270                     }
272                     $DataSet2->AddPoint($dateSeries, 'date');
273                     $DataSet2->SetAbsciseLabelSerie('date');  
275                     $Test2 = new pChart(800,230);  
276                     $Test2->setFixedScale(0.0001,($max*1.1));  
277                     $Test2->setFontProperties("./themes/default/fonts/LiberationSans-Regular.ttf",10);  
278                     $Test2->setGraphArea(50,30,585,200);  
279                     $Test2->drawFilledRoundedRectangle(7,7,693,223,5,240,240,240);  
280                     $Test2->drawRoundedRectangle(5,5,695,225,5,230,230,230);  
281                     $Test2->drawGraphArea(255,255,255,TRUE);  
282                     $Test2->drawGrid(4,TRUE,200,200,200,50);  
283                     $Test2->drawTreshold(0,143,55,72,TRUE,TRUE);  
284                     $Test2->drawTitle(50,22,"Plugin usage over time",50,50,50,585);  
286                     if(count($dates)){
287                         $Test2->drawScale($DataSet2->GetData(),$DataSet2->GetDataDescription(),SCALE_NORMAL,150,150,150,TRUE,0,2);     
288                     }
290                     // Draw the cubic curve graph  
291                     if(count($dataArray)){
292                         $Test2->drawFilledLineGraph($DataSet2->GetData(),$DataSet2->GetDataDescription(),50,TRUE);
293                     }
295                     // Add error series
296                     $errors = array();
297                     foreach($res['errorsPerInterval'] as $dateStr => $count){
298                         $date = strtotime($dateStr);
299                         if($count !=0) $count = ($count);
300                         $errors[$date] = $count;
301                     }
303                     $DataSet2->AddPoint($errors, 'Errors');
304                     $DataSet2->SetSerieName(_('Error'), 'Errors');
305                     $DataSet2->AddSerie('Errors');
306                     $seriesNumber ++;
307                    
308                     $Test2->setColorPalette($seriesNumber-1,255,0,0);   
310                     // Draw legend
311                     $Test2->drawLegend(650,30,$DataSet2->GetDataDescription(),255,255,255);  
313                     // Remove plugin usage from data series, just keep error series.
314                     foreach($dataArray as $categoryName => $list){
315                         $DataSet2->RemoveSerie($categoryName);
316                     }
317     
318                     // Draw right scale (Errors per day)
319                     $Test2->setFixedScale(0.0001,(max($errors) +1) *1.1);
320                     $Test2->drawRightScale($DataSet2->GetData(),$DataSet2->GetDataDescription(),SCALE_NORMAL,120,150,150,TRUE,0,2);
321                     $Test2->drawBarGraph($DataSet2->GetData(),$DataSet2->GetDataDescription());
323                     $file = '/tmp/graph_'.$this->graphID_2;
324                     $Test2->Render($file);
325                     session::set('statistics::graphFile'.$this->graphID_2,$file);
336                         
337                 
342                     // Prepare Data 
343                     $graphData = array();
344                     foreach($res['usagePerInterval'] as $dateStr => $data){
345                         $date = strtotime($dateStr);
346                         foreach($data as $name => $val){
347                             $graphData[$name][$date] = $val;
348                         }
349                     }
350    
351                     // Sort Data 
352                     foreach($graphData as $key => $data)
353                         ksort($graphData[$key]);
355                     // Generate new and unique graph id
356                     $this->graphID_3 = preg_replace("/[^0-9]/","",microtime(TRUE));
358                     // Prepare transmitted data, sort it by date and collect 
359                     //  transmitted timestamps to be able to print the x-Axis labels.
360                     $DataSet3 = new pData;  
362                     $max = max($graphData['max_mem']);
364                     $DataSet3->AddPoint(array_values($graphData['max_mem']), 'max_mem');
365                     $DataSet3->AddPoint(array_values($graphData['avg_mem']), 'avg_mem');
366                     $DataSet3->AddPoint(array_values($graphData['min_mem']), 'min_mem');
368                     $DataSet3->SetSerieName('Min Memory', 'min_mem');
369                     $DataSet3->SetSerieName('Max Memory', 'max_mem');
370                     $DataSet3->SetSerieName('Average Memory', 'avg_mem');
372                     $DataSet3->AddAllSeries();  
373                     $DataSet3->AddPoint($dateSeries, 'date');
374                     $DataSet3->SetAbsciseLabelSerie('date');
376                     $Test3 = new pChart(800,230);  
377                     $Test3->setFixedScale(0.0001,($max*1.1));  
378                     $Test3->setFontProperties("./themes/default/fonts/LiberationSans-Regular.ttf",10);  
379                     $Test3->setGraphArea(50,30,585,200);  
380                     $Test3->drawFilledRoundedRectangle(7,7,693,223,5,240,240,240);  
381                     $Test3->drawRoundedRectangle(5,5,695,225,5,230,230,230);  
382                     $Test3->drawGraphArea(255,255,255,TRUE);  
383                     $Test3->drawGrid(4,TRUE,200,200,200,50);  
384                     $Test3->drawTreshold(0,143,55,72,TRUE,TRUE);  
385                     $Test3->drawTitle(50,22,"Memory usage",50,50,50,585);  
387                     $Test3->drawScale($DataSet3->GetData(),$DataSet3->GetDataDescription(),SCALE_NORMAL,150,150,150,TRUE,0,2, FALSE);
388                     $Test3->drawFilledCubicCurve($DataSet3->GetData(),$DataSet3->GetDataDescription(),.1,50); 
390                     $file = '/tmp/graph_'.$this->graphID_3;
391                     $Test3->Render($file);
392                     session::set('statistics::graphFile'.$this->graphID_3,$file);
400                     // Generate new and unique graph id
401                     $this->graphID_4 = preg_replace("/[^0-9]/","",microtime(TRUE));
403                     // Prepare transmitted data, sort it by date and collect 
404                     //  transmitted timestamps to be able to print the x-Axis labels.
405                     $DataSet4 = new pData;  
407                     $max = max($graphData['max_dur']);
409                     $DataSet4->AddPoint(array_values($graphData['max_dur']), 'max_dur');
410                     $DataSet4->AddPoint(array_values($graphData['avg_dur']), 'avg_dur');
411                     $DataSet4->AddPoint(array_values($graphData['min_dur']), 'min_dur');
413                     $DataSet4->SetSerieName('Min dur', 'min_dur');
414                     $DataSet4->SetSerieName('Max dur', 'max_dur');
415                     $DataSet4->SetSerieName('Average dur', 'avg_dur');
417                     $DataSet4->AddAllSeries();  
418                     $DataSet4->AddPoint($dateSeries, 'date');
419                     $DataSet4->SetAbsciseLabelSerie('date');
421                     $Test4 = new pChart(800,230);  
422                     $Test4->setFixedScale(0.0001,($max*1.1));  
423                     $Test4->setFontProperties("./themes/default/fonts/LiberationSans-Regular.ttf",10);  
424                     $Test4->setGraphArea(50,30,585,200);  
425                     $Test4->drawFilledRoundedRectangle(7,7,693,223,5,240,240,240);  
426                     $Test4->drawRoundedRectangle(5,5,695,225,5,230,230,230);  
427                     $Test4->drawGraphArea(255,255,255,TRUE);  
428                     $Test4->drawGrid(4,TRUE,200,200,200,50);  
429                     $Test4->drawTreshold(0,143,55,72,TRUE,TRUE);  
430                     $Test4->drawTitle(50,22,"Render time",50,50,50,585);  
432                     $Test4->drawScale($DataSet4->GetData(),$DataSet4->GetDataDescription(),SCALE_NORMAL,150,150,150,TRUE,0,2, FALSE);
433                     $Test4->drawFilledCubicCurve($DataSet4->GetData(),$DataSet4->GetDataDescription(),.1,50); 
435                     $file= '/tmp/graph_'.$this->graphID_4;
436                     $Test4->Render($file);
437                     session::set('statistics::graphFile'.$this->graphID_4,$file);
446                     // Generate new and unique graph id
447                     $this->graphID_5 = preg_replace("/[^0-9]/","",microtime(TRUE));
449                     // Prepare transmitted data, sort it by date and collect 
450                     //  transmitted timestamps to be able to print the x-Axis labels.
451                     $DataSet5 = new pData;  
453                     $max = max($graphData['max_load']);
455                     $DataSet5->AddPoint(array_values($graphData['max_load']), 'max_load');
456                     $DataSet5->AddPoint(array_values($graphData['avg_load']), 'avg_load');
457                     $DataSet5->AddPoint(array_values($graphData['min_load']), 'min_load');
459                     $DataSet5->SetSerieName('Min Load', 'min_load');
460                     $DataSet5->SetSerieName('Max Load', 'max_load');
461                     $DataSet5->SetSerieName('Average Load', 'avg_load');
463                     $DataSet5->AddAllSeries();  
464                     $DataSet5->AddPoint($dateSeries, 'date');
465                     $DataSet5->SetAbsciseLabelSerie('date');
467                     $Test5 = new pChart(800,230);  
468                     $Test5->setFixedScale(0.0001,($max*1.1));  
469                     $Test5->setFontProperties("./themes/default/fonts/LiberationSans-Regular.ttf",10);  
470                     $Test5->setGraphArea(50,30,585,200);  
471                     $Test5->drawFilledRoundedRectangle(7,7,693,223,5,240,240,240);  
472                     $Test5->drawRoundedRectangle(5,5,695,225,5,230,230,230);  
473                     $Test5->drawGraphArea(255,255,255,TRUE);  
474                     $Test5->drawGrid(4,TRUE,200,200,200,50);  
475                     $Test5->drawTreshold(0,143,55,72,TRUE,TRUE);  
476                     $Test5->drawTitle(50,22,"CPU load",50,50,50,585);  
478                     $Test5->drawScale($DataSet5->GetData(),$DataSet5->GetDataDescription(),SCALE_NORMAL,150,150,150,TRUE,0,2, FALSE);
479                     $Test5->drawFilledCubicCurve($DataSet5->GetData(),$DataSet5->GetDataDescription(),.1,50); 
481                     $file = '/tmp/graph_'.$this->graphID_5;
482                     $Test5->Render($file);
483                     session::set('statistics::graphFile'.$this->graphID_5,$file);
485                 }
486             }
487         }
489         $smarty->assign('graphID_1', $this->graphID_1);
490         $smarty->assign('graphID_2', $this->graphID_2);
491         $smarty->assign('graphID_3', $this->graphID_3);
492         $smarty->assign('graphID_4', $this->graphID_4);
493         $smarty->assign('graphID_5', $this->graphID_5);
494         $smarty->assign('unsbmittedFiles', count($this->unsbmittedFiles));
495         $smarty->assign('unsbmittedFilesMsg', 
496                 sprintf(
497                     _("You have currently %s unsubmitted statistic collection, do you want to transmit them now?"),
498                     count($this->unsbmittedFiles)));
499         return($smarty->fetch(get_template_path('statistics.tpl', TRUE)));
500     }
503     function check()
504     {
505         $messages = plugin::check();
506         return($messages);
507     }
510     function save_object()
511     {
512         plugin::save_object();
513     }
516     /*! \brief      This method tries to translate category names.
517      *  @param      The category name to translate
518      *  @return     String  The translated category names.
519      */
520     function getCategoryTranslation($name)
521     {
522         $ret ="";
523         
524         // Extract category names from the given string.
525         $list = preg_split("/, /", $name);
526    
527         // We do not have a category for systems directly, so we've to map all system types to 'System'.
528         // If we do not map to _(Systems) the graph legend will be half screen width.
529         if(count(array_intersect(array('server','terminal','workstation', 'opsi', 'component'), $list))){
530             return(_("Systems"));
531         }
533         // Walk through category names and try to find a translation.
534         foreach($list as $cat){
535             $cat = trim($cat);
536             if(isset($this->catTranslations[$cat])){
537                 $ret .= _($this->catTranslations[$cat]).", ";
538             }else{
539                 $ret .= $cat.", ";
540             }
541         }
542         return(rtrim($ret, ', '));
543     }
545 ?>