]> git.sur5r.net Git - bacula/bacula/blob - gui/bacula-web/bweb.inc.php
4c968212f72186eb9cfecba6e28dc3140543fcfd
[bacula/bacula] / gui / bacula-web / bweb.inc.php
1 <?php
2 /* 
3 +-------------------------------------------------------------------------+
4 | Copyright (C) 2004-2005 Juan Luis Frances Jiminez                       |
5 |                                                                         |
6 | This program is free software; you can redistribute it and/or           |
7 | modify it under the terms of the GNU General Public License             |
8 | as published by the Free Software Foundation; either version 2          |
9 | of the License, or (at your option) any later version.                  |
10 |                                                                         |
11 | This program is distributed in the hope that it will be useful,         |
12 | but WITHOUT ANY WARRANTY; without even the implied warranty of          |
13 | MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the           |
14 | GNU General Public License for more details.                            |
15 +-------------------------------------------------------------------------+ 
16 */
17 // Last Err: 11
18 define('CONFIG_DIR', "configs");
19 define('CONFIG_FILE', "bacula.conf");
20 define('BACULA_TYPE_BYTES_FILES', 1);
21 define('BACULA_TYPE_FILES_JOBID', 2);
22 define('BACULA_TYPE_BYTES_ENDTIME_ALLJOBS', 69);
23
24 require_once "paths.php";
25 require_once "DB.php";                                                                                                                  // Pear DB
26 require_once "config.inc.php";
27 require_once "bgraph.inc.php";
28 require_once($smarty_path."Config_File.class.php");
29
30 if (!function_exists('array_fill')) {                                                                                   // For PHP < 4.2.0 users 
31     require_once('array_fill.func.php');
32 }
33
34 class Bweb extends DB {
35
36     var $StartDate;
37     var $EndDate;
38     var $driver;
39         var $dbs;
40         var $dbs_name;
41         
42         public $db_link;                                                // Database link
43         private $db_dsn;                                                // Data Source Name
44         
45         private $config_file;                                   // Config filename
46         private $config;                                                // Loaded config from bacula.conf
47         private $catalogs = array();                    // Catalog array
48
49     function __construct()
50         {             
51                 $this->catalogs = array();
52                 
53                 // Loading configuration
54                 $this->config_file = getcwd() . '/configs/bacula.conf';
55                 if( !$this->load_config() )
56                         die( "Unable to load configuration");
57                         
58                 //echo "Number of catalog defined " . count($this->catalogs) . "<br />";
59                 
60                 /*
61                 $conf = new Config_File (CONFIG_DIR);
62                 $this->dbs = array();
63
64                 $i = 2;
65                 $sections = $conf->get(CONFIG_FILE,"DATABASE","host");
66                 array_push($this->dbs, "DATABASE");
67
68                 while ( !empty($sections) ) {                
69                         $sections = $conf->get(CONFIG_FILE,"DATABASE".$i,"host");
70                         if ( !empty($sections) )
71                                 array_push($this->dbs,"DATABASE".$i);
72                         $i++;
73                 }
74
75                 if ( $i < 4)
76                         $sec = "DATABASE";
77                 else {
78                         if ( !empty($_POST['sel_database']) ) {
79                                 $_SESSION['DATABASE'] = $_POST['sel_database'];
80                                 $sec = $_POST['sel_database'];
81                         } else {
82                                 if (isset($_SESSION['DATABASE']) )
83                                         $sec = $_SESSION['DATABASE'];
84                                 else
85                                         $sec = "DATABASE";
86                         }
87                 }
88
89         $this->dsn['hostspec'] = $conf->get(CONFIG_FILE,$sec,"host");
90         $this->dsn['username'] = $conf->get(CONFIG_FILE,$sec,"login");
91         $this->dsn['password'] = $conf->get(CONFIG_FILE,$sec,"pass");
92         $this->dsn['database'] = $conf->get(CONFIG_FILE,$sec,"db_name");
93         $this->dsn['phptype']  = $conf->get(CONFIG_FILE,$sec,"db_type");   // mysql, pgsql
94         
95                 if (  $conf->get(CONFIG_FILE,$sec,"db_port") )
96                         $this->dsn[port] = $conf->get(CONFIG_FILE,$sec,"db_port");
97                 */
98                 
99                 // Construct a valid dsn
100         $this->db_dsn['hostspec'] = $this->catalogs[0]["host"];
101         $this->db_dsn['username'] = $this->catalogs[0]["login"];
102                 $this->db_dsn['password'] = $this->catalogs[0]["pass"];
103                 $this->db_dsn['database'] = $this->catalogs[0]["db_name"];
104                 $this->db_dsn['phptype']  = $this->catalogs[0]["db_type"];
105                 
106                                         
107         $this->db_link = $this->connect($this->db_dsn);
108         
109                 if (DB::isError($this->db_link)) {
110                         die($this->db_link->getMessage());
111                 }else {
112                         $this->driver = $this->db_dsn['phptype'];                            
113             register_shutdown_function(array(&$this,'close'));
114                         $this->dbs_name = $this->db_dsn['database'];
115                 }
116         }
117                 
118     function load_config()
119         {
120                 $this->config = parse_ini_file( $this->config_file, true );
121                 
122                 if( !$this->config == false ) {
123                         // Loading database connection information
124                         foreach( $this->config as $parameter => $value )
125                         {
126                                 //echo "Param $parameter = $value <br />";
127                                 if( is_array($value) ){         // Parsing database section
128                                         array_push( $this->catalogs, $value );
129                                 }
130                         }
131                         return true;
132                 }else
133                         return false;
134         }
135         
136         public function get_config_param( $param )
137         {
138                 if( isset( $this->config[$param] ) )
139                         return $this->config[$param];
140                 else
141                         return false;
142         }
143         
144         public function Get_Nb_Catalogs() 
145         {
146                 return count( $this->catalogs );
147         }
148         
149         
150         function close() 
151         {
152                 $this->db_link->disconnect();
153     }      
154
155         
156          
157         function CalculateBytesPeriod($server,$StartDate,$EndPeriod) {   // Bytes transferred in a period.
158
159                 $result =& $this->db_link->query("select SUM(JobBytes) from Job WHERE EndTime < '$EndPeriod' and EndTime > '$StartDate' and Name='$server'")
160                         or die("classes.inc: Error query: 1");
161                 $return =& $result->fetchRow(); 
162                 return $return[0];
163         }//end function
164
165         
166          
167         function CalculateFilesPeriod($server,$StartDate,$EndPeriod) {    // Number of files transferred in a period.
168
169                 $result =& $this->db_link->query("select SUM(JobFiles) from Job WHERE EndTime < '$EndPeriod' and EndTime > '$StartDate' and Name='$server'")
170                         or die("classes.inc: Error query: 2");
171                 $return =& $result->fetchRow();
172                 return $return[0];
173         }//end function 
174
175                  
176
177         function PrepareDate($StartDateMonth,$StartDateDay,$StartDateYear,$EndDateMonth,$EndDateDay,$EndDateYear) {  // Convert date for Smarty. Check if only works with Mysql.
178         
179                 $this->StartDate=$StartDateYear."-".$StartDateMonth."-".$StartDateDay." 00:00:00";
180                 $this->EndDate=$EndDateYear."-".$EndDateMonth."-".$EndDateDay." 23:59:59";  // last day full
181                 
182         }//end function
183  
184                 function human_file_size( $size, $decimal = 2 )
185                 {
186                         $unit_id = 0;
187                         $lisible = false;
188                         $units = array('B','KB','MB','GB','TB');
189                         $hsize = $size;
190                                 
191                         while( !$lisible ) {
192                                 if ( $hsize >= 1024 ) {
193                                         $hsize    = $hsize / 1024;
194                                         $unit_id += 1;
195                                 } 
196                                 else {
197                                         $lisible = true;
198                                 } 
199                         } 
200                         // Format human size
201                         $hsize = sprintf("%." . $decimal . "f", $hsize);
202                         return $hsize . ' ' . $units[$unit_id];
203                 } // end function
204
205                 
206                 function GetDbSize() 
207                 {
208                         $database_size = 0;
209                         if ( $this->driver == "mysql") {
210                                 $dbsize = $this->db_link->query("show table status") or die ("classes.inc: Error query: 3");
211                                 
212                                 if ( $dbsize->numRows() ) {
213                                         while ( $res = $dbsize->fetchRow(DB_FETCHMODE_ASSOC) )
214                                                 $database_size += $res["Data_length"];
215                 } else {
216                                         return 0;
217                                 } // end if else
218             } // end if
219             else if ( $this->driver == "pgsql") {
220                                 $dbsize = $this->db_link->query("select pg_database_size('$this->dbs_name')") or die ("classes.inc: Error query: 4");
221                                 
222                                 if (PEAR::isError($dbsize))
223                                         die($dbsize->getMessage());
224                     
225                                 if ( $dbsize->numRows() ) {
226                                         while ( $res = $dbsize->fetchRow() )
227                                                 $database_size += $res[0];
228                 } else {
229                                         return 0;
230                                 }
231             } // end if       
232                                 
233                         $dbsize->free();
234                 
235                         return $this->human_file_size( $database_size );  
236         } // end function GetDbSize()
237                 
238                 public function Get_Nb_Clients()
239                 {
240                         $clients = $this->db_link->query("SELECT COUNT(*) AS nb_client FROM Client");
241                         if( PEAR::isError($clients) )
242                                 die( "Unable to get client number" );
243                         else
244                                 return $clients->fetchRow( DB_FETCHMODE_ASSOC );
245                 }
246
247                 // Return an array of volumes ordered by poolid and volume name
248                 function GetVolumeList() {
249
250                 $volumes   = array();
251                 $query     = "";
252                                 $debug     = false;
253                                 
254                                 // Get the list of pools id
255                                 $query = "SELECT Pool.poolid, Pool.name FROM Pool ORDER BY Pool.poolid";
256                                 
257                                 $this->db_link->setFetchMode(DB_FETCHMODE_ASSOC);
258                                 $pools = $this->db_link->query( $query );
259                                 
260                                 if( PEAR::isError( $pools ) )
261                                         die("Error: Failed to get pool list <br />SQL Query: $query<br />" . $pools->getMessage() );
262                                 
263                                 while( $pool = $pools->fetchRow() ) {
264                                         switch( $this->driver )
265                                         {
266                                                 case 'mysql':
267 /*
268                                                         $query  = "SELECT Media.VolumeName, Media.VolBytes, Media.VolStatus, Pool.Name, Media.MediaType,Media.LastWritten, FROM_UNIXTIME(UNIX_TIMESTAMP(Media.LastWritten)+Media.VolRetention ) AS expire 
269                                                                            FROM Pool LEFT JOIN Media ON Media.PoolId=Pool.PoolId WHERE poolid='$pool[0]' 
270                                                                            ORDER BY Media.VolumeName";
271 */
272                                                         $query  = "SELECT Media.volumename, Media.volbytes, Media.volstatus, Media.mediatype, Media.lastwritten, Media.volretention
273                                                                            FROM Media LEFT JOIN Pool ON Media.poolid = Pool.poolid
274                                                                        WHERE Media.poolid = '". $pool['poolid'] . "' ORDER BY Media.volumename";
275                                                 break;
276                                                 case 'pgsql':
277                                                         $query  = "SELECT media.volumename, media.volbytes, media.volstatus, media.mediatype, media.lastwritten, media.volretention
278                                                                            FROM media LEFT JOIN pool ON media.poolid = pool.poolid
279                                                                        WHERE media.poolid = '". $pool['poolid'] . "' ORDER BY media.volumename";
280                                                         /*
281                                                         $query  = "SELECT Media.VolumeName, Media.VolBytes,Media.VolStatus,Pool.Name,Media.MediaType,Media.LastWritten, Media.LastWritten + Media.VolRetention * interval '1 second' AS expire 
282                                                                            FROM Pool LEFT JOIN Media ON media.poolid=pool.poolid WHERE poolid='$pool[0]' 
283                                                                            ORDER BY Media.VolumeName";
284                                                         */
285                                                 break;
286                                                 case 'sqlite':
287                                                         $query  = "";           // not yet implemented
288                                                 break;
289                                                 default:
290                                                 break;
291                                         } // end switch
292                                         
293                                         $this->db_link->setFetchMode(DB_FETCHMODE_ASSOC);
294                                         $medias = $this->db_link->query( $query );
295
296                                         if( PEAR::isError( $medias ) ) {
297                                                 die( "Failed to get media list for pool $volume[0] <br /> " . $medias->getMessage() );
298                                         }else {
299                                                 if( $debug ) echo "Found " . $medias->numRows() . " medias for pool " . $pool['name'] . " <br />";
300                                         
301                                                 // Create array key for each pool
302                                                 if( !array_key_exists( $pool['name'], $volumes) )
303                                                 {
304                                                         $volumes[ $pool['name'] ] = array();
305                                                 }
306                                                 while( $media = $medias->fetchRow() ) {
307                                                         if( $debug ) {
308                                                                 var_dump( $media );
309                                                         }
310                                                         // If the pool is empty (no volumes in this pool)
311                                                         if( $medias->numRows() == 0 ) {
312                                                                 if( $debug ) echo "No media in pool " . $pool['name'] . "<br />";
313                                                         } else {
314                                                                         if( $media['lastwritten'] != "0000-00-00 00:00:00" ) {
315                                                                                 // Calculate expiration date if the volume is Full
316                                                                                 if( $media['volstatus'] == 'Full' ) {
317                                                                                         $expire_date     = strtotime($media['lastwritten']) + $media['volretention'];
318                                                                                         $media['expire'] = strftime("%Y-%m-%d", $expire_date);
319                                                                                 }else {
320                                                                                         $media['expire'] = 'N/A';
321                                                                                 }
322                                                                                 // Media used bytes in a human format
323                                                                                 $media['volbytes'] = $this->human_file_size( $media['volbytes'] );
324                                                                                 //echo "volume " . $media['volumename'] . 'vol bytes' .$media['volbytes'] . '<br />';
325                                                                         } else {
326                                                                                 $media['lastwritten'] = "N/A";
327                                                                                 $media['expire']      = "N/A";
328                                                                                 $media['volbytes']        = "0 KB";
329                                                                         }                                                               
330                                                                 // Add the media in pool array
331                                                                 array_push( $volumes[ $pool['name']], $media);
332                                                         }
333                                                 } // end while
334                                         } // end if else
335                                 } // end while
336                                 return $volumes;
337         } // end function GetVolumeList()
338                 
339                 public function GetLastJobs( $delay = LAST_DAY )
340                 {
341                         $query          = "";
342                         $start_date = "";
343                         $end_date       = "";
344                         
345                         // Interval calculation
346                         $end_date   = mktime();
347                         $start_date = $end_date - $delay;
348                         
349                         $start_date = date( "Y-m-d H:m:s", $start_date );
350                         $end_date   = date( "Y-m-d H:m:s", $end_date );
351                         
352                         switch( $this->driver )
353                         {
354                                 case 'mysql':
355                                         $query  = 'SELECT COUNT(JobId) AS completed_jobs ';
356                                         $query .= 'FROM Job ';
357                                         $query .= "WHERE EndTime BETWEEN '$start_date' AND '$end_date' ";
358                                         $query .= "AND JobStatus = 'T'";
359                                 break;
360                         }
361                 
362                         $jobs = $this->db_link->query( $query );
363                 
364                         if (PEAR::isError( $jobs ) ) {
365                                 die( "Unable to get last completed jobs status from catalog<br />" . $status->getMessage() );
366                         }else {
367                                 return $jobs->fetchRow();
368                         }
369                 } // end function GetLastJobStatus()
370                 
371                 public function GetLastErrorJobs( $delay = LAST_DAY )
372                 {
373                         $query          = "";
374                         
375                         // Interval calculation
376                         $end_date   = mktime();
377                         $start_date = $end_date - $delay;
378                         
379                         $start_date = date( "Y-m-d H:m:s", $start_date );
380                         $end_date   = date( "Y-m-d H:m:s", $end_date );
381                         
382                         //echo "start date: $start_date <br />";
383                         //echo "end date: $end_date <br />";
384                         
385                         switch( $this->driver )
386                         {
387                                 default:
388                                         $query  = 'SELECT COUNT(JobId) AS failed_jobs ';
389                                         $query .= 'FROM Job ';
390                                         $query .= "WHERE EndTime BETWEEN '$start_date' AND '$end_date' ";
391                                         $query .= "AND JobStatus = 'f'";
392                                 break;
393                         }                               
394                         $result = $this->db_link->query( $query );
395                         
396                         if (PEAR::isError( $result ) ) {
397                                 die( "Unable to get last failed jobs status from catalog<br />query = $query <br />" . $result->getMessage() );
398                         }else {
399                                 return $result->fetchRow( DB_FETCHMODE_ASSOC );
400                         } // end if else
401                 } // end function GetLastErrorJobs
402                 
403                 // Return the list of Pools in a array
404                 public function Get_Pools_List()
405                 {
406                         $pool_list = array();
407                         $result    = "";
408                         
409                         $query = "SELECT Name, PoolId FROM Pool";
410                         
411                         $result = $this->db_link->query ( $query );
412         
413                         if( PEAR::isError( $result ) ) {
414                                 die( "Unable to get the pool list from catalog" );                              
415                         }else {
416                                 while( $pool = $result->fetchRow(DB_FETCHMODE_ASSOC) ) {
417                                         array_push( $pool_list, array( $pool['Name'] => $pool['PoolId'] ) );
418                                 }
419                                 return $pool_list;
420                         }
421                 }
422                 
423                 public function Get_BackupJob_Names()
424                 {
425                         $query          = "SELECT Name FROM Job GROUP BY Name";
426                         $backupjobs = array();
427                         
428                         $result = $this->db_link->query( $query );
429                         
430                         if (PEAR::isError( $result ) ) {
431                                 die("Unable to get BackupJobs list from catalog" );
432                         }else{
433                                 while( $backupjob = $result->fetchRow( DB_FETCHMODE_ASSOC ) ) {
434                                         array_push( $backupjobs, $backupjob["Name"] );
435                                 }
436                                 return $backupjobs;
437                         }
438                 }
439                 
440                 public function Get_ElapsedTime_Job( $delay = LAST_DAY )
441                 {
442                         $query                  = "";
443                         $total_elapsed  = 0;
444                         
445                         // Interval calculation
446                         $end_date   = mktime();
447                         $start_date = $end_date - $delay;
448                         
449                         $start_date = date( "Y-m-d H:m:s", $start_date );
450                         $end_date   = date( "Y-m-d H:m:s", $end_date );
451                         
452                         switch( $this->driver )
453                         {
454                                 case 'mysql':
455                                         $query  = "SELECT UNIX_TIMESTAMP(EndTime) - UNIX_TIMESTAMP(StartTime) AS elapsed from Job ";
456                                         $query .= "WHERE EndTime BETWEEN '$start_date' AND '$end_date'";
457                                 break;
458                         }
459                         $result = $this->db_link->query( $query );
460                         
461                         if( PEAR::isError($result) ){
462                                 die( "Unable to get elapsed time for jobs from catalog<br />query = $query <br />" . $result->getMessage() );
463                         }else {
464                                 while( $time = $result->fetchRow( DB_FETCHMODE_ASSOC ) ) {
465                                         //echo 'elapsed = ' . $time['elapsed'] . '<br />';
466                                         $total_elapsed += $time['elapsed'];
467                                 }
468                                 // Verify if elapsed time is more than 1 day
469                                 if ( $total_elapsed > 86400 ) {
470                                         return gmstrftime("%d days %H:%M:%S", $total_elapsed );
471                                 }else {
472                                         return gmstrftime("%H:%M:%S", $total_elapsed );
473                                 }
474                         }
475                 }
476                 
477                 // Return Jobs statistics for a specific interval such as
478                 // - Completed jobs number
479                 // - Failed jobs number
480                 // - Waiting jobs number
481                 // The returned values will be used by a Bgraph classe
482                 public function GetJobsStatistics( $type = 'completed', $delay = LAST_DAY )
483                 {
484                         $query  = "";
485                         $where  = "";
486                         $jobs   = "";
487                         $label  = "";
488                         $res    = "";
489                         
490                         // Interval calculation
491                         $end_date   = mktime();
492                         $start_date = $end_date - $delay;
493                         
494                         $start_date = date( "Y-m-d H:m:s", $start_date );
495                         $end_date   = date( "Y-m-d H:m:s", $end_date );
496                         
497                         // Job status
498                         switch( $type )
499                         {
500                                 case 'completed':
501                                         $where = "AND JobStatus = 'T' ";
502                                         $label = "Completed";
503                                 break;
504                                 case 'completed_errors':
505                                         $where = "AND JobStatus = 'E' ";
506                                         $label = "Completed with errors";
507                                 break;
508                                 case 'failed':
509                                         $where = "AND JobStatus = 'f' ";
510                                         $label = "Failed";
511                                 break;
512                                 case 'waiting':
513                                         $where = "AND JobStatus IN ('F','S','M','m','s','j','c','d','t') ";
514                                         $label = "Waiting";
515                                 break;
516                                 case 'created':
517                                         $where = "AND JobStatus = 'C' ";
518                                         $label = "Created but not running";
519                                 break;
520                                 case 'running':
521                                         $where = "AND JobStatus = 'R' ";
522                                         $label = "Running";
523                                 break;
524                                 case 'error':
525                                         $where = "AND JobStatus IN ('e','f') ";
526                                         $label = "Errors";
527                                 break;
528                         }
529                         
530                         $query  = 'SELECT COUNT(JobId) AS ' . $type . ' ';
531                         $query .= 'FROM Job ';
532                         $query .= "WHERE EndTime BETWEEN '$start_date' AND '$end_date' ";
533                         $query .= $where;
534                 
535                         $jobs = $this->db_link->query( $query );
536                 
537                         if (PEAR::isError( $jobs ) ) {
538                                 die( "Unable to get last $type jobs status from catalog<br />" . $status->getMessage() );
539                         }else {
540                                 $res = $jobs->fetchRow();
541                                 return array( $label , current($res) );
542                         }
543                 } // end function GetJobsStatistics()
544                 
545                 public function GetPoolsStatistics( $pools )
546                 {
547                         foreach( $pools as $pool_name => $pool ) {
548                                 //var_dump( $pool );
549                                 $query = "SELECT COUNT(*) AS nb_vol FROM Media WHERE PoolId = '$pool'";
550                                 //echo $query . '<br />';
551                                 //echo 'Pool name ' . $pool_name . '<br />';
552                                 $result = $this->db_link->query( $query );
553                                 
554                                 if( PEAR::isError( $result ) ) {
555                                         die("Unable to get volume number from catalog");
556                                 }else{
557                                         $nb_vol = $result->fetchRow();
558                                         return array( $pool_name, $nb_vol['nb_vol'] );
559                                 }
560                         }
561                 }
562                 
563 } // end class Bweb
564 ?>