ViewVC Help
View File | Revision Log | Show Annotations | Download File
/cvs/deliantra/server/lib/cf.pm
(Generate patch)

Comparing deliantra/server/lib/cf.pm (file contents):
Revision 1.529 by root, Wed Apr 28 11:28:22 2010 UTC vs.
Revision 1.539 by root, Tue May 4 22:49:21 2010 UTC

20# The authors can be reached via e-mail to <support@deliantra.net> 20# The authors can be reached via e-mail to <support@deliantra.net>
21# 21#
22 22
23package cf; 23package cf;
24 24
25use 5.10.0; 25use common::sense;
26use utf8;
27use strict qw(vars subs);
28 26
29use Symbol; 27use Symbol;
30use List::Util; 28use List::Util;
31use Socket; 29use Socket;
32use EV; 30use EV;
106our $RANDOMDIR = "$LOCALDIR/random"; 104our $RANDOMDIR = "$LOCALDIR/random";
107our $BDBDIR = "$LOCALDIR/db"; 105our $BDBDIR = "$LOCALDIR/db";
108our $PIDFILE = "$LOCALDIR/pid"; 106our $PIDFILE = "$LOCALDIR/pid";
109our $RUNTIMEFILE = "$LOCALDIR/runtime"; 107our $RUNTIMEFILE = "$LOCALDIR/runtime";
110 108
111our %RESOURCE; 109our %RESOURCE; # unused
112 110
113our $OUTPUT_RATE_MIN = 3000; 111our $OUTPUT_RATE_MIN = 3000;
114our $OUTPUT_RATE_MAX = 1000000; 112our $OUTPUT_RATE_MAX = 1000000;
115 113
116our $MAX_LINKS = 32; # how many chained exits to follow 114our $MAX_LINKS = 32; # how many chained exits to follow
252 250
253=back 251=back
254 252
255=cut 253=cut
256 254
255sub error(@) { LOG llevError, join "", @_ }
256sub warn (@) { LOG llevWarn , join "", @_ }
257sub info (@) { LOG llevInfo , join "", @_ }
258sub debug(@) { LOG llevDebug, join "", @_ }
259sub trace(@) { LOG llevTrace, join "", @_ }
260
257$Coro::State::WARNHOOK = sub { 261$Coro::State::WARNHOOK = sub {
258 my $msg = join "", @_; 262 my $msg = join "", @_;
259 263
260 $msg .= "\n" 264 $msg .= "\n"
261 unless $msg =~ /\n$/; 265 unless $msg =~ /\n$/;
262 266
263 $msg =~ s/([\x00-\x08\x0b-\x1f])/sprintf "\\x%02x", ord $1/ge; 267 $msg =~ s/([\x00-\x08\x0b-\x1f])/sprintf "\\x%02x", ord $1/ge;
264 268
265 LOG llevError, $msg; 269 LOG llevWarn, $msg;
266}; 270};
267 271
268$Coro::State::DIEHOOK = sub { 272$Coro::State::DIEHOOK = sub {
269 return unless $^S eq 0; # "eq", not "==" 273 return unless $^S eq 0; # "eq", not "=="
270 274
271 warn Carp::longmess $_[0]; 275 error Carp::longmess $_[0];
272 276
273 if (in_main) {#d# 277 if (in_main) {#d#
274 warn "DIEHOOK called in main context, Coro bug?\n";#d# 278 error "DIEHOOK called in main context, Coro bug?\n";#d#
275 return;#d# 279 return;#d#
276 }#d# 280 }#d#
277 281
278 # kill coroutine otherwise 282 # kill coroutine otherwise
279 Coro::terminate 283 Coro::terminate
512=cut 516=cut
513 517
514sub sync_job(&) { 518sub sync_job(&) {
515 my ($job) = @_; 519 my ($job) = @_;
516 520
517 if ($Coro::current == $Coro::main) { 521 if (in_main) {
518 my $time = AE::time; 522 my $time = AE::time;
519 523
520 # this is the main coro, too bad, we have to block 524 # this is the main coro, too bad, we have to block
521 # till the operation succeeds, freezing the server :/ 525 # till the operation succeeds, freezing the server :/
522 526
523 LOG llevError, Carp::longmess "sync job";#d# 527 #LOG llevError, Carp::longmess "sync job";#d#
524 528
525 my $freeze_guard = freeze_mainloop; 529 my $freeze_guard = freeze_mainloop;
526 530
527 my $busy = 1; 531 my $busy = 1;
528 my @res; 532 my @res;
529 533
530 (async { 534 (async {
531 $Coro::current->desc ("sync job coro"); 535 $Coro::current->desc ("sync job coro");
532 @res = eval { $job->() }; 536 @res = eval { $job->() };
533 warn $@ if $@; 537 error $@ if $@;
534 undef $busy; 538 undef $busy;
535 })->prio (Coro::PRIO_MAX); 539 })->prio (Coro::PRIO_MAX);
536 540
537 while ($busy) { 541 while ($busy) {
538 if (Coro::nready) { 542 if (Coro::nready) {
651within each server. 655within each server.
652 656
653=cut 657=cut
654 658
655sub db_table($) { 659sub db_table($) {
660 cf::error "db_get called from main context"
661 if $Coro::current == $Coro::main;
662
656 my ($name) = @_; 663 my ($name) = @_;
657 my $db = BDB::db_create $DB_ENV; 664 my $db = BDB::db_create $DB_ENV;
658 665
659 eval { 666 eval {
660 $db->set_flags (BDB::CHKSUM); 667 $db->set_flags (BDB::CHKSUM);
670} 677}
671 678
672our $DB; 679our $DB;
673 680
674sub db_init { 681sub db_init {
675 cf::sync_job {
676 $DB ||= db_table "db"; 682 $DB ||= db_table "db";
677 };
678} 683}
679 684
680sub db_get($$) { 685sub db_get($$) {
681 my $key = "$_[0]/$_[1]"; 686 my $key = "$_[0]/$_[1]";
682 687
683 cf::sync_job { 688 cf::error "db_get called from main context"
689 if $Coro::current == $Coro::main;
690
684 BDB::db_get $DB, undef, $key, my $data; 691 BDB::db_get $DB, undef, $key, my $data;
685 692
686 $! ? () 693 $! ? ()
687 : $data 694 : $data
688 }
689} 695}
690 696
691sub db_put($$$) { 697sub db_put($$$) {
692 BDB::dbreq_pri 4; 698 BDB::dbreq_pri 4;
693 BDB::db_put $DB, undef, "$_[0]/$_[1]", $_[2], 0, sub { }; 699 BDB::db_put $DB, undef, "$_[0]/$_[1]", $_[2], 0, sub { };
749 755
750 my $t1 = Time::HiRes::time; 756 my $t1 = Time::HiRes::time;
751 my $data = $process->(\@data); 757 my $data = $process->(\@data);
752 my $t2 = Time::HiRes::time; 758 my $t2 = Time::HiRes::time;
753 759
754 warn "cache: '$id' processed in ", $t2 - $t1, "s\n"; 760 info "cache: '$id' processed in ", $t2 - $t1, "s\n";
755 761
756 db_put cache => "$id/data", $data; 762 db_put cache => "$id/data", $data;
757 db_put cache => "$id/md5" , $md5; 763 db_put cache => "$id/md5" , $md5;
758 db_put cache => "$id/meta", $meta; 764 db_put cache => "$id/meta", $meta;
759 765
769 775
770=cut 776=cut
771 777
772sub datalog($@) { 778sub datalog($@) {
773 my ($type, %kv) = @_; 779 my ($type, %kv) = @_;
774 warn "DATALOG ", JSON::XS->new->ascii->encode ({ %kv, type => $type }); 780 info "DATALOG ", JSON::XS->new->ascii->encode ({ %kv, type => $type });
775} 781}
776 782
777=back 783=back
778 784
779=cut 785=cut
974 980
975 } elsif (exists $cb_id{$type}) { 981 } elsif (exists $cb_id{$type}) {
976 _attach_cb $registry, $cb_id{$type}, $prio, shift @arg; 982 _attach_cb $registry, $cb_id{$type}, $prio, shift @arg;
977 983
978 } elsif (ref $type) { 984 } elsif (ref $type) {
979 warn "attaching objects not supported, ignoring.\n"; 985 error "attaching objects not supported, ignoring.\n";
980 986
981 } else { 987 } else {
982 shift @arg; 988 shift @arg;
983 warn "attach argument '$type' not supported, ignoring.\n"; 989 error "attach argument '$type' not supported, ignoring.\n";
984 } 990 }
985 } 991 }
986} 992}
987 993
988sub _object_attach { 994sub _object_attach {
998 _attach $registry, $klass, @attach; 1004 _attach $registry, $klass, @attach;
999 } 1005 }
1000 1006
1001 $obj->{$name} = \%arg; 1007 $obj->{$name} = \%arg;
1002 } else { 1008 } else {
1003 warn "object uses attachment '$name' which is not available, postponing.\n"; 1009 info "object uses attachment '$name' which is not available, postponing.\n";
1004 } 1010 }
1005 1011
1006 $obj->{_attachment}{$name} = undef; 1012 $obj->{_attachment}{$name} = undef;
1007} 1013}
1008 1014
1067 1073
1068 for (@$callbacks) { 1074 for (@$callbacks) {
1069 eval { &{$_->[1]} }; 1075 eval { &{$_->[1]} };
1070 1076
1071 if ($@) { 1077 if ($@) {
1072 warn "$@";
1073 warn "... while processing $EVENT[$event][0](@_) event, skipping processing altogether.\n"; 1078 error "$@", "... while processing $EVENT[$event][0](@_) event, skipping processing altogether.\n";
1074 override; 1079 override;
1075 } 1080 }
1076 1081
1077 return 1 if $override; 1082 return 1 if $override;
1078 } 1083 }
1157 for (@$attach) { 1162 for (@$attach) {
1158 my ($klass, @attach) = @$_; 1163 my ($klass, @attach) = @$_;
1159 _attach $registry, $klass, @attach; 1164 _attach $registry, $klass, @attach;
1160 } 1165 }
1161 } else { 1166 } else {
1162 warn "object uses attachment '$name' that is not available, postponing.\n"; 1167 info "object uses attachment '$name' that is not available, postponing.\n";
1163 } 1168 }
1164 } 1169 }
1165} 1170}
1166 1171
1167cf::attachable->attach ( 1172cf::attachable->attach (
1194 my ($filename, $rdata, $objs) = @_; 1199 my ($filename, $rdata, $objs) = @_;
1195 1200
1196 sync_job { 1201 sync_job {
1197 if (length $$rdata) { 1202 if (length $$rdata) {
1198 utf8::decode (my $decname = $filename); 1203 utf8::decode (my $decname = $filename);
1199 warn sprintf "saving %s (%d,%d)\n", 1204 trace sprintf "saving %s (%d,%d)\n",
1200 $decname, length $$rdata, scalar @$objs 1205 $decname, length $$rdata, scalar @$objs
1201 if $VERBOSE_IO; 1206 if $VERBOSE_IO;
1202 1207
1203 if (my $fh = aio_open "$filename~", O_WRONLY | O_CREAT, 0600) { 1208 if (my $fh = aio_open "$filename~", O_WRONLY | O_CREAT, 0600) {
1204 aio_chmod $fh, SAVE_MODE; 1209 aio_chmod $fh, SAVE_MODE;
1205 aio_write $fh, 0, (length $$rdata), $$rdata, 0; 1210 aio_write $fh, 0, (length $$rdata), $$rdata, 0;
1228 aio_rename "$filename~", $filename; 1233 aio_rename "$filename~", $filename;
1229 1234
1230 $filename =~ s%/[^/]+$%%; 1235 $filename =~ s%/[^/]+$%%;
1231 aio_pathsync $filename if $cf::USE_FSYNC; 1236 aio_pathsync $filename if $cf::USE_FSYNC;
1232 } else { 1237 } else {
1233 warn "unable to save objects: $filename~: $!\n"; 1238 error "unable to save objects: $filename~: $!\n";
1234 } 1239 }
1235 } else { 1240 } else {
1236 aio_unlink $filename; 1241 aio_unlink $filename;
1237 aio_unlink "$filename.pst"; 1242 aio_unlink "$filename.pst";
1238 } 1243 }
1262 my $st = eval { Coro::Storable::thaw $av }; 1267 my $st = eval { Coro::Storable::thaw $av };
1263 $av = $st->{objs}; 1268 $av = $st->{objs};
1264 } 1269 }
1265 1270
1266 utf8::decode (my $decname = $filename); 1271 utf8::decode (my $decname = $filename);
1267 warn sprintf "loading %s (%d,%d)\n", 1272 trace sprintf "loading %s (%d,%d)\n",
1268 $decname, length $data, scalar @{$av || []} 1273 $decname, length $data, scalar @{$av || []}
1269 if $VERBOSE_IO; 1274 if $VERBOSE_IO;
1270 1275
1271 ($data, $av) 1276 ($data, $av)
1272} 1277}
1273 1278
1366 1371
1367 $pl->ext_reply ($reply, @reply) 1372 $pl->ext_reply ($reply, @reply)
1368 if $reply; 1373 if $reply;
1369 1374
1370 } else { 1375 } else {
1371 warn "player " . ($pl->ob->name) . " sent unparseable ext message: <$buf>\n"; 1376 error "player " . ($pl->ob->name) . " sent unparseable ext message: <$buf>\n";
1372 } 1377 }
1373 1378
1374 cf::override; 1379 cf::override;
1375 }, 1380 },
1376); 1381);
1387 1392
1388 $grp 1393 $grp
1389} 1394}
1390 1395
1391sub load_extensions { 1396sub load_extensions {
1397 info "loading extensions...";
1398
1392 cf::sync_job { 1399 cf::sync_job {
1393 my %todo; 1400 my %todo;
1394 1401
1395 for my $path (<$LIBDIR/*.ext>) { 1402 for my $path (<$LIBDIR/*.ext>) {
1396 next unless -r $path; 1403 next unless -r $path;
1414 1421
1415 $ext{meta} = { map { (split /=/, $_, 2)[0, 1] } split /\s+/, $1 } 1422 $ext{meta} = { map { (split /=/, $_, 2)[0, 1] } split /\s+/, $1 }
1416 if $source =~ /\A#!.*?perl.*?#\s*(.*)$/m; 1423 if $source =~ /\A#!.*?perl.*?#\s*(.*)$/m;
1417 1424
1418 $ext{source} = 1425 $ext{source} =
1419 "package $pkg; use 5.10.0; use strict 'vars', 'subs'; use utf8;\n" 1426 "package $pkg; use common::sense;\n"
1420 . "#line 1 \"$path\"\n{\n" 1427 . "#line 1 \"$path\"\n{\n"
1421 . $source 1428 . $source
1422 . "\n};\n1"; 1429 . "\n};\n1";
1423 1430
1424 $todo{$base} = \%ext; 1431 $todo{$base} = \%ext;
1436 for (split /,\s*/, $v->{meta}{depends}) { 1443 for (split /,\s*/, $v->{meta}{depends}) {
1437 next ext 1444 next ext
1438 unless exists $done{$_}; 1445 unless exists $done{$_};
1439 } 1446 }
1440 1447
1441 warn "... pass $pass, loading '$k' into '$v->{pkg}'\n"; 1448 trace "... pass $pass, loading '$k' into '$v->{pkg}'\n";
1442 1449
1443 my $active = eval $v->{source}; 1450 my $active = eval $v->{source};
1444 1451
1445 if (length $@) { 1452 if (length $@) {
1446 warn "$v->{path}: $@\n"; 1453 error "$v->{path}: $@\n";
1454 undef $@; # work around perl 5.10.0 utf-8 caching bug
1447 1455
1448 cf::cleanup "mandatory extension '$k' failed to load, exiting." 1456 cf::cleanup "mandatory extension '$k' failed to load, exiting."
1449 if exists $v->{meta}{mandatory}; 1457 if exists $v->{meta}{mandatory};
1450 1458
1451 warn "$v->{base}: optional extension cannot be loaded, skipping.\n"; 1459 warn "$v->{base}: optional extension cannot be loaded, skipping.\n";
1453 } else { 1461 } else {
1454 $done{$k} = delete $todo{$k}; 1462 $done{$k} = delete $todo{$k};
1455 push @EXTS, $v->{pkg}; 1463 push @EXTS, $v->{pkg};
1456 $progress = 1; 1464 $progress = 1;
1457 1465
1458 warn "$v->{base}: extension inactive.\n" 1466 info "$v->{base}: extension inactive.\n"
1459 unless $active; 1467 unless $active;
1460 } 1468 }
1461 } 1469 }
1462 1470
1463 unless ($progress) { 1471 unless ($progress) {
1839 1847
1840sub register { 1848sub register {
1841 my (undef, $regex, $prio) = @_; 1849 my (undef, $regex, $prio) = @_;
1842 my $pkg = caller; 1850 my $pkg = caller;
1843 1851
1844 no strict;
1845 push @{"$pkg\::ISA"}, __PACKAGE__; 1852 push @{"$pkg\::ISA"}, __PACKAGE__;
1846 1853
1847 $EXT_MAP{$pkg} = [$prio, qr<$regex>]; 1854 $EXT_MAP{$pkg} = [$prio, qr<$regex>];
1848} 1855}
1849 1856
2183} 2190}
2184 2191
2185sub find_sync { 2192sub find_sync {
2186 my ($path, $origin) = @_; 2193 my ($path, $origin) = @_;
2187 2194
2188 cf::sync_job { find $path, $origin } 2195 return cf::LOG cf::llevError | cf::logBacktrace, "do_find_sync"
2196 if $Coro::current == $Coro::main;
2197
2198 find $path, $origin
2189} 2199}
2190 2200
2191sub do_load_sync { 2201sub do_load_sync {
2192 my ($map) = @_; 2202 my ($map) = @_;
2193 2203
2194 cf::LOG cf::llevDebug | cf::logBacktrace, "do_load_sync" 2204 return cf::LOG cf::llevError | cf::logBacktrace, "do_load_sync"
2195 if $Coro::current == $Coro::main; 2205 if $Coro::current == $Coro::main;
2196 2206
2197 cf::sync_job { $map->load }; 2207 $map->load;
2198} 2208}
2199 2209
2200our %MAP_PREFETCH; 2210our %MAP_PREFETCH;
2201our $MAP_PREFETCHER = undef; 2211our $MAP_PREFETCHER = undef;
2202 2212
2314 2324
2315 my $lock = cf::lock_acquire "map_data:$self->{path}"; 2325 my $lock = cf::lock_acquire "map_data:$self->{path}";
2316 2326
2317 return if $self->players; 2327 return if $self->players;
2318 2328
2319 warn "resetting map ", $self->path, "\n"; 2329 cf::trace "resetting map ", $self->path, "\n";
2320 2330
2321 $self->in_memory (cf::MAP_SWAPPED); 2331 $self->in_memory (cf::MAP_SWAPPED);
2322 2332
2323 # need to save uniques path 2333 # need to save uniques path
2324 unless ($self->{deny_save}) { 2334 unless ($self->{deny_save}) {
2689 2699
2690sub cf::object::player::goto { 2700sub cf::object::player::goto {
2691 my ($self, $path, $x, $y, $check, $done) = @_; 2701 my ($self, $path, $x, $y, $check, $done) = @_;
2692 2702
2693 if ($self->{_link_recursion} >= $MAX_LINKS) { 2703 if ($self->{_link_recursion} >= $MAX_LINKS) {
2694 warn "FATAL: link recursion exceeded, ", $self->name, " goto $path $x $y, redirecting."; 2704 error "FATAL: link recursion exceeded, ", $self->name, " goto $path $x $y, redirecting.";
2695 $self->failmsg ("Something went wrong inside the server - please contact an administrator!"); 2705 $self->failmsg ("Something went wrong inside the server - please contact an administrator!");
2696 ($path, $x, $y) = @$EMERGENCY_POSITION; 2706 ($path, $x, $y) = @$EMERGENCY_POSITION;
2697 } 2707 }
2698 2708
2699 # do generation counting so two concurrent goto's will be executed in-order 2709 # do generation counting so two concurrent goto's will be executed in-order
2847 $self->message ("Something went wrong deep within the deliantra server. " 2857 $self->message ("Something went wrong deep within the deliantra server. "
2848 . "I'll try to bring you back to the map you were before. " 2858 . "I'll try to bring you back to the map you were before. "
2849 . "Please report this to the dungeon master!", 2859 . "Please report this to the dungeon master!",
2850 cf::NDI_UNIQUE | cf::NDI_RED); 2860 cf::NDI_UNIQUE | cf::NDI_RED);
2851 2861
2852 warn "ERROR in enter_exit: $@"; 2862 error "ERROR in enter_exit: $@";
2853 $self->leave_link; 2863 $self->leave_link;
2854 } 2864 }
2855 })->prio (1); 2865 })->prio (1);
2856} 2866}
2857 2867
3170 3180
3171 $ns->ext_reply ($reply, @reply) 3181 $ns->ext_reply ($reply, @reply)
3172 if $reply; 3182 if $reply;
3173 3183
3174 } else { 3184 } else {
3175 warn "client " . ($ns->pl ? $ns->pl->ob->name : $ns->host) . " sent unparseable exti message: <$buf>\n"; 3185 error "client " . ($ns->pl ? $ns->pl->ob->name : $ns->host) . " sent unparseable exti message: <$buf>\n";
3176 } 3186 }
3177 3187
3178 cf::override; 3188 cf::override;
3179 }, 3189 },
3180); 3190);
3261 decrease split destroy change_exp value msg lore send_msg)], 3271 decrease split destroy change_exp value msg lore send_msg)],
3262 ["cf::object::player" => qw(player)], 3272 ["cf::object::player" => qw(player)],
3263 ["cf::player" => qw(peaceful send_msg)], 3273 ["cf::player" => qw(peaceful send_msg)],
3264 ["cf::map" => qw(trigger)], 3274 ["cf::map" => qw(trigger)],
3265) { 3275) {
3266 no strict 'refs';
3267 my ($pkg, @funs) = @$_; 3276 my ($pkg, @funs) = @$_;
3268 *{"safe::$pkg\::$_"} = $safe_hole->wrap (\&{"$pkg\::$_"}) 3277 *{"safe::$pkg\::$_"} = $safe_hole->wrap (\&{"$pkg\::$_"})
3269 for @funs; 3278 for @funs;
3270} 3279}
3271 3280
3310 local @cf::_safe_eval_args = values %vars; 3319 local @cf::_safe_eval_args = values %vars;
3311 @res = wantarray ? eval eval : scalar eval $eval; 3320 @res = wantarray ? eval eval : scalar eval $eval;
3312 } 3321 }
3313 3322
3314 if ($@) { 3323 if ($@) {
3315 warn "$@"; 3324 warn "$@",
3316 warn "while executing safe code '$code'\n"; 3325 "while executing safe code '$code'\n",
3317 warn "with arguments " . (join " ", %vars) . "\n"; 3326 "with arguments " . (join " ", %vars) . "\n";
3318 } 3327 }
3319 3328
3320 wantarray ? @res : $res[0] 3329 wantarray ? @res : $res[0]
3321} 3330}
3322 3331
3356 # for this (global event?) 3365 # for this (global event?)
3357 %ext::player_env::MUSIC_FACE_CACHE = (); 3366 %ext::player_env::MUSIC_FACE_CACHE = ();
3358 3367
3359 my $enc = JSON::XS->new->utf8->canonical->relaxed; 3368 my $enc = JSON::XS->new->utf8->canonical->relaxed;
3360 3369
3361 warn "loading facedata from $path\n"; 3370 trace "loading facedata from $path\n";
3362 3371
3363 my $facedata; 3372 my $facedata;
3364 0 < aio_load $path, $facedata 3373 0 < aio_load $path, $facedata
3365 or die "$path: $!"; 3374 or die "$path: $!";
3366 3375
3400 3409
3401 if (my $smooth = cf::face::find $info->{smooth}) { 3410 if (my $smooth = cf::face::find $info->{smooth}) {
3402 cf::face::set_smooth $idx, $smooth; 3411 cf::face::set_smooth $idx, $smooth;
3403 cf::face::set_smoothlevel $idx, $info->{smoothlevel}; 3412 cf::face::set_smoothlevel $idx, $info->{smoothlevel};
3404 } else { 3413 } else {
3405 warn "smooth face '$info->{smooth}' not found for face '$face'"; 3414 error "smooth face '$info->{smooth}' not found for face '$face'";
3406 } 3415 }
3407 3416
3408 cf::cede_to_tick; 3417 cf::cede_to_tick;
3409 } 3418 }
3410 } 3419 }
3428 my $idx = (cf::face::find $name) || cf::face::alloc $name; 3437 my $idx = (cf::face::find $name) || cf::face::alloc $name;
3429 3438
3430 cf::face::set_data $idx, 0, $info->{data}, $info->{hash}; 3439 cf::face::set_data $idx, 0, $info->{data}, $info->{hash};
3431 cf::face::set_type $idx, $info->{type}; 3440 cf::face::set_type $idx, $info->{type};
3432 } else { 3441 } else {
3433 $RESOURCE{$name} = $info; 3442 $RESOURCE{$name} = $info; # unused
3434 } 3443 }
3435 3444
3436 cf::cede_to_tick; 3445 cf::cede_to_tick;
3437 } 3446 }
3438 } 3447 }
3439 3448
3440 cf::global->invoke (EVENT_GLOBAL_RESOURCE_UPDATE); 3449 cf::global->invoke (EVENT_GLOBAL_RESOURCE_UPDATE);
3441 3450
3442 1 3451 1
3443} 3452}
3444
3445cf::global->attach (on_resource_update => sub {
3446 if (my $soundconf = $RESOURCE{"res/sound.conf"}) {
3447 $soundconf = JSON::XS->new->utf8->relaxed->decode ($soundconf->{data});
3448
3449 for (0 .. SOUND_CAST_SPELL_0 - 1) {
3450 my $sound = $soundconf->{compat}[$_]
3451 or next;
3452
3453 my $face = cf::face::find "sound/$sound->[1]";
3454 cf::sound::set $sound->[0] => $face;
3455 cf::sound::old_sound_index $_, $face; # gcfclient-compat
3456 }
3457
3458 while (my ($k, $v) = each %{$soundconf->{event}}) {
3459 my $face = cf::face::find "sound/$v";
3460 cf::sound::set $k => $face;
3461 }
3462 }
3463});
3464 3453
3465register_exticmd fx_want => sub { 3454register_exticmd fx_want => sub {
3466 my ($ns, $want) = @_; 3455 my ($ns, $want) = @_;
3467 3456
3468 while (my ($k, $v) = each %$want) { 3457 while (my ($k, $v) = each %$want) {
3507sub reload_treasures { 3496sub reload_treasures {
3508 load_resource_file "$DATADIR/treasures" 3497 load_resource_file "$DATADIR/treasures"
3509 or die "unable to load treasurelists\n"; 3498 or die "unable to load treasurelists\n";
3510} 3499}
3511 3500
3501sub reload_sound {
3502 trace "loading sound config from $DATADIR/sound\n";
3503
3504 0 < Coro::AIO::aio_load "$DATADIR/sound", my $data
3505 or die "$DATADIR/sound $!";
3506
3507 my $soundconf = JSON::XS->new->utf8->relaxed->decode ($data);
3508
3509 for (0 .. SOUND_CAST_SPELL_0 - 1) {
3510 my $sound = $soundconf->{compat}[$_]
3511 or next;
3512
3513 my $face = cf::face::find "sound/$sound->[1]";
3514 cf::sound::set $sound->[0] => $face;
3515 cf::sound::old_sound_index $_, $face; # gcfclient-compat
3516 }
3517
3518 while (my ($k, $v) = each %{$soundconf->{event}}) {
3519 my $face = cf::face::find "sound/$v";
3520 cf::sound::set $k => $face;
3521 }
3522}
3523
3512sub reload_resources { 3524sub reload_resources {
3513 warn "reloading resource files...\n"; 3525 trace "reloading resource files...\n";
3514 3526
3515 reload_facedata; 3527 reload_facedata;
3528 reload_sound;
3516 reload_archetypes; 3529 reload_archetypes;
3517 reload_regions; 3530 reload_regions;
3518 reload_treasures; 3531 reload_treasures;
3519 3532
3520 warn "finished reloading resource files\n"; 3533 trace "finished reloading resource files\n";
3521} 3534}
3522 3535
3523sub reload_config { 3536sub reload_config {
3524 warn "reloading config file...\n"; 3537 trace "reloading config file...\n";
3525 3538
3526 open my $fh, "<:utf8", "$CONFDIR/config" 3539 open my $fh, "<:utf8", "$CONFDIR/config"
3527 or return; 3540 or return;
3528 3541
3529 local $/; 3542 local $/;
3540 and die "WARNING: m(un)lockall failed: $!\n"; 3553 and die "WARNING: m(un)lockall failed: $!\n";
3541 }; 3554 };
3542 warn $@ if $@; 3555 warn $@ if $@;
3543 } 3556 }
3544 3557
3545 warn "finished reloading resource files\n"; 3558 trace "finished reloading resource files\n";
3546} 3559}
3547 3560
3548sub pidfile() { 3561sub pidfile() {
3549 sysopen my $fh, $PIDFILE, O_RDWR | O_CREAT 3562 sysopen my $fh, $PIDFILE, O_RDWR | O_CREAT
3550 or die "$PIDFILE: $!"; 3563 or die "$PIDFILE: $!";
3563 seek $fh, 0, 0; 3576 seek $fh, 0, 0;
3564 print $fh $$; 3577 print $fh $$;
3565} 3578}
3566 3579
3567sub main_loop { 3580sub main_loop {
3568 warn "EV::loop starting\n"; 3581 trace "EV::loop starting\n";
3569 if (1) { 3582 if (1) {
3570 EV::loop; 3583 EV::loop;
3571 } 3584 }
3572 warn "EV::loop returned\n"; 3585 trace "EV::loop returned\n";
3573 goto &main_loop unless $REALLY_UNLOOP; 3586 goto &main_loop unless $REALLY_UNLOOP;
3574} 3587}
3575 3588
3576sub main { 3589sub main {
3577 cf::init_globals; # initialise logging 3590 cf::init_globals; # initialise logging
3625 3638
3626 (pop @POST_INIT)->(0) while @POST_INIT; 3639 (pop @POST_INIT)->(0) while @POST_INIT;
3627 }; 3640 };
3628 3641
3629 cf::object::thawer::errors_are_fatal 0; 3642 cf::object::thawer::errors_are_fatal 0;
3630 warn "parse errors in files are no longer fatal from this point on.\n"; 3643 info "parse errors in files are no longer fatal from this point on.\n";
3631 3644
3632 main_loop; 3645 main_loop;
3633} 3646}
3634 3647
3635############################################################################# 3648#############################################################################
3676 or return; 3689 or return;
3677 3690
3678 aio_rename "$RUNTIMEFILE~", $RUNTIMEFILE 3691 aio_rename "$RUNTIMEFILE~", $RUNTIMEFILE
3679 and return; 3692 and return;
3680 3693
3681 warn sprintf "runtime file written (%gs).\n", AE::time - $t0; 3694 trace sprintf "runtime file written (%gs).\n", AE::time - $t0;
3682 3695
3683 1 3696 1
3684} 3697}
3685 3698
3686our $uuid_lock; 3699our $uuid_lock;
3698 or return; 3711 or return;
3699 3712
3700 my $value = uuid_seq uuid_cur; 3713 my $value = uuid_seq uuid_cur;
3701 3714
3702 unless ($value) { 3715 unless ($value) {
3703 warn "cowardly refusing to write zero uuid value!\n"; 3716 info "cowardly refusing to write zero uuid value!\n";
3704 return; 3717 return;
3705 } 3718 }
3706 3719
3707 my $value = uuid_str $value + $uuid_skip; 3720 my $value = uuid_str $value + $uuid_skip;
3708 $uuid_skip = 0; 3721 $uuid_skip = 0;
3718 or return; 3731 or return;
3719 3732
3720 aio_rename "$uuid~", $uuid 3733 aio_rename "$uuid~", $uuid
3721 and return; 3734 and return;
3722 3735
3723 warn "uuid file written ($value).\n"; 3736 trace "uuid file written ($value).\n";
3724 3737
3725 1 3738 1
3726 3739
3727} 3740}
3728 3741
3734} 3747}
3735 3748
3736sub emergency_save() { 3749sub emergency_save() {
3737 my $freeze_guard = cf::freeze_mainloop; 3750 my $freeze_guard = cf::freeze_mainloop;
3738 3751
3739 warn "emergency_perl_save: enter\n"; 3752 info "emergency_perl_save: enter\n";
3753
3754 # this is a trade-off: we want to be very quick here, so
3755 # save all maps without fsync, and later call a global sync
3756 # (which in turn might be very very slow)
3757 local $USE_FSYNC = 0;
3740 3758
3741 cf::sync_job { 3759 cf::sync_job {
3742 # this is a trade-off: we want to be very quick here, so 3760 cf::write_runtime_sync; # external watchdog should not bark
3743 # save all maps without fsync, and later call a global sync
3744 # (which in turn might be very very slow)
3745 local $USE_FSYNC = 0;
3746 3761
3747 # use a peculiar iteration method to avoid tripping on perl 3762 # use a peculiar iteration method to avoid tripping on perl
3748 # refcount bugs in for. also avoids problems with players 3763 # refcount bugs in for. also avoids problems with players
3749 # and maps saved/destroyed asynchronously. 3764 # and maps saved/destroyed asynchronously.
3750 warn "emergency_perl_save: begin player save\n"; 3765 info "emergency_perl_save: begin player save\n";
3751 for my $login (keys %cf::PLAYER) { 3766 for my $login (keys %cf::PLAYER) {
3752 my $pl = $cf::PLAYER{$login} or next; 3767 my $pl = $cf::PLAYER{$login} or next;
3753 $pl->valid or next; 3768 $pl->valid or next;
3754 delete $pl->{unclean_save}; # not strictly necessary, but cannot hurt 3769 delete $pl->{unclean_save}; # not strictly necessary, but cannot hurt
3755 $pl->save; 3770 $pl->save;
3756 } 3771 }
3757 warn "emergency_perl_save: end player save\n"; 3772 info "emergency_perl_save: end player save\n";
3758 3773
3774 cf::write_runtime_sync; # external watchdog should not bark
3775
3759 warn "emergency_perl_save: begin map save\n"; 3776 info "emergency_perl_save: begin map save\n";
3760 for my $path (keys %cf::MAP) { 3777 for my $path (keys %cf::MAP) {
3761 my $map = $cf::MAP{$path} or next; 3778 my $map = $cf::MAP{$path} or next;
3762 $map->valid or next; 3779 $map->valid or next;
3763 $map->save; 3780 $map->save;
3764 } 3781 }
3765 warn "emergency_perl_save: end map save\n"; 3782 info "emergency_perl_save: end map save\n";
3766 3783
3784 cf::write_runtime_sync; # external watchdog should not bark
3785
3767 warn "emergency_perl_save: begin database checkpoint\n"; 3786 info "emergency_perl_save: begin database checkpoint\n";
3768 BDB::db_env_txn_checkpoint $DB_ENV; 3787 BDB::db_env_txn_checkpoint $DB_ENV;
3769 warn "emergency_perl_save: end database checkpoint\n"; 3788 info "emergency_perl_save: end database checkpoint\n";
3770 3789
3771 warn "emergency_perl_save: begin write uuid\n"; 3790 info "emergency_perl_save: begin write uuid\n";
3772 write_uuid_sync 1; 3791 write_uuid_sync 1;
3773 warn "emergency_perl_save: end write uuid\n"; 3792 info "emergency_perl_save: end write uuid\n";
3793
3794 cf::write_runtime_sync; # external watchdog should not bark
3795
3796 trace "emergency_perl_save: syncing database to disk";
3797 BDB::db_env_txn_checkpoint $DB_ENV;
3798
3799 info "emergency_perl_save: starting sync\n";
3800 IO::AIO::aio_sync sub {
3801 info "emergency_perl_save: finished sync\n";
3802 };
3803
3804 cf::write_runtime_sync; # external watchdog should not bark
3805
3806 trace "emergency_perl_save: flushing outstanding aio requests";
3807 while (IO::AIO::nreqs || BDB::nreqs) {
3808 Coro::EV::timer_once 0.01; # let the sync_job do it's thing
3809 }
3810
3811 cf::write_runtime_sync; # external watchdog should not bark
3774 }; 3812 };
3775 3813
3776 warn "emergency_perl_save: starting sync()\n";
3777 IO::AIO::aio_sync sub {
3778 warn "emergency_perl_save: finished sync()\n";
3779 };
3780
3781 warn "emergency_perl_save: leave\n"; 3814 info "emergency_perl_save: leave\n";
3782} 3815}
3783 3816
3784sub post_cleanup { 3817sub post_cleanup {
3785 my ($make_core) = @_; 3818 my ($make_core) = @_;
3786 3819
3820 IO::AIO::flush;
3821
3787 warn Carp::longmess "post_cleanup backtrace" 3822 error Carp::longmess "post_cleanup backtrace"
3788 if $make_core; 3823 if $make_core;
3789 3824
3790 my $fh = pidfile; 3825 my $fh = pidfile;
3791 unlink $PIDFILE if <$fh> == $$; 3826 unlink $PIDFILE if <$fh> == $$;
3792} 3827}
3817} 3852}
3818 3853
3819sub do_reload_perl() { 3854sub do_reload_perl() {
3820 # can/must only be called in main 3855 # can/must only be called in main
3821 if (in_main) { 3856 if (in_main) {
3822 warn "can only reload from main coroutine"; 3857 error "can only reload from main coroutine";
3823 return; 3858 return;
3824 } 3859 }
3825 3860
3826 return if $RELOAD++; 3861 return if $RELOAD++;
3827 3862
3828 my $t1 = AE::time; 3863 my $t1 = AE::time;
3829 3864
3830 while ($RELOAD) { 3865 while ($RELOAD) {
3831 warn "reloading..."; 3866 info "reloading...";
3832 3867
3833 warn "entering sync_job"; 3868 trace "entering sync_job";
3834 3869
3835 cf::sync_job { 3870 cf::sync_job {
3836 cf::write_runtime_sync; # external watchdog should not bark
3837 cf::emergency_save; 3871 cf::emergency_save;
3838 cf::write_runtime_sync; # external watchdog should not bark
3839 3872
3840 warn "syncing database to disk";
3841 BDB::db_env_txn_checkpoint $DB_ENV;
3842
3843 # if anything goes wrong in here, we should simply crash as we already saved
3844
3845 warn "flushing outstanding aio requests";
3846 while (IO::AIO::nreqs || BDB::nreqs) {
3847 Coro::EV::timer_once 0.01; # let the sync_job do it's thing
3848 }
3849
3850 warn "cancelling all extension coros"; 3873 trace "cancelling all extension coros";
3851 $_->cancel for values %EXT_CORO; 3874 $_->cancel for values %EXT_CORO;
3852 %EXT_CORO = (); 3875 %EXT_CORO = ();
3853 3876
3854 warn "removing commands"; 3877 trace "removing commands";
3855 %COMMAND = (); 3878 %COMMAND = ();
3856 3879
3857 warn "removing ext/exti commands"; 3880 trace "removing ext/exti commands";
3858 %EXTCMD = (); 3881 %EXTCMD = ();
3859 %EXTICMD = (); 3882 %EXTICMD = ();
3860 3883
3861 warn "unloading/nuking all extensions"; 3884 trace "unloading/nuking all extensions";
3862 for my $pkg (@EXTS) { 3885 for my $pkg (@EXTS) {
3863 warn "... unloading $pkg"; 3886 trace "... unloading $pkg";
3864 3887
3865 if (my $cb = $pkg->can ("unload")) { 3888 if (my $cb = $pkg->can ("unload")) {
3866 eval { 3889 eval {
3867 $cb->($pkg); 3890 $cb->($pkg);
3868 1 3891 1
3869 } or warn "$pkg unloaded, but with errors: $@"; 3892 } or error "$pkg unloaded, but with errors: $@";
3870 } 3893 }
3871 3894
3872 warn "... clearing $pkg"; 3895 trace "... clearing $pkg";
3873 clear_package $pkg; 3896 clear_package $pkg;
3874 } 3897 }
3875 3898
3876 warn "unloading all perl modules loaded from $LIBDIR"; 3899 trace "unloading all perl modules loaded from $LIBDIR";
3877 while (my ($k, $v) = each %INC) { 3900 while (my ($k, $v) = each %INC) {
3878 next unless $v =~ /^\Q$LIBDIR\E\/.*\.pm$/; 3901 next unless $v =~ /^\Q$LIBDIR\E\/.*\.pm$/;
3879 3902
3880 warn "... unloading $k"; 3903 trace "... unloading $k";
3881 delete $INC{$k}; 3904 delete $INC{$k};
3882 3905
3883 $k =~ s/\.pm$//; 3906 $k =~ s/\.pm$//;
3884 $k =~ s/\//::/g; 3907 $k =~ s/\//::/g;
3885 3908
3888 } 3911 }
3889 3912
3890 clear_package $k; 3913 clear_package $k;
3891 } 3914 }
3892 3915
3893 warn "getting rid of safe::, as good as possible"; 3916 trace "getting rid of safe::, as good as possible";
3894 clear_package "safe::$_" 3917 clear_package "safe::$_"
3895 for qw(cf::attachable cf::object cf::object::player cf::client cf::player cf::map cf::party cf::region); 3918 for qw(cf::attachable cf::object cf::object::player cf::client cf::player cf::map cf::party cf::region);
3896 3919
3897 warn "unloading cf.pm \"a bit\""; 3920 trace "unloading cf.pm \"a bit\"";
3898 delete $INC{"cf.pm"}; 3921 delete $INC{"cf.pm"};
3899 delete $INC{"cf/$_.pm"} for @EXTRA_MODULES; 3922 delete $INC{"cf/$_.pm"} for @EXTRA_MODULES;
3900 3923
3901 # don't, removes xs symbols, too, 3924 # don't, removes xs symbols, too,
3902 # and global variables created in xs 3925 # and global variables created in xs
3903 #clear_package __PACKAGE__; 3926 #clear_package __PACKAGE__;
3904 3927
3905 warn "unload completed, starting to reload now"; 3928 info "unload completed, starting to reload now";
3906 3929
3907 warn "reloading cf.pm"; 3930 trace "reloading cf.pm";
3908 require cf; 3931 require cf;
3909 cf::_connect_to_perl_1; 3932 cf::_connect_to_perl_1;
3910 3933
3911 warn "loading config and database again"; 3934 trace "loading config and database again";
3912 cf::reload_config; 3935 cf::reload_config;
3913 3936
3914 warn "loading extensions"; 3937 trace "loading extensions";
3915 cf::load_extensions; 3938 cf::load_extensions;
3916 3939
3917 if ($REATTACH_ON_RELOAD) { 3940 if ($REATTACH_ON_RELOAD) {
3918 warn "reattaching attachments to objects/players"; 3941 trace "reattaching attachments to objects/players";
3919 _global_reattach; # objects, sockets 3942 _global_reattach; # objects, sockets
3920 warn "reattaching attachments to maps"; 3943 trace "reattaching attachments to maps";
3921 reattach $_ for values %MAP; 3944 reattach $_ for values %MAP;
3922 warn "reattaching attachments to players"; 3945 trace "reattaching attachments to players";
3923 reattach $_ for values %PLAYER; 3946 reattach $_ for values %PLAYER;
3924 } 3947 }
3925 3948
3926 warn "running post_init jobs"; 3949 trace "running post_init jobs";
3927 (pop @POST_INIT)->(1) while @POST_INIT; 3950 (pop @POST_INIT)->(1) while @POST_INIT;
3928 3951
3929 warn "leaving sync_job"; 3952 trace "leaving sync_job";
3930 3953
3931 1 3954 1
3932 } or do { 3955 } or do {
3933 warn $@; 3956 error $@;
3934 cf::cleanup "error while reloading, exiting."; 3957 cf::cleanup "error while reloading, exiting.";
3935 }; 3958 };
3936 3959
3937 warn "reloaded"; 3960 info "reloaded";
3938 --$RELOAD; 3961 --$RELOAD;
3939 } 3962 }
3940 3963
3941 $t1 = AE::time - $t1; 3964 $t1 = AE::time - $t1;
3942 warn "reload completed in ${t1}s\n"; 3965 info "reload completed in ${t1}s\n";
3943}; 3966};
3944 3967
3945our $RELOAD_WATCHER; # used only during reload 3968our $RELOAD_WATCHER; # used only during reload
3946 3969
3947sub reload_perl() { 3970sub reload_perl() {
4007 if ($NOW >= $NEXT_RUNTIME_WRITE) { 4030 if ($NOW >= $NEXT_RUNTIME_WRITE) {
4008 $NEXT_RUNTIME_WRITE = List::Util::max $NEXT_RUNTIME_WRITE + 10, $NOW + 5.; 4031 $NEXT_RUNTIME_WRITE = List::Util::max $NEXT_RUNTIME_WRITE + 10, $NOW + 5.;
4009 Coro::async_pool { 4032 Coro::async_pool {
4010 $Coro::current->{desc} = "runtime saver"; 4033 $Coro::current->{desc} = "runtime saver";
4011 write_runtime_sync 4034 write_runtime_sync
4012 or warn "ERROR: unable to write runtime file: $!"; 4035 or error "ERROR: unable to write runtime file: $!";
4013 }; 4036 };
4014 } 4037 }
4015 4038
4016 if (my $sig = shift @WAIT_FOR_TICK_BEGIN) { 4039 if (my $sig = shift @WAIT_FOR_TICK_BEGIN) {
4017 $sig->send; 4040 $sig->send;
4025 4048
4026 if (0) { 4049 if (0) {
4027 if ($NEXT_TICK) { 4050 if ($NEXT_TICK) {
4028 my $jitter = $TICK_START - $NEXT_TICK; 4051 my $jitter = $TICK_START - $NEXT_TICK;
4029 $JITTER = $JITTER * 0.75 + $jitter * 0.25; 4052 $JITTER = $JITTER * 0.75 + $jitter * 0.25;
4030 warn "jitter $JITTER\n";#d# 4053 debug "jitter $JITTER\n";#d#
4031 } 4054 }
4032 } 4055 }
4033} 4056}
4034 4057
4035{ 4058{

Diff Legend

Removed lines
+ Added lines
< Changed lines
> Changed lines