3 +-------------------------------------------------------------------------+
4 | Copyright (C) 2004-2005 Juan Luis Frances Jiminez |
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. |
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 +-------------------------------------------------------------------------+
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);
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");
30 if (!function_exists('array_fill')) { // For PHP < 4.2.0 users
31 require_once('array_fill.func.php');
34 class Bweb extends DB {
42 public $db_link; // Database link
43 private $db_dsn; // Data Source Name
45 private $config_file; // Config filename
46 private $config; // Loaded config from bacula.conf
47 private $catalogs = array(); // Catalog array
49 function __construct()
51 $this->catalogs = array();
53 // Loading configuration
54 $this->config_file = getcwd() . '/configs/bacula.conf';
55 if( !$this->load_config() )
56 die( "Unable to load configuration");
58 //echo "Number of catalog defined " . count($this->catalogs) . "<br />";
61 $conf = new Config_File (CONFIG_DIR);
65 $sections = $conf->get(CONFIG_FILE,"DATABASE","host");
66 array_push($this->dbs, "DATABASE");
68 while ( !empty($sections) ) {
69 $sections = $conf->get(CONFIG_FILE,"DATABASE".$i,"host");
70 if ( !empty($sections) )
71 array_push($this->dbs,"DATABASE".$i);
78 if ( !empty($_POST['sel_database']) ) {
79 $_SESSION['DATABASE'] = $_POST['sel_database'];
80 $sec = $_POST['sel_database'];
82 if (isset($_SESSION['DATABASE']) )
83 $sec = $_SESSION['DATABASE'];
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
95 if ( $conf->get(CONFIG_FILE,$sec,"db_port") )
96 $this->dsn[port] = $conf->get(CONFIG_FILE,$sec,"db_port");
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"];
107 $this->db_link = $this->connect($this->db_dsn);
109 if (DB::isError($this->db_link)) {
110 die($this->db_link->getMessage());
112 $this->driver = $this->db_dsn['phptype'];
113 register_shutdown_function(array(&$this,'close'));
114 $this->dbs_name = $this->db_dsn['database'];
118 function load_config()
120 $this->config = parse_ini_file( $this->config_file, true );
122 if( !$this->config == false ) {
123 // Loading database connection information
124 foreach( $this->config as $parameter => $value )
126 //echo "Param $parameter = $value <br />";
127 if( is_array($value) ){ // Parsing database section
128 array_push( $this->catalogs, $value );
136 public function get_config_param( $param )
138 if( isset( $this->config[$param] ) )
139 return $this->config[$param];
144 public function Get_Nb_Catalogs()
146 return count( $this->catalogs );
152 $this->db_link->disconnect();
157 function CalculateBytesPeriod($server,$StartDate,$EndPeriod) { // Bytes transferred in a period.
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();
167 function CalculateFilesPeriod($server,$StartDate,$EndPeriod) { // Number of files transferred in a period.
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();
177 function PrepareDate($StartDateMonth,$StartDateDay,$StartDateYear,$EndDateMonth,$EndDateDay,$EndDateYear) { // Convert date for Smarty. Check if only works with Mysql.
179 $this->StartDate=$StartDateYear."-".$StartDateMonth."-".$StartDateDay." 00:00:00";
180 $this->EndDate=$EndDateYear."-".$EndDateMonth."-".$EndDateDay." 23:59:59"; // last day full
184 // Return humanized size with default unit of GB
185 // if auto provide for unit argument, automaticaly decide which unit
186 function human_file_size( $size, $decimal = 2, $unit = 'auto' )
190 $units = array('B','KB','MB','GB','TB');
197 if ( $hsize >= 1024 ) {
198 $hsize = $hsize / 1024;
208 $p = array_search( $unit, $units);
209 $hsize = $hsize / pow(1024,$p);
213 $hsize = sprintf("%." . $decimal . "f", $hsize);
214 $hsize = $hsize . ' ' . $units[$unit_id];
222 if ( $this->driver == "mysql") {
223 $dbsize = $this->db_link->query("show table status") or die ("classes.inc: Error query: 3");
225 if ( $dbsize->numRows() ) {
226 while ( $res = $dbsize->fetchRow(DB_FETCHMODE_ASSOC) )
227 $database_size += $res["Data_length"];
232 else if ( $this->driver == "pgsql") {
233 $dbsize = $this->db_link->query("select pg_database_size('$this->dbs_name')") or die ("classes.inc: Error query: 4");
235 if (PEAR::isError($dbsize))
236 die($dbsize->getMessage());
238 if ( $dbsize->numRows() ) {
239 while ( $res = $dbsize->fetchRow() )
240 $database_size += $res[0];
248 return $this->human_file_size( $database_size );
249 } // end function GetDbSize()
251 public function Get_Nb_Clients()
253 $clients = $this->db_link->query("SELECT COUNT(*) AS nb_client FROM Client");
254 if( PEAR::isError($clients) )
255 die( "Unable to get client number" );
257 return $clients->fetchRow( DB_FETCHMODE_ASSOC );
260 // Return an array of volumes ordered by poolid and volume name
261 function GetVolumeList() {
267 // Get the list of pools id
268 $query = "SELECT Pool.poolid, Pool.name FROM Pool ORDER BY Pool.poolid";
270 //$this->db_link->setFetchMode(DB_FETCHMODE_ASSOC);
271 $pools = $this->db_link->query( $query );
273 if( PEAR::isError( $pools ) )
274 die("Error: Failed to get pool list <br />SQL Query: $query<br />" . $pools->getMessage() );
276 while( $pool = $pools->fetchRow( DB_FETCHMODE_ASSOC ) ) {
277 switch( $this->driver )
281 $query = "SELECT Media.VolumeName, Media.VolBytes, Media.VolStatus, Pool.Name, Media.MediaType,Media.LastWritten, FROM_UNIXTIME(UNIX_TIMESTAMP(Media.LastWritten)+Media.VolRetention ) AS expire
282 FROM Pool LEFT JOIN Media ON Media.PoolId=Pool.PoolId WHERE poolid='$pool[0]'
283 ORDER BY Media.VolumeName";
285 $query = "SELECT Media.volumename, Media.volbytes, Media.volstatus, Media.mediatype, Media.lastwritten, Media.volretention
286 FROM Media LEFT JOIN Pool ON Media.poolid = Pool.poolid
287 WHERE Media.poolid = '". $pool['poolid'] . "' ORDER BY Media.volumename";
290 $query = "SELECT media.volumename, media.volbytes, media.volstatus, media.mediatype, media.lastwritten, media.volretention
291 FROM media LEFT JOIN pool ON media.poolid = pool.poolid
292 WHERE media.poolid = '". $pool['poolid'] . "' ORDER BY media.volumename";
294 $query = "SELECT Media.VolumeName, Media.VolBytes,Media.VolStatus,Pool.Name,Media.MediaType,Media.LastWritten, Media.LastWritten + Media.VolRetention * interval '1 second' AS expire
295 FROM Pool LEFT JOIN Media ON media.poolid=pool.poolid WHERE poolid='$pool[0]'
296 ORDER BY Media.VolumeName";
300 $query = ""; // not yet implemented
306 //$this->db_link->setFetchMode(DB_FETCHMODE_ASSOC);
307 $medias = $this->db_link->query( $query );
309 if( PEAR::isError( $medias ) ) {
310 die( "Failed to get media list for pool $volume[0] <br /> " . $medias->getMessage() );
312 if( $debug ) echo "Found " . $medias->numRows() . " medias for pool " . $pool['name'] . " <br />";
314 // Create array key for each pool
315 if( !array_key_exists( $pool['name'], $volumes) )
317 $volumes[ $pool['name'] ] = array();
319 while( $media = $medias->fetchRow( DB_FETCHMODE_ASSOC ) ) {
323 // If the pool is empty (no volumes in this pool)
324 if( $medias->numRows() == 0 ) {
325 if( $debug ) echo "No media in pool " . $pool['name'] . "<br />";
327 if( $media['lastwritten'] != "0000-00-00 00:00:00" ) {
328 // Calculate expiration date if the volume is Full
329 if( $media['volstatus'] == 'Full' ) {
330 $expire_date = strtotime($media['lastwritten']) + $media['volretention'];
331 $media['expire'] = strftime("%Y-%m-%d", $expire_date);
333 $media['expire'] = 'N/A';
335 // Media used bytes in a human format
336 $media['volbytes'] = $this->human_file_size( $media['volbytes'] );
337 //echo "volume " . $media['volumename'] . 'vol bytes' .$media['volbytes'] . '<br />';
339 $media['lastwritten'] = "N/A";
340 $media['expire'] = "N/A";
341 $media['volbytes'] = "0 KB";
343 // Add the media in pool array
344 array_push( $volumes[ $pool['name']], $media);
350 } // end function GetVolumeList()
352 public function CountJobs( $delay = LAST_DAY, $status )
354 $query = "SELECT COUNT(JobId) AS job_nb FROM Job ";
356 // Interval condition for SQL query
357 $end_date = mktime();
358 $start_date = $end_date - $delay;
360 $start_date = date( "Y-m-d H:i:s", $start_date );
361 $end_date = date( "Y-m-d H:i:s", $end_date );
363 $query .= "WHERE EndTime BETWEEN '$start_date' AND '$end_date' ";
365 // Job Status for SQL query
369 $query .= "AND JobStatus = 'T' ";
372 $query .= "AND JobStatus = 'f' ";
376 $jobs = $this->db_link->query( $query );
378 if (PEAR::isError( $jobs ) ) {
379 die( "Unable to get last $status jobs number from catalog <br />" . $status->getMessage() );
381 return $jobs->fetchRow( DB_FETCHMODE_ASSOC );
385 // Return the list of Pools in a array
386 public function Get_Pools_List()
388 $pool_list = array();
391 $query = "SELECT Name, PoolId FROM Pool";
393 $result = $this->db_link->query ( $query );
395 if( PEAR::isError( $result ) ) {
396 die( "Unable to get the pool list from catalog" );
398 while( $pool = $result->fetchRow(DB_FETCHMODE_ASSOC) ) {
399 array_push( $pool_list, array( $pool['Name'] => $pool['PoolId'] ) );
405 public function Get_BackupJob_Names()
407 $query = "SELECT Name FROM Job GROUP BY Name";
408 $backupjobs = array();
410 $result = $this->db_link->query( $query );
412 if (PEAR::isError( $result ) ) {
413 die("Unable to get BackupJobs list from catalog" );
415 while( $backupjob = $result->fetchRow( DB_FETCHMODE_ASSOC ) ) {
416 array_push( $backupjobs, $backupjob["Name"] );
422 public function Get_ElapsedTime_Job( $delay = LAST_DAY )
427 // Interval calculation
428 $end_date = mktime();
429 $start_date = $end_date - $delay;
431 $start_date = date( "Y-m-d H:i:s", $start_date );
432 $end_date = date( "Y-m-d H:i:s", $end_date );
434 switch( $this->driver )
437 $query = "SELECT UNIX_TIMESTAMP(EndTime) - UNIX_TIMESTAMP(StartTime) AS elapsed from Job ";
438 $query .= "WHERE EndTime BETWEEN '$start_date' AND '$end_date'";
441 $result = $this->db_link->query( $query );
443 if( PEAR::isError($result) ){
444 die( "Unable to get elapsed time for jobs from catalog<br />query = $query <br />" . $result->getMessage() );
446 while( $time = $result->fetchRow( DB_FETCHMODE_ASSOC ) ) {
447 //echo 'elapsed = ' . $time['elapsed'] . '<br />';
448 $total_elapsed += $time['elapsed'];
450 // Verify if elapsed time is more than 1 day
451 if ( $total_elapsed > 86400 ) {
452 return date("%d days H:i:s", $total_elapsed );
454 return date("H:i:s", $total_elapsed );
459 // Return Jobs statistics for a specific interval such as
460 // - Completed jobs number
461 // - Failed jobs number
462 // - Waiting jobs number
463 // The returned values will be used by a Bgraph classe
464 public function GetJobsStatistics( $type = 'completed', $delay = LAST_DAY )
472 // Interval calculation
473 $end_date = mktime();
474 $start_date = $end_date - $delay;
476 $start_date = date( "Y-m-d H:i:s", $start_date );
477 $end_date = date( "Y-m-d H:i:s", $end_date );
483 $where = "AND JobStatus = 'T' ";
484 $label = "Completed";
486 case 'completed_errors':
487 $where = "AND JobStatus = 'E' ";
488 $label = "Completed with errors";
491 $where = "AND JobStatus = 'f' ";
495 $where = "AND JobStatus IN ('F','S','M','m','s','j','c','d','t') ";
499 $where = "AND JobStatus = 'C' ";
500 $label = "Created but not running";
503 $where = "AND JobStatus = 'R' ";
507 $where = "AND JobStatus IN ('e','f') ";
512 $query = 'SELECT COUNT(JobId) AS ' . $type . ' ';
513 $query .= 'FROM Job ';
514 $query .= "WHERE EndTime BETWEEN '$start_date' AND '$end_date' ";
517 $jobs = $this->db_link->query( $query );
519 if (PEAR::isError( $jobs ) ) {
520 die( "Unable to get last $type jobs status from catalog<br />" . $status->getMessage() );
522 $res = $jobs->fetchRow();
523 return array( $label , current($res) );
525 } // end function GetJobsStatistics()
527 public function GetPoolsStatistics( $pools )
529 foreach( $pools as $pool_name => $pool ) {
531 $query = "SELECT COUNT(*) AS nb_vol FROM Media WHERE PoolId = '$pool'";
532 //echo $query . '<br />';
533 //echo 'Pool name ' . $pool_name . '<br />';
534 $result = $this->db_link->query( $query );
536 if( PEAR::isError( $result ) ) {
537 die("Unable to get volume number from catalog");
539 $nb_vol = $result->fetchRow(DB_FETCHMODE_ASSOC);
540 return array( $pool_name, $nb_vol['nb_vol'] );
545 public function GetStoredFiles()
548 $query = "SELECT COUNT(FilenameId) AS nbfiles FROM Filename";
549 $result = $this->db_link->query( $query );
551 if( !PEAR::isError($result) ) {
552 $nbfiles = $result->fetchRow(DB_FETCHMODE_ASSOC);
553 $nbfiles = $nbfiles['nbfiles'];
555 die("Unable to get protected files from catalog");
560 public function GetStoredBytes( $delay = LAST_DAY )
562 $query = "SELECT SUM(JobBytes) as stored_bytes FROM Job ";
564 // Interval calculation
565 $end_date = mktime();
566 $start_date = $end_date - $delay;
568 $start_date = date( "Y-m-d H:i:s", $start_date );
569 $end_date = date( "Y-m-d H:i:s", $end_date );
571 if( $delay != ALL ) {
572 $query .= "WHERE EndTime BETWEEN '$start_date' AND '$end_date'";
575 $result = $this->db_link->query( $query );
577 if( PEAR::isError( $result ) ) {
578 die( "Unable to get Job Bytes from catalog" );
580 return $result->fetchRow( DB_FETCHMODE_ASSOC );
584 public function GetStoredBytesByInterval( $start_date, $end_date )
586 $query = "SELECT SUM(JobBytes) as stored_bytes, EndTime FROM Job WHERE EndTime BETWEEN '$start_date' AND '$end_date'";
588 $result = $this->db_link->query( $query );
590 if( PEAR::isError( $result ) ) {
591 die( "Unable to get Job Bytes from catalog" );
594 $tmp = $result->fetchRow( DB_FETCHMODE_ASSOC );
596 $day = date( "D d", strtotime($end_date) );
598 if( isset( $tmp['stored_bytes'] ) ) {
599 $hbytes = $this->human_file_size( $tmp['stored_bytes'], 3, 'GB');
600 $hbytes = explode( " ", $hbytes );
601 $stored_bytes = $hbytes[0];
604 return array( $day, $stored_bytes );