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'] );
331 $media['lastwritten'] = "N/A";
332 $media['expire'] = "N/A";
333 $media['volbytes'] = "0 KB";
337 if( count( $volumes[ $pool['name'] ] ) % 2)
338 $media['class'] = 'odd';
340 // Add the media in pool array
341 array_push( $volumes[ $pool['name']], $media);
347 } // end function GetVolumeList()
349 public function CountJobs( $delay = LAST_DAY, $status = 'any' )
351 $query = "SELECT COUNT(JobId) AS job_nb FROM Job ";
355 // Interval condition for SQL query
356 if( $delay != ALL ) {
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 $where_delay = "WHERE EndTime BETWEEN '$start_date' AND '$end_date' ";
366 if( $status != 'any' ) {
370 $where_status = "JobStatus = 'T' ";
373 $where_status = "JobStatus IN ('f','E') ";
376 $where_status = "JobStatus = 'A' ";
379 $where_status = "JobStatus IN ('F','S','M','m','s','j','c','d','t') ";
384 if( !empty($where_delay) )
385 $query = $query . $where_delay . 'AND ' . $where_status;
387 if( !empty($where_status) )
388 $query = $query . 'WHERE ' . $where_status;
391 $jobs = $this->db_link->query( $query );
393 if (PEAR::isError( $jobs ) ) {
394 die( "Unable to get last $status jobs number from catalog <br />" . $jobs->getMessage() );
396 $jobs = $jobs->fetchRow( DB_FETCHMODE_ASSOC );
397 return $jobs['job_nb'];
401 // Return the list of Pools in a array
402 public function Get_Pools_List()
404 $pool_list = array();
407 $query = "SELECT Name, PoolId FROM Pool";
409 $result = $this->db_link->query ( $query );
411 if( PEAR::isError( $result ) ) {
412 die( "Unable to get the pool list from catalog" );
414 while( $pool = $result->fetchRow(DB_FETCHMODE_ASSOC) ) {
415 array_push( $pool_list, array( $pool['Name'] => $pool['PoolId'] ) );
421 public function Get_BackupJob_Names()
423 $query = "SELECT Name FROM Job GROUP BY Name";
424 $backupjobs = array();
426 $result = $this->db_link->query( $query );
428 if (PEAR::isError( $result ) ) {
429 die("Unable to get BackupJobs list from catalog" );
431 while( $backupjob = $result->fetchRow( DB_FETCHMODE_ASSOC ) ) {
432 array_push( $backupjobs, $backupjob["Name"] );
438 // Return elasped time string for a job
439 function Get_ElapsedTime( $start_time, $end_time )
441 $diff = $end_time - $start_time;
443 $daysDiff = sprintf("%02d", floor($diff/60/60/24) );
444 $diff -= $daysDiff*60*60*24;
446 $hrsDiff = sprintf("%02d", floor($diff/60/60) );
447 $diff -= $hrsDiff*60*60;
449 $minsDiff = sprintf("%02d", floor($diff/60) );
450 $diff -= $minsDiff*60;
451 $secsDiff = sprintf("%02d", $diff );
454 return $daysDiff . 'day(s) ' . $hrsDiff.':' . $minsDiff . ':' . $secsDiff;
456 return $hrsDiff . ':' . $minsDiff . ':' . $secsDiff;
459 public function Get_ElapsedTime_Job( $delay = LAST_DAY )
464 // Interval calculation
465 $end_date = mktime();
466 $start_date = $end_date - $delay;
468 $start_date = date( "Y-m-d H:i:s", $start_date );
469 $end_date = date( "Y-m-d H:i:s", $end_date );
471 switch( $this->driver )
474 $query = "SELECT UNIX_TIMESTAMP(EndTime) - UNIX_TIMESTAMP(StartTime) AS elapsed from Job ";
475 $query .= "WHERE EndTime BETWEEN '$start_date' AND '$end_date'";
478 $result = $this->db_link->query( $query );
480 if( PEAR::isError($result) ){
481 die( "Unable to get elapsed time for jobs from catalog<br />query = $query <br />" . $result->getMessage() );
483 while( $time = $result->fetchRow( DB_FETCHMODE_ASSOC ) ) {
484 //echo 'elapsed = ' . $time['elapsed'] . '<br />';
485 $total_elapsed += $time['elapsed'];
487 // Verify if elapsed time is more than 1 day
488 if ( $total_elapsed > LAST_DAY ) {
489 return date("%d days H:i:s", $total_elapsed );
491 return date("H:i:s", $total_elapsed );
496 // Return Jobs statistics for a specific interval such as
497 // - Completed jobs number
498 // - Failed jobs number
499 // - Waiting jobs number
500 // The returned values will be used by a Bgraph classe
501 public function GetJobsStatistics( $type = 'completed', $delay = LAST_DAY )
509 // Interval calculation
510 $end_date = mktime();
511 $start_date = $end_date - $delay;
513 $start_date = date( "Y-m-d H:i:s", $start_date );
514 $end_date = date( "Y-m-d H:i:s", $end_date );
520 $where = "AND JobStatus = 'T' ";
521 $label = "Completed";
523 case 'terminated_errors':
524 $where = $interval_where . "JobStatus = 'E' ";
525 $label = "Terminated with errors";
528 $where = "AND JobStatus = 'f' ";
532 $where = "AND JobStatus IN ('F','S','M','m','s','j','c','d','t') ";
536 $where = "AND JobStatus = 'C' ";
537 $label = "Created but not running";
540 $where = "AND JobStatus = 'R' ";
544 $where = "AND JobStatus IN ('e','f') ";
549 $query = 'SELECT COUNT(JobId) AS ' . $type . ' ';
550 $query .= 'FROM Job ';
551 $query .= "WHERE EndTime BETWEEN '$start_date' AND '$end_date' ";
554 $jobs = $this->db_link->query( $query );
556 if (PEAR::isError( $jobs ) ) {
557 die( "Unable to get last $type jobs status from catalog<br />" . $status->getMessage() );
559 $res = $jobs->fetchRow();
560 return array( $label , current($res) );
562 } // end function GetJobsStatistics()
564 public function GetPoolsStatistics( $pools )
566 foreach( $pools as $pool_name => $pool ) {
568 $query = "SELECT COUNT(*) AS nb_vol FROM Media WHERE PoolId = '$pool'";
569 //echo $query . '<br />';
570 //echo 'Pool name ' . $pool_name . '<br />';
571 $result = $this->db_link->query( $query );
573 if( PEAR::isError( $result ) ) {
574 die("Unable to get volume number from catalog");
576 $nb_vol = $result->fetchRow(DB_FETCHMODE_ASSOC);
577 return array( $pool_name, $nb_vol['nb_vol'] );
582 public function GetStoredFiles()
585 $query = "SELECT COUNT(FilenameId) AS nbfiles FROM Filename";
586 $result = $this->db_link->query( $query );
588 if( !PEAR::isError($result) ) {
589 $nbfiles = $result->fetchRow(DB_FETCHMODE_ASSOC);
590 $nbfiles = $nbfiles['nbfiles'];
592 die("Unable to get protected files from catalog");
597 public function GetStoredBytes( $delay = LAST_DAY )
599 $query = "SELECT SUM(JobBytes) as stored_bytes FROM Job ";
601 // Interval calculation
602 $end_date = mktime();
603 $start_date = $end_date - $delay;
605 $start_date = date( "Y-m-d H:i:s", $start_date );
606 $end_date = date( "Y-m-d H:i:s", $end_date );
608 if( $delay != ALL ) {
609 $query .= "WHERE EndTime BETWEEN '$start_date' AND '$end_date'";
612 $result = $this->db_link->query( $query );
614 if( PEAR::isError( $result ) ) {
615 die( "Unable to get Job Bytes from catalog" );
617 return $result->fetchRow( DB_FETCHMODE_ASSOC );
621 public function GetStoredBytesByInterval( $start_date, $end_date )
623 $query = "SELECT SUM(JobBytes) as stored_bytes, EndTime FROM Job WHERE EndTime BETWEEN '$start_date' AND '$end_date'";
625 $result = $this->db_link->query( $query );
627 if( PEAR::isError( $result ) ) {
628 die( "Unable to get Job Bytes from catalog" );
631 $tmp = $result->fetchRow( DB_FETCHMODE_ASSOC );
633 $day = date( "D d", strtotime($end_date) );
635 if( isset( $tmp['stored_bytes'] ) ) {
636 $hbytes = $this->human_file_size( $tmp['stored_bytes'], 3, 'GB');
637 $hbytes = explode( " ", $hbytes );
638 $stored_bytes = $hbytes[0];
641 return array( $day, $stored_bytes );
645 public function GetStoredBytesByJob( $jobname, $start_date, $end_date )
647 $query = "SELECT SUM(JobBytes) as stored_bytes, EndTime FROM Job ";
648 $query .= "WHERE ( EndTime BETWEEN '$start_date' AND '$end_date' ) AND ";
649 $query .= "Name = '$jobname'";
651 $result = $this->db_link->query( $query );
653 if( PEAR::isError( $result ) ) {
654 die( "Unable to get Job Bytes from catalog" );
657 $tmp = $result->fetchRow( DB_FETCHMODE_ASSOC );
659 $day = date( "D d", strtotime($end_date) );
661 if( isset( $tmp['stored_bytes'] ) ) {
662 $hbytes = $this->human_file_size( $tmp['stored_bytes'], 3, 'GB');
663 $hbytes = explode( " ", $hbytes );
664 $stored_bytes = $hbytes[0];
667 return array( $day, $stored_bytes );