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($smarty_path."Smarty.class.php");
20 require_once "DB.php"; // Pear DB
21 require_once "config.inc.php";
22 require_once "bgraph.inc.php";
24 class Bweb extends DB {
33 public $db_link; // Database link
34 private $db_dsn; // Data Source Name
36 private $config_file; // Config filename
37 private $config; // Loaded config from bacula.conf
38 private $catalogs = array(); // Catalog array
40 function __construct()
42 $this->catalogs = array();
44 // Loading configuration
45 $this->config_file = getcwd() . '/configs/bacula.conf';
47 if( !$this->load_config() )
48 die( "Unable to load configuration");
50 // Construct a valid dsn
51 $this->db_dsn['hostspec'] = $this->catalogs[0]["host"];
52 $this->db_dsn['username'] = $this->catalogs[0]["login"];
53 $this->db_dsn['password'] = $this->catalogs[0]["pass"];
54 $this->db_dsn['database'] = $this->catalogs[0]["db_name"];
55 $this->db_dsn['phptype'] = $this->catalogs[0]["db_type"];
58 $this->db_link = $this->connect($this->db_dsn);
60 if (DB::isError($this->db_link)) {
61 die($this->db_link->getMessage());
63 $this->driver = $this->db_dsn['phptype'];
64 register_shutdown_function(array(&$this,'close'));
65 $this->dbs_name = $this->db_dsn['database'];
68 // Initialize smarty template classe
70 // Initialize smarty gettext function
71 $this->init_gettext();
74 // Initialize Smarty template classe
77 $this->tpl = new Smarty();
79 $this->tpl->compile_check = true;
80 $this->tpl->debugging = false;
81 $this->tpl->force_compile = true;
83 $this->tpl->template_dir = "./templates";
84 $this->tpl->compile_dir = "./templates_c";
85 $this->tpl->config_dir = "./configs";
88 function init_gettext()
90 global $smarty_gettext_path;
92 if ( function_exists("gettext") ) {
93 require_once( $smarty_gettext_path."smarty_gettext.php" );
94 $this->tpl->register_block('t','smarty_translate');
96 $language = $this->get_config_param("lang");
98 putenv("LANG=$language");
99 setlocale(LC_ALL, $language);
100 bindtextdomain($domain,"./locale");
104 function smarty_translate($params, $text, &$smarty) {
107 $smarty->register_block('t','smarty_translate');
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 );
244 } // end function GetDbSize()
246 public function Get_Nb_Clients()
248 $clients = $this->db_link->query("SELECT COUNT(*) AS nb_client FROM Client");
249 if( PEAR::isError($clients) )
250 die( "Unable to get client number" );
252 return $clients->fetchRow( DB_FETCHMODE_ASSOC );
255 // Return an array of volumes ordered by poolid and volume name
256 function GetVolumeList() {
262 // Get the list of pools id
263 $query = "SELECT Pool.poolid, Pool.name FROM Pool ORDER BY Pool.poolid";
265 //$this->db_link->setFetchMode(DB_FETCHMODE_ASSOC);
266 $pools = $this->db_link->query( $query );
268 if( PEAR::isError( $pools ) )
269 die("Error: Failed to get pool list <br />SQL Query: $query<br />" . $pools->getMessage() );
271 while( $pool = $pools->fetchRow( DB_FETCHMODE_ASSOC ) ) {
272 switch( $this->driver )
275 $query = "SELECT Media.volumename, Media.volbytes, Media.volstatus, Media.mediatype, Media.lastwritten, Media.volretention
276 FROM Media LEFT JOIN Pool ON Media.poolid = Pool.poolid
277 WHERE Media.poolid = '". $pool['poolid'] . "' ORDER BY Media.volumename";
280 $query = "SELECT media.volumename, media.volbytes, media.volstatus, media.mediatype, media.lastwritten, media.volretention
281 FROM media LEFT JOIN pool ON media.poolid = pool.poolid
282 WHERE media.poolid = '". $pool['poolid'] . "' ORDER BY media.volumename";
285 $query = ""; // not yet implemented
291 $medias = $this->db_link->query( $query );
293 if( PEAR::isError( $medias ) ) {
294 die( "Failed to get media list for pool $volume[0] <br /> " . $medias->getMessage() );
296 if( $debug ) echo "Found " . $medias->numRows() . " medias for pool " . $pool['name'] . " <br />";
298 // Create array key for each pool
299 if( !array_key_exists( $pool['name'], $volumes) )
301 $volumes[ $pool['name'] ] = array();
303 while( $media = $medias->fetchRow( DB_FETCHMODE_ASSOC ) ) {
307 // If the pool is empty (no volumes in this pool)
308 if( $medias->numRows() == 0 ) {
309 if( $debug ) echo "No media in pool " . $pool['name'] . "<br />";
311 if( $media['lastwritten'] != "0000-00-00 00:00:00" ) {
312 // Calculate expiration date if the volume is Full
313 if( $media['volstatus'] == 'Full' ) {
314 $expire_date = strtotime($media['lastwritten']) + $media['volretention'];
315 $media['expire'] = strftime("%Y-%m-%d", $expire_date);
317 $media['expire'] = 'N/A';
319 // Media used bytes in a human format
320 $media['volbytes'] = $this->human_file_size( $media['volbytes'] );
322 $media['lastwritten'] = "N/A";
323 $media['expire'] = "N/A";
324 $media['volbytes'] = "0 KB";
328 if( count( $volumes[ $pool['name'] ] ) % 2)
329 $media['class'] = 'odd';
331 // Add the media in pool array
332 array_push( $volumes[ $pool['name']], $media);
338 } // end function GetVolumeList()
340 public function CountJobsbyLevel( $delay = LAST_DAY, $level = 'F' )
342 $end_date = mktime();
343 $start_date = $end_date - $delay;
345 $start_date = date( "Y-m-d H:i:s", $start_date );
346 $end_date = date( "Y-m-d H:i:s", $end_date );
348 $query = "SELECT COUNT(JobId) as jobs FROM Job ";
349 $query .= "WHERE (EndTime BETWEEN '$start_date' AND '$end_date') AND ";
350 $query .= "Level = '$level' ";
352 $result = $this->db_link->query( $query );
354 if (PEAR::isError( $result ) ) {
355 die( "Unable to get number of jobs with $level status from catalog <br />" . $result->getMessage() );
357 $jobs = $result->fetchRow( DB_FETCHMODE_ASSOC );
358 return $jobs['jobs'];
363 public function CountJobs( $delay = LAST_DAY, $status = 'any' )
365 $query = "SELECT COUNT(JobId) AS job_nb FROM Job ";
369 // Interval condition for SQL query
370 if( $delay != ALL ) {
371 $end_date = mktime();
372 $start_date = $end_date - $delay;
374 $start_date = date( "Y-m-d H:i:s", $start_date );
375 $end_date = date( "Y-m-d H:i:s", $end_date );
377 $where_delay = "WHERE EndTime BETWEEN '$start_date' AND '$end_date' ";
380 if( $status != 'any' ) {
384 $where_status = "JobStatus = 'T' ";
387 $where_status = "JobStatus IN ('f','E') ";
390 $where_status = "JobStatus = 'A' ";
393 $where_status = "JobStatus IN ('F','S','M','m','s','j','c','d','t') ";
398 if( !empty($where_delay) )
399 $query = $query . $where_delay . 'AND ' . $where_status;
401 if( !empty($where_status) )
402 $query = $query . 'WHERE ' . $where_status;
405 $jobs = $this->db_link->query( $query );
407 if (PEAR::isError( $jobs ) ) {
408 die( "Unable to get last $status jobs number from catalog <br />" . $jobs->getMessage() );
410 $jobs = $jobs->fetchRow( DB_FETCHMODE_ASSOC );
411 return $jobs['job_nb'];
415 // Return the list of Pools in a array
416 public function Get_Pools_List()
418 $pool_list = array();
421 $query = "SELECT Name, PoolId FROM Pool";
423 $result = $this->db_link->query ( $query );
425 if( PEAR::isError( $result ) ) {
426 die( "Unable to get the pool list from catalog" );
428 while( $pool = $result->fetchRow(DB_FETCHMODE_ASSOC) ) {
429 array_push( $pool_list, array( $pool['Name'] => $pool['PoolId'] ) );
435 public function Get_BackupJob_Names()
437 $query = "SELECT Name FROM Job GROUP BY Name";
438 $backupjobs = array();
440 $result = $this->db_link->query( $query );
442 if (PEAR::isError( $result ) ) {
443 die("Unable to get BackupJobs list from catalog" );
445 while( $backupjob = $result->fetchRow( DB_FETCHMODE_ASSOC ) ) {
446 array_push( $backupjobs, $backupjob["Name"] );
452 // Return elasped time string for a job
453 function Get_ElapsedTime( $start_time, $end_time )
455 $diff = $end_time - $start_time;
457 $daysDiff = sprintf("%02d", floor($diff/60/60/24) );
458 $diff -= $daysDiff*60*60*24;
460 $hrsDiff = sprintf("%02d", floor($diff/60/60) );
461 $diff -= $hrsDiff*60*60;
463 $minsDiff = sprintf("%02d", floor($diff/60) );
464 $diff -= $minsDiff*60;
465 $secsDiff = sprintf("%02d", $diff );
468 return $daysDiff . 'day(s) ' . $hrsDiff.':' . $minsDiff . ':' . $secsDiff;
470 return $hrsDiff . ':' . $minsDiff . ':' . $secsDiff;
473 public function Get_ElapsedTime_Job( $delay = LAST_DAY )
478 // Interval calculation
479 $end_date = mktime();
480 $start_date = $end_date - $delay;
482 $start_date = date( "Y-m-d H:i:s", $start_date );
483 $end_date = date( "Y-m-d H:i:s", $end_date );
485 switch( $this->driver )
488 $query = "SELECT UNIX_TIMESTAMP(EndTime) - UNIX_TIMESTAMP(StartTime) AS elapsed from Job ";
489 $query .= "WHERE EndTime BETWEEN '$start_date' AND '$end_date'";
492 $result = $this->db_link->query( $query );
494 if( PEAR::isError($result) ){
495 die( "Unable to get elapsed time for jobs from catalog<br />query = $query <br />" . $result->getMessage() );
497 while( $time = $result->fetchRow( DB_FETCHMODE_ASSOC ) ) {
498 //echo 'elapsed = ' . $time['elapsed'] . '<br />';
499 $total_elapsed += $time['elapsed'];
501 // Verify if elapsed time is more than 1 day
502 if ( $total_elapsed > LAST_DAY ) {
503 return date("%d days H:i:s", $total_elapsed );
505 return date("H:i:s", $total_elapsed );
510 // Return Jobs statistics for a specific interval such as
511 // - Completed jobs number
512 // - Failed jobs number
513 // - Waiting jobs number
514 // The returned values will be used by a Bgraph classe
515 public function GetJobsStatistics( $type = 'completed', $delay = LAST_DAY )
523 // Interval calculation
524 $end_date = mktime();
525 $start_date = $end_date - $delay;
527 $start_date = date( "Y-m-d H:i:s", $start_date );
528 $end_date = date( "Y-m-d H:i:s", $end_date );
530 $interval_where = "(EndTime BETWEEN '$start_date' AND '$end_date') AND ";
536 $where = $interval_where . "JobStatus = 'T' ";
537 $label = "Completed";
539 case 'terminated_errors':
540 $where = $interval_where . "JobStatus = 'E' ";
541 $label = "Terminated with errors";
544 $where = $interval_where . "JobStatus = 'f' ";
548 $where = "JobStatus IN ('F','S','M','m','s','j','c','d','t') ";
552 $where = "JobStatus = 'C' ";
553 $label = "Created but not running";
556 $where = "JobStatus = 'R' ";
560 $where = $interval_where . "JobStatus IN ('e','f') ";
565 $query = 'SELECT COUNT(JobId) AS ' . $type . ' ';
566 $query .= 'FROM Job ';
567 $query .= "WHERE $where ";
569 //echo 'query = ' . $query . '<br />';
571 $jobs = $this->db_link->query( $query );
573 if (PEAR::isError( $jobs ) ) {
574 die( "Unable to get last $type jobs status from catalog<br />" . $status->getMessage() );
576 $res = $jobs->fetchRow();
577 return array( $label , current($res) );
579 } // end function GetJobsStatistics()
581 public function GetPoolsStatistics( $pools )
583 foreach( $pools as $pool_name => $pool ) {
585 $query = "SELECT COUNT(*) AS nb_vol FROM Media WHERE PoolId = '$pool'";
586 //echo $query . '<br />';
587 //echo 'Pool name ' . $pool_name . '<br />';
588 $result = $this->db_link->query( $query );
590 if( PEAR::isError( $result ) ) {
591 die("Unable to get volume number from catalog");
593 $nb_vol = $result->fetchRow(DB_FETCHMODE_ASSOC);
594 return array( $pool_name, $nb_vol['nb_vol'] );
599 public function GetStoredFiles( $delay = LAST_DAY )
603 $query = "SELECT SUM(JobFiles) AS stored_files FROM Job ";
605 // Interval calculation
606 $end_date = mktime();
607 $start_date = $end_date - $delay;
609 $start_date = date( "Y-m-d H:i:s", $start_date );
610 $end_date = date( "Y-m-d H:i:s", $end_date );
613 $query .= "WHERE EndTime BETWEEN '$start_date' AND '$end_date'";
615 $result = $this->db_link->query( $query );
617 if( !PEAR::isError($result) ) {
618 $nbfiles = $result->fetchRow(DB_FETCHMODE_ASSOC);
619 $totalfiles = $totalfiles + $nbfiles['stored_files'];
621 die("Unable to get protected files from catalog <br />" . $result->getMessage() );
627 public function GetStoredBytes( $delay = LAST_DAY )
629 $query = "SELECT SUM(JobBytes) as stored_bytes FROM Job ";
631 // Interval calculation
632 $end_date = mktime();
633 $start_date = $end_date - $delay;
635 $start_date = date( "Y-m-d H:i:s", $start_date );
636 $end_date = date( "Y-m-d H:i:s", $end_date );
639 $query .= "WHERE EndTime BETWEEN '$start_date' AND '$end_date'";
641 $result = $this->db_link->query( $query );
643 if( PEAR::isError( $result ) ) {
644 die( "Unable to get Job Bytes from catalog" );
646 return $result->fetchRow( DB_FETCHMODE_ASSOC );
650 public function GetStoredBytesByInterval( $start_date, $end_date )
652 $query = "SELECT SUM(JobBytes) as stored_bytes, EndTime FROM Job WHERE EndTime BETWEEN '$start_date' AND '$end_date'";
654 $result = $this->db_link->query( $query );
656 if( PEAR::isError( $result ) ) {
657 die( "Unable to get Job Bytes from catalog" );
660 $tmp = $result->fetchRow( DB_FETCHMODE_ASSOC );
662 $day = date( "D d", strtotime($end_date) );
664 if( isset( $tmp['stored_bytes'] ) ) {
665 $hbytes = $this->human_file_size( $tmp['stored_bytes'], 3, 'GB');
666 $hbytes = explode( " ", $hbytes );
667 $stored_bytes = $hbytes[0];
670 return array( $day, $stored_bytes );
674 public function GetStoredBytesByJob( $jobname, $start_date, $end_date )
676 $query = "SELECT SUM(JobBytes) as stored_bytes, EndTime FROM Job ";
677 $query .= "WHERE ( EndTime BETWEEN '$start_date' AND '$end_date' ) AND ";
678 $query .= "Name = '$jobname'";
680 $result = $this->db_link->query( $query );
682 if( PEAR::isError( $result ) ) {
683 die( "Unable to get Job Bytes from catalog" );
686 $tmp = $result->fetchRow( DB_FETCHMODE_ASSOC );
688 $day = date( "D d", strtotime($end_date) );
690 if( isset( $tmp['stored_bytes'] ) ) {
691 $hbytes = $this->human_file_size( $tmp['stored_bytes'], 3, 'GB');
692 $hbytes = explode( " ", $hbytes );
693 $stored_bytes = $hbytes[0];
696 return array( $day, $stored_bytes );
700 public function GetStoredFilesByJob( $jobname, $start_date, $end_date )
702 $query = "SELECT SUM(JobFiles) as stored_files, EndTime FROM Job ";
703 $query .= "WHERE ( EndTime BETWEEN '$start_date' AND '$end_date' ) AND ";
704 $query .= "Name = '$jobname'";
706 $result = $this->db_link->query( $query );
708 if( PEAR::isError( $result ) ) {
709 die( "Unable to get Job Files from catalog" );
712 $tmp = $result->fetchRow( DB_FETCHMODE_ASSOC );
714 $day = date( "D d", strtotime($end_date) );
715 $stored_files = $tmp['stored_files'];
717 return array( $day, $stored_files );