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.513 by root, Mon Apr 12 05:22:38 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 = 4000; 111our $OUTPUT_RATE_MIN = 3000;
114our $OUTPUT_RATE_MAX = 100000; 112our $OUTPUT_RATE_MAX = 1000000;
113
114our $MAX_LINKS = 32; # how many chained exits to follow
115our $VERBOSE_IO = 1;
115 116
116our $TICK = MAX_TIME * 1e-6; # this is a CONSTANT(!) 117our $TICK = MAX_TIME * 1e-6; # this is a CONSTANT(!)
117our $NEXT_RUNTIME_WRITE; # when should the runtime file be written 118our $NEXT_RUNTIME_WRITE; # when should the runtime file be written
118our $NEXT_TICK; 119our $NEXT_TICK;
119our $USE_FSYNC = 1; # use fsync to write maps - default on 120our $USE_FSYNC = 1; # use fsync to write maps - default on
165 166
166our $EMERGENCY_POSITION; 167our $EMERGENCY_POSITION;
167 168
168sub cf::map::normalise; 169sub cf::map::normalise;
169 170
171sub in_main() {
172 $Coro::current == $Coro::main
173}
174
170############################################################################# 175#############################################################################
171 176
172%REFLECT = (); 177%REFLECT = ();
173for (@REFLECT) { 178for (@REFLECT) {
174 my $reflect = JSON::XS::decode_json $_; 179 my $reflect = JSON::XS::decode_json $_;
245 250
246=back 251=back
247 252
248=cut 253=cut
249 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
250$Coro::State::WARNHOOK = sub { 261$Coro::State::WARNHOOK = sub {
251 my $msg = join "", @_; 262 my $msg = join "", @_;
252 263
253 $msg .= "\n" 264 $msg .= "\n"
254 unless $msg =~ /\n$/; 265 unless $msg =~ /\n$/;
255 266
256 $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;
257 268
258 LOG llevError, $msg; 269 LOG llevWarn, $msg;
259}; 270};
260 271
261$Coro::State::DIEHOOK = sub { 272$Coro::State::DIEHOOK = sub {
262 return unless $^S eq 0; # "eq", not "==" 273 return unless $^S eq 0; # "eq", not "=="
263 274
264 warn Carp::longmess $_[0]; 275 error Carp::longmess $_[0];
265 276
266 if ($Coro::current == $Coro::main) {#d# 277 if (in_main) {#d#
267 warn "DIEHOOK called in main context, Coro bug?\n";#d# 278 error "DIEHOOK called in main context, Coro bug?\n";#d#
268 return;#d# 279 return;#d#
269 }#d# 280 }#d#
270 281
271 # kill coroutine otherwise 282 # kill coroutine otherwise
272 Coro::terminate 283 Coro::terminate
399} 410}
400 411
401=item cf::periodic $interval, $cb 412=item cf::periodic $interval, $cb
402 413
403Like EV::periodic, but randomly selects a starting point so that the actions 414Like EV::periodic, but randomly selects a starting point so that the actions
404get spread over timer. 415get spread over time.
405 416
406=cut 417=cut
407 418
408sub periodic($$) { 419sub periodic($$) {
409 my ($interval, $cb) = @_; 420 my ($interval, $cb) = @_;
505=cut 516=cut
506 517
507sub sync_job(&) { 518sub sync_job(&) {
508 my ($job) = @_; 519 my ($job) = @_;
509 520
510 if ($Coro::current == $Coro::main) { 521 if (in_main) {
511 my $time = AE::time; 522 my $time = AE::time;
512 523
513 # this is the main coro, too bad, we have to block 524 # this is the main coro, too bad, we have to block
514 # till the operation succeeds, freezing the server :/ 525 # till the operation succeeds, freezing the server :/
515 526
516 LOG llevError, Carp::longmess "sync job";#d# 527 #LOG llevError, Carp::longmess "sync job";#d#
517 528
518 my $freeze_guard = freeze_mainloop; 529 my $freeze_guard = freeze_mainloop;
519 530
520 my $busy = 1; 531 my $busy = 1;
521 my @res; 532 my @res;
522 533
523 (async { 534 (async {
524 $Coro::current->desc ("sync job coro"); 535 $Coro::current->desc ("sync job coro");
525 @res = eval { $job->() }; 536 @res = eval { $job->() };
526 warn $@ if $@; 537 error $@ if $@;
527 undef $busy; 538 undef $busy;
528 })->prio (Coro::PRIO_MAX); 539 })->prio (Coro::PRIO_MAX);
529 540
530 while ($busy) { 541 while ($busy) {
531 if (Coro::nready) { 542 if (Coro::nready) {
587 reset_signals; 598 reset_signals;
588 &$cb 599 &$cb
589 }, @args; 600 }, @args;
590 601
591 wantarray ? @res : $res[-1] 602 wantarray ? @res : $res[-1]
603}
604
605sub objinfo {
606 (
607 "counter value" => cf::object::object_count,
608 "objects created" => cf::object::create_count,
609 "objects destroyed" => cf::object::destroy_count,
610 "freelist size" => cf::object::free_count,
611 "allocated objects" => cf::object::objects_size,
612 "active objects" => cf::object::actives_size,
613 )
592} 614}
593 615
594=item $coin = coin_from_name $name 616=item $coin = coin_from_name $name
595 617
596=cut 618=cut
633within each server. 655within each server.
634 656
635=cut 657=cut
636 658
637sub db_table($) { 659sub db_table($) {
660 cf::error "db_get called from main context"
661 if $Coro::current == $Coro::main;
662
638 my ($name) = @_; 663 my ($name) = @_;
639 my $db = BDB::db_create $DB_ENV; 664 my $db = BDB::db_create $DB_ENV;
640 665
641 eval { 666 eval {
642 $db->set_flags (BDB::CHKSUM); 667 $db->set_flags (BDB::CHKSUM);
652} 677}
653 678
654our $DB; 679our $DB;
655 680
656sub db_init { 681sub db_init {
657 cf::sync_job {
658 $DB ||= db_table "db"; 682 $DB ||= db_table "db";
659 };
660} 683}
661 684
662sub db_get($$) { 685sub db_get($$) {
663 my $key = "$_[0]/$_[1]"; 686 my $key = "$_[0]/$_[1]";
664 687
665 cf::sync_job { 688 cf::error "db_get called from main context"
689 if $Coro::current == $Coro::main;
690
666 BDB::db_get $DB, undef, $key, my $data; 691 BDB::db_get $DB, undef, $key, my $data;
667 692
668 $! ? () 693 $! ? ()
669 : $data 694 : $data
670 }
671} 695}
672 696
673sub db_put($$$) { 697sub db_put($$$) {
674 BDB::dbreq_pri 4; 698 BDB::dbreq_pri 4;
675 BDB::db_put $DB, undef, "$_[0]/$_[1]", $_[2], 0, sub { }; 699 BDB::db_put $DB, undef, "$_[0]/$_[1]", $_[2], 0, sub { };
731 755
732 my $t1 = Time::HiRes::time; 756 my $t1 = Time::HiRes::time;
733 my $data = $process->(\@data); 757 my $data = $process->(\@data);
734 my $t2 = Time::HiRes::time; 758 my $t2 = Time::HiRes::time;
735 759
736 warn "cache: '$id' processed in ", $t2 - $t1, "s\n"; 760 info "cache: '$id' processed in ", $t2 - $t1, "s\n";
737 761
738 db_put cache => "$id/data", $data; 762 db_put cache => "$id/data", $data;
739 db_put cache => "$id/md5" , $md5; 763 db_put cache => "$id/md5" , $md5;
740 db_put cache => "$id/meta", $meta; 764 db_put cache => "$id/meta", $meta;
741 765
751 775
752=cut 776=cut
753 777
754sub datalog($@) { 778sub datalog($@) {
755 my ($type, %kv) = @_; 779 my ($type, %kv) = @_;
756 warn "DATALOG ", JSON::XS->new->ascii->encode ({ %kv, type => $type }); 780 info "DATALOG ", JSON::XS->new->ascii->encode ({ %kv, type => $type });
757} 781}
758 782
759=back 783=back
760 784
761=cut 785=cut
956 980
957 } elsif (exists $cb_id{$type}) { 981 } elsif (exists $cb_id{$type}) {
958 _attach_cb $registry, $cb_id{$type}, $prio, shift @arg; 982 _attach_cb $registry, $cb_id{$type}, $prio, shift @arg;
959 983
960 } elsif (ref $type) { 984 } elsif (ref $type) {
961 warn "attaching objects not supported, ignoring.\n"; 985 error "attaching objects not supported, ignoring.\n";
962 986
963 } else { 987 } else {
964 shift @arg; 988 shift @arg;
965 warn "attach argument '$type' not supported, ignoring.\n"; 989 error "attach argument '$type' not supported, ignoring.\n";
966 } 990 }
967 } 991 }
968} 992}
969 993
970sub _object_attach { 994sub _object_attach {
980 _attach $registry, $klass, @attach; 1004 _attach $registry, $klass, @attach;
981 } 1005 }
982 1006
983 $obj->{$name} = \%arg; 1007 $obj->{$name} = \%arg;
984 } else { 1008 } else {
985 warn "object uses attachment '$name' which is not available, postponing.\n"; 1009 info "object uses attachment '$name' which is not available, postponing.\n";
986 } 1010 }
987 1011
988 $obj->{_attachment}{$name} = undef; 1012 $obj->{_attachment}{$name} = undef;
989} 1013}
990 1014
1049 1073
1050 for (@$callbacks) { 1074 for (@$callbacks) {
1051 eval { &{$_->[1]} }; 1075 eval { &{$_->[1]} };
1052 1076
1053 if ($@) { 1077 if ($@) {
1054 warn "$@";
1055 warn "... while processing $EVENT[$event][0](@_) event, skipping processing altogether.\n"; 1078 error "$@", "... while processing $EVENT[$event][0](@_) event, skipping processing altogether.\n";
1056 override; 1079 override;
1057 } 1080 }
1058 1081
1059 return 1 if $override; 1082 return 1 if $override;
1060 } 1083 }
1139 for (@$attach) { 1162 for (@$attach) {
1140 my ($klass, @attach) = @$_; 1163 my ($klass, @attach) = @$_;
1141 _attach $registry, $klass, @attach; 1164 _attach $registry, $klass, @attach;
1142 } 1165 }
1143 } else { 1166 } else {
1144 warn "object uses attachment '$name' that is not available, postponing.\n"; 1167 info "object uses attachment '$name' that is not available, postponing.\n";
1145 } 1168 }
1146 } 1169 }
1147} 1170}
1148 1171
1149cf::attachable->attach ( 1172cf::attachable->attach (
1176 my ($filename, $rdata, $objs) = @_; 1199 my ($filename, $rdata, $objs) = @_;
1177 1200
1178 sync_job { 1201 sync_job {
1179 if (length $$rdata) { 1202 if (length $$rdata) {
1180 utf8::decode (my $decname = $filename); 1203 utf8::decode (my $decname = $filename);
1181 warn sprintf "saving %s (%d,%d)\n", 1204 trace sprintf "saving %s (%d,%d)\n",
1182 $decname, length $$rdata, scalar @$objs; 1205 $decname, length $$rdata, scalar @$objs
1206 if $VERBOSE_IO;
1183 1207
1184 if (my $fh = aio_open "$filename~", O_WRONLY | O_CREAT, 0600) { 1208 if (my $fh = aio_open "$filename~", O_WRONLY | O_CREAT, 0600) {
1185 aio_chmod $fh, SAVE_MODE; 1209 aio_chmod $fh, SAVE_MODE;
1186 aio_write $fh, 0, (length $$rdata), $$rdata, 0; 1210 aio_write $fh, 0, (length $$rdata), $$rdata, 0;
1187 if ($cf::USE_FSYNC) { 1211 if ($cf::USE_FSYNC) {
1209 aio_rename "$filename~", $filename; 1233 aio_rename "$filename~", $filename;
1210 1234
1211 $filename =~ s%/[^/]+$%%; 1235 $filename =~ s%/[^/]+$%%;
1212 aio_pathsync $filename if $cf::USE_FSYNC; 1236 aio_pathsync $filename if $cf::USE_FSYNC;
1213 } else { 1237 } else {
1214 warn "unable to save objects: $filename~: $!\n"; 1238 error "unable to save objects: $filename~: $!\n";
1215 } 1239 }
1216 } else { 1240 } else {
1217 aio_unlink $filename; 1241 aio_unlink $filename;
1218 aio_unlink "$filename.pst"; 1242 aio_unlink "$filename.pst";
1219 } 1243 }
1243 my $st = eval { Coro::Storable::thaw $av }; 1267 my $st = eval { Coro::Storable::thaw $av };
1244 $av = $st->{objs}; 1268 $av = $st->{objs};
1245 } 1269 }
1246 1270
1247 utf8::decode (my $decname = $filename); 1271 utf8::decode (my $decname = $filename);
1248 warn sprintf "loading %s (%d,%d)\n", 1272 trace sprintf "loading %s (%d,%d)\n",
1249 $decname, length $data, scalar @{$av || []}; 1273 $decname, length $data, scalar @{$av || []}
1274 if $VERBOSE_IO;
1250 1275
1251 ($data, $av) 1276 ($data, $av)
1252} 1277}
1253 1278
1254=head2 COMMAND CALLBACKS 1279=head2 COMMAND CALLBACKS
1346 1371
1347 $pl->ext_reply ($reply, @reply) 1372 $pl->ext_reply ($reply, @reply)
1348 if $reply; 1373 if $reply;
1349 1374
1350 } else { 1375 } else {
1351 warn "player " . ($pl->ob->name) . " sent unparseable ext message: <$buf>\n"; 1376 error "player " . ($pl->ob->name) . " sent unparseable ext message: <$buf>\n";
1352 } 1377 }
1353 1378
1354 cf::override; 1379 cf::override;
1355 }, 1380 },
1356); 1381);
1367 1392
1368 $grp 1393 $grp
1369} 1394}
1370 1395
1371sub load_extensions { 1396sub load_extensions {
1397 info "loading extensions...";
1398
1372 cf::sync_job { 1399 cf::sync_job {
1373 my %todo; 1400 my %todo;
1374 1401
1375 for my $path (<$LIBDIR/*.ext>) { 1402 for my $path (<$LIBDIR/*.ext>) {
1376 next unless -r $path; 1403 next unless -r $path;
1394 1421
1395 $ext{meta} = { map { (split /=/, $_, 2)[0, 1] } split /\s+/, $1 } 1422 $ext{meta} = { map { (split /=/, $_, 2)[0, 1] } split /\s+/, $1 }
1396 if $source =~ /\A#!.*?perl.*?#\s*(.*)$/m; 1423 if $source =~ /\A#!.*?perl.*?#\s*(.*)$/m;
1397 1424
1398 $ext{source} = 1425 $ext{source} =
1399 "package $pkg; use 5.10.0; use strict 'vars', 'subs'; use utf8;\n" 1426 "package $pkg; use common::sense;\n"
1400 . "#line 1 \"$path\"\n{\n" 1427 . "#line 1 \"$path\"\n{\n"
1401 . $source 1428 . $source
1402 . "\n};\n1"; 1429 . "\n};\n1";
1403 1430
1404 $todo{$base} = \%ext; 1431 $todo{$base} = \%ext;
1416 for (split /,\s*/, $v->{meta}{depends}) { 1443 for (split /,\s*/, $v->{meta}{depends}) {
1417 next ext 1444 next ext
1418 unless exists $done{$_}; 1445 unless exists $done{$_};
1419 } 1446 }
1420 1447
1421 warn "... pass $pass, loading '$k' into '$v->{pkg}'\n"; 1448 trace "... pass $pass, loading '$k' into '$v->{pkg}'\n";
1422 1449
1423 my $active = eval $v->{source}; 1450 my $active = eval $v->{source};
1424 1451
1425 if (length $@) { 1452 if (length $@) {
1426 warn "$v->{path}: $@\n"; 1453 error "$v->{path}: $@\n";
1454 undef $@; # work around perl 5.10.0 utf-8 caching bug
1427 1455
1428 cf::cleanup "mandatory extension '$k' failed to load, exiting." 1456 cf::cleanup "mandatory extension '$k' failed to load, exiting."
1429 if exists $v->{meta}{mandatory}; 1457 if exists $v->{meta}{mandatory};
1458
1459 warn "$v->{base}: optional extension cannot be loaded, skipping.\n";
1460 delete $todo{$k};
1430 } else { 1461 } else {
1431 $done{$k} = delete $todo{$k}; 1462 $done{$k} = delete $todo{$k};
1432 push @EXTS, $v->{pkg}; 1463 push @EXTS, $v->{pkg};
1433 $progress = 1; 1464 $progress = 1;
1434 1465
1435 warn "$v->{base}: extension inactive.\n" 1466 info "$v->{base}: extension inactive.\n"
1436 unless $active; 1467 unless $active;
1437 } 1468 }
1438 } 1469 }
1439 1470
1440 unless ($progress) { 1471 unless ($progress) {
1612 $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
1613 1644
1614 $pl->invoke (cf::EVENT_PLAYER_LOGOUT, 1) if $pl->active; 1645 $pl->invoke (cf::EVENT_PLAYER_LOGOUT, 1) if $pl->active;
1615 $pl->deactivate; 1646 $pl->deactivate;
1616 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;
1617 $pl->ob->check_score;
1618 $pl->invoke (cf::EVENT_PLAYER_QUIT); 1648 $pl->invoke (cf::EVENT_PLAYER_QUIT);
1619 $pl->ns->destroy if $pl->ns; 1649 $pl->ns->destroy if $pl->ns;
1620 1650
1621 my $path = playerdir $pl; 1651 my $path = playerdir $pl;
1622 my $temp = "$path~$cf::RUNTIME~deleting~"; 1652 my $temp = "$path~$cf::RUNTIME~deleting~";
1677 \@logins 1707 \@logins
1678} 1708}
1679 1709
1680=item $player->maps 1710=item $player->maps
1681 1711
1712=item cf::player::maps $login
1713
1682Returns an arrayref of map paths that are private for this 1714Returns an arrayref of map paths that are private for this
1683player. May block. 1715player. May block.
1684 1716
1685=cut 1717=cut
1686 1718
1747 1779
1748=cut 1780=cut
1749 1781
1750sub find_by_path($) { 1782sub find_by_path($) {
1751 my ($path) = @_; 1783 my ($path) = @_;
1784
1785 $path =~ s/^~[^\/]*//; # skip ~login
1752 1786
1753 my ($match, $specificity); 1787 my ($match, $specificity);
1754 1788
1755 for my $region (list) { 1789 for my $region (list) {
1756 if ($region->{match} && $path =~ $region->{match}) { 1790 if ($region->{match} && $path =~ $region->{match}) {
1813 1847
1814sub register { 1848sub register {
1815 my (undef, $regex, $prio) = @_; 1849 my (undef, $regex, $prio) = @_;
1816 my $pkg = caller; 1850 my $pkg = caller;
1817 1851
1818 no strict;
1819 push @{"$pkg\::ISA"}, __PACKAGE__; 1852 push @{"$pkg\::ISA"}, __PACKAGE__;
1820 1853
1821 $EXT_MAP{$pkg} = [$prio, qr<$regex>]; 1854 $EXT_MAP{$pkg} = [$prio, qr<$regex>];
1822} 1855}
1823 1856
1824# also paths starting with '/' 1857# also paths starting with '/'
1825$EXT_MAP{"cf::map"} = [0, qr{^(?=/)}]; 1858$EXT_MAP{"cf::map::wrap"} = [0, qr{^(?=/)}];
1826 1859
1827sub thawer_merge { 1860sub thawer_merge {
1828 my ($self, $merge) = @_; 1861 my ($self, $merge) = @_;
1829 1862
1830 # we have to keep some variables in memory intact 1863 # we have to keep some variables in memory intact
2140 or next; 2173 or next;
2141 $neigh = find $neigh, $map 2174 $neigh = find $neigh, $map
2142 or next; 2175 or next;
2143 $neigh->load; 2176 $neigh->load;
2144 2177
2178 # now find the diagonal neighbours
2145 push @neigh, 2179 push @neigh,
2146 [$neigh->tile_path (($_ + 3) % 4), $neigh], 2180 [$neigh->tile_path (($_ + 3) % 4), $neigh],
2147 [$neigh->tile_path (($_ + 1) % 4), $neigh]; 2181 [$neigh->tile_path (($_ + 1) % 4), $neigh];
2148 } 2182 }
2149 2183
2156} 2190}
2157 2191
2158sub find_sync { 2192sub find_sync {
2159 my ($path, $origin) = @_; 2193 my ($path, $origin) = @_;
2160 2194
2161 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
2162} 2199}
2163 2200
2164sub do_load_sync { 2201sub do_load_sync {
2165 my ($map) = @_; 2202 my ($map) = @_;
2166 2203
2167 cf::LOG cf::llevDebug | cf::logBacktrace, "do_load_sync" 2204 return cf::LOG cf::llevError | cf::logBacktrace, "do_load_sync"
2168 if $Coro::current == $Coro::main; 2205 if $Coro::current == $Coro::main;
2169 2206
2170 cf::sync_job { $map->load }; 2207 $map->load;
2171} 2208}
2172 2209
2173our %MAP_PREFETCH; 2210our %MAP_PREFETCH;
2174our $MAP_PREFETCHER = undef; 2211our $MAP_PREFETCHER = undef;
2175 2212
2201 $MAP_PREFETCHER->prio (6); 2238 $MAP_PREFETCHER->prio (6);
2202 2239
2203 () 2240 ()
2204} 2241}
2205 2242
2243# common code, used by both ->save and ->swapout
2206sub save { 2244sub _save {
2207 my ($self) = @_; 2245 my ($self) = @_;
2208
2209 my $lock = cf::lock_acquire "map_data:$self->{path}";
2210 2246
2211 $self->{last_save} = $cf::RUNTIME; 2247 $self->{last_save} = $cf::RUNTIME;
2212 2248
2213 return unless $self->dirty; 2249 return unless $self->dirty;
2214 2250
2234 } else { 2270 } else {
2235 $self->_save_objects ($save, cf::IO_HEADER | cf::IO_OBJECTS | cf::IO_UNIQUES); 2271 $self->_save_objects ($save, cf::IO_HEADER | cf::IO_OBJECTS | cf::IO_UNIQUES);
2236 } 2272 }
2237} 2273}
2238 2274
2275sub save {
2276 my ($self) = @_;
2277
2278 my $lock = cf::lock_acquire "map_data:$self->{path}";
2279
2280 $self->_save;
2281}
2282
2239sub swap_out { 2283sub swap_out {
2240 my ($self) = @_; 2284 my ($self) = @_;
2241 2285
2242 # save first because save cedes
2243 $self->save;
2244
2245 my $lock = cf::lock_acquire "map_data:$self->{path}"; 2286 my $lock = cf::lock_acquire "map_data:$self->{path}";
2246 2287
2247 return if $self->players;
2248 return if $self->in_memory != cf::MAP_ACTIVE; 2288 return if $self->in_memory != cf::MAP_ACTIVE;
2249 return if $self->{deny_save}; 2289 return if $self->{deny_save};
2290 return if $self->players;
2250 2291
2292 # first deactivate the map and "unlink" it from the core
2293 $self->deactivate;
2294 $_->clear_links_to ($self) for values %cf::MAP;
2251 $self->in_memory (cf::MAP_SWAPPED); 2295 $self->in_memory (cf::MAP_SWAPPED);
2296
2297 # then atomically save
2298 $self->_save;
2299
2300 # then free the map
2301 $self->clear;
2302}
2303
2304sub reset_at {
2305 my ($self) = @_;
2306
2307 # TODO: safety, remove and allow resettable per-player maps
2308 return 1e99 if $self->{deny_reset};
2309
2310 my $time = $self->fixed_resettime ? $self->{instantiate_time} : $self->last_access;
2311 my $to = List::Util::min $MAX_RESET, $self->reset_timeout || $DEFAULT_RESET;
2312
2313 $time + $to
2314}
2315
2316sub should_reset {
2317 my ($self) = @_;
2318
2319 $self->reset_at <= $cf::RUNTIME
2320}
2321
2322sub reset {
2323 my ($self) = @_;
2324
2325 my $lock = cf::lock_acquire "map_data:$self->{path}";
2326
2327 return if $self->players;
2328
2329 cf::trace "resetting map ", $self->path, "\n";
2330
2331 $self->in_memory (cf::MAP_SWAPPED);
2332
2333 # need to save uniques path
2334 unless ($self->{deny_save}) {
2335 my $uniq = $self->uniq_path; utf8::encode $uniq;
2336
2337 $self->_save_objects ($uniq, cf::IO_UNIQUES)
2338 if $uniq;
2339 }
2340
2341 delete $cf::MAP{$self->path};
2252 2342
2253 $self->deactivate; 2343 $self->deactivate;
2254 $_->clear_links_to ($self) for values %cf::MAP; 2344 $_->clear_links_to ($self) for values %cf::MAP;
2255 $self->clear; 2345 $self->clear;
2256}
2257
2258sub reset_at {
2259 my ($self) = @_;
2260
2261 # TODO: safety, remove and allow resettable per-player maps
2262 return 1e99 if $self->{deny_reset};
2263
2264 my $time = $self->fixed_resettime ? $self->{instantiate_time} : $self->last_access;
2265 my $to = List::Util::min $MAX_RESET, $self->reset_timeout || $DEFAULT_RESET;
2266
2267 $time + $to
2268}
2269
2270sub should_reset {
2271 my ($self) = @_;
2272
2273 $self->reset_at <= $cf::RUNTIME
2274}
2275
2276sub reset {
2277 my ($self) = @_;
2278
2279 my $lock = cf::lock_acquire "map_data:$self->{path}";
2280
2281 return if $self->players;
2282
2283 warn "resetting map ", $self->path, "\n";
2284
2285 $self->in_memory (cf::MAP_SWAPPED);
2286
2287 # need to save uniques path
2288 unless ($self->{deny_save}) {
2289 my $uniq = $self->uniq_path; utf8::encode $uniq;
2290
2291 $self->_save_objects ($uniq, cf::IO_UNIQUES)
2292 if $uniq;
2293 }
2294
2295 delete $cf::MAP{$self->path};
2296
2297 $self->deactivate;
2298 $_->clear_links_to ($self) for values %cf::MAP;
2299 $self->clear;
2300 2346
2301 $self->unlink_save; 2347 $self->unlink_save;
2302 $self->destroy; 2348 $self->destroy;
2303} 2349}
2304 2350
2312 2358
2313 delete $cf::MAP{$self->path}; 2359 delete $cf::MAP{$self->path};
2314 2360
2315 $self->unlink_save; 2361 $self->unlink_save;
2316 2362
2317 bless $self, "cf::map"; 2363 bless $self, "cf::map::wrap";
2318 delete $self->{deny_reset}; 2364 delete $self->{deny_reset};
2319 $self->{deny_save} = 1; 2365 $self->{deny_save} = 1;
2320 $self->reset_timeout (1); 2366 $self->reset_timeout (1);
2321 $self->path ($self->{path} = "{nuke}/" . ($nuke_counter++)); 2367 $self->path ($self->{path} = "{nuke}/" . ($nuke_counter++));
2322 2368
2552 2598
2553Freezes the player and moves him/her to a special map (C<{link}>). 2599Freezes the player and moves him/her to a special map (C<{link}>).
2554 2600
2555The player should be reasonably safe there for short amounts of time (e.g. 2601The player should be reasonably safe there for short amounts of time (e.g.
2556for loading a map). You I<MUST> call C<leave_link> as soon as possible, 2602for loading a map). You I<MUST> call C<leave_link> as soon as possible,
2557though, as the palyer cannot control the character while it is on the link 2603though, as the player cannot control the character while it is on the link
2558map. 2604map.
2559 2605
2560Will never block. 2606Will never block.
2561 2607
2562=item $player_object->leave_link ($map, $x, $y) 2608=item $player_object->leave_link ($map, $x, $y)
2583sub cf::object::player::enter_link { 2629sub cf::object::player::enter_link {
2584 my ($self) = @_; 2630 my ($self) = @_;
2585 2631
2586 $self->deactivate_recursive; 2632 $self->deactivate_recursive;
2587 2633
2634 ++$self->{_link_recursion};
2635
2588 return if UNIVERSAL::isa $self->map, "ext::map_link"; 2636 return if UNIVERSAL::isa $self->map, "ext::map_link";
2589 2637
2590 $self->{_link_pos} ||= [$self->map->{path}, $self->x, $self->y] 2638 $self->{_link_pos} ||= [$self->map->{path}, $self->x, $self->y]
2591 if $self->map && $self->map->{path} ne "{link}"; 2639 if $self->map && $self->map->{path} ne "{link}";
2592 2640
2593 $self->enter_map ($LINK_MAP || link_map, 10, 10); 2641 $self->enter_map ($LINK_MAP || link_map, 3, 3);
2594} 2642}
2595 2643
2596sub cf::object::player::leave_link { 2644sub cf::object::player::leave_link {
2597 my ($self, $map, $x, $y) = @_; 2645 my ($self, $map, $x, $y) = @_;
2598 2646
2623 $map->load_neighbours; 2671 $map->load_neighbours;
2624 2672
2625 return unless $self->contr->active; 2673 return unless $self->contr->active;
2626 2674
2627 local $self->{_prev_pos} = $link_pos; # ugly hack for rent.ext 2675 local $self->{_prev_pos} = $link_pos; # ugly hack for rent.ext
2628 $self->enter_map ($map, $x, $y); 2676 if ($self->enter_map ($map, $x, $y)) {
2629 2677 # entering was successful
2678 delete $self->{_link_recursion};
2630 # only activate afterwards, to support waiting in hooks 2679 # only activate afterwards, to support waiting in hooks
2631 $self->activate_recursive; 2680 $self->activate_recursive;
2632} 2681 }
2633 2682
2683}
2684
2634=item $player_object->goto ($path, $x, $y[, $check->($map)[, $done->()]]) 2685=item $player_object->goto ($path, $x, $y[, $check->($map, $x, $y, $player)[, $done->($player)]])
2635 2686
2636Moves the player to the given map-path and coordinates by first freezing 2687Moves the player to the given map-path and coordinates by first freezing
2637her, loading and preparing them map, calling the provided $check callback 2688her, loading and preparing them map, calling the provided $check callback
2638that has to return the map if sucecssful, and then unfreezes the player on 2689that has to return the map if sucecssful, and then unfreezes the player on
2639the new (success) or old (failed) map position. In either case, $done will 2690the new (success) or old (failed) map position. In either case, $done will
2646 2697
2647our $GOTOGEN; 2698our $GOTOGEN;
2648 2699
2649sub cf::object::player::goto { 2700sub cf::object::player::goto {
2650 my ($self, $path, $x, $y, $check, $done) = @_; 2701 my ($self, $path, $x, $y, $check, $done) = @_;
2702
2703 if ($self->{_link_recursion} >= $MAX_LINKS) {
2704 error "FATAL: link recursion exceeded, ", $self->name, " goto $path $x $y, redirecting.";
2705 $self->failmsg ("Something went wrong inside the server - please contact an administrator!");
2706 ($path, $x, $y) = @$EMERGENCY_POSITION;
2707 }
2651 2708
2652 # 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
2653 my $gen = $self->{_goto_generation} = ++$GOTOGEN; 2710 my $gen = $self->{_goto_generation} = ++$GOTOGEN;
2654 2711
2655 $self->enter_link; 2712 $self->enter_link;
2679 my $map = eval { 2736 my $map = eval {
2680 my $map = defined $path ? cf::map::find $path : undef; 2737 my $map = defined $path ? cf::map::find $path : undef;
2681 2738
2682 if ($map) { 2739 if ($map) {
2683 $map = $map->customise_for ($self); 2740 $map = $map->customise_for ($self);
2684 $map = $check->($map) if $check && $map; 2741 $map = $check->($map, $x, $y, $self) if $check && $map;
2685 } else { 2742 } else {
2686 $self->message ("The exit to '$path' is closed.", cf::NDI_UNIQUE | cf::NDI_RED); 2743 $self->message ("The exit to '$path' is closed.", cf::NDI_UNIQUE | cf::NDI_RED);
2687 } 2744 }
2688 2745
2689 $map 2746 $map
2697 if ($gen == $self->{_goto_generation}) { 2754 if ($gen == $self->{_goto_generation}) {
2698 delete $self->{_goto_generation}; 2755 delete $self->{_goto_generation};
2699 $self->leave_link ($map, $x, $y); 2756 $self->leave_link ($map, $x, $y);
2700 } 2757 }
2701 2758
2702 $done->() if $done; 2759 $done->($self) if $done;
2703 })->prio (1); 2760 })->prio (1);
2704} 2761}
2705 2762
2706=item $player_object->enter_exit ($exit_object) 2763=item $player_object->enter_exit ($exit_object)
2707 2764
2800 $self->message ("Something went wrong deep within the deliantra server. " 2857 $self->message ("Something went wrong deep within the deliantra server. "
2801 . "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. "
2802 . "Please report this to the dungeon master!", 2859 . "Please report this to the dungeon master!",
2803 cf::NDI_UNIQUE | cf::NDI_RED); 2860 cf::NDI_UNIQUE | cf::NDI_RED);
2804 2861
2805 warn "ERROR in enter_exit: $@"; 2862 error "ERROR in enter_exit: $@";
2806 $self->leave_link; 2863 $self->leave_link;
2807 } 2864 }
2808 })->prio (1); 2865 })->prio (1);
2809} 2866}
2810 2867
3123 3180
3124 $ns->ext_reply ($reply, @reply) 3181 $ns->ext_reply ($reply, @reply)
3125 if $reply; 3182 if $reply;
3126 3183
3127 } else { 3184 } else {
3128 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";
3129 } 3186 }
3130 3187
3131 cf::override; 3188 cf::override;
3132 }, 3189 },
3133); 3190);
3214 decrease split destroy change_exp value msg lore send_msg)], 3271 decrease split destroy change_exp value msg lore send_msg)],
3215 ["cf::object::player" => qw(player)], 3272 ["cf::object::player" => qw(player)],
3216 ["cf::player" => qw(peaceful send_msg)], 3273 ["cf::player" => qw(peaceful send_msg)],
3217 ["cf::map" => qw(trigger)], 3274 ["cf::map" => qw(trigger)],
3218) { 3275) {
3219 no strict 'refs';
3220 my ($pkg, @funs) = @$_; 3276 my ($pkg, @funs) = @$_;
3221 *{"safe::$pkg\::$_"} = $safe_hole->wrap (\&{"$pkg\::$_"}) 3277 *{"safe::$pkg\::$_"} = $safe_hole->wrap (\&{"$pkg\::$_"})
3222 for @funs; 3278 for @funs;
3223} 3279}
3224 3280
3263 local @cf::_safe_eval_args = values %vars; 3319 local @cf::_safe_eval_args = values %vars;
3264 @res = wantarray ? eval eval : scalar eval $eval; 3320 @res = wantarray ? eval eval : scalar eval $eval;
3265 } 3321 }
3266 3322
3267 if ($@) { 3323 if ($@) {
3268 warn "$@"; 3324 warn "$@",
3269 warn "while executing safe code '$code'\n"; 3325 "while executing safe code '$code'\n",
3270 warn "with arguments " . (join " ", %vars) . "\n"; 3326 "with arguments " . (join " ", %vars) . "\n";
3271 } 3327 }
3272 3328
3273 wantarray ? @res : $res[0] 3329 wantarray ? @res : $res[0]
3274} 3330}
3275 3331
3309 # for this (global event?) 3365 # for this (global event?)
3310 %ext::player_env::MUSIC_FACE_CACHE = (); 3366 %ext::player_env::MUSIC_FACE_CACHE = ();
3311 3367
3312 my $enc = JSON::XS->new->utf8->canonical->relaxed; 3368 my $enc = JSON::XS->new->utf8->canonical->relaxed;
3313 3369
3314 warn "loading facedata from $path\n"; 3370 trace "loading facedata from $path\n";
3315 3371
3316 my $facedata; 3372 my $facedata;
3317 0 < aio_load $path, $facedata 3373 0 < aio_load $path, $facedata
3318 or die "$path: $!"; 3374 or die "$path: $!";
3319 3375
3353 3409
3354 if (my $smooth = cf::face::find $info->{smooth}) { 3410 if (my $smooth = cf::face::find $info->{smooth}) {
3355 cf::face::set_smooth $idx, $smooth; 3411 cf::face::set_smooth $idx, $smooth;
3356 cf::face::set_smoothlevel $idx, $info->{smoothlevel}; 3412 cf::face::set_smoothlevel $idx, $info->{smoothlevel};
3357 } else { 3413 } else {
3358 warn "smooth face '$info->{smooth}' not found for face '$face'"; 3414 error "smooth face '$info->{smooth}' not found for face '$face'";
3359 } 3415 }
3360 3416
3361 cf::cede_to_tick; 3417 cf::cede_to_tick;
3362 } 3418 }
3363 } 3419 }
3381 my $idx = (cf::face::find $name) || cf::face::alloc $name; 3437 my $idx = (cf::face::find $name) || cf::face::alloc $name;
3382 3438
3383 cf::face::set_data $idx, 0, $info->{data}, $info->{hash}; 3439 cf::face::set_data $idx, 0, $info->{data}, $info->{hash};
3384 cf::face::set_type $idx, $info->{type}; 3440 cf::face::set_type $idx, $info->{type};
3385 } else { 3441 } else {
3386 $RESOURCE{$name} = $info; 3442 $RESOURCE{$name} = $info; # unused
3387 } 3443 }
3388 3444
3389 cf::cede_to_tick; 3445 cf::cede_to_tick;
3390 } 3446 }
3391 } 3447 }
3392 3448
3393 cf::global->invoke (EVENT_GLOBAL_RESOURCE_UPDATE); 3449 cf::global->invoke (EVENT_GLOBAL_RESOURCE_UPDATE);
3394 3450
3395 1 3451 1
3396} 3452}
3397
3398cf::global->attach (on_resource_update => sub {
3399 if (my $soundconf = $RESOURCE{"res/sound.conf"}) {
3400 $soundconf = JSON::XS->new->utf8->relaxed->decode ($soundconf->{data});
3401
3402 for (0 .. SOUND_CAST_SPELL_0 - 1) {
3403 my $sound = $soundconf->{compat}[$_]
3404 or next;
3405
3406 my $face = cf::face::find "sound/$sound->[1]";
3407 cf::sound::set $sound->[0] => $face;
3408 cf::sound::old_sound_index $_, $face; # gcfclient-compat
3409 }
3410
3411 while (my ($k, $v) = each %{$soundconf->{event}}) {
3412 my $face = cf::face::find "sound/$v";
3413 cf::sound::set $k => $face;
3414 }
3415 }
3416});
3417 3453
3418register_exticmd fx_want => sub { 3454register_exticmd fx_want => sub {
3419 my ($ns, $want) = @_; 3455 my ($ns, $want) = @_;
3420 3456
3421 while (my ($k, $v) = each %$want) { 3457 while (my ($k, $v) = each %$want) {
3460sub reload_treasures { 3496sub reload_treasures {
3461 load_resource_file "$DATADIR/treasures" 3497 load_resource_file "$DATADIR/treasures"
3462 or die "unable to load treasurelists\n"; 3498 or die "unable to load treasurelists\n";
3463} 3499}
3464 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
3465sub reload_resources { 3524sub reload_resources {
3466 warn "reloading resource files...\n"; 3525 trace "reloading resource files...\n";
3467 3526
3468 reload_facedata; 3527 reload_facedata;
3528 reload_sound;
3469 reload_archetypes; 3529 reload_archetypes;
3470 reload_regions; 3530 reload_regions;
3471 reload_treasures; 3531 reload_treasures;
3472 3532
3473 warn "finished reloading resource files\n"; 3533 trace "finished reloading resource files\n";
3474} 3534}
3475 3535
3476sub reload_config { 3536sub reload_config {
3477 warn "reloading config file...\n"; 3537 trace "reloading config file...\n";
3478 3538
3479 open my $fh, "<:utf8", "$CONFDIR/config" 3539 open my $fh, "<:utf8", "$CONFDIR/config"
3480 or return; 3540 or return;
3481 3541
3482 local $/; 3542 local $/;
3483 *CFG = YAML::XS::Load scalar <$fh>; 3543 *CFG = YAML::XS::Load scalar <$fh>;
3484 3544
3485 $EMERGENCY_POSITION = $CFG{emergency_position} || ["/world/world_105_115", 5, 37]; 3545 $EMERGENCY_POSITION = $CFG{emergency_position} || ["/world/world_104_115", 49, 38];
3486 3546
3487 $cf::map::MAX_RESET = $CFG{map_max_reset} if exists $CFG{map_max_reset}; 3547 $cf::map::MAX_RESET = $CFG{map_max_reset} if exists $CFG{map_max_reset};
3488 $cf::map::DEFAULT_RESET = $CFG{map_default_reset} if exists $CFG{map_default_reset}; 3548 $cf::map::DEFAULT_RESET = $CFG{map_default_reset} if exists $CFG{map_default_reset};
3489 3549
3490 if (exists $CFG{mlockall}) { 3550 if (exists $CFG{mlockall}) {
3493 and die "WARNING: m(un)lockall failed: $!\n"; 3553 and die "WARNING: m(un)lockall failed: $!\n";
3494 }; 3554 };
3495 warn $@ if $@; 3555 warn $@ if $@;
3496 } 3556 }
3497 3557
3498 warn "finished reloading resource files\n"; 3558 trace "finished reloading resource files\n";
3499} 3559}
3500 3560
3501sub pidfile() { 3561sub pidfile() {
3502 sysopen my $fh, $PIDFILE, O_RDWR | O_CREAT 3562 sysopen my $fh, $PIDFILE, O_RDWR | O_CREAT
3503 or die "$PIDFILE: $!"; 3563 or die "$PIDFILE: $!";
3516 seek $fh, 0, 0; 3576 seek $fh, 0, 0;
3517 print $fh $$; 3577 print $fh $$;
3518} 3578}
3519 3579
3520sub main_loop { 3580sub main_loop {
3521 warn "EV::loop starting\n"; 3581 trace "EV::loop starting\n";
3522 if (1) { 3582 if (1) {
3523 EV::loop; 3583 EV::loop;
3524 } 3584 }
3525 warn "EV::loop returned\n"; 3585 trace "EV::loop returned\n";
3526 goto &main_loop unless $REALLY_UNLOOP; 3586 goto &main_loop unless $REALLY_UNLOOP;
3527} 3587}
3528 3588
3529sub main { 3589sub main {
3530 cf::init_globals; # initialise logging 3590 cf::init_globals; # initialise logging
3531 3591
3532 LOG llevInfo, "Welcome to Deliantra, v" . VERSION; 3592 LOG llevInfo, "Welcome to Deliantra, v" . VERSION;
3533 LOG llevInfo, "Copyright (C) 2005-2008 Marc Alexander Lehmann / Robin Redeker / the Deliantra team."; 3593 LOG llevInfo, "Copyright (C) 2005-2008 Marc Alexander Lehmann / Robin Redeker / the Deliantra team.";
3534 LOG llevInfo, "Copyright (C) 1994 Mark Wedel."; 3594 LOG llevInfo, "Copyright (C) 1994 Mark Wedel.";
3535 LOG llevInfo, "Copyright (C) 1992 Frank Tore Johansen."; 3595 LOG llevInfo, "Copyright (C) 1992 Frank Tore Johansen.";
3536
3537 cf::init_experience;
3538 cf::init_anim;
3539 cf::init_attackmess;
3540 cf::init_dynamic;
3541 3596
3542 $Coro::current->prio (Coro::PRIO_MAX); # give the main loop max. priority 3597 $Coro::current->prio (Coro::PRIO_MAX); # give the main loop max. priority
3543 3598
3544 # we must not ever block the main coroutine 3599 # we must not ever block the main coroutine
3545 local $Coro::idle = sub { 3600 local $Coro::idle = sub {
3551 }; 3606 };
3552 3607
3553 evthread_start IO::AIO::poll_fileno; 3608 evthread_start IO::AIO::poll_fileno;
3554 3609
3555 cf::sync_job { 3610 cf::sync_job {
3611 cf::init_experience;
3612 cf::init_anim;
3613 cf::init_attackmess;
3614 cf::init_dynamic;
3615
3556 cf::load_settings; 3616 cf::load_settings;
3557 cf::load_materials; 3617 cf::load_materials;
3558 3618
3559 reload_resources; 3619 reload_resources;
3560 reload_config; 3620 reload_config;
3576 use POSIX (); 3636 use POSIX ();
3577 POSIX::close delete $ENV{LOCKUTIL_LOCK_FD} if exists $ENV{LOCKUTIL_LOCK_FD}; 3637 POSIX::close delete $ENV{LOCKUTIL_LOCK_FD} if exists $ENV{LOCKUTIL_LOCK_FD};
3578 3638
3579 (pop @POST_INIT)->(0) while @POST_INIT; 3639 (pop @POST_INIT)->(0) while @POST_INIT;
3580 }; 3640 };
3641
3642 cf::object::thawer::errors_are_fatal 0;
3643 info "parse errors in files are no longer fatal from this point on.\n";
3581 3644
3582 main_loop; 3645 main_loop;
3583} 3646}
3584 3647
3585############################################################################# 3648#############################################################################
3626 or return; 3689 or return;
3627 3690
3628 aio_rename "$RUNTIMEFILE~", $RUNTIMEFILE 3691 aio_rename "$RUNTIMEFILE~", $RUNTIMEFILE
3629 and return; 3692 and return;
3630 3693
3631 warn sprintf "runtime file written (%gs).\n", AE::time - $t0; 3694 trace sprintf "runtime file written (%gs).\n", AE::time - $t0;
3632 3695
3633 1 3696 1
3634} 3697}
3635 3698
3636our $uuid_lock; 3699our $uuid_lock;
3648 or return; 3711 or return;
3649 3712
3650 my $value = uuid_seq uuid_cur; 3713 my $value = uuid_seq uuid_cur;
3651 3714
3652 unless ($value) { 3715 unless ($value) {
3653 warn "cowardly refusing to write zero uuid value!\n"; 3716 info "cowardly refusing to write zero uuid value!\n";
3654 return; 3717 return;
3655 } 3718 }
3656 3719
3657 my $value = uuid_str $value + $uuid_skip; 3720 my $value = uuid_str $value + $uuid_skip;
3658 $uuid_skip = 0; 3721 $uuid_skip = 0;
3668 or return; 3731 or return;
3669 3732
3670 aio_rename "$uuid~", $uuid 3733 aio_rename "$uuid~", $uuid
3671 and return; 3734 and return;
3672 3735
3673 warn "uuid file written ($value).\n"; 3736 trace "uuid file written ($value).\n";
3674 3737
3675 1 3738 1
3676 3739
3677} 3740}
3678 3741
3684} 3747}
3685 3748
3686sub emergency_save() { 3749sub emergency_save() {
3687 my $freeze_guard = cf::freeze_mainloop; 3750 my $freeze_guard = cf::freeze_mainloop;
3688 3751
3689 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;
3690 3758
3691 cf::sync_job { 3759 cf::sync_job {
3692 # this is a trade-off: we want to be very quick here, so 3760 cf::write_runtime_sync; # external watchdog should not bark
3693 # save all maps without fsync, and later call a global sync
3694 # (which in turn might be very very slow)
3695 local $USE_FSYNC = 0;
3696 3761
3697 # use a peculiar iteration method to avoid tripping on perl 3762 # use a peculiar iteration method to avoid tripping on perl
3698 # refcount bugs in for. also avoids problems with players 3763 # refcount bugs in for. also avoids problems with players
3699 # and maps saved/destroyed asynchronously. 3764 # and maps saved/destroyed asynchronously.
3700 warn "emergency_perl_save: begin player save\n"; 3765 info "emergency_perl_save: begin player save\n";
3701 for my $login (keys %cf::PLAYER) { 3766 for my $login (keys %cf::PLAYER) {
3702 my $pl = $cf::PLAYER{$login} or next; 3767 my $pl = $cf::PLAYER{$login} or next;
3703 $pl->valid or next; 3768 $pl->valid or next;
3704 delete $pl->{unclean_save}; # not strictly necessary, but cannot hurt 3769 delete $pl->{unclean_save}; # not strictly necessary, but cannot hurt
3705 $pl->save; 3770 $pl->save;
3706 } 3771 }
3707 warn "emergency_perl_save: end player save\n"; 3772 info "emergency_perl_save: end player save\n";
3708 3773
3774 cf::write_runtime_sync; # external watchdog should not bark
3775
3709 warn "emergency_perl_save: begin map save\n"; 3776 info "emergency_perl_save: begin map save\n";
3710 for my $path (keys %cf::MAP) { 3777 for my $path (keys %cf::MAP) {
3711 my $map = $cf::MAP{$path} or next; 3778 my $map = $cf::MAP{$path} or next;
3712 $map->valid or next; 3779 $map->valid or next;
3713 $map->save; 3780 $map->save;
3714 } 3781 }
3715 warn "emergency_perl_save: end map save\n"; 3782 info "emergency_perl_save: end map save\n";
3716 3783
3784 cf::write_runtime_sync; # external watchdog should not bark
3785
3717 warn "emergency_perl_save: begin database checkpoint\n"; 3786 info "emergency_perl_save: begin database checkpoint\n";
3718 BDB::db_env_txn_checkpoint $DB_ENV; 3787 BDB::db_env_txn_checkpoint $DB_ENV;
3719 warn "emergency_perl_save: end database checkpoint\n"; 3788 info "emergency_perl_save: end database checkpoint\n";
3720 3789
3721 warn "emergency_perl_save: begin write uuid\n"; 3790 info "emergency_perl_save: begin write uuid\n";
3722 write_uuid_sync 1; 3791 write_uuid_sync 1;
3723 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
3724 }; 3812 };
3725 3813
3726 warn "emergency_perl_save: starting sync()\n";
3727 IO::AIO::aio_sync sub {
3728 warn "emergency_perl_save: finished sync()\n";
3729 };
3730
3731 warn "emergency_perl_save: leave\n"; 3814 info "emergency_perl_save: leave\n";
3732} 3815}
3733 3816
3734sub post_cleanup { 3817sub post_cleanup {
3735 my ($make_core) = @_; 3818 my ($make_core) = @_;
3736 3819
3820 IO::AIO::flush;
3821
3737 warn Carp::longmess "post_cleanup backtrace" 3822 error Carp::longmess "post_cleanup backtrace"
3738 if $make_core; 3823 if $make_core;
3739 3824
3740 my $fh = pidfile; 3825 my $fh = pidfile;
3741 unlink $PIDFILE if <$fh> == $$; 3826 unlink $PIDFILE if <$fh> == $$;
3742} 3827}
3762 my $leaf_symtab = *{$stem_symtab->{$leaf}}{HASH}; 3847 my $leaf_symtab = *{$stem_symtab->{$leaf}}{HASH};
3763 for my $name (keys %$leaf_symtab) { 3848 for my $name (keys %$leaf_symtab) {
3764 _gv_clear *{"$pkg$name"}; 3849 _gv_clear *{"$pkg$name"};
3765# use PApp::Util; PApp::Util::sv_dump *{"$pkg$name"}; 3850# use PApp::Util; PApp::Util::sv_dump *{"$pkg$name"};
3766 } 3851 }
3767 warn "cleared package $pkg\n";#d#
3768} 3852}
3769 3853
3770sub do_reload_perl() { 3854sub do_reload_perl() {
3771 # can/must only be called in main 3855 # can/must only be called in main
3772 if ($Coro::current != $Coro::main) { 3856 if (in_main) {
3773 warn "can only reload from main coroutine"; 3857 error "can only reload from main coroutine";
3774 return; 3858 return;
3775 } 3859 }
3776 3860
3777 return if $RELOAD++; 3861 return if $RELOAD++;
3778 3862
3779 my $t1 = AE::time; 3863 my $t1 = AE::time;
3780 3864
3781 while ($RELOAD) { 3865 while ($RELOAD) {
3782 warn "reloading..."; 3866 info "reloading...";
3783 3867
3784 warn "entering sync_job"; 3868 trace "entering sync_job";
3785 3869
3786 cf::sync_job { 3870 cf::sync_job {
3787 cf::write_runtime_sync; # external watchdog should not bark
3788 cf::emergency_save; 3871 cf::emergency_save;
3789 cf::write_runtime_sync; # external watchdog should not bark
3790 3872
3791 warn "syncing database to disk";
3792 BDB::db_env_txn_checkpoint $DB_ENV;
3793
3794 # if anything goes wrong in here, we should simply crash as we already saved
3795
3796 warn "flushing outstanding aio requests";
3797 while (IO::AIO::nreqs || BDB::nreqs) {
3798 Coro::EV::timer_once 0.01; # let the sync_job do it's thing
3799 }
3800
3801 warn "cancelling all extension coros"; 3873 trace "cancelling all extension coros";
3802 $_->cancel for values %EXT_CORO; 3874 $_->cancel for values %EXT_CORO;
3803 %EXT_CORO = (); 3875 %EXT_CORO = ();
3804 3876
3805 warn "removing commands"; 3877 trace "removing commands";
3806 %COMMAND = (); 3878 %COMMAND = ();
3807 3879
3808 warn "removing ext/exti commands"; 3880 trace "removing ext/exti commands";
3809 %EXTCMD = (); 3881 %EXTCMD = ();
3810 %EXTICMD = (); 3882 %EXTICMD = ();
3811 3883
3812 warn "unloading/nuking all extensions"; 3884 trace "unloading/nuking all extensions";
3813 for my $pkg (@EXTS) { 3885 for my $pkg (@EXTS) {
3814 warn "... unloading $pkg"; 3886 trace "... unloading $pkg";
3815 3887
3816 if (my $cb = $pkg->can ("unload")) { 3888 if (my $cb = $pkg->can ("unload")) {
3817 eval { 3889 eval {
3818 $cb->($pkg); 3890 $cb->($pkg);
3819 1 3891 1
3820 } or warn "$pkg unloaded, but with errors: $@"; 3892 } or error "$pkg unloaded, but with errors: $@";
3821 } 3893 }
3822 3894
3823 warn "... clearing $pkg"; 3895 trace "... clearing $pkg";
3824 clear_package $pkg; 3896 clear_package $pkg;
3825 } 3897 }
3826 3898
3827 warn "unloading all perl modules loaded from $LIBDIR"; 3899 trace "unloading all perl modules loaded from $LIBDIR";
3828 while (my ($k, $v) = each %INC) { 3900 while (my ($k, $v) = each %INC) {
3829 next unless $v =~ /^\Q$LIBDIR\E\/.*\.pm$/; 3901 next unless $v =~ /^\Q$LIBDIR\E\/.*\.pm$/;
3830 3902
3831 warn "... unloading $k"; 3903 trace "... unloading $k";
3832 delete $INC{$k}; 3904 delete $INC{$k};
3833 3905
3834 $k =~ s/\.pm$//; 3906 $k =~ s/\.pm$//;
3835 $k =~ s/\//::/g; 3907 $k =~ s/\//::/g;
3836 3908
3839 } 3911 }
3840 3912
3841 clear_package $k; 3913 clear_package $k;
3842 } 3914 }
3843 3915
3844 warn "getting rid of safe::, as good as possible"; 3916 trace "getting rid of safe::, as good as possible";
3845 clear_package "safe::$_" 3917 clear_package "safe::$_"
3846 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);
3847 3919
3848 warn "unloading cf.pm \"a bit\""; 3920 trace "unloading cf.pm \"a bit\"";
3849 delete $INC{"cf.pm"}; 3921 delete $INC{"cf.pm"};
3850 delete $INC{"cf/$_.pm"} for @EXTRA_MODULES; 3922 delete $INC{"cf/$_.pm"} for @EXTRA_MODULES;
3851 3923
3852 # don't, removes xs symbols, too, 3924 # don't, removes xs symbols, too,
3853 # and global variables created in xs 3925 # and global variables created in xs
3854 #clear_package __PACKAGE__; 3926 #clear_package __PACKAGE__;
3855 3927
3856 warn "unload completed, starting to reload now"; 3928 info "unload completed, starting to reload now";
3857 3929
3858 warn "reloading cf.pm"; 3930 trace "reloading cf.pm";
3859 require cf; 3931 require cf;
3860 cf::_connect_to_perl_1; 3932 cf::_connect_to_perl_1;
3861 3933
3862 warn "loading config and database again"; 3934 trace "loading config and database again";
3863 cf::reload_config; 3935 cf::reload_config;
3864 3936
3865 warn "loading extensions"; 3937 trace "loading extensions";
3866 cf::load_extensions; 3938 cf::load_extensions;
3867 3939
3868 if ($REATTACH_ON_RELOAD) { 3940 if ($REATTACH_ON_RELOAD) {
3869 warn "reattaching attachments to objects/players"; 3941 trace "reattaching attachments to objects/players";
3870 _global_reattach; # objects, sockets 3942 _global_reattach; # objects, sockets
3871 warn "reattaching attachments to maps"; 3943 trace "reattaching attachments to maps";
3872 reattach $_ for values %MAP; 3944 reattach $_ for values %MAP;
3873 warn "reattaching attachments to players"; 3945 trace "reattaching attachments to players";
3874 reattach $_ for values %PLAYER; 3946 reattach $_ for values %PLAYER;
3875 } 3947 }
3876 3948
3877 warn "running post_init jobs"; 3949 trace "running post_init jobs";
3878 (pop @POST_INIT)->(1) while @POST_INIT; 3950 (pop @POST_INIT)->(1) while @POST_INIT;
3879 3951
3880 warn "leaving sync_job"; 3952 trace "leaving sync_job";
3881 3953
3882 1 3954 1
3883 } or do { 3955 } or do {
3884 warn $@; 3956 error $@;
3885 cf::cleanup "error while reloading, exiting."; 3957 cf::cleanup "error while reloading, exiting.";
3886 }; 3958 };
3887 3959
3888 warn "reloaded"; 3960 info "reloaded";
3889 --$RELOAD; 3961 --$RELOAD;
3890 } 3962 }
3891 3963
3892 $t1 = AE::time - $t1; 3964 $t1 = AE::time - $t1;
3893 warn "reload completed in ${t1}s\n"; 3965 info "reload completed in ${t1}s\n";
3894}; 3966};
3895 3967
3896our $RELOAD_WATCHER; # used only during reload 3968our $RELOAD_WATCHER; # used only during reload
3897 3969
3898sub reload_perl() { 3970sub reload_perl() {
3958 if ($NOW >= $NEXT_RUNTIME_WRITE) { 4030 if ($NOW >= $NEXT_RUNTIME_WRITE) {
3959 $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.;
3960 Coro::async_pool { 4032 Coro::async_pool {
3961 $Coro::current->{desc} = "runtime saver"; 4033 $Coro::current->{desc} = "runtime saver";
3962 write_runtime_sync 4034 write_runtime_sync
3963 or warn "ERROR: unable to write runtime file: $!"; 4035 or error "ERROR: unable to write runtime file: $!";
3964 }; 4036 };
3965 } 4037 }
3966 4038
3967 if (my $sig = shift @WAIT_FOR_TICK_BEGIN) { 4039 if (my $sig = shift @WAIT_FOR_TICK_BEGIN) {
3968 $sig->send; 4040 $sig->send;
3976 4048
3977 if (0) { 4049 if (0) {
3978 if ($NEXT_TICK) { 4050 if ($NEXT_TICK) {
3979 my $jitter = $TICK_START - $NEXT_TICK; 4051 my $jitter = $TICK_START - $NEXT_TICK;
3980 $JITTER = $JITTER * 0.75 + $jitter * 0.25; 4052 $JITTER = $JITTER * 0.75 + $jitter * 0.25;
3981 warn "jitter $JITTER\n";#d# 4053 debug "jitter $JITTER\n";#d#
3982 } 4054 }
3983 } 4055 }
3984} 4056}
3985 4057
3986{ 4058{

Diff Legend

Removed lines
+ Added lines
< Changed lines
> Changed lines