]> git.sur5r.net Git - bacula/bacula/blob - gui/bacula-web/bweb.inc.php
2d329d5fd79ad4380c2d466318d3509e58a872da
[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 GetDataVolumes() {
185
186                 $volume = array();
187                 $res = $this->db_link->query("SELECT Name FROM Pool");
188                 while ( $tmp =& $res->fetchRow() ) {
189                         if ($this->driver == "mysql" )
190                                 $result = $this->db_link->query("select Media.VolumeName, Media.VolBytes,Media.VolStatus,Pool.Name,Media.MediaType,Media.LastWritten,FROM_UNIXTIME(UNIX_TIMESTAMP(Media.LastWritten)+Media.VolRetention ) as expire from Pool LEFT JOIN Media ON Media.PoolId=Pool.PoolId where Name='$tmp[0]' order by Media.VolumeName");
191                         else if ($this->driver == "pgsql")
192                                 $result = $this->db_link->db_query("select Media.VolumeName, Media.VolBytes,Media.VolStatus,Pool.Name,Media.MediaType,Media.LastWritten, Media.LastWritten + Media.VolRetention * interval '1 second' as expire from Pool LEFT JOIN Media ON Media.PoolId=Pool.PoolId where Name='$tmp[0]' order by Media.VolumeName");
193                         while ( $tmp1 = $result->fetchRow() ) {
194                                 $pos = array_key_exists($tmp[0],$volume);
195                                 if ($pos != FALSE)
196                                         array_push($volume["$tmp[0]"],$tmp1);
197                                 else
198                                         $volume += array($tmp[0]=>array($tmp1));
199                         }
200                 }
201                 
202                 $res->free();
203                 $result->free();
204                 return $volume;
205         }
206         
207                 function human_file_size( $size, $decimal = 2 )
208                 {
209                         $unit_id = 0;
210                         $lisible = false;
211                         $units = array('B','KB','MB','GB','TB');
212                         $hsize = $size;
213                                 
214                         while( !$lisible ) {
215                                 if ( $hsize >= 1024 ) {
216                                         $hsize    = $hsize / 1024;
217                                         $unit_id += 1;
218                                 } 
219                                 else {
220                                         $lisible = true;
221                                 } 
222                         } 
223                         // Format human size
224                         $hsize = sprintf("%." . $decimal . "f", $hsize);
225                         return $hsize . ' ' . $units[$unit_id];
226                 } // end function
227
228                 
229                 function GetDbSize() 
230                 {
231                         $database_size = 0;
232                         if ( $this->driver == "mysql") {
233                                 $dbsize = $this->db_link->query("show table status") or die ("classes.inc: Error query: 3");
234                                 
235                                 if ( $dbsize->numRows() ) {
236                                         while ( $res = $dbsize->fetchRow(DB_FETCHMODE_ASSOC) )
237                                                 $database_size += $res["Data_length"];
238                 } else {
239                                         return 0;
240                                 } // end if else
241             } // end if
242             else if ( $this->driver == "pgsql") {
243                                 $dbsize = $this->db_link->query("select pg_database_size('$this->dbs_name')") or die ("classes.inc: Error query: 4");
244                                 
245                                 if (PEAR::isError($dbsize))
246                                         die($dbsize->getMessage());
247                     
248                                 if ( $dbsize->numRows() ) {
249                                         while ( $res = $dbsize->fetchRow() )
250                                                 $database_size += $res[0];
251                 } else {
252                                         return 0;
253                                 }
254             } // end if       
255                                 
256                         $dbsize->free();
257                 
258                         return $this->human_file_size( $database_size );  
259         } // end function GetDbSize()
260                 
261                 public function Get_Nb_Clients()
262                 {
263                         $clients = $this->db_link->query("SELECT COUNT(*) AS nb_client FROM Client");
264                         if( PEAR::isError($clients) )
265                                 die( "Unable to get client number" );
266                         else
267                                 return $clients->fetchRow( DB_FETCHMODE_ASSOC );
268                 }
269
270                 // Return an array of volumes ordered by poolid and volume name
271                 function GetVolumeList() {
272
273                 $volumes   = array();
274                 $query     = "";
275                                 $debug     = false;
276                                 
277                                 // Get the list of pools id
278                                 $query = "SELECT Pool.poolid, Pool.name FROM Pool ORDER BY Pool.poolid";
279                                 
280                                 $this->db_link->setFetchMode(DB_FETCHMODE_ASSOC);
281                                 $pools = $this->db_link->query( $query );
282                                 
283                                 if( PEAR::isError( $pools ) )
284                                         die("Error: Failed to get pool list <br />SQL Query: $query<br />" . $pools->getMessage() );
285                                 
286                                 while( $pool = $pools->fetchRow() ) {
287                                         switch( $this->driver )
288                                         {
289                                                 case 'mysql':
290 /*
291                                                         $query  = "SELECT Media.VolumeName, Media.VolBytes, Media.VolStatus, Pool.Name, Media.MediaType,Media.LastWritten, FROM_UNIXTIME(UNIX_TIMESTAMP(Media.LastWritten)+Media.VolRetention ) AS expire 
292                                                                            FROM Pool LEFT JOIN Media ON Media.PoolId=Pool.PoolId WHERE poolid='$pool[0]' 
293                                                                            ORDER BY Media.VolumeName";
294 */
295                                                         $query  = "SELECT Media.volumename, Media.volbytes, Media.volstatus, Media.mediatype, Media.lastwritten, Media.volretention
296                                                                            FROM Media LEFT JOIN Pool ON Media.poolid = Pool.poolid
297                                                                        WHERE Media.poolid = '". $pool['poolid'] . "' ORDER BY Media.volumename";
298                                                 break;
299                                                 case 'pgsql':
300                                                         $query  = "SELECT media.volumename, media.volbytes, media.volstatus, media.mediatype, media.lastwritten, media.volretention
301                                                                            FROM media LEFT JOIN pool ON media.poolid = pool.poolid
302                                                                        WHERE media.poolid = '". $pool['poolid'] . "' ORDER BY media.volumename";
303                                                         /*
304                                                         $query  = "SELECT Media.VolumeName, Media.VolBytes,Media.VolStatus,Pool.Name,Media.MediaType,Media.LastWritten, Media.LastWritten + Media.VolRetention * interval '1 second' AS expire 
305                                                                            FROM Pool LEFT JOIN Media ON media.poolid=pool.poolid WHERE poolid='$pool[0]' 
306                                                                            ORDER BY Media.VolumeName";
307                                                         */
308                                                 break;
309                                                 case 'sqlite':
310                                                         $query  = "";           // not yet implemented
311                                                 break;
312                                                 default:
313                                                 break;
314                                         } // end switch
315                                         
316                                         $this->db_link->setFetchMode(DB_FETCHMODE_ASSOC);
317                                         $medias = $this->db_link->query( $query );
318
319                                         if( PEAR::isError( $medias ) ) {
320                                                 die( "Failed to get media list for pool $volume[0] <br /> " . $medias->getMessage() );
321                                         }else {
322                                                 if( $debug ) echo "Found " . $medias->numRows() . " medias for pool " . $pool['name'] . " <br />";
323                                         
324                                                 // Create array key for each pool
325                                                 if( !array_key_exists( $pool['name'], $volumes) )
326                                                 {
327                                                         $volumes[ $pool['name'] ] = array();
328                                                 }
329                                                 while( $media = $medias->fetchRow() ) {
330                                                         if( $debug ) {
331                                                                 var_dump( $media );
332                                                         }
333
334                                                         if( $medias->numRows() == 0 ) {
335                                                                 if( $debug ) echo "No media in pool " . $pool['name'] . "<br />";
336                                                         } else {
337                                                                         if( ($media['lastwritten'] != "0000-00-00 00:00:00") && $media['volstatus'] == 'Full' ) {
338                                                                                 // Calculate expiration date
339                                                                                 $expire_date     = strtotime($media['lastwritten']) + $media['volretention'];
340                                                                                 $media['expire'] = strftime("%Y-%m-%d", $expire_date);
341                                                                                 
342                                                                                 // Media used size in a more readable format
343                                                                                 $media['volbytes'] = $this->human_file_size( $media['volbytes'] );
344                                                                         } else {
345                                                                                 $media['lastwritten'] = "N/A";
346                                                                                 $media['expire']      = "N/A";
347                                                                                 $media['volbytes']        = "0 KB";
348                                                                         }                                                               
349                                                                 // Add the media in pool array
350                                                                 array_push( $volumes[ $pool['name']], $media);
351                                                         }
352                                                 } // end while
353                                         } // end if else
354                                 } // end while
355                                 return $volumes;
356         } // end function GetVolumeList()
357                 
358                 public function GetLastJobs( $delay = LAST_DAY )
359                 {
360                         $query          = "";
361                         $start_date = "";
362                         $end_date       = "";
363                         
364                         // Interval calculation
365                         $end_date   = mktime();
366                         $start_date = $end_date - $delay;
367                         
368                         $start_date = date( "Y-m-d H:m:s", $start_date );
369                         $end_date   = date( "Y-m-d H:m:s", $end_date );
370                         
371                         switch( $this->driver )
372                         {
373                                 case 'mysql':
374                                         $query  = 'SELECT COUNT(JobId) AS completed_jobs ';
375                                         $query .= 'FROM Job ';
376                                         $query .= "WHERE EndTime BETWEEN '$start_date' AND '$end_date' ";
377                                         $query .= "AND JobStatus = 'T'";
378                                 break;
379                         }
380                 
381                         $jobs = $this->db_link->query( $query );
382                 
383                         if (PEAR::isError( $jobs ) ) {
384                                 die( "Unable to get last completed jobs status from catalog<br />" . $status->getMessage() );
385                         }else {
386                                 return $jobs->fetchRow();
387                         }
388                 } // end function GetLastJobStatus()
389                 
390                 public function GetLastErrorJobs( $delay = LAST_DAY )
391                 {
392                         $query          = "";
393                         $start_date = "";
394                         $end_date       = "";
395                         
396                         // Interval calculation
397                         $end_date   = mktime();
398                         $start_date = $end_date - $delay;
399                         
400                         $start_date = date( "Y-m-d H:m:s", $start_date );
401                         $end_date   = date( "Y-m-d H:m:s", $end_date );
402                         
403                         //echo "start date: $start_date <br />";
404                         //echo "end date: $end_date <br />";
405                         
406                         switch( $this->driver )
407                         {
408                                 default:
409                                         $query  = 'SELECT COUNT(JobId) AS failed_jobs ';
410                                         $query .= 'FROM Job ';
411                                         $query .= "WHERE EndTime BETWEEN '$start_date' AND '$end_date' ";
412                                         $query .= "AND JobStatus = 'f'";
413                                 break;
414                         }                               
415                         $result = $this->db_link->query( $query );
416                         
417                         if (PEAR::isError( $result ) ) {
418                                 die( "Unable to get last failed jobs status from catalog<br />query = $query <br />" . $result->getMessage() );
419                         }else {
420                                 return $result->fetchRow( DB_FETCHMODE_ASSOC );
421                         } // end if else
422                 } // end function GetLastErrorJobs
423                 
424                 public function Get_BackupJob_Names()
425                 {
426                         $query          = "SELECT Name FROM Job GROUP BY Name";
427                         $backupjobs = array();
428                         
429                         $result = $this->db_link->query( $query );
430                         
431                         if (PEAR::isError( $result ) ) {
432                                 die("Unable to get BackupJobs list from catalog" );
433                         }else{
434                                 while( $backupjob = $result->fetchRow( DB_FETCHMODE_ASSOC ) ) {
435                                         array_push( $backupjobs, $backupjob["Name"] );
436                                 }
437                                 return $backupjobs;
438                         }
439                 }
440                 
441                 public function Get_ElapsedTime_Job( $delay = LAST_DAY )
442                 {
443                         $query                  = "";
444                         $total_elapsed  = 0;
445                         
446                         // Interval calculation
447                         $end_date   = mktime();
448                         $start_date = $end_date - $delay;
449                         
450                         $start_date = date( "Y-m-d H:m:s", $start_date );
451                         $end_date   = date( "Y-m-d H:m:s", $end_date );
452                         
453                         switch( $this->driver )
454                         {
455                                 case 'mysql':
456                                         $query  = "SELECT UNIX_TIMESTAMP(EndTime) - UNIX_TIMESTAMP(StartTime) AS elapsed from Job ";
457                                         $query .= "WHERE EndTime BETWEEN '$start_date' AND '$end_date'";
458                                 break;
459                         }
460                         $result = $this->db_link->query( $query );
461                         
462                         if( PEAR::isError($result) ){
463                                 die( "Unable to get elapsed time for jobs from catalog<br />query = $query <br />" . $result->getMessage() );
464                         }else {
465                                 while( $time = $result->fetchRow( DB_FETCHMODE_ASSOC ) ) {
466                                         //echo 'elapsed = ' . $time['elapsed'] . '<br />';
467                                         $total_elapsed += $time['elapsed'];
468                                 }
469                                 // Verify if elapsed time is more than 1 day
470                                 if ( $total_elapsed > 86400 ) {
471                                         return gmstrftime("%d days %H:%M:%S", $total_elapsed );
472                                 }else {
473                                         return gmstrftime("%H:%M:%S", $total_elapsed );
474                                 }
475                         }
476                 }
477                         
478                 
479 } // end class Bweb
480 ?>