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 +-------------------------------------------------------------------------+
17 require_once "paths.php";
18 require_once "DB.php"; // Pear DB
19 require_once "config.inc.php";
20 require_once "bgraph.inc.php";
21 require_once($smarty_path."Config_File.class.php");
23 if (!function_exists('array_fill')) { // For PHP < 4.2.0 users
24 require_once('array_fill.func.php');
27 class Bweb extends DB {
35 public $db_link; // Database link
36 private $db_dsn; // Data Source Name
38 private $config_file; // Config filename
39 private $config; // Loaded config from bacula.conf
40 private $catalogs = array(); // Catalog array
42 function __construct()
44 $this->catalogs = array();
46 // Loading configuration
47 $this->config_file = getcwd() . '/configs/bacula.conf';
48 if( !$this->load_config() )
49 die( "Unable to load configuration");
51 //echo "Number of catalog defined " . count($this->catalogs) . "<br />";
54 $conf = new Config_File (CONFIG_DIR);
58 $sections = $conf->get(CONFIG_FILE,"DATABASE","host");
59 array_push($this->dbs, "DATABASE");
61 while ( !empty($sections) ) {
62 $sections = $conf->get(CONFIG_FILE,"DATABASE".$i,"host");
63 if ( !empty($sections) )
64 array_push($this->dbs,"DATABASE".$i);
71 if ( !empty($_POST['sel_database']) ) {
72 $_SESSION['DATABASE'] = $_POST['sel_database'];
73 $sec = $_POST['sel_database'];
75 if (isset($_SESSION['DATABASE']) )
76 $sec = $_SESSION['DATABASE'];
82 $this->dsn['hostspec'] = $conf->get(CONFIG_FILE,$sec,"host");
83 $this->dsn['username'] = $conf->get(CONFIG_FILE,$sec,"login");
84 $this->dsn['password'] = $conf->get(CONFIG_FILE,$sec,"pass");
85 $this->dsn['database'] = $conf->get(CONFIG_FILE,$sec,"db_name");
86 $this->dsn['phptype'] = $conf->get(CONFIG_FILE,$sec,"db_type"); // mysql, pgsql
88 if ( $conf->get(CONFIG_FILE,$sec,"db_port") )
89 $this->dsn[port] = $conf->get(CONFIG_FILE,$sec,"db_port");
92 // Construct a valid dsn
93 $this->db_dsn['hostspec'] = $this->catalogs[0]["host"];
94 $this->db_dsn['username'] = $this->catalogs[0]["login"];
95 $this->db_dsn['password'] = $this->catalogs[0]["pass"];
96 $this->db_dsn['database'] = $this->catalogs[0]["db_name"];
97 $this->db_dsn['phptype'] = $this->catalogs[0]["db_type"];
100 $this->db_link = $this->connect($this->db_dsn);
102 if (DB::isError($this->db_link)) {
103 die($this->db_link->getMessage());
105 $this->driver = $this->db_dsn['phptype'];
106 register_shutdown_function(array(&$this,'close'));
107 $this->dbs_name = $this->db_dsn['database'];
111 function load_config()
113 $this->config = parse_ini_file( $this->config_file, true );
115 if( !$this->config == false ) {
116 // Loading database connection information
117 foreach( $this->config as $parameter => $value )
119 //echo "Param $parameter = $value <br />";
120 if( is_array($value) ){ // Parsing database section
121 array_push( $this->catalogs, $value );
129 public function get_config_param( $param )
131 if( isset( $this->config[$param] ) )
132 return $this->config[$param];
137 public function Get_Nb_Catalogs()
139 return count( $this->catalogs );
145 $this->db_link->disconnect();
150 function CalculateBytesPeriod($server,$StartDate,$EndPeriod) { // Bytes transferred in a period.
152 $result =& $this->db_link->query("select SUM(JobBytes) from Job WHERE EndTime < '$EndPeriod' and EndTime > '$StartDate' and Name='$server'")
153 or die("classes.inc: Error query: 1");
154 $return =& $result->fetchRow();
160 function CalculateFilesPeriod($server,$StartDate,$EndPeriod) { // Number of files transferred in a period.
162 $result =& $this->db_link->query("select SUM(JobFiles) from Job WHERE EndTime < '$EndPeriod' and EndTime > '$StartDate' and Name='$server'")
163 or die("classes.inc: Error query: 2");
164 $return =& $result->fetchRow();
170 function PrepareDate($StartDateMonth,$StartDateDay,$StartDateYear,$EndDateMonth,$EndDateDay,$EndDateYear) { // Convert date for Smarty. Check if only works with Mysql.
172 $this->StartDate=$StartDateYear."-".$StartDateMonth."-".$StartDateDay." 00:00:00";
173 $this->EndDate=$EndDateYear."-".$EndDateMonth."-".$EndDateDay." 23:59:59"; // last day full
177 // Return humanized size with default unit of GB
178 // if auto provide for unit argument, automaticaly decide which unit
179 function human_file_size( $size, $decimal = 2, $unit = 'auto' )
183 $units = array('B','KB','MB','GB','TB');
190 if ( $hsize >= 1024 ) {
191 $hsize = $hsize / 1024;
201 $p = array_search( $unit, $units);
202 $hsize = $hsize / pow(1024,$p);
206 $hsize = sprintf("%." . $decimal . "f", $hsize);
207 $hsize = $hsize . ' ' . $units[$unit_id];
215 if ( $this->driver == "mysql") {
216 $dbsize = $this->db_link->query("show table status") or die ("classes.inc: Error query: 3");
218 if ( $dbsize->numRows() ) {
219 while ( $res = $dbsize->fetchRow(DB_FETCHMODE_ASSOC) )
220 $database_size += $res["Data_length"];
225 else if ( $this->driver == "pgsql") {
226 $dbsize = $this->db_link->query("select pg_database_size('$this->dbs_name')") or die ("classes.inc: Error query: 4");
228 if (PEAR::isError($dbsize))
229 die($dbsize->getMessage());
231 if ( $dbsize->numRows() ) {
232 while ( $res = $dbsize->fetchRow() )
233 $database_size += $res[0];
241 return $this->human_file_size( $database_size );
242 } // end function GetDbSize()
244 public function Get_Nb_Clients()
246 $clients = $this->db_link->query("SELECT COUNT(*) AS nb_client FROM Client");
247 if( PEAR::isError($clients) )
248 die( "Unable to get client number" );
250 return $clients->fetchRow( DB_FETCHMODE_ASSOC );
253 // Return an array of volumes ordered by poolid and volume name
254 function GetVolumeList() {
260 // Get the list of pools id
261 $query = "SELECT Pool.poolid, Pool.name FROM Pool ORDER BY Pool.poolid";
263 //$this->db_link->setFetchMode(DB_FETCHMODE_ASSOC);
264 $pools = $this->db_link->query( $query );
266 if( PEAR::isError( $pools ) )
267 die("Error: Failed to get pool list <br />SQL Query: $query<br />" . $pools->getMessage() );
269 while( $pool = $pools->fetchRow( DB_FETCHMODE_ASSOC ) ) {
270 switch( $this->driver )
274 $query = "SELECT Media.VolumeName, Media.VolBytes, Media.VolStatus, Pool.Name, Media.MediaType,Media.LastWritten, FROM_UNIXTIME(UNIX_TIMESTAMP(Media.LastWritten)+Media.VolRetention ) AS expire
275 FROM Pool LEFT JOIN Media ON Media.PoolId=Pool.PoolId WHERE poolid='$pool[0]'
276 ORDER BY Media.VolumeName";
278 $query = "SELECT Media.volumename, Media.volbytes, Media.volstatus, Media.mediatype, Media.lastwritten, Media.volretention
279 FROM Media LEFT JOIN Pool ON Media.poolid = Pool.poolid
280 WHERE Media.poolid = '". $pool['poolid'] . "' ORDER BY Media.volumename";
283 $query = "SELECT media.volumename, media.volbytes, media.volstatus, media.mediatype, media.lastwritten, media.volretention
284 FROM media LEFT JOIN pool ON media.poolid = pool.poolid
285 WHERE media.poolid = '". $pool['poolid'] . "' ORDER BY media.volumename";
287 $query = "SELECT Media.VolumeName, Media.VolBytes,Media.VolStatus,Pool.Name,Media.MediaType,Media.LastWritten, Media.LastWritten + Media.VolRetention * interval '1 second' AS expire
288 FROM Pool LEFT JOIN Media ON media.poolid=pool.poolid WHERE poolid='$pool[0]'
289 ORDER BY Media.VolumeName";
293 $query = ""; // not yet implemented
299 //$this->db_link->setFetchMode(DB_FETCHMODE_ASSOC);
300 $medias = $this->db_link->query( $query );
302 if( PEAR::isError( $medias ) ) {
303 die( "Failed to get media list for pool $volume[0] <br /> " . $medias->getMessage() );
305 if( $debug ) echo "Found " . $medias->numRows() . " medias for pool " . $pool['name'] . " <br />";
307 // Create array key for each pool
308 if( !array_key_exists( $pool['name'], $volumes) )
310 $volumes[ $pool['name'] ] = array();
312 while( $media = $medias->fetchRow( DB_FETCHMODE_ASSOC ) ) {
316 // If the pool is empty (no volumes in this pool)
317 if( $medias->numRows() == 0 ) {
318 if( $debug ) echo "No media in pool " . $pool['name'] . "<br />";
320 if( $media['lastwritten'] != "0000-00-00 00:00:00" ) {
321 // Calculate expiration date if the volume is Full
322 if( $media['volstatus'] == 'Full' ) {
323 $expire_date = strtotime($media['lastwritten']) + $media['volretention'];
324 $media['expire'] = strftime("%Y-%m-%d", $expire_date);
326 $media['expire'] = 'N/A';
328 // Media used bytes in a human format
329 $media['volbytes'] = $this->human_file_size( $media['volbytes'] );
330 //echo "volume " . $media['volumename'] . 'vol bytes' .$media['volbytes'] . '<br />';
332 $media['lastwritten'] = "N/A";
333 $media['expire'] = "N/A";
334 $media['volbytes'] = "0 KB";
336 // Add the media in pool array
337 array_push( $volumes[ $pool['name']], $media);
343 } // end function GetVolumeList()
345 public function CountJobs( $delay = LAST_DAY, $status )
347 $query = "SELECT COUNT(JobId) AS job_nb FROM Job ";
349 // Interval condition for SQL query
350 $end_date = mktime();
351 $start_date = $end_date - $delay;
353 $start_date = date( "Y-m-d H:i:s", $start_date );
354 $end_date = date( "Y-m-d H:i:s", $end_date );
356 $query .= "WHERE EndTime BETWEEN '$start_date' AND '$end_date' ";
358 // Job Status for SQL query
362 $query .= "AND JobStatus = 'T' ";
365 $query .= "AND JobStatus = 'f' ";
369 $jobs = $this->db_link->query( $query );
371 if (PEAR::isError( $jobs ) ) {
372 die( "Unable to get last $status jobs number from catalog <br />" . $status->getMessage() );
374 return $jobs->fetchRow( DB_FETCHMODE_ASSOC );
378 // Return the list of Pools in a array
379 public function Get_Pools_List()
381 $pool_list = array();
384 $query = "SELECT Name, PoolId FROM Pool";
386 $result = $this->db_link->query ( $query );
388 if( PEAR::isError( $result ) ) {
389 die( "Unable to get the pool list from catalog" );
391 while( $pool = $result->fetchRow(DB_FETCHMODE_ASSOC) ) {
392 array_push( $pool_list, array( $pool['Name'] => $pool['PoolId'] ) );
398 public function Get_BackupJob_Names()
400 $query = "SELECT Name FROM Job GROUP BY Name";
401 $backupjobs = array();
403 $result = $this->db_link->query( $query );
405 if (PEAR::isError( $result ) ) {
406 die("Unable to get BackupJobs list from catalog" );
408 while( $backupjob = $result->fetchRow( DB_FETCHMODE_ASSOC ) ) {
409 array_push( $backupjobs, $backupjob["Name"] );
415 public function Get_ElapsedTime_Job( $delay = LAST_DAY )
420 // Interval calculation
421 $end_date = mktime();
422 $start_date = $end_date - $delay;
424 $start_date = date( "Y-m-d H:i:s", $start_date );
425 $end_date = date( "Y-m-d H:i:s", $end_date );
427 switch( $this->driver )
430 $query = "SELECT UNIX_TIMESTAMP(EndTime) - UNIX_TIMESTAMP(StartTime) AS elapsed from Job ";
431 $query .= "WHERE EndTime BETWEEN '$start_date' AND '$end_date'";
434 $result = $this->db_link->query( $query );
436 if( PEAR::isError($result) ){
437 die( "Unable to get elapsed time for jobs from catalog<br />query = $query <br />" . $result->getMessage() );
439 while( $time = $result->fetchRow( DB_FETCHMODE_ASSOC ) ) {
440 //echo 'elapsed = ' . $time['elapsed'] . '<br />';
441 $total_elapsed += $time['elapsed'];
443 // Verify if elapsed time is more than 1 day
444 if ( $total_elapsed > 86400 ) {
445 return date("%d days H:i:s", $total_elapsed );
447 return date("H:i:s", $total_elapsed );
452 // Return Jobs statistics for a specific interval such as
453 // - Completed jobs number
454 // - Failed jobs number
455 // - Waiting jobs number
456 // The returned values will be used by a Bgraph classe
457 public function GetJobsStatistics( $type = 'completed', $delay = LAST_DAY )
465 // Interval calculation
466 $end_date = mktime();
467 $start_date = $end_date - $delay;
469 $start_date = date( "Y-m-d H:i:s", $start_date );
470 $end_date = date( "Y-m-d H:i:s", $end_date );
476 $where = "AND JobStatus = 'T' ";
477 $label = "Completed";
479 case 'completed_errors':
480 $where = "AND JobStatus = 'E' ";
481 $label = "Completed with errors";
484 $where = "AND JobStatus = 'f' ";
488 $where = "AND JobStatus IN ('F','S','M','m','s','j','c','d','t') ";
492 $where = "AND JobStatus = 'C' ";
493 $label = "Created but not running";
496 $where = "AND JobStatus = 'R' ";
500 $where = "AND JobStatus IN ('e','f') ";
505 $query = 'SELECT COUNT(JobId) AS ' . $type . ' ';
506 $query .= 'FROM Job ';
507 $query .= "WHERE EndTime BETWEEN '$start_date' AND '$end_date' ";
510 $jobs = $this->db_link->query( $query );
512 if (PEAR::isError( $jobs ) ) {
513 die( "Unable to get last $type jobs status from catalog<br />" . $status->getMessage() );
515 $res = $jobs->fetchRow();
516 return array( $label , current($res) );
518 } // end function GetJobsStatistics()
520 public function GetPoolsStatistics( $pools )
522 foreach( $pools as $pool_name => $pool ) {
524 $query = "SELECT COUNT(*) AS nb_vol FROM Media WHERE PoolId = '$pool'";
525 //echo $query . '<br />';
526 //echo 'Pool name ' . $pool_name . '<br />';
527 $result = $this->db_link->query( $query );
529 if( PEAR::isError( $result ) ) {
530 die("Unable to get volume number from catalog");
532 $nb_vol = $result->fetchRow(DB_FETCHMODE_ASSOC);
533 return array( $pool_name, $nb_vol['nb_vol'] );
538 public function GetStoredFiles()
541 $query = "SELECT COUNT(FilenameId) AS nbfiles FROM Filename";
542 $result = $this->db_link->query( $query );
544 if( !PEAR::isError($result) ) {
545 $nbfiles = $result->fetchRow(DB_FETCHMODE_ASSOC);
546 $nbfiles = $nbfiles['nbfiles'];
548 die("Unable to get protected files from catalog");
553 public function GetStoredBytes( $delay = LAST_DAY )
555 $query = "SELECT SUM(JobBytes) as stored_bytes FROM Job ";
557 // Interval calculation
558 $end_date = mktime();
559 $start_date = $end_date - $delay;
561 $start_date = date( "Y-m-d H:i:s", $start_date );
562 $end_date = date( "Y-m-d H:i:s", $end_date );
564 if( $delay != ALL ) {
565 $query .= "WHERE EndTime BETWEEN '$start_date' AND '$end_date'";
568 $result = $this->db_link->query( $query );
570 if( PEAR::isError( $result ) ) {
571 die( "Unable to get Job Bytes from catalog" );
573 return $result->fetchRow( DB_FETCHMODE_ASSOC );
577 public function GetStoredBytesByInterval( $start_date, $end_date )
579 $query = "SELECT SUM(JobBytes) as stored_bytes, EndTime FROM Job WHERE EndTime BETWEEN '$start_date' AND '$end_date'";
581 $result = $this->db_link->query( $query );
583 if( PEAR::isError( $result ) ) {
584 die( "Unable to get Job Bytes from catalog" );
587 $tmp = $result->fetchRow( DB_FETCHMODE_ASSOC );
589 $day = date( "D d", strtotime($end_date) );
591 if( isset( $tmp['stored_bytes'] ) ) {
592 $hbytes = $this->human_file_size( $tmp['stored_bytes'], 3, 'GB');
593 $hbytes = explode( " ", $hbytes );
594 $stored_bytes = $hbytes[0];
597 return array( $day, $stored_bytes );