ViewVC Help
View File | Revision Log | Show Annotations | Download File
/cvs/deliantra/Deliantra-Client/DC/DB.pm
Revision: 1.43
Committed: Fri Jan 9 22:38:17 2009 UTC (15 years, 5 months ago) by root
Branch: MAIN
Changes since 1.42: +55 -0 lines
Log Message:
*** empty log message ***

File Contents

# User Rev Content
1 root 1.1 =head1 NAME
2    
3 root 1.31 DC::DB - async. database and filesystem access for deliantra
4 root 1.1
5     =head1 SYNOPSIS
6    
7 root 1.29 use DC::DB;
8 root 1.1
9     =head1 DESCRIPTION
10    
11     =over 4
12    
13     =cut
14    
15 root 1.29 package DC::DB;
16 root 1.1
17     use strict;
18     use utf8;
19    
20 root 1.35 use File::Path ();
21 root 1.1 use Carp ();
22 root 1.5 use Storable ();
23 root 1.42 use AnyEvent::Util ();
24 root 1.9 use Config;
25 root 1.24 use BDB;
26 root 1.43 use Fcntl ();
27 root 1.1
28 root 1.29 use DC;
29 root 1.3
30 root 1.38 our $ODBDIR = "cfplus-" . BDB::VERSION_MAJOR . "." . BDB::VERSION_MINOR . "-$Config{archname}";
31     our $DBDIR = "client-" . BDB::VERSION_MAJOR . "." . BDB::VERSION_MINOR . "-$Config{archname}";
32 root 1.27 our $DB_HOME = "$Deliantra::VARDIR/$DBDIR";
33    
34 root 1.40 sub FIRST_TILE_ID () { 64 }
35    
36 root 1.35 unless (-d $DB_HOME) {
37     if (-d "$Deliantra::VARDIR/$ODBDIR") {
38     rename "$Deliantra::VARDIR/$ODBDIR", $DB_HOME;
39     print STDERR "INFO: moved old database from $Deliantra::VARDIR/$ODBDIR to $DB_HOME\n";
40     } elsif (-d "$Deliantra::OLDDIR/$ODBDIR") {
41     rename "$Deliantra::OLDDIR/$DBDIR", $DB_HOME;
42     print STDERR "INFO: moved old database from $Deliantra::OLDDIR/$ODBDIR to $DB_HOME\n";
43     } else {
44     File::Path::mkpath [$DB_HOME]
45     or die "unable to create database directory $DB_HOME: $!";
46     }
47 root 1.27 }
48 root 1.9
49 root 1.30 BDB::max_poll_time 0.03;
50 root 1.32 BDB::max_parallel 1;
51 root 1.30
52 root 1.24 our $DB_ENV;
53     our $DB_STATE;
54     our %DB_TABLE;
55 root 1.35 our $TILE_SEQ;
56 root 1.24
57 root 1.43 sub all_databases {
58     opendir my $fh, $DB_HOME
59     or return;
60    
61     grep !/^(?:\.|log\.|_)/, readdir $fh
62     }
63    
64     sub try_verify_env($) {
65     my ($env) = @_;
66    
67     # we lock the __db.register env file that has been created by now
68     # and check for the number of registered processes - if there is
69     # only one, we verify all databases, otherwise we skip this
70     open my $fh, "+<$DB_HOME/__db.register"
71     or die "__db.register: $!";
72    
73     open my $lock, "+>$DB_HOME/__lock"
74     or die "__lock: $!";
75    
76     flock $lock, &Fcntl::LOCK_EX
77     or die "flock: $!";
78    
79     # __db.register contains one record per process, with X signifying
80     # empty records (of course, this is completely private to bdb...)
81     my $count = grep /^[^X]/, <$fh>;
82    
83     if ($count == 1) {
84     # if any databases are corrupted, we simply delete all of them
85    
86     for (all_databases) {
87     my $dbh = db_create $env
88     or last;
89    
90     # a failed verify will panic the environment, which is fine with us
91     db_verify $dbh, "$DB_HOME/$_";
92    
93     return if $!; # nuke database and recreate if verification failure
94     }
95    
96     }
97    
98     # close probably cleans those up, but we also want to run on windows,
99     # so better be safe.
100     flock $lock, &Fcntl::LOCK_UN
101     or die "funlock: $!";
102    
103     1
104     }
105    
106 root 1.33 sub try_open_db {
107 root 1.35 File::Path::mkpath [$DB_HOME];
108 root 1.24
109 root 1.36 my $env = db_env_create;
110 root 1.24
111 root 1.36 $env->set_errfile (\*STDERR);
112     $env->set_msgfile (\*STDERR);
113     $env->set_verbose (-1, 1);
114 root 1.24
115 root 1.39 $env->set_flags (BDB::AUTO_COMMIT | BDB::REGION_INIT);
116     $env->set_flags (&BDB::LOG_AUTOREMOVE ) if BDB::VERSION v0, v4.7;
117     $env->log_set_config (&BDB::LOG_AUTO_REMOVE) if BDB::VERSION v4.7;
118    
119     $env->set_timeout (3, BDB::SET_TXN_TIMEOUT);
120     $env->set_timeout (3, BDB::SET_LOCK_TIMEOUT);
121    
122 root 1.36 $env->set_cachesize (0, 2048 * 1024, 0);
123 root 1.24
124 root 1.36 db_env_open $env, $DB_HOME,
125 root 1.24 BDB::CREATE | BDB::REGISTER | BDB::RECOVER | BDB::INIT_MPOOL | BDB::INIT_LOCK | BDB::INIT_TXN,
126     0666;
127    
128     $! and die "cannot open database environment $DB_HOME: " . BDB::strerror;
129    
130 root 1.43 # now we go through the registered processes, if there is only one, we verify all files
131     # to make sure windows didn'T corrupt them (as windows does....)
132     try_verify_env $env
133     or die "database environment failed verification";
134    
135 root 1.36 $DB_ENV = $env;
136    
137 root 1.24 1
138     }
139    
140     sub table($) {
141     $DB_TABLE{$_[0]} ||= do {
142     my ($table) = @_;
143    
144     $table =~ s/([^a-zA-Z0-9_\-])/sprintf "=%x=", ord $1/ge;
145    
146 root 1.41 $DB_ENV#d#
147     or return ::clienterror ("trying to create table $_[0] with empty db_env $DB_ENV" => 1);#d#
148    
149 root 1.24 my $db = db_create $DB_ENV;
150     $db->set_flags (BDB::CHKSUM);
151    
152     db_open $db, undef, $table, undef, BDB::BTREE,
153     BDB::AUTO_COMMIT | BDB::CREATE | BDB::READ_UNCOMMITTED, 0666;
154    
155     $! and "unable to open/create database table $_[0]: ". BDB::strerror;
156    
157     $db
158     }
159 root 1.9 }
160    
161 root 1.24 #############################################################################
162    
163 root 1.33 our $WATCHER;
164     our $SYNC;
165 root 1.34 our $facemap;
166 root 1.24
167 root 1.9 sub exists($$$) {
168 root 1.24 my ($db, $key, $cb) = @_;
169    
170     my $data;
171     db_get table $db, undef, $key, $data, 0, sub {
172     $cb->($! ? () : length $data);
173     };
174 root 1.9 }
175    
176 root 1.1 sub get($$$) {
177 root 1.24 my ($db, $key, $cb) = @_;
178    
179     my $data;
180     db_get table $db, undef, $key, $data, 0, sub {
181     $cb->($! ? () : $data);
182     };
183 root 1.1 }
184    
185     sub put($$$$) {
186 root 1.24 my ($db, $key, $data, $cb) = @_;
187    
188     db_put table $db, undef, $key, $data, 0, sub {
189     $cb->($!);
190     $SYNC->again unless $SYNC->is_active;
191     };
192 root 1.1 }
193    
194 root 1.24 sub do_table {
195     my ($db, $cb) = @_;
196    
197     $db = table $db;
198    
199     my $cursor = $db->cursor;
200     my %kv;
201    
202     for (;;) {
203     db_c_get $cursor, my $k, my $v, BDB::NEXT;
204     last if $!;
205     $kv{$k} = $v;
206     }
207    
208     $cb->(\%kv);
209 root 1.9 }
210    
211 root 1.24 sub do_get_tile_id {
212     my ($name, $cb) = @_;
213    
214     my $table = table "facemap";
215     my $id;
216    
217 root 1.35 db_get $table, undef, $name => $id, 0;
218 root 1.34 $! or return $cb->($id);
219 root 1.24
220 root 1.35 unless ($TILE_SEQ) {
221     $TILE_SEQ = $table->sequence;
222 root 1.40 $TILE_SEQ->initial_value (FIRST_TILE_ID);
223 root 1.35 $TILE_SEQ->set_cachesize (0);
224     db_sequence_open $TILE_SEQ, undef, "id", BDB::CREATE;
225     }
226 root 1.24
227 root 1.35 db_sequence_get $TILE_SEQ, undef, 1, my $id;
228 root 1.24
229 root 1.35 die "unable to allocate tile id: $!"
230     if $!;
231    
232     db_put $table, undef, $name => $id, 0;
233     $cb->($id);
234 root 1.24
235 root 1.15 }
236    
237 root 1.1 sub get_tile_id_sync($) {
238 root 1.20 my ($name) = @_;
239 root 1.1
240 root 1.34 $facemap->{$name} ||= do {
241 root 1.1 my $id;
242 root 1.24 do_get_tile_id $name, sub {
243     $id = $_[0];
244     };
245     BDB::flush;
246 root 1.1 $id
247     }
248     }
249    
250 root 1.24 #############################################################################
251    
252     sub path_of_res($) {
253     utf8::downgrade $_[0]; # bug in unpack "H*"
254     "$DB_HOME/res-data-" . unpack "H*", $_[0]
255     }
256    
257     sub sync {
258     # for debugging
259 root 1.29 #DC::DB::Server::req (sync => sub { });
260     DC::DB::Server::sync ();
261 root 1.24 }
262 root 1.1
263 root 1.24 sub unlink($$) {
264 root 1.29 DC::DB::Server::req (unlink => @_);
265 root 1.24 }
266 root 1.1
267 root 1.24 sub read_file($$) {
268 root 1.29 DC::DB::Server::req (read_file => @_);
269 root 1.24 }
270 root 1.1
271 root 1.24 sub write_file($$$) {
272 root 1.29 DC::DB::Server::req (write_file => @_);
273 root 1.24 }
274 root 1.1
275 root 1.24 sub prefetch_file($$$) {
276 root 1.29 DC::DB::Server::req (prefetch_file => @_);
277 root 1.24 }
278 root 1.1
279 root 1.24 sub logprint($$$) {
280 root 1.29 DC::DB::Server::req (logprint => @_);
281 root 1.1 }
282    
283 root 1.30 #############################################################################
284    
285 root 1.29 package DC::DB::Server;
286 root 1.1
287 root 1.24 use strict;
288 root 1.1
289 root 1.24 use EV ();
290     use Fcntl;
291 root 1.1
292     our %CB;
293     our $FH;
294     our $ID = "aaa0";
295     our ($fh_r_watcher, $fh_w_watcher);
296     our $sync_timer;
297     our $write_buf;
298     our $read_buf;
299    
300     sub fh_write {
301     my $len = syswrite $FH, $write_buf;
302    
303     substr $write_buf, 0, $len, "";
304    
305 root 1.14 $fh_w_watcher->stop
306 root 1.1 unless length $write_buf;
307     }
308    
309     sub fh_read {
310     my $status = sysread $FH, $read_buf, 16384, length $read_buf;
311    
312     die "FATAL: database process died\n"
313     if $status == 0 && defined $status;
314    
315     while () {
316     return if 4 > length $read_buf;
317     my $len = unpack "N", $read_buf;
318    
319     return if $len + 4 > length $read_buf;
320    
321     substr $read_buf, 0, 4, "";
322     my $res = Storable::thaw substr $read_buf, 0, $len, "";
323    
324     my ($id, @args) = @$res;
325     (delete $CB{$id})->(@args);
326     }
327     }
328    
329     sub sync {
330     # biggest mess evarr
331     my $fds; (vec $fds, fileno $FH, 1) = 1;
332    
333     while (1 < scalar keys %CB) {
334     my $r = $fds;
335     my $w = length $write_buf ? $fds : undef;
336     select $r, $w, undef, undef;
337    
338     fh_write if vec $w, fileno $FH, 1;
339     fh_read if vec $r, fileno $FH, 1;
340     }
341     }
342    
343     sub req {
344     my ($type, @args) = @_;
345     my $cb = pop @args;
346    
347     my $id = ++$ID;
348     $write_buf .= pack "N/a*", Storable::freeze [$id, $type, @args];
349     $CB{$id} = $cb;
350    
351 root 1.14 $fh_w_watcher->start;
352 root 1.1 }
353    
354 root 1.9 sub do_unlink {
355     unlink $_[0];
356     }
357    
358 root 1.16 sub do_read_file {
359     my ($path) = @_;
360    
361     utf8::downgrade $path;
362     open my $fh, "<:raw", $path
363     or return;
364     sysread $fh, my $buf, -s $fh;
365    
366     $buf
367     }
368    
369 root 1.9 sub do_write_file {
370 root 1.16 my ($path, $data) = @_;
371 root 1.9
372 root 1.16 utf8::downgrade $path;
373 root 1.9 utf8::downgrade $data;
374 root 1.16 open my $fh, ">:raw", $path
375 root 1.9 or return;
376 root 1.16 syswrite $fh, $data;
377 root 1.9 close $fh;
378    
379     1
380     }
381    
382 root 1.11 sub do_prefetch_file {
383 root 1.16 my ($path, $size) = @_;
384 root 1.11
385 root 1.16 utf8::downgrade $path;
386     open my $fh, "<:raw", $path
387 root 1.11 or return;
388     sysread $fh, my $buf, $size;
389    
390     1
391     }
392    
393 root 1.15 our %LOG_FH;
394    
395     sub do_logprint {
396     my ($path, $line) = @_;
397    
398     $LOG_FH{$path} ||= do {
399     open my $fh, ">>:utf8", $path
400     or warn "Couldn't open logfile $path: $!";
401    
402     $fh->autoflush (1);
403    
404     $fh
405     };
406    
407     my ($sec, $min, $hour, $mday, $mon, $year) = localtime time;
408    
409     my $ts = sprintf "%04d-%02d-%02d %02d:%02d:%02d",
410     $year + 1900, $mon + 1, $mday, $hour, $min, $sec;
411    
412     print { $LOG_FH{$path} } "$ts $line\n"
413     }
414    
415 root 1.1 sub run {
416 root 1.42 ($FH, my $fh) = AnyEvent::Util::portable_socketpair
417     or die "unable to create database socketpair: $!";
418 root 1.1
419     my $oldfh = select $FH; $| = 1; select $oldfh;
420     my $oldfh = select $fh; $| = 1; select $oldfh;
421    
422     my $pid = fork;
423    
424     if (defined $pid && !$pid) {
425 root 1.30 local $SIG{QUIT} = "IGNORE";
426 root 1.1 local $SIG{__DIE__};
427 root 1.15 local $SIG{__WARN__};
428 root 1.1 eval {
429     close $FH;
430    
431     while () {
432     4 == read $fh, my $len, 4
433     or last;
434     $len = unpack "N", $len;
435     $len == read $fh, my $req, $len
436     or die "unexpected eof while reading request";
437    
438     $req = Storable::thaw $req;
439    
440     my ($id, $type, @args) = @$req;
441 root 1.29 my $cb = DC::DB::Server->can ("do_$type")
442 root 1.1 or die "$type: unknown database request type\n";
443     my $res = pack "N/a*", Storable::freeze [$id, $cb->(@args)];
444     (syswrite $fh, $res) == length $res
445 root 1.21 or die "DB::write: $!";
446 root 1.1 }
447     };
448    
449     my $error = $@;
450    
451     eval {
452     Storable::store_fd [die => $error], $fh;
453     };
454    
455 root 1.25 warn $error
456     if $error;
457 root 1.24
458 root 1.29 DC::_exit 0;
459 root 1.1 }
460    
461     close $fh;
462 root 1.29 DC::fh_nonblocking $FH, 1;
463 root 1.1
464 root 1.2 $CB{die} = sub { die shift };
465 root 1.1
466 root 1.21 $fh_r_watcher = EV::io $FH, EV::READ , \&fh_read;
467     $fh_w_watcher = EV::io $FH, EV::WRITE, \&fh_write;
468 root 1.1 }
469    
470 root 1.6 sub stop {
471     close $FH;
472     }
473    
474 root 1.33 package DC::DB;
475    
476 root 1.35 sub nuke_db {
477     File::Path::mkpath [$DB_HOME];
478     eval { File::Path::rmtree $DB_HOME };
479     }
480    
481 root 1.33 sub open_db {
482     unless (eval { try_open_db }) {
483     warn "$@";#d#
484 root 1.35 eval { nuke_db };
485 root 1.33 try_open_db;
486     }
487    
488     # fetch the full face table first
489 root 1.34 unless ($facemap) {
490 root 1.33 do_table facemap => sub {
491 root 1.34 $facemap = $_[0];
492     delete $facemap->{id};
493     my %maptile = reverse %$facemap;#d#
494     if ((scalar keys %$facemap) != (scalar keys %maptile)) {#d#
495     $facemap = { };#d#
496 root 1.33 DC::error "FATAL: facemap is not a 1:1 mapping, please report this and delete your $DB_HOME directory!\n";#d#
497     }#d#
498     };
499     }
500    
501     $WATCHER = EV::io BDB::poll_fileno, EV::READ, \&BDB::poll_cb;
502     $SYNC = EV::timer_ns 0, 60, sub {
503     $_[0]->stop;
504     db_env_txn_checkpoint $DB_ENV, 0, 0, 0, sub { };
505     };
506     }
507    
508     END {
509 root 1.37 db_env_txn_checkpoint $DB_ENV, 0, 0, 0
510     if $DB_ENV;
511    
512 root 1.35 undef $TILE_SEQ;
513 root 1.33 %DB_TABLE = ();
514     undef $DB_ENV;
515     }
516    
517 root 1.1 1;
518    
519     =back
520    
521     =head1 AUTHOR
522    
523     Marc Lehmann <schmorp@schmorp.de>
524     http://home.schmorp.de/
525    
526     =cut
527