Added a new script gcm_maintenance.php to cleanup the database
[gnucomo.git] / src / gcm_daemon / gcm_maintenance.php
1 #!/usr/bin/php
2 <?PHP
3 /**********************************************************************************
4 **  (c) Copyright 2002, Brenno J.S.A.A.F. de Winter, De Winter Information Solutions
5 ** This is free software; you can redistribute it and/or modify it under the
6 ** terms of the GNU General Public License, see the file COPYING.
7 ***********************************************************************************/
8
9
10 /*
11    NAME          : check_database
12    AUTHOR        : Arjen Baart
13                    Andromeda Technology & Automation
14
15  $Log: gcm_maintenance.php,v $
16  Revision 1.1  2007-12-12 09:06:21  arjen
17  Added a new script gcm_maintenance.php to cleanup the database
18  and check referential integrity. Purging old log entries is
19  removed from the gcm_daemon script.
20
21
22 */
23
24 // $Id: gcm_maintenance.php,v 1.1 2007-12-12 09:06:21 arjen Exp $
25
26 ini_set('include_path', '.:./classes:../phpclasses');
27 ini_set('html_errors', 'false');
28
29 define("BATCHSIZE", 10000);
30
31 //Tell the log that we're up.
32 define_syslog_variables();
33
34 require_once "gnucomo_config.php";
35 require_once "db.class.php";
36
37 // Set the standard variables //
38
39 $purge_date     ="";            // Purge log entries until this date. Default: no purging
40 $project_name   = "gnucomo";    // name of the entire project
41 $app_name       = "gcm_maintenance"; // name of the application running
42
43 //Avoid time-limit issues
44 set_time_limit(0);
45
46 //  Scan the command arguments
47
48 for ($argi = 1; $argi < $argc; $argi++)
49 {
50    switch ($argv[$argi])
51    {
52    case "-c":
53       $argi++;
54       $project_name = $argv[$argi];
55       break;
56
57    case "-p":
58       $argi++;
59       $purge_date = $argv[$argi];
60       break;
61
62    default:
63       echo "Usage: gcm_daemon [-c configname] [-p purgedate]\n";
64       exit();
65       break;
66    }
67 }
68
69 // Read the database settings //
70 $class_settings = new gnucomo_config();
71 if (!$class_settings->read($project_name))
72 {
73    echo "Can not read Gnucomo configuration file for $project_name.\n";
74    exit();
75 }
76
77 openlog("gnucomo", LOG_PID, LOG_DAEMON);
78
79 //Open an connection to the database
80 $dbms_type = $class_settings->find_parameter("database", "type");
81 $dbms_host = $class_settings->find_parameter("database", "host");
82 $dbms_name = $class_settings->find_parameter("database", "name");
83 $dbms_user = $class_settings->find_parameter("gcm_daemon", "user");
84 $dbms_password = $class_settings->find_parameter("gcm_daemon", "password");
85
86 db_select($dbms_type);
87 $dbms = new db();
88 $dbms->db_host = $dbms_host;
89 $dbms->db_name = $dbms_name;
90 $dbms->db_user = $dbms_user;
91 $dbms->db_password = $dbms_password;
92 $dbms->db_connect($class_settings->database());
93
94 if ($dbms->have_db_connection() == "FALSE")
95 {
96    exit ("Database connection failed.");
97 }
98
99    if ($purge_date != "")
100    {
101       purge_old_logs($purge_date);
102    }
103
104    // Check the references from the abuse list to the logs
105
106
107    $abuse_result = $dbms->query("select source, nr_abuses, masklen(source) from object_abuse
108                                  where status='dropped' and masklen(source)=32 and objectid=1 order by source");
109    for ($ab = 0; $ab < $dbms->num_rows($abuse_result); $ab++)
110    {
111       $logentries = 0;
112       $abuse = $dbms->fetch_object($abuse_result, $ab);
113       $nr_abuses = $abuse->nr_abuses;
114       $log_res = $dbms->query("select logid from log_abuse where source='" . $abuse->source . "' and objectid=1");
115
116       if ($dbms->num_rows($log_res) != $nr_abuses)
117       {
118          echo "Mismatch in nr of abuses. Corrected.\n";
119          $dbms->query("update object_abuse set nr_abuses=" . $dbms->num_rows($log_res) .
120                       " where source='" . $abuse->source . "' and objectid=1");
121       }
122       if ($dbms->num_rows($log_res) == 0)
123       {
124          echo "  Removing ", $abuse->source, "\n";
125          $dbms->query("delete from object_abuse where source='". $abuse->source . "' and objectid=1");
126       }
127       else
128       {
129          $logref_res = $dbms->query("select logid from log where logid in
130                                     (select logid from log_abuse where source='" . $abuse->source . "' and objectid=1)");
131          $logentries = $dbms->num_rows($logref_res);
132          if ($logentries == 0)
133          {
134             echo "All references to log entries are lost. Purging log_abuse table.\n";
135             $dbms->query("delete from log_abuse where source='" . $abuse->source . "' and objectid=1");
136             
137          }
138       }
139       echo $abuse->source . "\t$nr_abuses\t" . $dbms->num_rows($log_res) . "\t" . $logentries . "\n";
140    }
141
142    //  Gather the statistics for each object
143
144    $obj_result = $dbms->query("SELECT objectid FROM object");
145    for ($obj = 0; $obj < $dbms->num_rows($obj_result); $obj++)
146    {
147       $object = $dbms->fetch_object($obj_result, $obj);
148       echo "Gathering statistics for object " . $object->objectid . "\n";
149       GatherStatistics($object->objectid);
150    }
151
152
153 function purge_old_logs($purge_date)
154 {
155    global $dbms;
156
157    /*
158     *   Make a temporary table with the logids of the old log entries
159     *   We don't want to repeat a selection on the large log table itself.
160     */
161
162    echo "Purging log entries before $purge_date\n";
163
164    $dbms->query("CREATE TABLE gcm_deamon_old_log AS SELECT logid FROM log WHERE timestamp < '$purge_date'");
165    $dbms->query("SELECT logid FROM gcm_deamon_old_log");
166    echo $dbms->num_rows() . " log entries found.\n";
167
168    //  Clean up notifications that are left without reference to the log.
169
170    $r = $dbms->query("select notificationid from log_notification where logid in
171                          (select logid from gcm_deamon_old_log) group by notificationid");
172    echo "Notifications that may be affected:\n";
173    $notifications = array();
174    for ($i=0; $i < $dbms->num_rows(); $i++)
175    {
176       $notif = $dbms->fetch_object($r, $i);
177       $notifications[] = $notif->notificationid;
178       echo $notif->notificationid . "\n";
179    }
180    $dbms->query("delete from log_notification where logid in
181                          (select logid from gcm_deamon_old_log)");
182
183    //  Clean up any notifications that have no more logs left
184    foreach ($notifications as $notif)
185    {
186       $c = $dbms->fetch_object($dbms->query("select count(*) from log_notification where notificationid=$notif"), 0);
187       echo "Notification $notif has " . $c->count . " log entries left.\n";
188       if ($c->count == 0)
189       {
190          echo "Cleaning up notification $notif.\n";
191          $dbms->query("delete from action_user where notificationid=$notif");
192          $dbms->query("delete from notification where notificationid=$notif");
193       }
194    }
195
196    //  Clean up abuses that are left without reference to the log.
197
198    $r = $dbms->query("select source from log_abuse where logid in
199                          (select logid from gcm_deamon_old_log) group by source");
200    echo "Abusing IP addresses that may be affected:\n";
201    $abusers = array();
202    for ($i = 0; $i < $dbms->num_rows(); $i++)
203    {
204       $ab = $dbms->fetch_object($r, $i);
205       $abusers[] = $ab->source;
206       echo $ab->source . "\n";
207    }
208    $dbms->query("delete from log_abuse where logid in
209                    (select logid from gcm_deamon_old_log)");
210
211    foreach ($abusers as $src)
212    {
213       $c = $dbms->fetch_object($dbms->query("select count(*) from log_abuse where source='$src'"), 0);
214       echo "IP address $src has " . $c->count . " log entries left.\n";
215       if ($c->count == 0)
216       {
217          echo "Cleaning up abusing address $src.\n";
218          $dbms->query("delete from object_abuse where source='$src'");
219       }
220    }
221
222    $dbms->query("delete from log where logid in
223                          (select logid from gcm_deamon_old_log)");
224
225    $dbms->query("drop table gcm_deamon_old_log");
226 }
227
228
229 /*
230  *   Update a single statistic for some object.
231  *   If it does not yet exist, it will be created.
232  */
233
234 function UpdateStatistic($objectid, $name, $value)
235 {
236    global $dbms;
237
238    $result = $dbms->query("SELECT objectid FROM object_statistics WHERE
239              objectid='$objectid' AND statname='$name'");
240    if ($dbms->num_rows() == 0)
241    {
242       $dbms->query("INSERT INTO object_statistics VALUES
243                     ('$objectid', '$name', '$value')");
244    }
245    else
246    {
247       $dbms->query("UPDATE object_statistics SET statvalue='$value' WHERE
248            statname='$name' AND objectid='$objectid'");
249    }
250 }
251
252 /*
253  *   Gather the statistics for a single object ($objectid).
254  *   We count the number of parameters, removed parameters, notifications
255  *   closed notifications and log entries. The totals of these are
256  *   maintained in a separate table: object_statistics.
257  */
258
259 function GatherStatistics($objectid)
260 {
261    global $dbms;
262
263    //  Gather statistics on parameters
264
265    $r = $dbms->query("SELECT paramid FROM parameter WHERE objectid=CAST('"
266                         . $objectid . "' AS BIGINT)");
267    $nr_parameters = $dbms->num_rows($r);
268
269    $removed_parameters = 0;
270    for ($p = 0; $p < $nr_parameters; $p++)
271    {
272       $param = pg_fetch_object($r, $p);
273       $qry ="select change_nature from history where paramid= CAST('";
274       $qry .= $param->paramid . "' AS BIGINT) order by modified desc";
275       $rhist = $dbms->query($qry);
276       if ($dbms->num_rows($rhist) == 0)
277       {
278          echo "ERROR: No history for parameter id " . $param->paramid . "\n";
279       }
280       else
281       {
282          $hist = $dbms->fetch_object($rhist, 0);
283          if ($hist->change_nature == "REMOVED")
284          {
285             $removed_parameters++;
286          }
287       }
288    }
289
290    UpdateStatistic($objectid, 'parameters', $nr_parameters);
291    UpdateStatistic($objectid, 'removed_parameters', $removed_parameters);
292
293    //  Gather statistics on notifications
294
295    $r = $dbms->query("SELECT count(notificationid) FROM notification WHERE
296                        objectid = CAST('" . $objectid . "' AS BIGINT)");
297    $cnt = $dbms->fetch_object($r, 0);
298    UpdateStatistic($objectid, 'notifications', $cnt->count);
299
300    $r = $dbms->query("SELECT count(notificationid) FROM notification WHERE
301                        objectid = CAST('" . $objectid . "' AS BIGINT) AND statuscode ='cls'");
302    $cnt = $dbms->fetch_object($r, 0);
303    UpdateStatistic($objectid, 'closed_notifications', $cnt->count);
304
305    //  Gather statistics on log entries
306
307    $r = $dbms->query("SELECT count(logid) FROM log WHERE
308                        objectid = CAST('" . $objectid . "' AS BIGINT)");
309    $cnt = $dbms->fetch_object($r, 0);
310    UpdateStatistic($objectid, 'logs', $cnt->count);
311 }