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.527 by root, Fri Apr 23 04:32:47 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
117our $VERBOSE_IO = 0;#d# 115our $VERBOSE_IO = 1;
118 116
119our $TICK = MAX_TIME * 1e-6; # this is a CONSTANT(!) 117our $TICK = MAX_TIME * 1e-6; # this is a CONSTANT(!)
120our $NEXT_RUNTIME_WRITE; # when should the runtime file be written 118our $NEXT_RUNTIME_WRITE; # when should the runtime file be written
121our $NEXT_TICK; 119our $NEXT_TICK;
122our $USE_FSYNC = 1; # use fsync to write maps - default on 120our $USE_FSYNC = 1; # use fsync to write maps - default on
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) {
1635 $pl->password ("*"); # this should lock out the player until we have nuked the dir 1643 $pl->password ("*"); # this should lock out the player until we have nuked the dir
1636 1644
1637 $pl->invoke (cf::EVENT_PLAYER_LOGOUT, 1) if $pl->active; 1645 $pl->invoke (cf::EVENT_PLAYER_LOGOUT, 1) if $pl->active;
1638 $pl->deactivate; 1646 $pl->deactivate;
1639 my $killer = cf::arch::get "killer_quit"; $pl->killer ($killer); $killer->destroy; 1647 my $killer = cf::arch::get "killer_quit"; $pl->killer ($killer); $killer->destroy;
1640 $pl->ob->check_score;
1641 $pl->invoke (cf::EVENT_PLAYER_QUIT); 1648 $pl->invoke (cf::EVENT_PLAYER_QUIT);
1642 $pl->ns->destroy if $pl->ns; 1649 $pl->ns->destroy if $pl->ns;
1643 1650
1644 my $path = playerdir $pl; 1651 my $path = playerdir $pl;
1645 my $temp = "$path~$cf::RUNTIME~deleting~"; 1652 my $temp = "$path~$cf::RUNTIME~deleting~";
1840 1847
1841sub register { 1848sub register {
1842 my (undef, $regex, $prio) = @_; 1849 my (undef, $regex, $prio) = @_;
1843 my $pkg = caller; 1850 my $pkg = caller;
1844 1851
1845 no strict;
1846 push @{"$pkg\::ISA"}, __PACKAGE__; 1852 push @{"$pkg\::ISA"}, __PACKAGE__;
1847 1853
1848 $EXT_MAP{$pkg} = [$prio, qr<$regex>]; 1854 $EXT_MAP{$pkg} = [$prio, qr<$regex>];
1849} 1855}
1850 1856
2184} 2190}
2185 2191
2186sub find_sync { 2192sub find_sync {
2187 my ($path, $origin) = @_; 2193 my ($path, $origin) = @_;
2188 2194
2189 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
2190} 2199}
2191 2200
2192sub do_load_sync { 2201sub do_load_sync {
2193 my ($map) = @_; 2202 my ($map) = @_;
2194 2203
2195 cf::LOG cf::llevDebug | cf::logBacktrace, "do_load_sync" 2204 return cf::LOG cf::llevError | cf::logBacktrace, "do_load_sync"
2196 if $Coro::current == $Coro::main; 2205 if $Coro::current == $Coro::main;
2197 2206
2198 cf::sync_job { $map->load }; 2207 $map->load;
2199} 2208}
2200 2209
2201our %MAP_PREFETCH; 2210our %MAP_PREFETCH;
2202our $MAP_PREFETCHER = undef; 2211our $MAP_PREFETCHER = undef;
2203 2212
2315 2324
2316 my $lock = cf::lock_acquire "map_data:$self->{path}"; 2325 my $lock = cf::lock_acquire "map_data:$self->{path}";
2317 2326
2318 return if $self->players; 2327 return if $self->players;
2319 2328
2320 warn "resetting map ", $self->path, "\n"; 2329 cf::trace "resetting map ", $self->path, "\n";
2321 2330
2322 $self->in_memory (cf::MAP_SWAPPED); 2331 $self->in_memory (cf::MAP_SWAPPED);
2323 2332
2324 # need to save uniques path 2333 # need to save uniques path
2325 unless ($self->{deny_save}) { 2334 unless ($self->{deny_save}) {
2690 2699
2691sub cf::object::player::goto { 2700sub cf::object::player::goto {
2692 my ($self, $path, $x, $y, $check, $done) = @_; 2701 my ($self, $path, $x, $y, $check, $done) = @_;
2693 2702
2694 if ($self->{_link_recursion} >= $MAX_LINKS) { 2703 if ($self->{_link_recursion} >= $MAX_LINKS) {
2695 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.";
2696 $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!");
2697 ($path, $x, $y) = @$EMERGENCY_POSITION; 2706 ($path, $x, $y) = @$EMERGENCY_POSITION;
2698 } 2707 }
2699 2708
2700 # 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
2848 $self->message ("Something went wrong deep within the deliantra server. " 2857 $self->message ("Something went wrong deep within the deliantra server. "
2849 . "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. "
2850 . "Please report this to the dungeon master!", 2859 . "Please report this to the dungeon master!",
2851 cf::NDI_UNIQUE | cf::NDI_RED); 2860 cf::NDI_UNIQUE | cf::NDI_RED);
2852 2861
2853 warn "ERROR in enter_exit: $@"; 2862 error "ERROR in enter_exit: $@";
2854 $self->leave_link; 2863 $self->leave_link;
2855 } 2864 }
2856 })->prio (1); 2865 })->prio (1);
2857} 2866}
2858 2867
3171 3180
3172 $ns->ext_reply ($reply, @reply) 3181 $ns->ext_reply ($reply, @reply)
3173 if $reply; 3182 if $reply;
3174 3183
3175 } else { 3184 } else {
3176 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";
3177 } 3186 }
3178 3187
3179 cf::override; 3188 cf::override;
3180 }, 3189 },
3181); 3190);
3262 decrease split destroy change_exp value msg lore send_msg)], 3271 decrease split destroy change_exp value msg lore send_msg)],
3263 ["cf::object::player" => qw(player)], 3272 ["cf::object::player" => qw(player)],
3264 ["cf::player" => qw(peaceful send_msg)], 3273 ["cf::player" => qw(peaceful send_msg)],
3265 ["cf::map" => qw(trigger)], 3274 ["cf::map" => qw(trigger)],
3266) { 3275) {
3267 no strict 'refs';
3268 my ($pkg, @funs) = @$_; 3276 my ($pkg, @funs) = @$_;
3269 *{"safe::$pkg\::$_"} = $safe_hole->wrap (\&{"$pkg\::$_"}) 3277 *{"safe::$pkg\::$_"} = $safe_hole->wrap (\&{"$pkg\::$_"})
3270 for @funs; 3278 for @funs;
3271} 3279}
3272 3280
3311 local @cf::_safe_eval_args = values %vars; 3319 local @cf::_safe_eval_args = values %vars;
3312 @res = wantarray ? eval eval : scalar eval $eval; 3320 @res = wantarray ? eval eval : scalar eval $eval;
3313 } 3321 }
3314 3322
3315 if ($@) { 3323 if ($@) {
3316 warn "$@"; 3324 warn "$@",
3317 warn "while executing safe code '$code'\n"; 3325 "while executing safe code '$code'\n",
3318 warn "with arguments " . (join " ", %vars) . "\n"; 3326 "with arguments " . (join " ", %vars) . "\n";
3319 } 3327 }
3320 3328
3321 wantarray ? @res : $res[0] 3329 wantarray ? @res : $res[0]
3322} 3330}
3323 3331
3357 # for this (global event?) 3365 # for this (global event?)
3358 %ext::player_env::MUSIC_FACE_CACHE = (); 3366 %ext::player_env::MUSIC_FACE_CACHE = ();
3359 3367
3360 my $enc = JSON::XS->new->utf8->canonical->relaxed; 3368 my $enc = JSON::XS->new->utf8->canonical->relaxed;
3361 3369
3362 warn "loading facedata from $path\n"; 3370 trace "loading facedata from $path\n";
3363 3371
3364 my $facedata; 3372 my $facedata;
3365 0 < aio_load $path, $facedata 3373 0 < aio_load $path, $facedata
3366 or die "$path: $!"; 3374 or die "$path: $!";
3367 3375
3401 3409
3402 if (my $smooth = cf::face::find $info->{smooth}) { 3410 if (my $smooth = cf::face::find $info->{smooth}) {
3403 cf::face::set_smooth $idx, $smooth; 3411 cf::face::set_smooth $idx, $smooth;
3404 cf::face::set_smoothlevel $idx, $info->{smoothlevel}; 3412 cf::face::set_smoothlevel $idx, $info->{smoothlevel};
3405 } else { 3413 } else {
3406 warn "smooth face '$info->{smooth}' not found for face '$face'"; 3414 error "smooth face '$info->{smooth}' not found for face '$face'";
3407 } 3415 }
3408 3416
3409 cf::cede_to_tick; 3417 cf::cede_to_tick;
3410 } 3418 }
3411 } 3419 }
3429 my $idx = (cf::face::find $name) || cf::face::alloc $name; 3437 my $idx = (cf::face::find $name) || cf::face::alloc $name;
3430 3438
3431 cf::face::set_data $idx, 0, $info->{data}, $info->{hash}; 3439 cf::face::set_data $idx, 0, $info->{data}, $info->{hash};
3432 cf::face::set_type $idx, $info->{type}; 3440 cf::face::set_type $idx, $info->{type};
3433 } else { 3441 } else {
3434 $RESOURCE{$name} = $info; 3442 $RESOURCE{$name} = $info; # unused
3435 } 3443 }
3436 3444
3437 cf::cede_to_tick; 3445 cf::cede_to_tick;
3438 } 3446 }
3439 } 3447 }
3440 3448
3441 cf::global->invoke (EVENT_GLOBAL_RESOURCE_UPDATE); 3449 cf::global->invoke (EVENT_GLOBAL_RESOURCE_UPDATE);
3442 3450
3443 1 3451 1
3444} 3452}
3445
3446cf::global->attach (on_resource_update => sub {
3447 if (my $soundconf = $RESOURCE{"res/sound.conf"}) {
3448 $soundconf = JSON::XS->new->utf8->relaxed->decode ($soundconf->{data});
3449
3450 for (0 .. SOUND_CAST_SPELL_0 - 1) {
3451 my $sound = $soundconf->{compat}[$_]
3452 or next;
3453
3454 my $face = cf::face::find "sound/$sound->[1]";
3455 cf::sound::set $sound->[0] => $face;
3456 cf::sound::old_sound_index $_, $face; # gcfclient-compat
3457 }
3458
3459 while (my ($k, $v) = each %{$soundconf->{event}}) {
3460 my $face = cf::face::find "sound/$v";
3461 cf::sound::set $k => $face;
3462 }
3463 }
3464});
3465 3453
3466register_exticmd fx_want => sub { 3454register_exticmd fx_want => sub {
3467 my ($ns, $want) = @_; 3455 my ($ns, $want) = @_;
3468 3456
3469 while (my ($k, $v) = each %$want) { 3457 while (my ($k, $v) = each %$want) {
3508sub reload_treasures { 3496sub reload_treasures {
3509 load_resource_file "$DATADIR/treasures" 3497 load_resource_file "$DATADIR/treasures"
3510 or die "unable to load treasurelists\n"; 3498 or die "unable to load treasurelists\n";
3511} 3499}
3512 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
3513sub reload_resources { 3524sub reload_resources {
3514 warn "reloading resource files...\n"; 3525 trace "reloading resource files...\n";
3515 3526
3516 reload_facedata; 3527 reload_facedata;
3528 reload_sound;
3517 reload_archetypes; 3529 reload_archetypes;
3518 reload_regions; 3530 reload_regions;
3519 reload_treasures; 3531 reload_treasures;
3520 3532
3521 warn "finished reloading resource files\n"; 3533 trace "finished reloading resource files\n";
3522} 3534}
3523 3535
3524sub reload_config { 3536sub reload_config {
3525 warn "reloading config file...\n"; 3537 trace "reloading config file...\n";
3526 3538
3527 open my $fh, "<:utf8", "$CONFDIR/config" 3539 open my $fh, "<:utf8", "$CONFDIR/config"
3528 or return; 3540 or return;
3529 3541
3530 local $/; 3542 local $/;
3541 and die "WARNING: m(un)lockall failed: $!\n"; 3553 and die "WARNING: m(un)lockall failed: $!\n";
3542 }; 3554 };
3543 warn $@ if $@; 3555 warn $@ if $@;
3544 } 3556 }
3545 3557
3546 warn "finished reloading resource files\n"; 3558 trace "finished reloading resource files\n";
3547} 3559}
3548 3560
3549sub pidfile() { 3561sub pidfile() {
3550 sysopen my $fh, $PIDFILE, O_RDWR | O_CREAT 3562 sysopen my $fh, $PIDFILE, O_RDWR | O_CREAT
3551 or die "$PIDFILE: $!"; 3563 or die "$PIDFILE: $!";
3564 seek $fh, 0, 0; 3576 seek $fh, 0, 0;
3565 print $fh $$; 3577 print $fh $$;
3566} 3578}
3567 3579
3568sub main_loop { 3580sub main_loop {
3569 warn "EV::loop starting\n"; 3581 trace "EV::loop starting\n";
3570 if (1) { 3582 if (1) {
3571 EV::loop; 3583 EV::loop;
3572 } 3584 }
3573 warn "EV::loop returned\n"; 3585 trace "EV::loop returned\n";
3574 goto &main_loop unless $REALLY_UNLOOP; 3586 goto &main_loop unless $REALLY_UNLOOP;
3575} 3587}
3576 3588
3577sub main { 3589sub main {
3578 cf::init_globals; # initialise logging 3590 cf::init_globals; # initialise logging
3626 3638
3627 (pop @POST_INIT)->(0) while @POST_INIT; 3639 (pop @POST_INIT)->(0) while @POST_INIT;
3628 }; 3640 };
3629 3641
3630 cf::object::thawer::errors_are_fatal 0; 3642 cf::object::thawer::errors_are_fatal 0;
3631 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";
3632 3644
3633 main_loop; 3645 main_loop;
3634} 3646}
3635 3647
3636############################################################################# 3648#############################################################################
3677 or return; 3689 or return;
3678 3690
3679 aio_rename "$RUNTIMEFILE~", $RUNTIMEFILE 3691 aio_rename "$RUNTIMEFILE~", $RUNTIMEFILE
3680 and return; 3692 and return;
3681 3693
3682 warn sprintf "runtime file written (%gs).\n", AE::time - $t0; 3694 trace sprintf "runtime file written (%gs).\n", AE::time - $t0;
3683 3695
3684 1 3696 1
3685} 3697}
3686 3698
3687our $uuid_lock; 3699our $uuid_lock;
3699 or return; 3711 or return;
3700 3712
3701 my $value = uuid_seq uuid_cur; 3713 my $value = uuid_seq uuid_cur;
3702 3714
3703 unless ($value) { 3715 unless ($value) {
3704 warn "cowardly refusing to write zero uuid value!\n"; 3716 info "cowardly refusing to write zero uuid value!\n";
3705 return; 3717 return;
3706 } 3718 }
3707 3719
3708 my $value = uuid_str $value + $uuid_skip; 3720 my $value = uuid_str $value + $uuid_skip;
3709 $uuid_skip = 0; 3721 $uuid_skip = 0;
3719 or return; 3731 or return;
3720 3732
3721 aio_rename "$uuid~", $uuid 3733 aio_rename "$uuid~", $uuid
3722 and return; 3734 and return;
3723 3735
3724 warn "uuid file written ($value).\n"; 3736 trace "uuid file written ($value).\n";
3725 3737
3726 1 3738 1
3727 3739
3728} 3740}
3729 3741
3735} 3747}
3736 3748
3737sub emergency_save() { 3749sub emergency_save() {
3738 my $freeze_guard = cf::freeze_mainloop; 3750 my $freeze_guard = cf::freeze_mainloop;
3739 3751
3740 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;
3741 3758
3742 cf::sync_job { 3759 cf::sync_job {
3743 # this is a trade-off: we want to be very quick here, so 3760 cf::write_runtime_sync; # external watchdog should not bark
3744 # save all maps without fsync, and later call a global sync
3745 # (which in turn might be very very slow)
3746 local $USE_FSYNC = 0;
3747 3761
3748 # use a peculiar iteration method to avoid tripping on perl 3762 # use a peculiar iteration method to avoid tripping on perl
3749 # refcount bugs in for. also avoids problems with players 3763 # refcount bugs in for. also avoids problems with players
3750 # and maps saved/destroyed asynchronously. 3764 # and maps saved/destroyed asynchronously.
3751 warn "emergency_perl_save: begin player save\n"; 3765 info "emergency_perl_save: begin player save\n";
3752 for my $login (keys %cf::PLAYER) { 3766 for my $login (keys %cf::PLAYER) {
3753 my $pl = $cf::PLAYER{$login} or next; 3767 my $pl = $cf::PLAYER{$login} or next;
3754 $pl->valid or next; 3768 $pl->valid or next;
3755 delete $pl->{unclean_save}; # not strictly necessary, but cannot hurt 3769 delete $pl->{unclean_save}; # not strictly necessary, but cannot hurt
3756 $pl->save; 3770 $pl->save;
3757 } 3771 }
3758 warn "emergency_perl_save: end player save\n"; 3772 info "emergency_perl_save: end player save\n";
3759 3773
3774 cf::write_runtime_sync; # external watchdog should not bark
3775
3760 warn "emergency_perl_save: begin map save\n"; 3776 info "emergency_perl_save: begin map save\n";
3761 for my $path (keys %cf::MAP) { 3777 for my $path (keys %cf::MAP) {
3762 my $map = $cf::MAP{$path} or next; 3778 my $map = $cf::MAP{$path} or next;
3763 $map->valid or next; 3779 $map->valid or next;
3764 $map->save; 3780 $map->save;
3765 } 3781 }
3766 warn "emergency_perl_save: end map save\n"; 3782 info "emergency_perl_save: end map save\n";
3767 3783
3784 cf::write_runtime_sync; # external watchdog should not bark
3785
3768 warn "emergency_perl_save: begin database checkpoint\n"; 3786 info "emergency_perl_save: begin database checkpoint\n";
3769 BDB::db_env_txn_checkpoint $DB_ENV; 3787 BDB::db_env_txn_checkpoint $DB_ENV;
3770 warn "emergency_perl_save: end database checkpoint\n"; 3788 info "emergency_perl_save: end database checkpoint\n";
3771 3789
3772 warn "emergency_perl_save: begin write uuid\n"; 3790 info "emergency_perl_save: begin write uuid\n";
3773 write_uuid_sync 1; 3791 write_uuid_sync 1;
3774 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
3775 }; 3812 };
3776 3813
3777 warn "emergency_perl_save: starting sync()\n";
3778 IO::AIO::aio_sync sub {
3779 warn "emergency_perl_save: finished sync()\n";
3780 };
3781
3782 warn "emergency_perl_save: leave\n"; 3814 info "emergency_perl_save: leave\n";
3783} 3815}
3784 3816
3785sub post_cleanup { 3817sub post_cleanup {
3786 my ($make_core) = @_; 3818 my ($make_core) = @_;
3787 3819
3820 IO::AIO::flush;
3821
3788 warn Carp::longmess "post_cleanup backtrace" 3822 error Carp::longmess "post_cleanup backtrace"
3789 if $make_core; 3823 if $make_core;
3790 3824
3791 my $fh = pidfile; 3825 my $fh = pidfile;
3792 unlink $PIDFILE if <$fh> == $$; 3826 unlink $PIDFILE if <$fh> == $$;
3793} 3827}
3818} 3852}
3819 3853
3820sub do_reload_perl() { 3854sub do_reload_perl() {
3821 # can/must only be called in main 3855 # can/must only be called in main
3822 if (in_main) { 3856 if (in_main) {
3823 warn "can only reload from main coroutine"; 3857 error "can only reload from main coroutine";
3824 return; 3858 return;
3825 } 3859 }
3826 3860
3827 return if $RELOAD++; 3861 return if $RELOAD++;
3828 3862
3829 my $t1 = AE::time; 3863 my $t1 = AE::time;
3830 3864
3831 while ($RELOAD) { 3865 while ($RELOAD) {
3832 warn "reloading..."; 3866 info "reloading...";
3833 3867
3834 warn "entering sync_job"; 3868 trace "entering sync_job";
3835 3869
3836 cf::sync_job { 3870 cf::sync_job {
3837 cf::write_runtime_sync; # external watchdog should not bark
3838 cf::emergency_save; 3871 cf::emergency_save;
3839 cf::write_runtime_sync; # external watchdog should not bark
3840 3872
3841 warn "syncing database to disk";
3842 BDB::db_env_txn_checkpoint $DB_ENV;
3843
3844 # if anything goes wrong in here, we should simply crash as we already saved
3845
3846 warn "flushing outstanding aio requests";
3847 while (IO::AIO::nreqs || BDB::nreqs) {
3848 Coro::EV::timer_once 0.01; # let the sync_job do it's thing
3849 }
3850
3851 warn "cancelling all extension coros"; 3873 trace "cancelling all extension coros";
3852 $_->cancel for values %EXT_CORO; 3874 $_->cancel for values %EXT_CORO;
3853 %EXT_CORO = (); 3875 %EXT_CORO = ();
3854 3876
3855 warn "removing commands"; 3877 trace "removing commands";
3856 %COMMAND = (); 3878 %COMMAND = ();
3857 3879
3858 warn "removing ext/exti commands"; 3880 trace "removing ext/exti commands";
3859 %EXTCMD = (); 3881 %EXTCMD = ();
3860 %EXTICMD = (); 3882 %EXTICMD = ();
3861 3883
3862 warn "unloading/nuking all extensions"; 3884 trace "unloading/nuking all extensions";
3863 for my $pkg (@EXTS) { 3885 for my $pkg (@EXTS) {
3864 warn "... unloading $pkg"; 3886 trace "... unloading $pkg";
3865 3887
3866 if (my $cb = $pkg->can ("unload")) { 3888 if (my $cb = $pkg->can ("unload")) {
3867 eval { 3889 eval {
3868 $cb->($pkg); 3890 $cb->($pkg);
3869 1 3891 1
3870 } or warn "$pkg unloaded, but with errors: $@"; 3892 } or error "$pkg unloaded, but with errors: $@";
3871 } 3893 }
3872 3894
3873 warn "... clearing $pkg"; 3895 trace "... clearing $pkg";
3874 clear_package $pkg; 3896 clear_package $pkg;
3875 } 3897 }
3876 3898
3877 warn "unloading all perl modules loaded from $LIBDIR"; 3899 trace "unloading all perl modules loaded from $LIBDIR";
3878 while (my ($k, $v) = each %INC) { 3900 while (my ($k, $v) = each %INC) {
3879 next unless $v =~ /^\Q$LIBDIR\E\/.*\.pm$/; 3901 next unless $v =~ /^\Q$LIBDIR\E\/.*\.pm$/;
3880 3902
3881 warn "... unloading $k"; 3903 trace "... unloading $k";
3882 delete $INC{$k}; 3904 delete $INC{$k};
3883 3905
3884 $k =~ s/\.pm$//; 3906 $k =~ s/\.pm$//;
3885 $k =~ s/\//::/g; 3907 $k =~ s/\//::/g;
3886 3908
3889 } 3911 }
3890 3912
3891 clear_package $k; 3913 clear_package $k;
3892 } 3914 }
3893 3915
3894 warn "getting rid of safe::, as good as possible"; 3916 trace "getting rid of safe::, as good as possible";
3895 clear_package "safe::$_" 3917 clear_package "safe::$_"
3896 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);
3897 3919
3898 warn "unloading cf.pm \"a bit\""; 3920 trace "unloading cf.pm \"a bit\"";
3899 delete $INC{"cf.pm"}; 3921 delete $INC{"cf.pm"};
3900 delete $INC{"cf/$_.pm"} for @EXTRA_MODULES; 3922 delete $INC{"cf/$_.pm"} for @EXTRA_MODULES;
3901 3923
3902 # don't, removes xs symbols, too, 3924 # don't, removes xs symbols, too,
3903 # and global variables created in xs 3925 # and global variables created in xs
3904 #clear_package __PACKAGE__; 3926 #clear_package __PACKAGE__;
3905 3927
3906 warn "unload completed, starting to reload now"; 3928 info "unload completed, starting to reload now";
3907 3929
3908 warn "reloading cf.pm"; 3930 trace "reloading cf.pm";
3909 require cf; 3931 require cf;
3910 cf::_connect_to_perl_1; 3932 cf::_connect_to_perl_1;
3911 3933
3912 warn "loading config and database again"; 3934 trace "loading config and database again";
3913 cf::reload_config; 3935 cf::reload_config;
3914 3936
3915 warn "loading extensions"; 3937 trace "loading extensions";
3916 cf::load_extensions; 3938 cf::load_extensions;
3917 3939
3918 if ($REATTACH_ON_RELOAD) { 3940 if ($REATTACH_ON_RELOAD) {
3919 warn "reattaching attachments to objects/players"; 3941 trace "reattaching attachments to objects/players";
3920 _global_reattach; # objects, sockets 3942 _global_reattach; # objects, sockets
3921 warn "reattaching attachments to maps"; 3943 trace "reattaching attachments to maps";
3922 reattach $_ for values %MAP; 3944 reattach $_ for values %MAP;
3923 warn "reattaching attachments to players"; 3945 trace "reattaching attachments to players";
3924 reattach $_ for values %PLAYER; 3946 reattach $_ for values %PLAYER;
3925 } 3947 }
3926 3948
3927 warn "running post_init jobs"; 3949 trace "running post_init jobs";
3928 (pop @POST_INIT)->(1) while @POST_INIT; 3950 (pop @POST_INIT)->(1) while @POST_INIT;
3929 3951
3930 warn "leaving sync_job"; 3952 trace "leaving sync_job";
3931 3953
3932 1 3954 1
3933 } or do { 3955 } or do {
3934 warn $@; 3956 error $@;
3935 cf::cleanup "error while reloading, exiting."; 3957 cf::cleanup "error while reloading, exiting.";
3936 }; 3958 };
3937 3959
3938 warn "reloaded"; 3960 info "reloaded";
3939 --$RELOAD; 3961 --$RELOAD;
3940 } 3962 }
3941 3963
3942 $t1 = AE::time - $t1; 3964 $t1 = AE::time - $t1;
3943 warn "reload completed in ${t1}s\n"; 3965 info "reload completed in ${t1}s\n";
3944}; 3966};
3945 3967
3946our $RELOAD_WATCHER; # used only during reload 3968our $RELOAD_WATCHER; # used only during reload
3947 3969
3948sub reload_perl() { 3970sub reload_perl() {
4008 if ($NOW >= $NEXT_RUNTIME_WRITE) { 4030 if ($NOW >= $NEXT_RUNTIME_WRITE) {
4009 $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.;
4010 Coro::async_pool { 4032 Coro::async_pool {
4011 $Coro::current->{desc} = "runtime saver"; 4033 $Coro::current->{desc} = "runtime saver";
4012 write_runtime_sync 4034 write_runtime_sync
4013 or warn "ERROR: unable to write runtime file: $!"; 4035 or error "ERROR: unable to write runtime file: $!";
4014 }; 4036 };
4015 } 4037 }
4016 4038
4017 if (my $sig = shift @WAIT_FOR_TICK_BEGIN) { 4039 if (my $sig = shift @WAIT_FOR_TICK_BEGIN) {
4018 $sig->send; 4040 $sig->send;
4026 4048
4027 if (0) { 4049 if (0) {
4028 if ($NEXT_TICK) { 4050 if ($NEXT_TICK) {
4029 my $jitter = $TICK_START - $NEXT_TICK; 4051 my $jitter = $TICK_START - $NEXT_TICK;
4030 $JITTER = $JITTER * 0.75 + $jitter * 0.25; 4052 $JITTER = $JITTER * 0.75 + $jitter * 0.25;
4031 warn "jitter $JITTER\n";#d# 4053 debug "jitter $JITTER\n";#d#
4032 } 4054 }
4033 } 4055 }
4034} 4056}
4035 4057
4036{ 4058{

Diff Legend

Removed lines
+ Added lines
< Changed lines
> Changed lines