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 = 'any' )
347 $query = "SELECT COUNT(JobId) AS job_nb FROM Job ";
351 // Interval condition for SQL query
352 if( $delay != ALL ) {
353 $end_date = mktime();
354 $start_date = $end_date - $delay;
356 $start_date = date( "Y-m-d H:i:s", $start_date );
357 $end_date = date( "Y-m-d H:i:s", $end_date );
359 $where_delay = "WHERE EndTime BETWEEN '$start_date' AND '$end_date' ";
362 if( $status != 'any' ) {
366 $where_status = "JobStatus = 'T' ";
369 $where_status = "JobStatus = 'f' ";
372 $where_status = "JobStatus = 'A' ";
377 if( !empty($where_delay) )
378 $query = $query . $where_delay . 'AND ' . $where_status;
380 if( !empty($where_status) )
381 $query = $query . 'WHERE ' . $where_status;
384 $jobs = $this->db_link->query( $query );
386 if (PEAR::isError( $jobs ) ) {
387 die( "Unable to get last $status jobs number from catalog <br />" . $jobs->getMessage() );
389 $jobs = $jobs->fetchRow( DB_FETCHMODE_ASSOC );
390 return $jobs['job_nb'];
394 // Return the list of Pools in a array
395 public function Get_Pools_List()
397 $pool_list = array();
400 $query = "SELECT Name, PoolId FROM Pool";
402 $result = $this->db_link->query ( $query );
404 if( PEAR::isError( $result ) ) {
405 die( "Unable to get the pool list from catalog" );
407 while( $pool = $result->fetchRow(DB_FETCHMODE_ASSOC) ) {
408 array_push( $pool_list, array( $pool['Name'] => $pool['PoolId'] ) );
414 public function Get_BackupJob_Names()
416 $query = "SELECT Name FROM Job GROUP BY Name";
417 $backupjobs = array();
419 $result = $this->db_link->query( $query );
421 if (PEAR::isError( $result ) ) {
422 die("Unable to get BackupJobs list from catalog" );
424 while( $backupjob = $result->fetchRow( DB_FETCHMODE_ASSOC ) ) {
425 array_push( $backupjobs, $backupjob["Name"] );
431 // Return elasped time string for a job
432 function Get_ElapsedTime( $start_time, $end_time )
434 $diff = $end_time - $start_time;
436 $daysDiff = sprintf("%02d", floor($diff/60/60/24) );
437 $diff -= $daysDiff*60*60*24;
439 $hrsDiff = sprintf("%02d", floor($diff/60/60) );
440 $diff -= $hrsDiff*60*60;
442 $minsDiff = sprintf("%02d", floor($diff/60) );
443 $diff -= $minsDiff*60;
444 $secsDiff = sprintf("%02d", $diff );
447 return $daysDiff . 'day(s) ' . $hrsDiff.':' . $minsDiff . ':' . $secsDiff;
449 return $hrsDiff . ':' . $minsDiff . ':' . $secsDiff;
452 public function Get_ElapsedTime_Job( $delay = LAST_DAY )
457 // Interval calculation
458 $end_date = mktime();
459 $start_date = $end_date - $delay;
461 $start_date = date( "Y-m-d H:i:s", $start_date );
462 $end_date = date( "Y-m-d H:i:s", $end_date );
464 switch( $this->driver )
467 $query = "SELECT UNIX_TIMESTAMP(EndTime) - UNIX_TIMESTAMP(StartTime) AS elapsed from Job ";
468 $query .= "WHERE EndTime BETWEEN '$start_date' AND '$end_date'";
471 $result = $this->db_link->query( $query );
473 if( PEAR::isError($result) ){
474 die( "Unable to get elapsed time for jobs from catalog<br />query = $query <br />" . $result->getMessage() );
476 while( $time = $result->fetchRow( DB_FETCHMODE_ASSOC ) ) {
477 //echo 'elapsed = ' . $time['elapsed'] . '<br />';
478 $total_elapsed += $time['elapsed'];
480 // Verify if elapsed time is more than 1 day
481 if ( $total_elapsed > LAST_DAY ) {
482 return date("%d days H:i:s", $total_elapsed );
484 return date("H:i:s", $total_elapsed );
489 // Return Jobs statistics for a specific interval such as
490 // - Completed jobs number
491 // - Failed jobs number
492 // - Waiting jobs number
493 // The returned values will be used by a Bgraph classe
494 public function GetJobsStatistics( $type = 'completed', $delay = LAST_DAY )
502 // Interval calculation
503 $end_date = mktime();
504 $start_date = $end_date - $delay;
506 $start_date = date( "Y-m-d H:i:s", $start_date );
507 $end_date = date( "Y-m-d H:i:s", $end_date );
513 $where = "AND JobStatus = 'T' ";
514 $label = "Completed";
516 case 'terminated_errors':
517 $where = $interval_where . "JobStatus = 'E' ";
518 $label = "Terminated with errors";
521 $where = "AND JobStatus = 'f' ";
525 $where = "AND JobStatus IN ('F','S','M','m','s','j','c','d','t') ";
529 $where = "AND JobStatus = 'C' ";
530 $label = "Created but not running";
533 $where = "AND JobStatus = 'R' ";
537 $where = "AND JobStatus IN ('e','f') ";
542 $query = 'SELECT COUNT(JobId) AS ' . $type . ' ';
543 $query .= 'FROM Job ';
544 $query .= "WHERE EndTime BETWEEN '$start_date' AND '$end_date' ";
547 $jobs = $this->db_link->query( $query );
549 if (PEAR::isError( $jobs ) ) {
550 die( "Unable to get last $type jobs status from catalog<br />" . $status->getMessage() );
552 $res = $jobs->fetchRow();
553 return array( $label , current($res) );
555 } // end function GetJobsStatistics()
557 public function GetPoolsStatistics( $pools )
559 foreach( $pools as $pool_name => $pool ) {
561 $query = "SELECT COUNT(*) AS nb_vol FROM Media WHERE PoolId = '$pool'";
562 //echo $query . '<br />';
563 //echo 'Pool name ' . $pool_name . '<br />';
564 $result = $this->db_link->query( $query );
566 if( PEAR::isError( $result ) ) {
567 die("Unable to get volume number from catalog");
569 $nb_vol = $result->fetchRow(DB_FETCHMODE_ASSOC);
570 return array( $pool_name, $nb_vol['nb_vol'] );
575 public function GetStoredFiles()
578 $query = "SELECT COUNT(FilenameId) AS nbfiles FROM Filename";
579 $result = $this->db_link->query( $query );
581 if( !PEAR::isError($result) ) {
582 $nbfiles = $result->fetchRow(DB_FETCHMODE_ASSOC);
583 $nbfiles = $nbfiles['nbfiles'];
585 die("Unable to get protected files from catalog");
590 public function GetStoredBytes( $delay = LAST_DAY )
592 $query = "SELECT SUM(JobBytes) as stored_bytes FROM Job ";
594 // Interval calculation
595 $end_date = mktime();
596 $start_date = $end_date - $delay;
598 $start_date = date( "Y-m-d H:i:s", $start_date );
599 $end_date = date( "Y-m-d H:i:s", $end_date );
601 if( $delay != ALL ) {
602 $query .= "WHERE EndTime BETWEEN '$start_date' AND '$end_date'";
605 $result = $this->db_link->query( $query );
607 if( PEAR::isError( $result ) ) {
608 die( "Unable to get Job Bytes from catalog" );
610 return $result->fetchRow( DB_FETCHMODE_ASSOC );
614 public function GetStoredBytesByInterval( $start_date, $end_date )
616 $query = "SELECT SUM(JobBytes) as stored_bytes, EndTime FROM Job WHERE EndTime BETWEEN '$start_date' AND '$end_date'";
618 $result = $this->db_link->query( $query );
620 if( PEAR::isError( $result ) ) {
621 die( "Unable to get Job Bytes from catalog" );
624 $tmp = $result->fetchRow( DB_FETCHMODE_ASSOC );
626 $day = date( "D d", strtotime($end_date) );
628 if( isset( $tmp['stored_bytes'] ) ) {
629 $hbytes = $this->human_file_size( $tmp['stored_bytes'], 3, 'GB');
630 $hbytes = explode( " ", $hbytes );
631 $stored_bytes = $hbytes[0];
634 return array( $day, $stored_bytes );