Code

Updated stats detection
[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();
87         $unsubmitted = array();
88         foreach($available as $key => $day){
89             if(!isset($alreadyTransmitted[$key])) $unsubmitted [$key] = $day;
90         }
92         // Exclude statistic collection from today, they are still active and cannot be submitted.
93         $curDate =  date('Y-m-d');
94         if(isset($unsubmitted)) unset($unsubmitted[$curDate]);
96         return($unsubmitted);  
97     }
100     /*! \brief      Request a list of dates for which the server can return statistics.
101         @param      Array   A list of dates    $ret=[iso-str] = timestamp
102      */ 
103     function getStatisticsDatesFromServer()
104     {
105         $res = $this->rpcHandle->getInstanceStatDates();
106         $dates = array();
107         if(!$this->rpcHandle->success()){
108             msg_dialog::display(_("Error"),msgPool::rpcError($this->rpcHandle->get_error()),ERROR_DIALOG);
109         }else{
110             foreach($res as $date){
111                 $dates[$date] = strtotime($date);
112             }
113         }
114         return($dates);
115     }
118     function execute()
119     {
120         if(isset($_POST['graph1DatePicker1'])) $this->graph1DatePicker1 = get_post('graph1DatePicker1');
121         if(isset($_POST['graph1DatePicker2'])) $this->graph1DatePicker2 = get_post('graph1DatePicker2');
123         $smarty = get_smarty();
124         $smarty->assign('graph1DatePicker1', $this->graph1DatePicker1);
125         $smarty->assign('graph1DatePicker2', $this->graph1DatePicker2);
127         // Do not render anything if we are not prepared to send and receive data via rpc.
128         $smarty->assign("rpcConfigured", $this->rpcConfigured);
129         $smarty->assign("validRpcHandle", TRUE);
130         if(!$this->rpcConfigured || !$this->rpcHandle){
131             $smarty->assign("validRpcHandle", FALSE);
132             return($smarty->fetch(get_template_path('statistics.tpl', TRUE)));
133         }
135         // Send stats 
136         if(isset($_POST['transmitStatistics'])){
137             $this->unsbmittedFiles = $this->getUnsubmittedStatistics();
138             foreach($this->unsbmittedFiles as $filename => $date){
139                 $tmp = stats::dumpTables($filename);
140                 $dump = array();
141                 foreach($tmp as $entry){
142                     $dump[] = array_values($entry);
143                 }
144                 $res = $this->rpcHandle->updateInstanceStatus($dump);
145                 if(!$this->rpcHandle->success()){
146                     msg_dialog::display(_("Error"),msgPool::rpcError($this->rpcHandle->get_error()),ERROR_DIALOG);
147                 }else{
148                     stats::removeStatsFile($filename);
149                     echo "Inserted ".$res." entries for date ".date('d.m.Y', $date)."<br>";
150                 }
151             }
152             $this->unsbmittedFiles = $this->getUnsubmittedStatistics();
153         }
155         // Transmit daily statistics to GOsa-Server
156         if(isset($_POST['receiveStatistics'])){
158             // First try to retrieve values via RPC
159             if ($this->config->get_cfg_value("core","gosaRpcServer") != ""){
161                 $start = strtotime($this->graph1DatePicker1);
162                 $stop  = strtotime($this->graph1DatePicker2);
164                 // Request statistics now
165                 $res = $this->rpcHandle->getInstanceStats($start,$stop);
166                 if(!$this->rpcHandle->success()){
167                     msg_dialog::display(_("Error"),msgPool::rpcError($this->rpcHandle->get_error()),ERROR_DIALOG);
168                 }
170                 if($res && $this->rpcHandle->success()){
172                     // Include pChart 
173                     new pChartInclude();
175                     // Get most used categories, but only eight at once.
176                     if(count($res['actionsPerCategory'])){
178                         // --------
179                         // Generate PIE chart of most used categories
180                         // --------
182                         arsort($res['actionsPerCategory']);
184                         $mostUsedCategories = array_slice($res['actionsPerCategory'],0,8);
186                         // Dataset definition   
187                         $DataSet = new pData;  
188                         $this->graphID_1 = preg_replace("/[^0-9]/","",microtime(TRUE));
190                         $values = array_values($mostUsedCategories);
192                         $keys = array_keys($mostUsedCategories);
193                         foreach($keys as $id => $cat){
194                             $keys[$id] = $this->getCategoryTranslation($cat);
195                         }
197                         $DataSet->AddPoint($values,"Serie1");  
198                         $DataSet->AddAllSeries();  
199                         $DataSet->AddPoint($keys,"Serie2");  
200                         $DataSet->SetAbsciseLabelSerie("Serie2");  
202                         // Initialise the graph  
203                         $Test = new pChart(500,200);  
204                         $Test->setFontProperties("./themes/default/fonts/LiberationSans-Regular.ttf",10);  
207                         $Test->drawPieGraph($DataSet->GetData(),$DataSet->GetDataDescription(),150,90,110,PIE_PERCENTAGE,TRUE,50,20,5);  
208                         $Test->drawPieLegend(310,15,$DataSet->GetData(),$DataSet->GetDataDescription(),200,255,200);  
210                         $file = '/tmp/graph_'.$this->graphID_1;
211                         $Test->Render($file);
212                         session::set('statistics::graphFile'.$this->graphID_1,$file);
213                     }
215                     // --------
216                     // Generate combined line and car chart of plugin usage, ldap execution time and errors 
217                     // --------
219                     // Generate new and unique graph id
220                     $this->graphID_2 = preg_replace("/[^0-9]/","",microtime(TRUE));
222                     // Prepare transmitted data, sort it by date and collect 
223                     //  transmitted timestamps to be able to print the x-Axis labels.
224                     $dataArray = array();
225                     $dates = array();
226                     $DataSet2 = new pData;  
227                     $max = 1;
228                     $seriesNumber = 0;
229                     foreach($res['actionsPerInterval'] as $category => $entriesPerDate){
231                         // Collect data per category and store used timestamps
232                         foreach($entriesPerDate as $dateStr => $count){
233                             $date = strtotime($dateStr);
234                             $dates[$date]=$date;
236                             // Do not append empty data                            
237                             if(empty($category)) continue;
238                             if($count) $count = ($count);
239                             $dataArray[$category][$date] = $count;
240                         }
241                       
242  
243                         // Do not append empty data 
244                         if(empty($category)) continue;
246                         // Sort results. 
247                         ksort($dataArray[$category]);
249                         // Add results to our data set.
250                         $DataSet2->AddPoint($dataArray[$category], $category);
251                         $DataSet2->SetSerieName($this->getCategoryTranslation($category), $category);
252                         $Test->setLabel($DataSet->GetData(),$DataSet->GetDataDescription(),"Serie1",0,"Daily incomes");  
253                         $DataSet2->AddSerie($category);
254                         $seriesNumber++;
256                         // Detect maximum value, to adjust the Y-Axis
257                         $tmpMax = max($dataArray[$category]);
258                         if($tmpMax > $max) $max = $tmpMax;
259                     }
260                     ksort($dates);
262                     // Prepare date strings for X-Axis, only print a given number of 
263                     //  of labels to keep the axis readable.
264                     $Xam = 5; // Number of labels
265                     $cnt = 0;
266                     $dateSeries = array();
267                     foreach($dates as $stamp){
268                         if((count($dates) <= $Xam) || ($cnt % (floor(count($dates) / $Xam )) == 0)){
269                             $dateSeries[$stamp] = date('d.m.Y',$stamp);
270                         }else{
271                             $dateSeries[$stamp] = ' ';
272                         }
273                         $cnt ++;    
274                     }
276                     $DataSet2->AddPoint($dateSeries, 'date');
277                     $DataSet2->SetAbsciseLabelSerie('date');  
279                     $Test2 = new pChart(800,230);  
280                     $Test2->setFixedScale(0.0001,($max*1.1));  
281                     $Test2->setFontProperties("./themes/default/fonts/LiberationSans-Regular.ttf",10);  
282                     $Test2->setGraphArea(50,30,585,200);  
283                     $Test2->drawFilledRoundedRectangle(7,7,693,223,5,240,240,240);  
284                     $Test2->drawRoundedRectangle(5,5,695,225,5,230,230,230);  
285                     $Test2->drawGraphArea(255,255,255,TRUE);  
286                     $Test2->drawGrid(4,TRUE,200,200,200,50);  
287                     $Test2->drawTreshold(0,143,55,72,TRUE,TRUE);  
288                     $Test2->drawTitle(50,22,"Plugin usage over time",50,50,50,585);  
290                     if(count($dates)){
291                         $Test2->drawScale($DataSet2->GetData(),$DataSet2->GetDataDescription(),SCALE_NORMAL,150,150,150,TRUE,0,2);     
292                     }
294                     // Draw the cubic curve graph  
295                     if(count($dataArray)){
296                         $Test2->drawFilledLineGraph($DataSet2->GetData(),$DataSet2->GetDataDescription(),50,TRUE);
297                     }
299                     // Add error series
300                     $errors = array();
301                     foreach($res['errorsPerInterval'] as $dateStr => $count){
302                         $date = strtotime($dateStr);
303                         if($count !=0) $count = ($count);
304                         $errors[$date] = $count;
305                     }
307                     $DataSet2->AddPoint($errors, 'Errors');
308                     $DataSet2->SetSerieName(_('Error'), 'Errors');
309                     $DataSet2->AddSerie('Errors');
310                     $seriesNumber ++;
311                    
312                     $Test2->setColorPalette($seriesNumber-1,255,0,0);   
314                     // Draw legend
315                     $Test2->drawLegend(650,30,$DataSet2->GetDataDescription(),255,255,255);  
317                     // Remove plugin usage from data series, just keep error series.
318                     foreach($dataArray as $categoryName => $list){
319                         $DataSet2->RemoveSerie($categoryName);
320                     }
321     
322                     // Draw right scale (Errors per day)
323                     $Test2->setFixedScale(0.0001,(max($errors) +1) *1.1);
324                     $Test2->drawRightScale($DataSet2->GetData(),$DataSet2->GetDataDescription(),SCALE_NORMAL,120,150,150,TRUE,0,2);
325                     $Test2->drawBarGraph($DataSet2->GetData(),$DataSet2->GetDataDescription());
327                     $file = '/tmp/graph_'.$this->graphID_2;
328                     $Test2->Render($file);
329                     session::set('statistics::graphFile'.$this->graphID_2,$file);
340                         
341                 
346                     // Prepare Data 
347                     $graphData = array();
348                     foreach($res['usagePerInterval'] as $dateStr => $data){
349                         $date = strtotime($dateStr);
350                         foreach($data as $name => $val){
351                             $graphData[$name][$date] = $val;
352                         }
353                     }
354    
355                     // Sort Data 
356                     foreach($graphData as $key => $data)
357                         ksort($graphData[$key]);
359                     // Generate new and unique graph id
360                     $this->graphID_3 = preg_replace("/[^0-9]/","",microtime(TRUE));
362                     // Prepare transmitted data, sort it by date and collect 
363                     //  transmitted timestamps to be able to print the x-Axis labels.
364                     $DataSet3 = new pData;  
366                     $max = max($graphData['max_mem']);
368                     $DataSet3->AddPoint(array_values($graphData['max_mem']), 'max_mem');
369                     $DataSet3->AddPoint(array_values($graphData['avg_mem']), 'avg_mem');
370                     $DataSet3->AddPoint(array_values($graphData['min_mem']), 'min_mem');
372                     $DataSet3->SetSerieName('Min Memory', 'min_mem');
373                     $DataSet3->SetSerieName('Max Memory', 'max_mem');
374                     $DataSet3->SetSerieName('Average Memory', 'avg_mem');
376                     $DataSet3->AddAllSeries();  
377                     $DataSet3->AddPoint($dateSeries, 'date');
378                     $DataSet3->SetAbsciseLabelSerie('date');
380                     $Test3 = new pChart(800,230);  
381                     $Test3->setFixedScale(0.0001,($max*1.1));  
382                     $Test3->setFontProperties("./themes/default/fonts/LiberationSans-Regular.ttf",10);  
383                     $Test3->setGraphArea(50,30,585,200);  
384                     $Test3->drawFilledRoundedRectangle(7,7,693,223,5,240,240,240);  
385                     $Test3->drawRoundedRectangle(5,5,695,225,5,230,230,230);  
386                     $Test3->drawGraphArea(255,255,255,TRUE);  
387                     $Test3->drawGrid(4,TRUE,200,200,200,50);  
388                     $Test3->drawTreshold(0,143,55,72,TRUE,TRUE);  
389                     $Test3->drawTitle(50,22,"Memory usage",50,50,50,585);  
391                     $Test3->drawScale($DataSet3->GetData(),$DataSet3->GetDataDescription(),SCALE_NORMAL,150,150,150,TRUE,0,2, FALSE);
392                     $Test3->drawFilledCubicCurve($DataSet3->GetData(),$DataSet3->GetDataDescription(),.1,50); 
394                     $file = '/tmp/graph_'.$this->graphID_3;
395                     $Test3->Render($file);
396                     session::set('statistics::graphFile'.$this->graphID_3,$file);
404                     // Generate new and unique graph id
405                     $this->graphID_4 = preg_replace("/[^0-9]/","",microtime(TRUE));
407                     // Prepare transmitted data, sort it by date and collect 
408                     //  transmitted timestamps to be able to print the x-Axis labels.
409                     $DataSet4 = new pData;  
411                     $max = max($graphData['max_dur']);
413                     $DataSet4->AddPoint(array_values($graphData['max_dur']), 'max_dur');
414                     $DataSet4->AddPoint(array_values($graphData['avg_dur']), 'avg_dur');
415                     $DataSet4->AddPoint(array_values($graphData['min_dur']), 'min_dur');
417                     $DataSet4->SetSerieName('Min dur', 'min_dur');
418                     $DataSet4->SetSerieName('Max dur', 'max_dur');
419                     $DataSet4->SetSerieName('Average dur', 'avg_dur');
421                     $DataSet4->AddAllSeries();  
422                     $DataSet4->AddPoint($dateSeries, 'date');
423                     $DataSet4->SetAbsciseLabelSerie('date');
425                     $Test4 = new pChart(800,230);  
426                     $Test4->setFixedScale(0.0001,($max*1.1));  
427                     $Test4->setFontProperties("./themes/default/fonts/LiberationSans-Regular.ttf",10);  
428                     $Test4->setGraphArea(50,30,585,200);  
429                     $Test4->drawFilledRoundedRectangle(7,7,693,223,5,240,240,240);  
430                     $Test4->drawRoundedRectangle(5,5,695,225,5,230,230,230);  
431                     $Test4->drawGraphArea(255,255,255,TRUE);  
432                     $Test4->drawGrid(4,TRUE,200,200,200,50);  
433                     $Test4->drawTreshold(0,143,55,72,TRUE,TRUE);  
434                     $Test4->drawTitle(50,22,"Render time",50,50,50,585);  
436                     $Test4->drawScale($DataSet4->GetData(),$DataSet4->GetDataDescription(),SCALE_NORMAL,150,150,150,TRUE,0,2, FALSE);
437                     $Test4->drawFilledCubicCurve($DataSet4->GetData(),$DataSet4->GetDataDescription(),.1,50); 
439                     $file= '/tmp/graph_'.$this->graphID_4;
440                     $Test4->Render($file);
441                     session::set('statistics::graphFile'.$this->graphID_4,$file);
450                     // Generate new and unique graph id
451                     $this->graphID_5 = preg_replace("/[^0-9]/","",microtime(TRUE));
453                     // Prepare transmitted data, sort it by date and collect 
454                     //  transmitted timestamps to be able to print the x-Axis labels.
455                     $DataSet5 = new pData;  
457                     $max = max($graphData['max_load']);
459                     $DataSet5->AddPoint(array_values($graphData['max_load']), 'max_load');
460                     $DataSet5->AddPoint(array_values($graphData['avg_load']), 'avg_load');
461                     $DataSet5->AddPoint(array_values($graphData['min_load']), 'min_load');
463                     $DataSet5->SetSerieName('Min Load', 'min_load');
464                     $DataSet5->SetSerieName('Max Load', 'max_load');
465                     $DataSet5->SetSerieName('Average Load', 'avg_load');
467                     $DataSet5->AddAllSeries();  
468                     $DataSet5->AddPoint($dateSeries, 'date');
469                     $DataSet5->SetAbsciseLabelSerie('date');
471                     $Test5 = new pChart(800,230);  
472                     $Test5->setFixedScale(0.0001,($max*1.1));  
473                     $Test5->setFontProperties("./themes/default/fonts/LiberationSans-Regular.ttf",10);  
474                     $Test5->setGraphArea(50,30,585,200);  
475                     $Test5->drawFilledRoundedRectangle(7,7,693,223,5,240,240,240);  
476                     $Test5->drawRoundedRectangle(5,5,695,225,5,230,230,230);  
477                     $Test5->drawGraphArea(255,255,255,TRUE);  
478                     $Test5->drawGrid(4,TRUE,200,200,200,50);  
479                     $Test5->drawTreshold(0,143,55,72,TRUE,TRUE);  
480                     $Test5->drawTitle(50,22,"CPU load",50,50,50,585);  
482                     $Test5->drawScale($DataSet5->GetData(),$DataSet5->GetDataDescription(),SCALE_NORMAL,150,150,150,TRUE,0,2, FALSE);
483                     $Test5->drawFilledCubicCurve($DataSet5->GetData(),$DataSet5->GetDataDescription(),.1,50); 
485                     $file = '/tmp/graph_'.$this->graphID_5;
486                     $Test5->Render($file);
487                     session::set('statistics::graphFile'.$this->graphID_5,$file);
489                 }
490             }
491         }
493         $smarty->assign('graphID_1', $this->graphID_1);
494         $smarty->assign('graphID_2', $this->graphID_2);
495         $smarty->assign('graphID_3', $this->graphID_3);
496         $smarty->assign('graphID_4', $this->graphID_4);
497         $smarty->assign('graphID_5', $this->graphID_5);
498         $smarty->assign('unsbmittedFiles', count($this->unsbmittedFiles));
499         $smarty->assign('unsbmittedFilesMsg', 
500                 sprintf(
501                     _("You have currently %s unsubmitted statistic collection, do you want to transmit them now?"),
502                     count($this->unsbmittedFiles)));
503         return($smarty->fetch(get_template_path('statistics.tpl', TRUE)));
504     }
507     function check()
508     {
509         $messages = plugin::check();
510         return($messages);
511     }
514     function save_object()
515     {
516         plugin::save_object();
517     }
520     /*! \brief      This method tries to translate category names.
521      *  @param      The category name to translate
522      *  @return     String  The translated category names.
523      */
524     function getCategoryTranslation($name)
525     {
526         $ret ="";
527         
528         // Extract category names from the given string.
529         $list = preg_split("/, /", $name);
530    
531         // We do not have a category for systems directly, so we've to map all system types to 'System'.
532         // If we do not map to _(Systems) the graph legend will be half screen width.
533         if(count(array_intersect(array('server','terminal','workstation', 'opsi', 'component'), $list))){
534             return(_("Systems"));
535         }
537         // Walk through category names and try to find a translation.
538         foreach($list as $cat){
539             $cat = trim($cat);
540             if(isset($this->catTranslations[$cat])){
541                 $ret .= _($this->catTranslations[$cat]).", ";
542             }else{
543                 $ret .= $cat.", ";
544             }
545         }
546         return(rtrim($ret, ', '));
547     }
549 ?>