syncshadowdb 9.71 KB
Newer Older
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25
#!/usr/bonsaitools/bin/perl -w
# -*- Mode: perl; indent-tabs-mode: nil -*-
#
# The contents of this file are subject to the Mozilla Public
# License Version 1.1 (the "License"); you may not use this file
# except in compliance with the License. You may obtain a copy of
# the License at http://www.mozilla.org/MPL/
#
# Software distributed under the License is distributed on an "AS
# IS" basis, WITHOUT WARRANTY OF ANY KIND, either express or
# implied. See the License for the specific language governing
# rights and limitations under the License.
#
# The Original Code is the Bugzilla Bug Tracking System.
#
# The Initial Developer of the Original Code is Netscape Communications
# Corporation. Portions created by Netscape are
# Copyright (C) 1998 Netscape Communications Corporation. All
# Rights Reserved.
#
# Contributor(s): Terry Weissman <terry@mozilla.org>
#                 David Gardiner <david.gardiner@unisa.edu.au>

use strict;

26 27 28 29
use lib qw(.);

use Bugzilla::Config qw(:DEFAULT :admin);

30
require "globals.pl";
31
require "defparams.pl";
32 33 34 35 36 37

# Shut up misguided -w warnings about "used only once".  "use vars" just
# doesn't work for me.

sub sillyness {
    my $zz;
38
    open SAVEOUT,">/dev/null";
39
    $zz = $::db;
40 41 42 43
    $zz = $::dbwritesallowed;
}

my $verbose = 0;
44
my $syncall = 0;
45 46 47 48 49
my $shutdown = 0;
my $tempdir = "data";
my $force = 0;

my $shutdown_msg = "Bugzilla is temporarily disabled while the database is backed up. Try again in a few minutes.";
50 51

sub Usage {
52
    print "Usage: syncshadowdb [-v] [-syncall] [-shutdown] [-tempdir dirname] [-force]\n";
53 54 55
    exit;
}

56
while (my $opt = shift @ARGV) {
57 58 59 60 61
    if ($opt eq '-v') {
        $verbose = 1;
    } elsif ($opt eq '-syncall') {
        $syncall = 1;
        $verbose = 1;
62 63 64 65 66 67 68 69 70 71 72 73
    } elsif ($opt eq '-shutdown') {
        $shutdown = 1;
    } elsif ($opt eq '-tempdir') {
        my $dir = shift @ARGV;
        if (-d $dir) {
            $tempdir = $dir;
        } else {
            print "$dir does not exist or is not a directory.  No syncing performed";
            exit;
        }
    } elsif ($opt eq '-force') {
        $force = 1;
74 75 76
    } elsif ($opt eq '--') {
        # do nothing - null parameter so we can use
        # multi-param system() call in globals.pl
77 78 79
    } else {
        Usage();
    }
80 81 82
}
$| = 1;

83 84
my $logtostderr = 0;

85 86 87
sub Verbose ($) {
    my ($str) = (@_);
    if ($verbose) {
88 89 90 91 92
        if ($logtostderr) {
            print STDERR $str, "\n";
        } else {
            print $str, "\n";
        }
93 94 95 96 97 98 99 100
    }
}

if (!Param("shadowdb")) {
    Verbose("We don't have shadow databases turned on; no syncing performed.");
    exit;
}

101 102 103 104 105 106 107 108 109 110
if (Param("shutdownhtml") && ! $force) {
    Verbose("Bugzilla was shutdown prior to running syncshadowdb. \n" .
            "  If you wish to sync anyway, use the -force command line option");
    exit;
}

my $wasshutdown = "";
if ($shutdown) {
    Verbose ("Shutting down bugzilla and waiting for connections to clear");
    # Record the old shutdownhtml so it can be restored at the end (this will
111
    # only be an issue if we are called using the -force command line param)
112
    $wasshutdown = Param("shutdownhtml");
113
    SetParam('shutdownhtml', $shutdown_msg);
114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149
    WriteParams();
    # Now we need to wait for existing connections to this database to clear. We
    # do this by looking for connections to the main or shadow database using
    # 'mysqladmin processlist'
    my $cmd = "$::mysqlpath/mysqladmin -u $::db_user";
    if ($::db_pass) { $cmd .= " -p$::db_pass" }
    $cmd .= " processlist";
    my $found_proc = 1;
    # We need to put together a nice little regular expression to use in the
    # following loop that'll tell us if the return from mysqladmin contains
    # either the main or shadow database.
    my @dbs = ($::db_name, Param("shadowdb"));
    my $db_expr = "^\\s*(" . join ("\|", @dbs) . ")\\s*\$";
    # Don't let this thing wait forever...
    my $starttime = time();
    while ($found_proc) {
        $found_proc = 0;
        open (PROC, $cmd . "|");
        my @output = <PROC>;
        close (PROC);
        foreach my $line(@output) {
            my @info = split (/\|/, $line);
            # Ignore any line that doesn't have 9 pieces of info
            # or contain Id (pretty printing crap)
            if ($#info != 9 || $line =~ /Id/) { next }
            if ($info[4] =~ m/$db_expr/) {
                $found_proc = 1;
            }
        }
        # If there are still active connections to Bugzilla 10 minutes after
        # shutting it down, then something is wrong.
        if ((time() - $starttime) > 600) {
            # There should be a better way to notify the admin of something bad like
            # this happening.
            Verbose ("*** Waited for 10 minutes and there were still active \n" .
                     "    connections to the bugzilla database.  Giving up.");
150
            SetParam('shutdownhtml', $wasshutdown);
151 152 153 154 155 156 157
            WriteParams();
            exit;
        }
    }
}


158 159
my $wasusing = Param("queryagainstshadowdb");

160
SetParam('queryagainstshadowdb', 1);  # Force us to be able to use the
161 162 163 164
                                      # shadowdb, even if other processes
                                      # are not supposed to.


165 166
ConnectToDatabase(1);

167 168 169 170 171 172
Verbose("Acquiring lock");
if ( $syncall == 1) {
    SendSQL("SELECT GET_LOCK('synclock', 2700)");
} else {
    SendSQL("SELECT GET_LOCK('synclock', 1)");
}
173 174 175 176 177
if (!FetchOneColumn()) {
    Verbose("Couldn't get the lock to do the shadow database syncing.");
    exit;
}

178
my $shadowtable = "$::db_name.shadowlog";
179

180 181 182 183 184 185 186 187
if (!$syncall) {
    Verbose("Looking for requests to sync the whole database.");
    SendSQL("SELECT id FROM $shadowtable " .
            "WHERE reflected = 0 AND command = 'SYNCUP'");
    if (FetchOneColumn()) {
        $syncall = 1;
    }
}
188

189
if ($syncall) {
190
    Verbose("Syncing up the shadow database by copying entire database in.");
191
    if ($wasusing) {
192
        SetParam('queryagainstshadowdb',0);
193
        WriteParams();
194 195 196 197
        if (! $shutdown) {
            Verbose("Disabled reading from the shadowdb. Sleeping 10 seconds to let other procs catch up.");
            sleep(10);
        }
198
        SetParam('queryagainstshadowdb', 1);
199
    }
200 201
    my @tables;
    SendSQL("SHOW TABLES");
202
    my $query = "";
203 204 205
    while (MoreSQLData()) {
        my $table = FetchOneColumn();
        push(@tables, $table);
206 207 208 209 210
        if ($query) {
            $query .= ", $table WRITE";
        } else {
            $query = "LOCK TABLES $table WRITE";
        }
211
    }
212 213 214 215 216 217 218 219 220
    if (@tables) {
        Verbose("Locking entire shadow database");
        SendSQL($query);
        foreach my $table (@tables) {
            Verbose("Dropping old shadow table $table");
            SendSQL("DROP TABLE $table");
        }
        SendSQL("UNLOCK TABLES");
    }    
221 222 223 224 225
    # Carefully lock the whole real database for reading, except for the
    # shadowlog table, which we lock for writing.  Then dump everything
    # into the shadowdb database.  Then mark everything in the shadowlog
    # as reflected.  Only then unlock everything.  This sequence causes
    # us to be sure not to miss anything or get something twice.
226
    SendSQL("USE $::db_name");
227 228
    SendSQL("SHOW TABLES");
    @tables = ();
229
    $query = "LOCK TABLES shadowlog WRITE";
230 231 232 233 234 235 236 237 238
    while (MoreSQLData()) {
        my $table = FetchOneColumn();
        if ($table ne "shadowlog") {
            $query .= ", $table READ";
            push(@tables, $table);
        }
    }
    Verbose("Locking entire database");
    SendSQL($query);
239
    my $tempfile = "$tempdir/tmpsyncshadow.$$";
240
    Verbose("Dumping database to a temp file ($tempfile).");
241 242 243
    my @ARGS = ("-u", $::db_user);
    if ($::db_pass) { push @ARGS, "-p$::db_pass" }
    push @ARGS, "-l", "-e", $::db_name, @tables;
244 245 246
    open SAVEOUT, ">&STDOUT";     # stash the original output stream
    open STDOUT, ">$tempfile";    # redirect to file
    select STDOUT; $| = 1;        # disable buffering
247
    system("$::mysqlpath/mysqldump", @ARGS);
248
    open STDOUT, ">&SAVEOUT";     # redirect back to original stream
249
    Verbose("Restoring from tempfile into shadowdb");
250 251 252 253
    my $extra = "-u $::db_user";
    if ($::db_pass) {
        $extra .= " -p$::db_pass";
    }
254
    if ($verbose) {
255
        $extra .= " -v";
256
    }
257
    open(MYSQL, "cat $tempfile | $::mysqlpath/mysql $extra " .
258 259 260 261 262 263 264 265 266 267
         Param("shadowdb") . "|") || die "Couldn't do db copy";
    my $count = 0;
    while (<MYSQL>) {
        print ".";
        $count++;
        if ($count % 70 == 0) {
            print "\n";
        }
    }
    close(MYSQL);
268
    unlink($tempfile);
269 270 271
    Verbose("");
    
    
272
    $::dbwritesallowed = 1;
273 274
#    SendSQL("UPDATE shadowlog SET reflected = 1 WHERE reflected = 0", 1);
    SendSQL("DELETE FROM shadowlog", 1);
275
    SendSQL("UNLOCK TABLES");
276 277
    if ($wasusing) {
        Verbose("Reenabling other processes to read from the shadow db");
278
        SetParam('queryagainstshadowdb', 1);
279 280
        WriteParams();
    }
281 282
    if ($shutdown) {
        Verbose("Restoring the original shutdown message (if any)");
283
        SetParam('shutdownhtml', $wasshutdown);
284 285
        WriteParams();
    }
286 287 288
    Verbose("OK, done.");
}

289 290
Verbose("Looking for commands to execute.");
$::dbwritesallowed = 1;
291 292 293 294 295

# Make us low priority, to not block anyone who is trying to actually use
# the shadowdb.  Note that this is carefully coded to ignore errors; we want
# to keep going even on older mysqld's that don't have the
# SQL_LOW_PRIORITY_UPDATES option.
296
$::db->do("SET OPTION SQL_LOW_PRIORITY_UPDATES = 1"); 
297

298 299 300 301 302 303 304 305 306 307 308 309
while (1) {
    SendSQL("SELECT id, command FROM $shadowtable WHERE reflected = 0 " .
            "ORDER BY id LIMIT 1");
    my ($id, $command) = (FetchSQLData());
    if (!$id) {
        last;
    }
    Verbose("Executing command in shadow db: $command");
    SendSQL($command, 1);
    SendSQL("UPDATE $shadowtable SET reflected = 1 WHERE id = $id", 1);
}

310
Verbose("Releasing lock.");
311
SendSQL("SELECT RELEASE_LOCK('synclock')");