ViewVC Help
View File | Revision Log | Show Annotations | Download File
/cvs/deliantra/Deliantra-Client/DC/DB.pm
Revision: 1.46
Committed: Fri Jul 29 08:35:35 2011 UTC (12 years, 11 months ago) by root
Branch: MAIN
Changes since 1.45: +1 -1 lines
Log Message:
avoid triggering undefined behaviour

File Contents

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