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.514 by root, Mon Apr 12 17:13:36 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
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) {
644within each server. 655within each server.
645 656
646=cut 657=cut
647 658
648sub db_table($) { 659sub db_table($) {
660 cf::error "db_get called from main context"
661 if $Coro::current == $Coro::main;
662
649 my ($name) = @_; 663 my ($name) = @_;
650 my $db = BDB::db_create $DB_ENV; 664 my $db = BDB::db_create $DB_ENV;
651 665
652 eval { 666 eval {
653 $db->set_flags (BDB::CHKSUM); 667 $db->set_flags (BDB::CHKSUM);
663} 677}
664 678
665our $DB; 679our $DB;
666 680
667sub db_init { 681sub db_init {
668 cf::sync_job {
669 $DB ||= db_table "db"; 682 $DB ||= db_table "db";
670 };
671} 683}
672 684
673sub db_get($$) { 685sub db_get($$) {
674 my $key = "$_[0]/$_[1]"; 686 my $key = "$_[0]/$_[1]";
675 687
676 cf::sync_job { 688 cf::error "db_get called from main context"
689 if $Coro::current == $Coro::main;
690
677 BDB::db_get $DB, undef, $key, my $data; 691 BDB::db_get $DB, undef, $key, my $data;
678 692
679 $! ? () 693 $! ? ()
680 : $data 694 : $data
681 }
682} 695}
683 696
684sub db_put($$$) { 697sub db_put($$$) {
685 BDB::dbreq_pri 4; 698 BDB::dbreq_pri 4;
686 BDB::db_put $DB, undef, "$_[0]/$_[1]", $_[2], 0, sub { }; 699 BDB::db_put $DB, undef, "$_[0]/$_[1]", $_[2], 0, sub { };
742 755
743 my $t1 = Time::HiRes::time; 756 my $t1 = Time::HiRes::time;
744 my $data = $process->(\@data); 757 my $data = $process->(\@data);
745 my $t2 = Time::HiRes::time; 758 my $t2 = Time::HiRes::time;
746 759
747 warn "cache: '$id' processed in ", $t2 - $t1, "s\n"; 760 info "cache: '$id' processed in ", $t2 - $t1, "s\n";
748 761
749 db_put cache => "$id/data", $data; 762 db_put cache => "$id/data", $data;
750 db_put cache => "$id/md5" , $md5; 763 db_put cache => "$id/md5" , $md5;
751 db_put cache => "$id/meta", $meta; 764 db_put cache => "$id/meta", $meta;
752 765
762 775
763=cut 776=cut
764 777
765sub datalog($@) { 778sub datalog($@) {
766 my ($type, %kv) = @_; 779 my ($type, %kv) = @_;
767 warn "DATALOG ", JSON::XS->new->ascii->encode ({ %kv, type => $type }); 780 info "DATALOG ", JSON::XS->new->ascii->encode ({ %kv, type => $type });
768} 781}
769 782
770=back 783=back
771 784
772=cut 785=cut
967 980
968 } elsif (exists $cb_id{$type}) { 981 } elsif (exists $cb_id{$type}) {
969 _attach_cb $registry, $cb_id{$type}, $prio, shift @arg; 982 _attach_cb $registry, $cb_id{$type}, $prio, shift @arg;
970 983
971 } elsif (ref $type) { 984 } elsif (ref $type) {
972 warn "attaching objects not supported, ignoring.\n"; 985 error "attaching objects not supported, ignoring.\n";
973 986
974 } else { 987 } else {
975 shift @arg; 988 shift @arg;
976 warn "attach argument '$type' not supported, ignoring.\n"; 989 error "attach argument '$type' not supported, ignoring.\n";
977 } 990 }
978 } 991 }
979} 992}
980 993
981sub _object_attach { 994sub _object_attach {
991 _attach $registry, $klass, @attach; 1004 _attach $registry, $klass, @attach;
992 } 1005 }
993 1006
994 $obj->{$name} = \%arg; 1007 $obj->{$name} = \%arg;
995 } else { 1008 } else {
996 warn "object uses attachment '$name' which is not available, postponing.\n"; 1009 info "object uses attachment '$name' which is not available, postponing.\n";
997 } 1010 }
998 1011
999 $obj->{_attachment}{$name} = undef; 1012 $obj->{_attachment}{$name} = undef;
1000} 1013}
1001 1014
1060 1073
1061 for (@$callbacks) { 1074 for (@$callbacks) {
1062 eval { &{$_->[1]} }; 1075 eval { &{$_->[1]} };
1063 1076
1064 if ($@) { 1077 if ($@) {
1065 warn "$@";
1066 warn "... while processing $EVENT[$event][0](@_) event, skipping processing altogether.\n"; 1078 error "$@", "... while processing $EVENT[$event][0](@_) event, skipping processing altogether.\n";
1067 override; 1079 override;
1068 } 1080 }
1069 1081
1070 return 1 if $override; 1082 return 1 if $override;
1071 } 1083 }
1150 for (@$attach) { 1162 for (@$attach) {
1151 my ($klass, @attach) = @$_; 1163 my ($klass, @attach) = @$_;
1152 _attach $registry, $klass, @attach; 1164 _attach $registry, $klass, @attach;
1153 } 1165 }
1154 } else { 1166 } else {
1155 warn "object uses attachment '$name' that is not available, postponing.\n"; 1167 info "object uses attachment '$name' that is not available, postponing.\n";
1156 } 1168 }
1157 } 1169 }
1158} 1170}
1159 1171
1160cf::attachable->attach ( 1172cf::attachable->attach (
1187 my ($filename, $rdata, $objs) = @_; 1199 my ($filename, $rdata, $objs) = @_;
1188 1200
1189 sync_job { 1201 sync_job {
1190 if (length $$rdata) { 1202 if (length $$rdata) {
1191 utf8::decode (my $decname = $filename); 1203 utf8::decode (my $decname = $filename);
1192 warn sprintf "saving %s (%d,%d)\n", 1204 trace sprintf "saving %s (%d,%d)\n",
1193 $decname, length $$rdata, scalar @$objs; 1205 $decname, length $$rdata, scalar @$objs
1206 if $VERBOSE_IO;
1194 1207
1195 if (my $fh = aio_open "$filename~", O_WRONLY | O_CREAT, 0600) { 1208 if (my $fh = aio_open "$filename~", O_WRONLY | O_CREAT, 0600) {
1196 aio_chmod $fh, SAVE_MODE; 1209 aio_chmod $fh, SAVE_MODE;
1197 aio_write $fh, 0, (length $$rdata), $$rdata, 0; 1210 aio_write $fh, 0, (length $$rdata), $$rdata, 0;
1198 if ($cf::USE_FSYNC) { 1211 if ($cf::USE_FSYNC) {
1220 aio_rename "$filename~", $filename; 1233 aio_rename "$filename~", $filename;
1221 1234
1222 $filename =~ s%/[^/]+$%%; 1235 $filename =~ s%/[^/]+$%%;
1223 aio_pathsync $filename if $cf::USE_FSYNC; 1236 aio_pathsync $filename if $cf::USE_FSYNC;
1224 } else { 1237 } else {
1225 warn "unable to save objects: $filename~: $!\n"; 1238 error "unable to save objects: $filename~: $!\n";
1226 } 1239 }
1227 } else { 1240 } else {
1228 aio_unlink $filename; 1241 aio_unlink $filename;
1229 aio_unlink "$filename.pst"; 1242 aio_unlink "$filename.pst";
1230 } 1243 }
1254 my $st = eval { Coro::Storable::thaw $av }; 1267 my $st = eval { Coro::Storable::thaw $av };
1255 $av = $st->{objs}; 1268 $av = $st->{objs};
1256 } 1269 }
1257 1270
1258 utf8::decode (my $decname = $filename); 1271 utf8::decode (my $decname = $filename);
1259 warn sprintf "loading %s (%d,%d)\n", 1272 trace sprintf "loading %s (%d,%d)\n",
1260 $decname, length $data, scalar @{$av || []}; 1273 $decname, length $data, scalar @{$av || []}
1274 if $VERBOSE_IO;
1261 1275
1262 ($data, $av) 1276 ($data, $av)
1263} 1277}
1264 1278
1265=head2 COMMAND CALLBACKS 1279=head2 COMMAND CALLBACKS
1357 1371
1358 $pl->ext_reply ($reply, @reply) 1372 $pl->ext_reply ($reply, @reply)
1359 if $reply; 1373 if $reply;
1360 1374
1361 } else { 1375 } else {
1362 warn "player " . ($pl->ob->name) . " sent unparseable ext message: <$buf>\n"; 1376 error "player " . ($pl->ob->name) . " sent unparseable ext message: <$buf>\n";
1363 } 1377 }
1364 1378
1365 cf::override; 1379 cf::override;
1366 }, 1380 },
1367); 1381);
1378 1392
1379 $grp 1393 $grp
1380} 1394}
1381 1395
1382sub load_extensions { 1396sub load_extensions {
1397 info "loading extensions...";
1398
1383 cf::sync_job { 1399 cf::sync_job {
1384 my %todo; 1400 my %todo;
1385 1401
1386 for my $path (<$LIBDIR/*.ext>) { 1402 for my $path (<$LIBDIR/*.ext>) {
1387 next unless -r $path; 1403 next unless -r $path;
1405 1421
1406 $ext{meta} = { map { (split /=/, $_, 2)[0, 1] } split /\s+/, $1 } 1422 $ext{meta} = { map { (split /=/, $_, 2)[0, 1] } split /\s+/, $1 }
1407 if $source =~ /\A#!.*?perl.*?#\s*(.*)$/m; 1423 if $source =~ /\A#!.*?perl.*?#\s*(.*)$/m;
1408 1424
1409 $ext{source} = 1425 $ext{source} =
1410 "package $pkg; use 5.10.0; use strict 'vars', 'subs'; use utf8;\n" 1426 "package $pkg; use common::sense;\n"
1411 . "#line 1 \"$path\"\n{\n" 1427 . "#line 1 \"$path\"\n{\n"
1412 . $source 1428 . $source
1413 . "\n};\n1"; 1429 . "\n};\n1";
1414 1430
1415 $todo{$base} = \%ext; 1431 $todo{$base} = \%ext;
1427 for (split /,\s*/, $v->{meta}{depends}) { 1443 for (split /,\s*/, $v->{meta}{depends}) {
1428 next ext 1444 next ext
1429 unless exists $done{$_}; 1445 unless exists $done{$_};
1430 } 1446 }
1431 1447
1432 warn "... pass $pass, loading '$k' into '$v->{pkg}'\n"; 1448 trace "... pass $pass, loading '$k' into '$v->{pkg}'\n";
1433 1449
1434 my $active = eval $v->{source}; 1450 my $active = eval $v->{source};
1435 1451
1436 if (length $@) { 1452 if (length $@) {
1437 warn "$v->{path}: $@\n"; 1453 error "$v->{path}: $@\n";
1454 undef $@; # work around perl 5.10.0 utf-8 caching bug
1438 1455
1439 cf::cleanup "mandatory extension '$k' failed to load, exiting." 1456 cf::cleanup "mandatory extension '$k' failed to load, exiting."
1440 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};
1441 } else { 1461 } else {
1442 $done{$k} = delete $todo{$k}; 1462 $done{$k} = delete $todo{$k};
1443 push @EXTS, $v->{pkg}; 1463 push @EXTS, $v->{pkg};
1444 $progress = 1; 1464 $progress = 1;
1445 1465
1446 warn "$v->{base}: extension inactive.\n" 1466 info "$v->{base}: extension inactive.\n"
1447 unless $active; 1467 unless $active;
1448 } 1468 }
1449 } 1469 }
1450 1470
1451 unless ($progress) { 1471 unless ($progress) {
1623 $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
1624 1644
1625 $pl->invoke (cf::EVENT_PLAYER_LOGOUT, 1) if $pl->active; 1645 $pl->invoke (cf::EVENT_PLAYER_LOGOUT, 1) if $pl->active;
1626 $pl->deactivate; 1646 $pl->deactivate;
1627 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;
1628 $pl->ob->check_score;
1629 $pl->invoke (cf::EVENT_PLAYER_QUIT); 1648 $pl->invoke (cf::EVENT_PLAYER_QUIT);
1630 $pl->ns->destroy if $pl->ns; 1649 $pl->ns->destroy if $pl->ns;
1631 1650
1632 my $path = playerdir $pl; 1651 my $path = playerdir $pl;
1633 my $temp = "$path~$cf::RUNTIME~deleting~"; 1652 my $temp = "$path~$cf::RUNTIME~deleting~";
1688 \@logins 1707 \@logins
1689} 1708}
1690 1709
1691=item $player->maps 1710=item $player->maps
1692 1711
1712=item cf::player::maps $login
1713
1693Returns an arrayref of map paths that are private for this 1714Returns an arrayref of map paths that are private for this
1694player. May block. 1715player. May block.
1695 1716
1696=cut 1717=cut
1697 1718
1758 1779
1759=cut 1780=cut
1760 1781
1761sub find_by_path($) { 1782sub find_by_path($) {
1762 my ($path) = @_; 1783 my ($path) = @_;
1784
1785 $path =~ s/^~[^\/]*//; # skip ~login
1763 1786
1764 my ($match, $specificity); 1787 my ($match, $specificity);
1765 1788
1766 for my $region (list) { 1789 for my $region (list) {
1767 if ($region->{match} && $path =~ $region->{match}) { 1790 if ($region->{match} && $path =~ $region->{match}) {
1824 1847
1825sub register { 1848sub register {
1826 my (undef, $regex, $prio) = @_; 1849 my (undef, $regex, $prio) = @_;
1827 my $pkg = caller; 1850 my $pkg = caller;
1828 1851
1829 no strict;
1830 push @{"$pkg\::ISA"}, __PACKAGE__; 1852 push @{"$pkg\::ISA"}, __PACKAGE__;
1831 1853
1832 $EXT_MAP{$pkg} = [$prio, qr<$regex>]; 1854 $EXT_MAP{$pkg} = [$prio, qr<$regex>];
1833} 1855}
1834 1856
1835# also paths starting with '/' 1857# also paths starting with '/'
1836$EXT_MAP{"cf::map"} = [0, qr{^(?=/)}]; 1858$EXT_MAP{"cf::map::wrap"} = [0, qr{^(?=/)}];
1837 1859
1838sub thawer_merge { 1860sub thawer_merge {
1839 my ($self, $merge) = @_; 1861 my ($self, $merge) = @_;
1840 1862
1841 # we have to keep some variables in memory intact 1863 # we have to keep some variables in memory intact
2151 or next; 2173 or next;
2152 $neigh = find $neigh, $map 2174 $neigh = find $neigh, $map
2153 or next; 2175 or next;
2154 $neigh->load; 2176 $neigh->load;
2155 2177
2178 # now find the diagonal neighbours
2156 push @neigh, 2179 push @neigh,
2157 [$neigh->tile_path (($_ + 3) % 4), $neigh], 2180 [$neigh->tile_path (($_ + 3) % 4), $neigh],
2158 [$neigh->tile_path (($_ + 1) % 4), $neigh]; 2181 [$neigh->tile_path (($_ + 1) % 4), $neigh];
2159 } 2182 }
2160 2183
2167} 2190}
2168 2191
2169sub find_sync { 2192sub find_sync {
2170 my ($path, $origin) = @_; 2193 my ($path, $origin) = @_;
2171 2194
2172 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
2173} 2199}
2174 2200
2175sub do_load_sync { 2201sub do_load_sync {
2176 my ($map) = @_; 2202 my ($map) = @_;
2177 2203
2178 cf::LOG cf::llevDebug | cf::logBacktrace, "do_load_sync" 2204 return cf::LOG cf::llevError | cf::logBacktrace, "do_load_sync"
2179 if $Coro::current == $Coro::main; 2205 if $Coro::current == $Coro::main;
2180 2206
2181 cf::sync_job { $map->load }; 2207 $map->load;
2182} 2208}
2183 2209
2184our %MAP_PREFETCH; 2210our %MAP_PREFETCH;
2185our $MAP_PREFETCHER = undef; 2211our $MAP_PREFETCHER = undef;
2186 2212
2212 $MAP_PREFETCHER->prio (6); 2238 $MAP_PREFETCHER->prio (6);
2213 2239
2214 () 2240 ()
2215} 2241}
2216 2242
2243# common code, used by both ->save and ->swapout
2217sub save { 2244sub _save {
2218 my ($self) = @_; 2245 my ($self) = @_;
2219
2220 my $lock = cf::lock_acquire "map_data:$self->{path}";
2221 2246
2222 $self->{last_save} = $cf::RUNTIME; 2247 $self->{last_save} = $cf::RUNTIME;
2223 2248
2224 return unless $self->dirty; 2249 return unless $self->dirty;
2225 2250
2245 } else { 2270 } else {
2246 $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);
2247 } 2272 }
2248} 2273}
2249 2274
2275sub save {
2276 my ($self) = @_;
2277
2278 my $lock = cf::lock_acquire "map_data:$self->{path}";
2279
2280 $self->_save;
2281}
2282
2250sub swap_out { 2283sub swap_out {
2251 my ($self) = @_; 2284 my ($self) = @_;
2252 2285
2253 # save first because save cedes
2254 $self->save;
2255
2256 my $lock = cf::lock_acquire "map_data:$self->{path}"; 2286 my $lock = cf::lock_acquire "map_data:$self->{path}";
2257 2287
2258 return if $self->players;
2259 return if $self->in_memory != cf::MAP_ACTIVE; 2288 return if $self->in_memory != cf::MAP_ACTIVE;
2260 return if $self->{deny_save}; 2289 return if $self->{deny_save};
2290 return if $self->players;
2261 2291
2292 # first deactivate the map and "unlink" it from the core
2293 $self->deactivate;
2294 $_->clear_links_to ($self) for values %cf::MAP;
2262 $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};
2263 2342
2264 $self->deactivate; 2343 $self->deactivate;
2265 $_->clear_links_to ($self) for values %cf::MAP; 2344 $_->clear_links_to ($self) for values %cf::MAP;
2266 $self->clear; 2345 $self->clear;
2267}
2268
2269sub reset_at {
2270 my ($self) = @_;
2271
2272 # TODO: safety, remove and allow resettable per-player maps
2273 return 1e99 if $self->{deny_reset};
2274
2275 my $time = $self->fixed_resettime ? $self->{instantiate_time} : $self->last_access;
2276 my $to = List::Util::min $MAX_RESET, $self->reset_timeout || $DEFAULT_RESET;
2277
2278 $time + $to
2279}
2280
2281sub should_reset {
2282 my ($self) = @_;
2283
2284 $self->reset_at <= $cf::RUNTIME
2285}
2286
2287sub reset {
2288 my ($self) = @_;
2289
2290 my $lock = cf::lock_acquire "map_data:$self->{path}";
2291
2292 return if $self->players;
2293
2294 warn "resetting map ", $self->path, "\n";
2295
2296 $self->in_memory (cf::MAP_SWAPPED);
2297
2298 # need to save uniques path
2299 unless ($self->{deny_save}) {
2300 my $uniq = $self->uniq_path; utf8::encode $uniq;
2301
2302 $self->_save_objects ($uniq, cf::IO_UNIQUES)
2303 if $uniq;
2304 }
2305
2306 delete $cf::MAP{$self->path};
2307
2308 $self->deactivate;
2309 $_->clear_links_to ($self) for values %cf::MAP;
2310 $self->clear;
2311 2346
2312 $self->unlink_save; 2347 $self->unlink_save;
2313 $self->destroy; 2348 $self->destroy;
2314} 2349}
2315 2350
2323 2358
2324 delete $cf::MAP{$self->path}; 2359 delete $cf::MAP{$self->path};
2325 2360
2326 $self->unlink_save; 2361 $self->unlink_save;
2327 2362
2328 bless $self, "cf::map"; 2363 bless $self, "cf::map::wrap";
2329 delete $self->{deny_reset}; 2364 delete $self->{deny_reset};
2330 $self->{deny_save} = 1; 2365 $self->{deny_save} = 1;
2331 $self->reset_timeout (1); 2366 $self->reset_timeout (1);
2332 $self->path ($self->{path} = "{nuke}/" . ($nuke_counter++)); 2367 $self->path ($self->{path} = "{nuke}/" . ($nuke_counter++));
2333 2368
2563 2598
2564Freezes 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}>).
2565 2600
2566The 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.
2567for 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,
2568though, 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
2569map. 2604map.
2570 2605
2571Will never block. 2606Will never block.
2572 2607
2573=item $player_object->leave_link ($map, $x, $y) 2608=item $player_object->leave_link ($map, $x, $y)
2594sub cf::object::player::enter_link { 2629sub cf::object::player::enter_link {
2595 my ($self) = @_; 2630 my ($self) = @_;
2596 2631
2597 $self->deactivate_recursive; 2632 $self->deactivate_recursive;
2598 2633
2634 ++$self->{_link_recursion};
2635
2599 return if UNIVERSAL::isa $self->map, "ext::map_link"; 2636 return if UNIVERSAL::isa $self->map, "ext::map_link";
2600 2637
2601 $self->{_link_pos} ||= [$self->map->{path}, $self->x, $self->y] 2638 $self->{_link_pos} ||= [$self->map->{path}, $self->x, $self->y]
2602 if $self->map && $self->map->{path} ne "{link}"; 2639 if $self->map && $self->map->{path} ne "{link}";
2603 2640
2604 $self->enter_map ($LINK_MAP || link_map, 10, 10); 2641 $self->enter_map ($LINK_MAP || link_map, 3, 3);
2605} 2642}
2606 2643
2607sub cf::object::player::leave_link { 2644sub cf::object::player::leave_link {
2608 my ($self, $map, $x, $y) = @_; 2645 my ($self, $map, $x, $y) = @_;
2609 2646
2634 $map->load_neighbours; 2671 $map->load_neighbours;
2635 2672
2636 return unless $self->contr->active; 2673 return unless $self->contr->active;
2637 2674
2638 local $self->{_prev_pos} = $link_pos; # ugly hack for rent.ext 2675 local $self->{_prev_pos} = $link_pos; # ugly hack for rent.ext
2639 $self->enter_map ($map, $x, $y); 2676 if ($self->enter_map ($map, $x, $y)) {
2640 2677 # entering was successful
2678 delete $self->{_link_recursion};
2641 # only activate afterwards, to support waiting in hooks 2679 # only activate afterwards, to support waiting in hooks
2642 $self->activate_recursive; 2680 $self->activate_recursive;
2643} 2681 }
2644 2682
2683}
2684
2645=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)]])
2646 2686
2647Moves 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
2648her, loading and preparing them map, calling the provided $check callback 2688her, loading and preparing them map, calling the provided $check callback
2649that 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
2650the 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
2657 2697
2658our $GOTOGEN; 2698our $GOTOGEN;
2659 2699
2660sub cf::object::player::goto { 2700sub cf::object::player::goto {
2661 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 }
2662 2708
2663 # 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
2664 my $gen = $self->{_goto_generation} = ++$GOTOGEN; 2710 my $gen = $self->{_goto_generation} = ++$GOTOGEN;
2665 2711
2666 $self->enter_link; 2712 $self->enter_link;
2690 my $map = eval { 2736 my $map = eval {
2691 my $map = defined $path ? cf::map::find $path : undef; 2737 my $map = defined $path ? cf::map::find $path : undef;
2692 2738
2693 if ($map) { 2739 if ($map) {
2694 $map = $map->customise_for ($self); 2740 $map = $map->customise_for ($self);
2695 $map = $check->($map) if $check && $map; 2741 $map = $check->($map, $x, $y, $self) if $check && $map;
2696 } else { 2742 } else {
2697 $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);
2698 } 2744 }
2699 2745
2700 $map 2746 $map
2708 if ($gen == $self->{_goto_generation}) { 2754 if ($gen == $self->{_goto_generation}) {
2709 delete $self->{_goto_generation}; 2755 delete $self->{_goto_generation};
2710 $self->leave_link ($map, $x, $y); 2756 $self->leave_link ($map, $x, $y);
2711 } 2757 }
2712 2758
2713 $done->() if $done; 2759 $done->($self) if $done;
2714 })->prio (1); 2760 })->prio (1);
2715} 2761}
2716 2762
2717=item $player_object->enter_exit ($exit_object) 2763=item $player_object->enter_exit ($exit_object)
2718 2764
2811 $self->message ("Something went wrong deep within the deliantra server. " 2857 $self->message ("Something went wrong deep within the deliantra server. "
2812 . "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. "
2813 . "Please report this to the dungeon master!", 2859 . "Please report this to the dungeon master!",
2814 cf::NDI_UNIQUE | cf::NDI_RED); 2860 cf::NDI_UNIQUE | cf::NDI_RED);
2815 2861
2816 warn "ERROR in enter_exit: $@"; 2862 error "ERROR in enter_exit: $@";
2817 $self->leave_link; 2863 $self->leave_link;
2818 } 2864 }
2819 })->prio (1); 2865 })->prio (1);
2820} 2866}
2821 2867
3134 3180
3135 $ns->ext_reply ($reply, @reply) 3181 $ns->ext_reply ($reply, @reply)
3136 if $reply; 3182 if $reply;
3137 3183
3138 } else { 3184 } else {
3139 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";
3140 } 3186 }
3141 3187
3142 cf::override; 3188 cf::override;
3143 }, 3189 },
3144); 3190);
3225 decrease split destroy change_exp value msg lore send_msg)], 3271 decrease split destroy change_exp value msg lore send_msg)],
3226 ["cf::object::player" => qw(player)], 3272 ["cf::object::player" => qw(player)],
3227 ["cf::player" => qw(peaceful send_msg)], 3273 ["cf::player" => qw(peaceful send_msg)],
3228 ["cf::map" => qw(trigger)], 3274 ["cf::map" => qw(trigger)],
3229) { 3275) {
3230 no strict 'refs';
3231 my ($pkg, @funs) = @$_; 3276 my ($pkg, @funs) = @$_;
3232 *{"safe::$pkg\::$_"} = $safe_hole->wrap (\&{"$pkg\::$_"}) 3277 *{"safe::$pkg\::$_"} = $safe_hole->wrap (\&{"$pkg\::$_"})
3233 for @funs; 3278 for @funs;
3234} 3279}
3235 3280
3274 local @cf::_safe_eval_args = values %vars; 3319 local @cf::_safe_eval_args = values %vars;
3275 @res = wantarray ? eval eval : scalar eval $eval; 3320 @res = wantarray ? eval eval : scalar eval $eval;
3276 } 3321 }
3277 3322
3278 if ($@) { 3323 if ($@) {
3279 warn "$@"; 3324 warn "$@",
3280 warn "while executing safe code '$code'\n"; 3325 "while executing safe code '$code'\n",
3281 warn "with arguments " . (join " ", %vars) . "\n"; 3326 "with arguments " . (join " ", %vars) . "\n";
3282 } 3327 }
3283 3328
3284 wantarray ? @res : $res[0] 3329 wantarray ? @res : $res[0]
3285} 3330}
3286 3331
3320 # for this (global event?) 3365 # for this (global event?)
3321 %ext::player_env::MUSIC_FACE_CACHE = (); 3366 %ext::player_env::MUSIC_FACE_CACHE = ();
3322 3367
3323 my $enc = JSON::XS->new->utf8->canonical->relaxed; 3368 my $enc = JSON::XS->new->utf8->canonical->relaxed;
3324 3369
3325 warn "loading facedata from $path\n"; 3370 trace "loading facedata from $path\n";
3326 3371
3327 my $facedata; 3372 my $facedata;
3328 0 < aio_load $path, $facedata 3373 0 < aio_load $path, $facedata
3329 or die "$path: $!"; 3374 or die "$path: $!";
3330 3375
3364 3409
3365 if (my $smooth = cf::face::find $info->{smooth}) { 3410 if (my $smooth = cf::face::find $info->{smooth}) {
3366 cf::face::set_smooth $idx, $smooth; 3411 cf::face::set_smooth $idx, $smooth;
3367 cf::face::set_smoothlevel $idx, $info->{smoothlevel}; 3412 cf::face::set_smoothlevel $idx, $info->{smoothlevel};
3368 } else { 3413 } else {
3369 warn "smooth face '$info->{smooth}' not found for face '$face'"; 3414 error "smooth face '$info->{smooth}' not found for face '$face'";
3370 } 3415 }
3371 3416
3372 cf::cede_to_tick; 3417 cf::cede_to_tick;
3373 } 3418 }
3374 } 3419 }
3392 my $idx = (cf::face::find $name) || cf::face::alloc $name; 3437 my $idx = (cf::face::find $name) || cf::face::alloc $name;
3393 3438
3394 cf::face::set_data $idx, 0, $info->{data}, $info->{hash}; 3439 cf::face::set_data $idx, 0, $info->{data}, $info->{hash};
3395 cf::face::set_type $idx, $info->{type}; 3440 cf::face::set_type $idx, $info->{type};
3396 } else { 3441 } else {
3397 $RESOURCE{$name} = $info; 3442 $RESOURCE{$name} = $info; # unused
3398 } 3443 }
3399 3444
3400 cf::cede_to_tick; 3445 cf::cede_to_tick;
3401 } 3446 }
3402 } 3447 }
3403 3448
3404 cf::global->invoke (EVENT_GLOBAL_RESOURCE_UPDATE); 3449 cf::global->invoke (EVENT_GLOBAL_RESOURCE_UPDATE);
3405 3450
3406 1 3451 1
3407} 3452}
3408
3409cf::global->attach (on_resource_update => sub {
3410 if (my $soundconf = $RESOURCE{"res/sound.conf"}) {
3411 $soundconf = JSON::XS->new->utf8->relaxed->decode ($soundconf->{data});
3412
3413 for (0 .. SOUND_CAST_SPELL_0 - 1) {
3414 my $sound = $soundconf->{compat}[$_]
3415 or next;
3416
3417 my $face = cf::face::find "sound/$sound->[1]";
3418 cf::sound::set $sound->[0] => $face;
3419 cf::sound::old_sound_index $_, $face; # gcfclient-compat
3420 }
3421
3422 while (my ($k, $v) = each %{$soundconf->{event}}) {
3423 my $face = cf::face::find "sound/$v";
3424 cf::sound::set $k => $face;
3425 }
3426 }
3427});
3428 3453
3429register_exticmd fx_want => sub { 3454register_exticmd fx_want => sub {
3430 my ($ns, $want) = @_; 3455 my ($ns, $want) = @_;
3431 3456
3432 while (my ($k, $v) = each %$want) { 3457 while (my ($k, $v) = each %$want) {
3471sub reload_treasures { 3496sub reload_treasures {
3472 load_resource_file "$DATADIR/treasures" 3497 load_resource_file "$DATADIR/treasures"
3473 or die "unable to load treasurelists\n"; 3498 or die "unable to load treasurelists\n";
3474} 3499}
3475 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
3476sub reload_resources { 3524sub reload_resources {
3477 warn "reloading resource files...\n"; 3525 trace "reloading resource files...\n";
3478 3526
3479 reload_facedata; 3527 reload_facedata;
3528 reload_sound;
3480 reload_archetypes; 3529 reload_archetypes;
3481 reload_regions; 3530 reload_regions;
3482 reload_treasures; 3531 reload_treasures;
3483 3532
3484 warn "finished reloading resource files\n"; 3533 trace "finished reloading resource files\n";
3485} 3534}
3486 3535
3487sub reload_config { 3536sub reload_config {
3488 warn "reloading config file...\n"; 3537 trace "reloading config file...\n";
3489 3538
3490 open my $fh, "<:utf8", "$CONFDIR/config" 3539 open my $fh, "<:utf8", "$CONFDIR/config"
3491 or return; 3540 or return;
3492 3541
3493 local $/; 3542 local $/;
3494 *CFG = YAML::XS::Load scalar <$fh>; 3543 *CFG = YAML::XS::Load scalar <$fh>;
3495 3544
3496 $EMERGENCY_POSITION = $CFG{emergency_position} || ["/world/world_105_115", 5, 37]; 3545 $EMERGENCY_POSITION = $CFG{emergency_position} || ["/world/world_104_115", 49, 38];
3497 3546
3498 $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};
3499 $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};
3500 3549
3501 if (exists $CFG{mlockall}) { 3550 if (exists $CFG{mlockall}) {
3504 and die "WARNING: m(un)lockall failed: $!\n"; 3553 and die "WARNING: m(un)lockall failed: $!\n";
3505 }; 3554 };
3506 warn $@ if $@; 3555 warn $@ if $@;
3507 } 3556 }
3508 3557
3509 warn "finished reloading resource files\n"; 3558 trace "finished reloading resource files\n";
3510} 3559}
3511 3560
3512sub pidfile() { 3561sub pidfile() {
3513 sysopen my $fh, $PIDFILE, O_RDWR | O_CREAT 3562 sysopen my $fh, $PIDFILE, O_RDWR | O_CREAT
3514 or die "$PIDFILE: $!"; 3563 or die "$PIDFILE: $!";
3527 seek $fh, 0, 0; 3576 seek $fh, 0, 0;
3528 print $fh $$; 3577 print $fh $$;
3529} 3578}
3530 3579
3531sub main_loop { 3580sub main_loop {
3532 warn "EV::loop starting\n"; 3581 trace "EV::loop starting\n";
3533 if (1) { 3582 if (1) {
3534 EV::loop; 3583 EV::loop;
3535 } 3584 }
3536 warn "EV::loop returned\n"; 3585 trace "EV::loop returned\n";
3537 goto &main_loop unless $REALLY_UNLOOP; 3586 goto &main_loop unless $REALLY_UNLOOP;
3538} 3587}
3539 3588
3540sub main { 3589sub main {
3541 cf::init_globals; # initialise logging 3590 cf::init_globals; # initialise logging
3542 3591
3543 LOG llevInfo, "Welcome to Deliantra, v" . VERSION; 3592 LOG llevInfo, "Welcome to Deliantra, v" . VERSION;
3544 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.";
3545 LOG llevInfo, "Copyright (C) 1994 Mark Wedel."; 3594 LOG llevInfo, "Copyright (C) 1994 Mark Wedel.";
3546 LOG llevInfo, "Copyright (C) 1992 Frank Tore Johansen."; 3595 LOG llevInfo, "Copyright (C) 1992 Frank Tore Johansen.";
3547
3548 cf::init_experience;
3549 cf::init_anim;
3550 cf::init_attackmess;
3551 cf::init_dynamic;
3552 3596
3553 $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
3554 3598
3555 # we must not ever block the main coroutine 3599 # we must not ever block the main coroutine
3556 local $Coro::idle = sub { 3600 local $Coro::idle = sub {
3562 }; 3606 };
3563 3607
3564 evthread_start IO::AIO::poll_fileno; 3608 evthread_start IO::AIO::poll_fileno;
3565 3609
3566 cf::sync_job { 3610 cf::sync_job {
3611 cf::init_experience;
3612 cf::init_anim;
3613 cf::init_attackmess;
3614 cf::init_dynamic;
3615
3567 cf::load_settings; 3616 cf::load_settings;
3568 cf::load_materials; 3617 cf::load_materials;
3569 3618
3570 reload_resources; 3619 reload_resources;
3571 reload_config; 3620 reload_config;
3587 use POSIX (); 3636 use POSIX ();
3588 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};
3589 3638
3590 (pop @POST_INIT)->(0) while @POST_INIT; 3639 (pop @POST_INIT)->(0) while @POST_INIT;
3591 }; 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";
3592 3644
3593 main_loop; 3645 main_loop;
3594} 3646}
3595 3647
3596############################################################################# 3648#############################################################################
3637 or return; 3689 or return;
3638 3690
3639 aio_rename "$RUNTIMEFILE~", $RUNTIMEFILE 3691 aio_rename "$RUNTIMEFILE~", $RUNTIMEFILE
3640 and return; 3692 and return;
3641 3693
3642 warn sprintf "runtime file written (%gs).\n", AE::time - $t0; 3694 trace sprintf "runtime file written (%gs).\n", AE::time - $t0;
3643 3695
3644 1 3696 1
3645} 3697}
3646 3698
3647our $uuid_lock; 3699our $uuid_lock;
3659 or return; 3711 or return;
3660 3712
3661 my $value = uuid_seq uuid_cur; 3713 my $value = uuid_seq uuid_cur;
3662 3714
3663 unless ($value) { 3715 unless ($value) {
3664 warn "cowardly refusing to write zero uuid value!\n"; 3716 info "cowardly refusing to write zero uuid value!\n";
3665 return; 3717 return;
3666 } 3718 }
3667 3719
3668 my $value = uuid_str $value + $uuid_skip; 3720 my $value = uuid_str $value + $uuid_skip;
3669 $uuid_skip = 0; 3721 $uuid_skip = 0;
3679 or return; 3731 or return;
3680 3732
3681 aio_rename "$uuid~", $uuid 3733 aio_rename "$uuid~", $uuid
3682 and return; 3734 and return;
3683 3735
3684 warn "uuid file written ($value).\n"; 3736 trace "uuid file written ($value).\n";
3685 3737
3686 1 3738 1
3687 3739
3688} 3740}
3689 3741
3695} 3747}
3696 3748
3697sub emergency_save() { 3749sub emergency_save() {
3698 my $freeze_guard = cf::freeze_mainloop; 3750 my $freeze_guard = cf::freeze_mainloop;
3699 3751
3700 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;
3701 3758
3702 cf::sync_job { 3759 cf::sync_job {
3703 # this is a trade-off: we want to be very quick here, so 3760 cf::write_runtime_sync; # external watchdog should not bark
3704 # save all maps without fsync, and later call a global sync
3705 # (which in turn might be very very slow)
3706 local $USE_FSYNC = 0;
3707 3761
3708 # use a peculiar iteration method to avoid tripping on perl 3762 # use a peculiar iteration method to avoid tripping on perl
3709 # refcount bugs in for. also avoids problems with players 3763 # refcount bugs in for. also avoids problems with players
3710 # and maps saved/destroyed asynchronously. 3764 # and maps saved/destroyed asynchronously.
3711 warn "emergency_perl_save: begin player save\n"; 3765 info "emergency_perl_save: begin player save\n";
3712 for my $login (keys %cf::PLAYER) { 3766 for my $login (keys %cf::PLAYER) {
3713 my $pl = $cf::PLAYER{$login} or next; 3767 my $pl = $cf::PLAYER{$login} or next;
3714 $pl->valid or next; 3768 $pl->valid or next;
3715 delete $pl->{unclean_save}; # not strictly necessary, but cannot hurt 3769 delete $pl->{unclean_save}; # not strictly necessary, but cannot hurt
3716 $pl->save; 3770 $pl->save;
3717 } 3771 }
3718 warn "emergency_perl_save: end player save\n"; 3772 info "emergency_perl_save: end player save\n";
3719 3773
3774 cf::write_runtime_sync; # external watchdog should not bark
3775
3720 warn "emergency_perl_save: begin map save\n"; 3776 info "emergency_perl_save: begin map save\n";
3721 for my $path (keys %cf::MAP) { 3777 for my $path (keys %cf::MAP) {
3722 my $map = $cf::MAP{$path} or next; 3778 my $map = $cf::MAP{$path} or next;
3723 $map->valid or next; 3779 $map->valid or next;
3724 $map->save; 3780 $map->save;
3725 } 3781 }
3726 warn "emergency_perl_save: end map save\n"; 3782 info "emergency_perl_save: end map save\n";
3727 3783
3784 cf::write_runtime_sync; # external watchdog should not bark
3785
3728 warn "emergency_perl_save: begin database checkpoint\n"; 3786 info "emergency_perl_save: begin database checkpoint\n";
3729 BDB::db_env_txn_checkpoint $DB_ENV; 3787 BDB::db_env_txn_checkpoint $DB_ENV;
3730 warn "emergency_perl_save: end database checkpoint\n"; 3788 info "emergency_perl_save: end database checkpoint\n";
3731 3789
3732 warn "emergency_perl_save: begin write uuid\n"; 3790 info "emergency_perl_save: begin write uuid\n";
3733 write_uuid_sync 1; 3791 write_uuid_sync 1;
3734 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
3735 }; 3812 };
3736 3813
3737 warn "emergency_perl_save: starting sync()\n";
3738 IO::AIO::aio_sync sub {
3739 warn "emergency_perl_save: finished sync()\n";
3740 };
3741
3742 warn "emergency_perl_save: leave\n"; 3814 info "emergency_perl_save: leave\n";
3743} 3815}
3744 3816
3745sub post_cleanup { 3817sub post_cleanup {
3746 my ($make_core) = @_; 3818 my ($make_core) = @_;
3747 3819
3820 IO::AIO::flush;
3821
3748 warn Carp::longmess "post_cleanup backtrace" 3822 error Carp::longmess "post_cleanup backtrace"
3749 if $make_core; 3823 if $make_core;
3750 3824
3751 my $fh = pidfile; 3825 my $fh = pidfile;
3752 unlink $PIDFILE if <$fh> == $$; 3826 unlink $PIDFILE if <$fh> == $$;
3753} 3827}
3773 my $leaf_symtab = *{$stem_symtab->{$leaf}}{HASH}; 3847 my $leaf_symtab = *{$stem_symtab->{$leaf}}{HASH};
3774 for my $name (keys %$leaf_symtab) { 3848 for my $name (keys %$leaf_symtab) {
3775 _gv_clear *{"$pkg$name"}; 3849 _gv_clear *{"$pkg$name"};
3776# use PApp::Util; PApp::Util::sv_dump *{"$pkg$name"}; 3850# use PApp::Util; PApp::Util::sv_dump *{"$pkg$name"};
3777 } 3851 }
3778 warn "cleared package $pkg\n";#d#
3779} 3852}
3780 3853
3781sub do_reload_perl() { 3854sub do_reload_perl() {
3782 # can/must only be called in main 3855 # can/must only be called in main
3783 if ($Coro::current != $Coro::main) { 3856 if (in_main) {
3784 warn "can only reload from main coroutine"; 3857 error "can only reload from main coroutine";
3785 return; 3858 return;
3786 } 3859 }
3787 3860
3788 return if $RELOAD++; 3861 return if $RELOAD++;
3789 3862
3790 my $t1 = AE::time; 3863 my $t1 = AE::time;
3791 3864
3792 while ($RELOAD) { 3865 while ($RELOAD) {
3793 warn "reloading..."; 3866 info "reloading...";
3794 3867
3795 warn "entering sync_job"; 3868 trace "entering sync_job";
3796 3869
3797 cf::sync_job { 3870 cf::sync_job {
3798 cf::write_runtime_sync; # external watchdog should not bark
3799 cf::emergency_save; 3871 cf::emergency_save;
3800 cf::write_runtime_sync; # external watchdog should not bark
3801 3872
3802 warn "syncing database to disk";
3803 BDB::db_env_txn_checkpoint $DB_ENV;
3804
3805 # if anything goes wrong in here, we should simply crash as we already saved
3806
3807 warn "flushing outstanding aio requests";
3808 while (IO::AIO::nreqs || BDB::nreqs) {
3809 Coro::EV::timer_once 0.01; # let the sync_job do it's thing
3810 }
3811
3812 warn "cancelling all extension coros"; 3873 trace "cancelling all extension coros";
3813 $_->cancel for values %EXT_CORO; 3874 $_->cancel for values %EXT_CORO;
3814 %EXT_CORO = (); 3875 %EXT_CORO = ();
3815 3876
3816 warn "removing commands"; 3877 trace "removing commands";
3817 %COMMAND = (); 3878 %COMMAND = ();
3818 3879
3819 warn "removing ext/exti commands"; 3880 trace "removing ext/exti commands";
3820 %EXTCMD = (); 3881 %EXTCMD = ();
3821 %EXTICMD = (); 3882 %EXTICMD = ();
3822 3883
3823 warn "unloading/nuking all extensions"; 3884 trace "unloading/nuking all extensions";
3824 for my $pkg (@EXTS) { 3885 for my $pkg (@EXTS) {
3825 warn "... unloading $pkg"; 3886 trace "... unloading $pkg";
3826 3887
3827 if (my $cb = $pkg->can ("unload")) { 3888 if (my $cb = $pkg->can ("unload")) {
3828 eval { 3889 eval {
3829 $cb->($pkg); 3890 $cb->($pkg);
3830 1 3891 1
3831 } or warn "$pkg unloaded, but with errors: $@"; 3892 } or error "$pkg unloaded, but with errors: $@";
3832 } 3893 }
3833 3894
3834 warn "... clearing $pkg"; 3895 trace "... clearing $pkg";
3835 clear_package $pkg; 3896 clear_package $pkg;
3836 } 3897 }
3837 3898
3838 warn "unloading all perl modules loaded from $LIBDIR"; 3899 trace "unloading all perl modules loaded from $LIBDIR";
3839 while (my ($k, $v) = each %INC) { 3900 while (my ($k, $v) = each %INC) {
3840 next unless $v =~ /^\Q$LIBDIR\E\/.*\.pm$/; 3901 next unless $v =~ /^\Q$LIBDIR\E\/.*\.pm$/;
3841 3902
3842 warn "... unloading $k"; 3903 trace "... unloading $k";
3843 delete $INC{$k}; 3904 delete $INC{$k};
3844 3905
3845 $k =~ s/\.pm$//; 3906 $k =~ s/\.pm$//;
3846 $k =~ s/\//::/g; 3907 $k =~ s/\//::/g;
3847 3908
3850 } 3911 }
3851 3912
3852 clear_package $k; 3913 clear_package $k;
3853 } 3914 }
3854 3915
3855 warn "getting rid of safe::, as good as possible"; 3916 trace "getting rid of safe::, as good as possible";
3856 clear_package "safe::$_" 3917 clear_package "safe::$_"
3857 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);
3858 3919
3859 warn "unloading cf.pm \"a bit\""; 3920 trace "unloading cf.pm \"a bit\"";
3860 delete $INC{"cf.pm"}; 3921 delete $INC{"cf.pm"};
3861 delete $INC{"cf/$_.pm"} for @EXTRA_MODULES; 3922 delete $INC{"cf/$_.pm"} for @EXTRA_MODULES;
3862 3923
3863 # don't, removes xs symbols, too, 3924 # don't, removes xs symbols, too,
3864 # and global variables created in xs 3925 # and global variables created in xs
3865 #clear_package __PACKAGE__; 3926 #clear_package __PACKAGE__;
3866 3927
3867 warn "unload completed, starting to reload now"; 3928 info "unload completed, starting to reload now";
3868 3929
3869 warn "reloading cf.pm"; 3930 trace "reloading cf.pm";
3870 require cf; 3931 require cf;
3871 cf::_connect_to_perl_1; 3932 cf::_connect_to_perl_1;
3872 3933
3873 warn "loading config and database again"; 3934 trace "loading config and database again";
3874 cf::reload_config; 3935 cf::reload_config;
3875 3936
3876 warn "loading extensions"; 3937 trace "loading extensions";
3877 cf::load_extensions; 3938 cf::load_extensions;
3878 3939
3879 if ($REATTACH_ON_RELOAD) { 3940 if ($REATTACH_ON_RELOAD) {
3880 warn "reattaching attachments to objects/players"; 3941 trace "reattaching attachments to objects/players";
3881 _global_reattach; # objects, sockets 3942 _global_reattach; # objects, sockets
3882 warn "reattaching attachments to maps"; 3943 trace "reattaching attachments to maps";
3883 reattach $_ for values %MAP; 3944 reattach $_ for values %MAP;
3884 warn "reattaching attachments to players"; 3945 trace "reattaching attachments to players";
3885 reattach $_ for values %PLAYER; 3946 reattach $_ for values %PLAYER;
3886 } 3947 }
3887 3948
3888 warn "running post_init jobs"; 3949 trace "running post_init jobs";
3889 (pop @POST_INIT)->(1) while @POST_INIT; 3950 (pop @POST_INIT)->(1) while @POST_INIT;
3890 3951
3891 warn "leaving sync_job"; 3952 trace "leaving sync_job";
3892 3953
3893 1 3954 1
3894 } or do { 3955 } or do {
3895 warn $@; 3956 error $@;
3896 cf::cleanup "error while reloading, exiting."; 3957 cf::cleanup "error while reloading, exiting.";
3897 }; 3958 };
3898 3959
3899 warn "reloaded"; 3960 info "reloaded";
3900 --$RELOAD; 3961 --$RELOAD;
3901 } 3962 }
3902 3963
3903 $t1 = AE::time - $t1; 3964 $t1 = AE::time - $t1;
3904 warn "reload completed in ${t1}s\n"; 3965 info "reload completed in ${t1}s\n";
3905}; 3966};
3906 3967
3907our $RELOAD_WATCHER; # used only during reload 3968our $RELOAD_WATCHER; # used only during reload
3908 3969
3909sub reload_perl() { 3970sub reload_perl() {
3969 if ($NOW >= $NEXT_RUNTIME_WRITE) { 4030 if ($NOW >= $NEXT_RUNTIME_WRITE) {
3970 $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.;
3971 Coro::async_pool { 4032 Coro::async_pool {
3972 $Coro::current->{desc} = "runtime saver"; 4033 $Coro::current->{desc} = "runtime saver";
3973 write_runtime_sync 4034 write_runtime_sync
3974 or warn "ERROR: unable to write runtime file: $!"; 4035 or error "ERROR: unable to write runtime file: $!";
3975 }; 4036 };
3976 } 4037 }
3977 4038
3978 if (my $sig = shift @WAIT_FOR_TICK_BEGIN) { 4039 if (my $sig = shift @WAIT_FOR_TICK_BEGIN) {
3979 $sig->send; 4040 $sig->send;
3987 4048
3988 if (0) { 4049 if (0) {
3989 if ($NEXT_TICK) { 4050 if ($NEXT_TICK) {
3990 my $jitter = $TICK_START - $NEXT_TICK; 4051 my $jitter = $TICK_START - $NEXT_TICK;
3991 $JITTER = $JITTER * 0.75 + $jitter * 0.25; 4052 $JITTER = $JITTER * 0.75 + $jitter * 0.25;
3992 warn "jitter $JITTER\n";#d# 4053 debug "jitter $JITTER\n";#d#
3993 } 4054 }
3994 } 4055 }
3995} 4056}
3996 4057
3997{ 4058{

Diff Legend

Removed lines
+ Added lines
< Changed lines
> Changed lines