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];
217 switch( $this->driver )
220 $query = "SELECT table_schema AS 'database', sum( data_length + index_length) AS 'dbsize' ";
221 $query .= "FROM information_schema.TABLES ";
222 $query .= "WHERE table_schema = 'bacula' ";
223 $query .= "GROUP BY table_schema";
226 $query = "SELECT pg_database_size('bacula') AS dbsize";
229 // Not yet implemented
234 $result = $this->db_link->query( $query );
236 if(! PEAR::isError( $result ) )
238 $db = $result->fetchRow( DB_FETCHMODE_ASSOC );
239 $database_size =+ $db['dbsize'];
241 die( "Unable to get database size<br />" . $jobs->getMessage() );
243 return $this->human_file_size( $database_size );
246 if ( $this->driver == "mysql") {
247 $dbsize = $this->db_link->query("show table status") or die ("classes.inc: Error query: 3");
249 if ( $dbsize->numRows() ) {
250 while ( $res = $dbsize->fetchRow(DB_FETCHMODE_ASSOC) )
251 $database_size += $res["Data_length"];
256 else if ( $this->driver == "pgsql") {
257 $dbsize = $this->db_link->query("select pg_database_size('$this->dbs_name')") or die ("classes.inc: Error query: 4");
259 if (PEAR::isError($dbsize))
260 die($dbsize->getMessage());
262 if ( $dbsize->numRows() ) {
263 while ( $res = $dbsize->fetchRow() )
264 $database_size += $res[0];
272 } // end function GetDbSize()
274 public function Get_Nb_Clients()
276 $clients = $this->db_link->query("SELECT COUNT(*) AS nb_client FROM Client");
277 if( PEAR::isError($clients) )
278 die( "Unable to get client number" );
280 return $clients->fetchRow( DB_FETCHMODE_ASSOC );
283 // Return an array of volumes ordered by poolid and volume name
284 function GetVolumeList() {
290 // Get the list of pools id
291 $query = "SELECT Pool.poolid, Pool.name FROM Pool ORDER BY Pool.poolid";
293 //$this->db_link->setFetchMode(DB_FETCHMODE_ASSOC);
294 $pools = $this->db_link->query( $query );
296 if( PEAR::isError( $pools ) )
297 die("Error: Failed to get pool list <br />SQL Query: $query<br />" . $pools->getMessage() );
299 while( $pool = $pools->fetchRow( DB_FETCHMODE_ASSOC ) ) {
300 switch( $this->driver )
304 $query = "SELECT Media.VolumeName, Media.VolBytes, Media.VolStatus, Pool.Name, Media.MediaType,Media.LastWritten, FROM_UNIXTIME(UNIX_TIMESTAMP(Media.LastWritten)+Media.VolRetention ) AS expire
305 FROM Pool LEFT JOIN Media ON Media.PoolId=Pool.PoolId WHERE poolid='$pool[0]'
306 ORDER BY Media.VolumeName";
308 $query = "SELECT Media.volumename, Media.volbytes, Media.volstatus, Media.mediatype, Media.lastwritten, Media.volretention
309 FROM Media LEFT JOIN Pool ON Media.poolid = Pool.poolid
310 WHERE Media.poolid = '". $pool['poolid'] . "' ORDER BY Media.volumename";
313 $query = "SELECT media.volumename, media.volbytes, media.volstatus, media.mediatype, media.lastwritten, media.volretention
314 FROM media LEFT JOIN pool ON media.poolid = pool.poolid
315 WHERE media.poolid = '". $pool['poolid'] . "' ORDER BY media.volumename";
317 $query = "SELECT Media.VolumeName, Media.VolBytes,Media.VolStatus,Pool.Name,Media.MediaType,Media.LastWritten, Media.LastWritten + Media.VolRetention * interval '1 second' AS expire
318 FROM Pool LEFT JOIN Media ON media.poolid=pool.poolid WHERE poolid='$pool[0]'
319 ORDER BY Media.VolumeName";
323 $query = ""; // not yet implemented
329 //$this->db_link->setFetchMode(DB_FETCHMODE_ASSOC);
330 $medias = $this->db_link->query( $query );
332 if( PEAR::isError( $medias ) ) {
333 die( "Failed to get media list for pool $volume[0] <br /> " . $medias->getMessage() );
335 if( $debug ) echo "Found " . $medias->numRows() . " medias for pool " . $pool['name'] . " <br />";
337 // Create array key for each pool
338 if( !array_key_exists( $pool['name'], $volumes) )
340 $volumes[ $pool['name'] ] = array();
342 while( $media = $medias->fetchRow( DB_FETCHMODE_ASSOC ) ) {
346 // If the pool is empty (no volumes in this pool)
347 if( $medias->numRows() == 0 ) {
348 if( $debug ) echo "No media in pool " . $pool['name'] . "<br />";
350 if( $media['lastwritten'] != "0000-00-00 00:00:00" ) {
351 // Calculate expiration date if the volume is Full
352 if( $media['volstatus'] == 'Full' ) {
353 $expire_date = strtotime($media['lastwritten']) + $media['volretention'];
354 $media['expire'] = strftime("%Y-%m-%d", $expire_date);
356 $media['expire'] = 'N/A';
358 // Media used bytes in a human format
359 $media['volbytes'] = $this->human_file_size( $media['volbytes'] );
361 $media['lastwritten'] = "N/A";
362 $media['expire'] = "N/A";
363 $media['volbytes'] = "0 KB";
367 if( count( $volumes[ $pool['name'] ] ) % 2)
368 $media['class'] = 'odd';
370 // Add the media in pool array
371 array_push( $volumes[ $pool['name']], $media);
377 } // end function GetVolumeList()
379 public function CountJobsbyLevel( $delay = LAST_DAY, $level = 'F' )
381 $end_date = mktime();
382 $start_date = $end_date - $delay;
384 $start_date = date( "Y-m-d H:i:s", $start_date );
385 $end_date = date( "Y-m-d H:i:s", $end_date );
387 $query = "SELECT COUNT(JobId) as jobs FROM Job ";
388 $query .= "WHERE (EndTime BETWEEN '$start_date' AND '$end_date') AND ";
389 $query .= "Level = '$level' ";
391 $result = $this->db_link->query( $query );
393 if (PEAR::isError( $result ) ) {
394 die( "Unable to get number of jobs with $level status from catalog <br />" . $result->getMessage() );
396 $jobs = $result->fetchRow( DB_FETCHMODE_ASSOC );
397 return $jobs['jobs'];
402 public function CountJobs( $delay = LAST_DAY, $status = 'any' )
404 $query = "SELECT COUNT(JobId) AS job_nb FROM Job ";
408 // Interval condition for SQL query
409 if( $delay != ALL ) {
410 $end_date = mktime();
411 $start_date = $end_date - $delay;
413 $start_date = date( "Y-m-d H:i:s", $start_date );
414 $end_date = date( "Y-m-d H:i:s", $end_date );
416 $where_delay = "WHERE EndTime BETWEEN '$start_date' AND '$end_date' ";
419 if( $status != 'any' ) {
423 $where_status = "JobStatus = 'T' ";
426 $where_status = "JobStatus IN ('f','E') ";
429 $where_status = "JobStatus = 'A' ";
432 $where_status = "JobStatus IN ('F','S','M','m','s','j','c','d','t') ";
437 if( !empty($where_delay) )
438 $query = $query . $where_delay . 'AND ' . $where_status;
440 if( !empty($where_status) )
441 $query = $query . 'WHERE ' . $where_status;
444 $jobs = $this->db_link->query( $query );
446 if (PEAR::isError( $jobs ) ) {
447 die( "Unable to get last $status jobs number from catalog <br />" . $jobs->getMessage() );
449 $jobs = $jobs->fetchRow( DB_FETCHMODE_ASSOC );
450 return $jobs['job_nb'];
454 // Return the list of Pools in a array
455 public function Get_Pools_List()
457 $pool_list = array();
460 $query = "SELECT Name, PoolId FROM Pool";
462 $result = $this->db_link->query ( $query );
464 if( PEAR::isError( $result ) ) {
465 die( "Unable to get the pool list from catalog" );
467 while( $pool = $result->fetchRow(DB_FETCHMODE_ASSOC) ) {
468 array_push( $pool_list, array( $pool['Name'] => $pool['PoolId'] ) );
474 public function Get_BackupJob_Names()
476 $query = "SELECT Name FROM Job GROUP BY Name";
477 $backupjobs = array();
479 $result = $this->db_link->query( $query );
481 if (PEAR::isError( $result ) ) {
482 die("Unable to get BackupJobs list from catalog" );
484 while( $backupjob = $result->fetchRow( DB_FETCHMODE_ASSOC ) ) {
485 array_push( $backupjobs, $backupjob["Name"] );
491 // Return elasped time string for a job
492 function Get_ElapsedTime( $start_time, $end_time )
494 $diff = $end_time - $start_time;
496 $daysDiff = sprintf("%02d", floor($diff/60/60/24) );
497 $diff -= $daysDiff*60*60*24;
499 $hrsDiff = sprintf("%02d", floor($diff/60/60) );
500 $diff -= $hrsDiff*60*60;
502 $minsDiff = sprintf("%02d", floor($diff/60) );
503 $diff -= $minsDiff*60;
504 $secsDiff = sprintf("%02d", $diff );
507 return $daysDiff . 'day(s) ' . $hrsDiff.':' . $minsDiff . ':' . $secsDiff;
509 return $hrsDiff . ':' . $minsDiff . ':' . $secsDiff;
512 public function Get_ElapsedTime_Job( $delay = LAST_DAY )
517 // Interval calculation
518 $end_date = mktime();
519 $start_date = $end_date - $delay;
521 $start_date = date( "Y-m-d H:i:s", $start_date );
522 $end_date = date( "Y-m-d H:i:s", $end_date );
524 switch( $this->driver )
527 $query = "SELECT UNIX_TIMESTAMP(EndTime) - UNIX_TIMESTAMP(StartTime) AS elapsed from Job ";
528 $query .= "WHERE EndTime BETWEEN '$start_date' AND '$end_date'";
531 $result = $this->db_link->query( $query );
533 if( PEAR::isError($result) ){
534 die( "Unable to get elapsed time for jobs from catalog<br />query = $query <br />" . $result->getMessage() );
536 while( $time = $result->fetchRow( DB_FETCHMODE_ASSOC ) ) {
537 //echo 'elapsed = ' . $time['elapsed'] . '<br />';
538 $total_elapsed += $time['elapsed'];
540 // Verify if elapsed time is more than 1 day
541 if ( $total_elapsed > LAST_DAY ) {
542 return date("%d days H:i:s", $total_elapsed );
544 return date("H:i:s", $total_elapsed );
549 // Return Jobs statistics for a specific interval such as
550 // - Completed jobs number
551 // - Failed jobs number
552 // - Waiting jobs number
553 // The returned values will be used by a Bgraph classe
554 public function GetJobsStatistics( $type = 'completed', $delay = LAST_DAY )
562 // Interval calculation
563 $end_date = mktime();
564 $start_date = $end_date - $delay;
566 $start_date = date( "Y-m-d H:i:s", $start_date );
567 $end_date = date( "Y-m-d H:i:s", $end_date );
569 $interval_where = "(EndTime BETWEEN '$start_date' AND '$end_date') AND ";
575 $where = $interval_where . "JobStatus = 'T' ";
576 $label = "Completed";
578 case 'terminated_errors':
579 $where = $interval_where . "JobStatus = 'E' ";
580 $label = "Terminated with errors";
583 $where = $interval_where . "JobStatus = 'f' ";
587 $where = "JobStatus IN ('F','S','M','m','s','j','c','d','t') ";
591 $where = "JobStatus = 'C' ";
592 $label = "Created but not running";
595 $where = "JobStatus = 'R' ";
599 $where = $interval_where . "JobStatus IN ('e','f') ";
604 $query = 'SELECT COUNT(JobId) AS ' . $type . ' ';
605 $query .= 'FROM Job ';
606 $query .= "WHERE $where ";
608 //echo 'query = ' . $query . '<br />';
610 $jobs = $this->db_link->query( $query );
612 if (PEAR::isError( $jobs ) ) {
613 die( "Unable to get last $type jobs status from catalog<br />" . $status->getMessage() );
615 $res = $jobs->fetchRow();
616 return array( $label , current($res) );
618 } // end function GetJobsStatistics()
620 public function GetPoolsStatistics( $pools )
622 foreach( $pools as $pool_name => $pool ) {
624 $query = "SELECT COUNT(*) AS nb_vol FROM Media WHERE PoolId = '$pool'";
625 //echo $query . '<br />';
626 //echo 'Pool name ' . $pool_name . '<br />';
627 $result = $this->db_link->query( $query );
629 if( PEAR::isError( $result ) ) {
630 die("Unable to get volume number from catalog");
632 $nb_vol = $result->fetchRow(DB_FETCHMODE_ASSOC);
633 return array( $pool_name, $nb_vol['nb_vol'] );
638 public function GetStoredFiles( $delay = LAST_DAY )
642 $query = "SELECT SUM(JobFiles) AS stored_files FROM Job ";
644 // Interval calculation
645 $end_date = mktime();
646 $start_date = $end_date - $delay;
648 $start_date = date( "Y-m-d H:i:s", $start_date );
649 $end_date = date( "Y-m-d H:i:s", $end_date );
652 $query .= "WHERE EndTime BETWEEN '$start_date' AND '$end_date'";
654 $result = $this->db_link->query( $query );
656 if( !PEAR::isError($result) ) {
657 $nbfiles = $result->fetchRow(DB_FETCHMODE_ASSOC);
658 $totalfiles = $totalfiles + $nbfiles['stored_files'];
660 die("Unable to get protected files from catalog <br />" . $result->getMessage() );
666 public function GetStoredBytes( $delay = LAST_DAY )
668 $query = "SELECT SUM(JobBytes) as stored_bytes FROM Job ";
670 // Interval calculation
671 $end_date = mktime();
672 $start_date = $end_date - $delay;
674 $start_date = date( "Y-m-d H:i:s", $start_date );
675 $end_date = date( "Y-m-d H:i:s", $end_date );
678 $query .= "WHERE EndTime BETWEEN '$start_date' AND '$end_date'";
680 $result = $this->db_link->query( $query );
682 if( PEAR::isError( $result ) ) {
683 die( "Unable to get Job Bytes from catalog" );
685 return $result->fetchRow( DB_FETCHMODE_ASSOC );
689 public function GetStoredBytesByInterval( $start_date, $end_date )
691 $query = "SELECT SUM(JobBytes) as stored_bytes, EndTime FROM Job WHERE EndTime BETWEEN '$start_date' AND '$end_date'";
693 $result = $this->db_link->query( $query );
695 if( PEAR::isError( $result ) ) {
696 die( "Unable to get Job Bytes from catalog" );
699 $tmp = $result->fetchRow( DB_FETCHMODE_ASSOC );
701 $day = date( "D d", strtotime($end_date) );
703 if( isset( $tmp['stored_bytes'] ) ) {
704 $hbytes = $this->human_file_size( $tmp['stored_bytes'], 3, 'GB');
705 $hbytes = explode( " ", $hbytes );
706 $stored_bytes = $hbytes[0];
709 return array( $day, $stored_bytes );
713 public function GetStoredBytesByJob( $jobname, $start_date, $end_date )
715 $query = "SELECT SUM(JobBytes) as stored_bytes, EndTime FROM Job ";
716 $query .= "WHERE ( EndTime BETWEEN '$start_date' AND '$end_date' ) AND ";
717 $query .= "Name = '$jobname'";
719 $result = $this->db_link->query( $query );
721 if( PEAR::isError( $result ) ) {
722 die( "Unable to get Job Bytes from catalog" );
725 $tmp = $result->fetchRow( DB_FETCHMODE_ASSOC );
727 $day = date( "D d", strtotime($end_date) );
729 if( isset( $tmp['stored_bytes'] ) ) {
730 $hbytes = $this->human_file_size( $tmp['stored_bytes'], 3, 'GB');
731 $hbytes = explode( " ", $hbytes );
732 $stored_bytes = $hbytes[0];
735 return array( $day, $stored_bytes );
739 public function GetStoredFilesByJob( $jobname, $start_date, $end_date )
741 $query = "SELECT SUM(JobFiles) as stored_files, EndTime FROM Job ";
742 $query .= "WHERE ( EndTime BETWEEN '$start_date' AND '$end_date' ) AND ";
743 $query .= "Name = '$jobname'";
745 $result = $this->db_link->query( $query );
747 if( PEAR::isError( $result ) ) {
748 die( "Unable to get Job Files from catalog" );
751 $tmp = $result->fetchRow( DB_FETCHMODE_ASSOC );
753 $day = date( "D d", strtotime($end_date) );
754 $stored_files = $tmp['stored_files'];
756 return array( $day, $stored_files );