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

Comparing cf.schmorp.de/server/lib/cf.pm (file contents):
Revision 1.168 by root, Sun Jan 14 00:37:14 2007 UTC vs.
Revision 1.211 by root, Tue Feb 13 16:23:32 2007 UTC

8use Storable; 8use Storable;
9use Opcode; 9use Opcode;
10use Safe; 10use Safe;
11use Safe::Hole; 11use Safe::Hole;
12 12
13use Coro 3.3 (); 13use Coro 3.5 ();
14use Coro::Event; 14use Coro::Event;
15use Coro::Timer; 15use Coro::Timer;
16use Coro::Signal; 16use Coro::Signal;
17use Coro::Semaphore; 17use Coro::Semaphore;
18use Coro::AIO; 18use Coro::AIO;
19 19
20use BDB ();
20use Data::Dumper; 21use Data::Dumper;
21use Digest::MD5; 22use Digest::MD5;
22use Fcntl; 23use Fcntl;
23use IO::AIO 2.32 (); 24use IO::AIO 2.32 ();
24use YAML::Syck (); 25use YAML::Syck ();
25use Time::HiRes; 26use Time::HiRes;
27use Compress::LZF;
28
29Compress::LZF::sfreeze_cr { }; # prime Compress::LZF so it does not use require later
26 30
27use Event; $Event::Eval = 1; # no idea why this is required, but it is 31use Event; $Event::Eval = 1; # no idea why this is required, but it is
28 32
29sub WF_AUTOCANCEL () { 1 } # automatically cancel this watcher on reload 33sub WF_AUTOCANCEL () { 1 } # automatically cancel this watcher on reload
30 34
48our $TICK_WATCHER; 52our $TICK_WATCHER;
49our $AIO_POLL_WATCHER; 53our $AIO_POLL_WATCHER;
50our $WRITE_RUNTIME_WATCHER; 54our $WRITE_RUNTIME_WATCHER;
51our $NEXT_TICK; 55our $NEXT_TICK;
52our $NOW; 56our $NOW;
57our $USE_FSYNC = 1; # use fsync to write maps - default off
58
59our $BDB_POLL_WATCHER;
60our $DB_ENV;
53 61
54our %CFG; 62our %CFG;
55 63
56our $UPTIME; $UPTIME ||= time; 64our $UPTIME; $UPTIME ||= time;
57our $RUNTIME; 65our $RUNTIME;
58 66
59our %PLAYER; # all users 67our %PLAYER; # all users
60our %MAP; # all maps 68our %MAP; # all maps
61our $LINK_MAP; # the special {link} map, which is always available 69our $LINK_MAP; # the special {link} map, which is always available
62our $RANDOM_MAPS = cf::localdir . "/random"; 70our $RANDOM_MAPS = cf::localdir . "/random";
71our $BDB_ENV_DIR = cf::localdir . "/db";
63 72
64our $WAIT_FOR_TICK; $WAIT_FOR_TICK ||= new Coro::Signal; 73our $WAIT_FOR_TICK; $WAIT_FOR_TICK ||= new Coro::Signal;
65our $WAIT_FOR_TICK_ONE; $WAIT_FOR_TICK_ONE ||= new Coro::Signal; 74our $WAIT_FOR_TICK_ONE; $WAIT_FOR_TICK_ONE ||= new Coro::Signal;
66 75
67# used to convert map paths into valid unix filenames by replacing / by ∕ 76# used to convert map paths into valid unix filenames by replacing / by ∕
80mkdir cf::localdir; 89mkdir cf::localdir;
81mkdir cf::localdir . "/" . cf::playerdir; 90mkdir cf::localdir . "/" . cf::playerdir;
82mkdir cf::localdir . "/" . cf::tmpdir; 91mkdir cf::localdir . "/" . cf::tmpdir;
83mkdir cf::localdir . "/" . cf::uniquedir; 92mkdir cf::localdir . "/" . cf::uniquedir;
84mkdir $RANDOM_MAPS; 93mkdir $RANDOM_MAPS;
94mkdir $BDB_ENV_DIR;
85 95
86our $EMERGENCY_POSITION; 96our $EMERGENCY_POSITION;
97
98sub cf::map::normalise;
87 99
88############################################################################# 100#############################################################################
89 101
90=head2 GLOBAL VARIABLES 102=head2 GLOBAL VARIABLES
91 103
344 356
345 $coro 357 $coro
346} 358}
347 359
348sub write_runtime { 360sub write_runtime {
361 $TICK_WATCHER->is_active or cf::cleanup "mainloop frozen but runtime active", 1;
362
349 my $runtime = cf::localdir . "/runtime"; 363 my $runtime = cf::localdir . "/runtime";
350 364
351 my $fh = aio_open "$runtime~", O_WRONLY | O_CREAT, 0644 365 my $fh = aio_open "$runtime~", O_WRONLY | O_CREAT, 0644
352 or return; 366 or return;
353 367
368 my $value = $cf::RUNTIME + 90 + 10;
354 my $value = $cf::RUNTIME + 1 + 10; # 10 is the runtime save interval, for a monotonic clock 369 # 10 is the runtime save interval, for a monotonic clock
370 # 60 allows for the watchdog to kill the server.
371
355 (aio_write $fh, 0, (length $value), $value, 0) <= 0 372 (aio_write $fh, 0, (length $value), $value, 0) <= 0
356 and return; 373 and return;
357 374
375 # always fsync - this file is important
358 aio_fsync $fh 376 aio_fsync $fh
359 and return; 377 and return;
360 378
361 close $fh 379 close $fh
362 or return; 380 or return;
503our @CB_TYPE = (); # registry for type (cf-object class) based events 521our @CB_TYPE = (); # registry for type (cf-object class) based events
504our @CB_MAP = (); 522our @CB_MAP = ();
505 523
506my %attachment; 524my %attachment;
507 525
526sub cf::attachable::thawer_merge {
527 # simply override everything except _meta
528 local $_[0]{_meta};
529 %{$_[0]} = %{$_[1]};
530}
531
508sub _attach_cb($$$$) { 532sub _attach_cb($$$$) {
509 my ($registry, $event, $prio, $cb) = @_; 533 my ($registry, $event, $prio, $cb) = @_;
510 534
511 use sort 'stable'; 535 use sort 'stable';
512 536
683# object support 707# object support
684 708
685sub reattach { 709sub reattach {
686 # basically do the same as instantiate, without calling instantiate 710 # basically do the same as instantiate, without calling instantiate
687 my ($obj) = @_; 711 my ($obj) = @_;
712
713 bless $obj, ref $obj; # re-bless in case extensions have been reloaded
688 714
689 my $registry = $obj->registry; 715 my $registry = $obj->registry;
690 716
691 @$registry = (); 717 @$registry = ();
692 718
739 $filename, length $$rdata, scalar @$objs; 765 $filename, length $$rdata, scalar @$objs;
740 766
741 if (my $fh = aio_open "$filename~", O_WRONLY | O_CREAT, 0600) { 767 if (my $fh = aio_open "$filename~", O_WRONLY | O_CREAT, 0600) {
742 chmod SAVE_MODE, $fh; 768 chmod SAVE_MODE, $fh;
743 aio_write $fh, 0, (length $$rdata), $$rdata, 0; 769 aio_write $fh, 0, (length $$rdata), $$rdata, 0;
744 aio_fsync $fh; 770 aio_fsync $fh if $cf::USE_FSYNC;
745 close $fh; 771 close $fh;
746 772
747 if (@$objs) { 773 if (@$objs) {
748 if (my $fh = aio_open "$filename.pst~", O_WRONLY | O_CREAT, 0600) { 774 if (my $fh = aio_open "$filename.pst~", O_WRONLY | O_CREAT, 0600) {
749 chmod SAVE_MODE, $fh; 775 chmod SAVE_MODE, $fh;
750 my $data = Storable::nfreeze { version => 1, objs => $objs }; 776 my $data = Storable::nfreeze { version => 1, objs => $objs };
751 aio_write $fh, 0, (length $data), $data, 0; 777 aio_write $fh, 0, (length $data), $data, 0;
752 aio_fsync $fh; 778 aio_fsync $fh if $cf::USE_FSYNC;
753 close $fh; 779 close $fh;
754 aio_rename "$filename.pst~", "$filename.pst"; 780 aio_rename "$filename.pst~", "$filename.pst";
755 } 781 }
756 } else { 782 } else {
757 aio_unlink "$filename.pst"; 783 aio_unlink "$filename.pst";
763 } 789 }
764 } else { 790 } else {
765 aio_unlink $filename; 791 aio_unlink $filename;
766 aio_unlink "$filename.pst"; 792 aio_unlink "$filename.pst";
767 } 793 }
794
795 #d##TODO# nuke non .map-files if exist
796 if ($filename =~ s/\.map$//) {
797 aio_unlink $filename;
798 aio_unlink "$filename.pst";
799 }
768 } 800 }
769} 801}
770 802
771sub object_freezer_as_string { 803sub object_freezer_as_string {
772 my ($rdata, $objs) = @_; 804 my ($rdata, $objs) = @_;
778 810
779sub object_thawer_load { 811sub object_thawer_load {
780 my ($filename) = @_; 812 my ($filename) = @_;
781 813
782 my ($data, $av); 814 my ($data, $av);
815
816 #d#TODO remove .map if file does not exist
817 aio_stat $filename and $filename =~ s/\.map$//;
783 818
784 (aio_load $filename, $data) >= 0 819 (aio_load $filename, $data) >= 0
785 or return; 820 or return;
786 821
787 unless (aio_stat "$filename.pst") { 822 unless (aio_stat "$filename.pst") {
949 984
950sub exists($) { 985sub exists($) {
951 my ($login) = @_; 986 my ($login) = @_;
952 987
953 $cf::PLAYER{$login} 988 $cf::PLAYER{$login}
954 or cf::sync_job { !aio_stat $login } 989 or cf::sync_job { !aio_stat path $login }
955} 990}
956 991
957sub find($) { 992sub find($) {
958 return $cf::PLAYER{$_[0]} || do { 993 return $cf::PLAYER{$_[0]} || do {
959 my $login = $_[0]; 994 my $login = $_[0];
1057=cut 1092=cut
1058 1093
1059sub maps($) { 1094sub maps($) {
1060 my ($pl) = @_; 1095 my ($pl) = @_;
1061 1096
1097 $pl = ref $pl ? $pl->ob->name : $pl;
1098
1062 my $files = aio_readdir playerdir $pl 1099 my $files = aio_readdir playerdir $pl
1063 or return; 1100 or return;
1064 1101
1065 my @paths; 1102 my @paths;
1066 1103
1067 for (@$files) { 1104 for (@$files) {
1068 utf8::decode $_; 1105 utf8::decode $_;
1069 next if /\.(?:pl|pst)$/; 1106 next if /\.(?:pl|pst)$/;
1070 next unless /^$PATH_SEP/o; 1107 next unless /^$PATH_SEP/o;
1071 1108
1072 s/\.map$//; 1109 push @paths, cf::map::normalise "~$pl/$_";
1073 push @paths, "~" . $pl->ob->name . "/" . $_;
1074 } 1110 }
1075 1111
1076 \@paths 1112 \@paths
1077} 1113}
1078 1114
1105 1141
1106use Fcntl; 1142use Fcntl;
1107use Coro::AIO; 1143use Coro::AIO;
1108 1144
1109use overload 1145use overload
1110 '""' => \&as_string; 1146 '""' => \&as_string,
1147 fallback => 1;
1111 1148
1112our $MAX_RESET = 3600; 1149our $MAX_RESET = 3600;
1113our $DEFAULT_RESET = 3000; 1150our $DEFAULT_RESET = 3000;
1114 1151
1115sub generate_random_map { 1152sub generate_random_map {
1116 my ($self, $rmp) = @_; 1153 my ($self, $rmp) = @_;
1117
1118 # mit "rum" bekleckern, nicht 1154 # mit "rum" bekleckern, nicht
1119 $self->_create_random_map ( 1155 $self->_create_random_map (
1120 $rmp->{wallstyle}, $rmp->{wall_name}, $rmp->{floorstyle}, $rmp->{monsterstyle}, 1156 $rmp->{wallstyle}, $rmp->{wall_name}, $rmp->{floorstyle}, $rmp->{monsterstyle},
1121 $rmp->{treasurestyle}, $rmp->{layoutstyle}, $rmp->{doorstyle}, $rmp->{decorstyle}, 1157 $rmp->{treasurestyle}, $rmp->{layoutstyle}, $rmp->{doorstyle}, $rmp->{decorstyle},
1122 $rmp->{origin_map}, $rmp->{final_map}, $rmp->{exitstyle}, $rmp->{this_map}, 1158 $rmp->{origin_map}, $rmp->{final_map}, $rmp->{exitstyle}, $rmp->{this_map},
1129 $rmp->{map_layout_style}, $rmp->{treasureoptions}, $rmp->{symmetry_used}, 1165 $rmp->{map_layout_style}, $rmp->{treasureoptions}, $rmp->{symmetry_used},
1130 (cf::region::find $rmp->{region}), $rmp->{custom} 1166 (cf::region::find $rmp->{region}), $rmp->{custom}
1131 ) 1167 )
1132} 1168}
1133 1169
1170=item cf::map->register ($regex, $prio)
1171
1172Register a handler for the map path matching the given regex at the
1173givne priority (higher is better, built-in handlers have priority 0, the
1174default).
1175
1176=cut
1177
1134sub register { 1178sub register {
1135 my (undef, $regex) = @_; 1179 my (undef, $regex, $prio) = @_;
1136 my $pkg = caller; 1180 my $pkg = caller;
1137 1181
1138 no strict; 1182 no strict;
1139 push @{"$pkg\::ISA"}, __PACKAGE__; 1183 push @{"$pkg\::ISA"}, __PACKAGE__;
1140 1184
1141 $EXT_MAP{$pkg} = qr<$regex>; 1185 $EXT_MAP{$pkg} = [$prio, qr<$regex>];
1142} 1186}
1143 1187
1144# also paths starting with '/' 1188# also paths starting with '/'
1145$EXT_MAP{"cf::map"} = qr{^(?=/)}; 1189$EXT_MAP{"cf::map"} = [0, qr{^(?=/)}];
1190
1191sub thawer_merge {
1192 my ($self, $merge) = @_;
1193
1194 # we have to keep some variables in memory intact
1195 local $self->{path};
1196 local $self->{load_path};
1197 local $self->{deny_save};
1198 local $self->{deny_reset};
1199
1200 $self->SUPER::thawer_merge ($merge);
1201}
1146 1202
1147sub normalise { 1203sub normalise {
1148 my ($path, $base) = @_; 1204 my ($path, $base) = @_;
1205
1206 $path = "$path"; # make sure its a string
1207
1208 $path =~ s/\.map$//;
1149 1209
1150 # map plan: 1210 # map plan:
1151 # 1211 #
1152 # /! non-realised random map exit (special hack!) 1212 # /! non-realised random map exit (special hack!)
1153 # {... are special paths that are not being touched 1213 # {... are special paths that are not being touched
1181 1241
1182 return $path if UNIVERSAL::isa $path, "cf::map"; # already a map object 1242 return $path if UNIVERSAL::isa $path, "cf::map"; # already a map object
1183 1243
1184 $path = normalise $path, $base; 1244 $path = normalise $path, $base;
1185 1245
1186 for my $pkg (keys %EXT_MAP) { 1246 for my $pkg (sort { $EXT_MAP{$b}[0] <=> $EXT_MAP{$a}[0] } keys %EXT_MAP) {
1187 if ($path =~ $EXT_MAP{$pkg}) { 1247 if ($path =~ $EXT_MAP{$pkg}[1]) {
1188 my $self = bless cf::map::new, $pkg; 1248 my $self = bless cf::map::new, $pkg;
1189 $self->{path} = $path; $self->path ($path); 1249 $self->{path} = $path; $self->path ($path);
1190 $self->init; # pass $1 etc. 1250 $self->init; # pass $1 etc.
1191 return $self; 1251 return $self;
1192 } 1252 }
1193 } 1253 }
1194 1254
1195 Carp::carp "unable to resolve path '$path'."; 1255 Carp::carp "unable to resolve path '$path' (base '$base').";
1196 () 1256 ()
1197} 1257}
1198 1258
1199sub init { 1259sub init {
1200 my ($self) = @_; 1260 my ($self) = @_;
1215 1275
1216# the original (read-only) location 1276# the original (read-only) location
1217sub load_path { 1277sub load_path {
1218 my ($self) = @_; 1278 my ($self) = @_;
1219 1279
1220 sprintf "%s/%s/%s", cf::datadir, cf::mapdir, $self->{path} 1280 sprintf "%s/%s/%s.map", cf::datadir, cf::mapdir, $self->{path}
1221} 1281}
1222 1282
1223# the temporary/swap location 1283# the temporary/swap location
1224sub save_path { 1284sub save_path {
1225 my ($self) = @_; 1285 my ($self) = @_;
1226 1286
1227 (my $path = $_[0]{path}) =~ s/\//$PATH_SEP/g; 1287 (my $path = $_[0]{path}) =~ s/\//$PATH_SEP/g;
1228 sprintf "%s/%s/%s", cf::localdir, cf::tmpdir, $path 1288 sprintf "%s/%s/%s.map", cf::localdir, cf::tmpdir, $path
1229} 1289}
1230 1290
1231# the unique path, undef == no special unique path 1291# the unique path, undef == no special unique path
1232sub uniq_path { 1292sub uniq_path {
1233 my ($self) = @_; 1293 my ($self) = @_;
1247 1307
1248sub unlink_save { 1308sub unlink_save {
1249 my ($self) = @_; 1309 my ($self) = @_;
1250 1310
1251 utf8::encode (my $save = $self->save_path); 1311 utf8::encode (my $save = $self->save_path);
1252 IO::AIO::aioreq_pri 4; IO::AIO::aio_unlink $save; 1312 IO::AIO::aioreq_pri 4; Coro::AIO::aio_unlink $save;
1253 IO::AIO::aioreq_pri 4; IO::AIO::aio_unlink "$save.pst"; 1313 IO::AIO::aioreq_pri 4; Coro::AIO::aio_unlink "$save.pst";
1314
1315 #d#TODO remove .map and also nuke
1316 $save =~ s/\.map// or return;#d#
1317 IO::AIO::aioreq_pri 4; Coro::AIO::aio_unlink $save;#d#
1318 IO::AIO::aioreq_pri 4; Coro::AIO::aio_unlink "$save.pst";#d#
1254} 1319}
1255 1320
1256sub load_header_from($) { 1321sub load_header_from($) {
1257 my ($self, $path) = @_; 1322 my ($self, $path) = @_;
1258 1323
1259 utf8::encode $path; 1324 utf8::encode $path;
1260 aio_open $path, O_RDONLY, 0 1325 #aio_open $path, O_RDONLY, 0
1261 or return; 1326 # or return;
1262 1327
1263 $self->_load_header ($path) 1328 $self->_load_header ($path)
1264 or return; 1329 or return;
1265 1330
1266 $self->{load_path} = $path; 1331 $self->{load_path} = $path;
1267 1332
1268 1 1333 1
1269} 1334}
1270 1335
1271sub load_orig { 1336sub load_header_orig {
1272 my ($self) = @_; 1337 my ($self) = @_;
1273 1338
1274 $self->load_header_from ($self->load_path) 1339 $self->load_header_from ($self->load_path)
1275} 1340}
1276 1341
1277sub load_temp { 1342sub load_header_temp {
1278 my ($self) = @_; 1343 my ($self) = @_;
1279 1344
1280 $self->load_header_from ($self->save_path) 1345 $self->load_header_from ($self->save_path)
1346}
1347
1348sub prepare_temp {
1349 my ($self) = @_;
1350
1351 $self->last_access ((delete $self->{last_access})
1352 || $cf::RUNTIME); #d#
1353 # safety
1354 $self->{instantiate_time} = $cf::RUNTIME
1355 if $self->{instantiate_time} > $cf::RUNTIME;
1356}
1357
1358sub prepare_orig {
1359 my ($self) = @_;
1360
1361 $self->{load_original} = 1;
1362 $self->{instantiate_time} = $cf::RUNTIME;
1363 $self->last_access ($cf::RUNTIME);
1364 $self->instantiate;
1281} 1365}
1282 1366
1283sub load_header { 1367sub load_header {
1284 my ($self) = @_; 1368 my ($self) = @_;
1285 1369
1286 if ($self->load_temp) { 1370 if ($self->load_header_temp) {
1287 $self->last_access ((delete $self->{last_access}) 1371 $self->prepare_temp;
1288 || $cf::RUNTIME); #d#
1289 # safety
1290 $self->{instantiate_time} = $cf::RUNTIME
1291 if $self->{instantiate_time} > $cf::RUNTIME;
1292 } else { 1372 } else {
1293 $self->load_orig 1373 $self->load_header_orig
1294 or return; 1374 or return;
1295 1375 $self->prepare_orig;
1296 $self->{load_original} = 1;
1297 $self->{instantiate_time} = $cf::RUNTIME;
1298 $self->last_access ($cf::RUNTIME);
1299 $self->instantiate;
1300 } 1376 }
1301 1377
1302 1 1378 1
1303} 1379}
1304 1380
1318 $map->{last_save} = $cf::RUNTIME; 1394 $map->{last_save} = $cf::RUNTIME;
1319 1395
1320 $map->load_header 1396 $map->load_header
1321 or return; 1397 or return;
1322 1398
1323 if ($map->should_reset) { 1399 if ($map->should_reset && 0) {#d#TODO# disabled, crashy (locking issue?)
1400 # doing this can freeze the server in a sync job, obviously
1401 #$cf::WAIT_FOR_TICK->wait;
1324 $map->reset; 1402 $map->reset;
1325 undef $guard; 1403 undef $guard;
1326 $map = find $path 1404 return find $path;
1327 or return;
1328 } 1405 }
1329 1406
1330 $cf::MAP{$path} = $map 1407 $cf::MAP{$path} = $map
1331 } 1408 }
1332} 1409}
1410
1411sub pre_load { }
1412sub post_load { }
1333 1413
1334sub load { 1414sub load {
1335 my ($self) = @_; 1415 my ($self) = @_;
1336 1416
1417 local $self->{deny_reset} = 1; # loading can take a long time
1418
1337 my $path = $self->{path}; 1419 my $path = $self->{path};
1338 my $guard = cf::lock_acquire "map_load:$path"; 1420 my $guard = cf::lock_acquire "map_load:$path";
1339 1421
1340 return if $self->in_memory != cf::MAP_SWAPPED; 1422 return if $self->in_memory != cf::MAP_SWAPPED;
1341 1423
1342 $self->in_memory (cf::MAP_LOADING); 1424 $self->in_memory (cf::MAP_LOADING);
1343 1425
1344 $self->alloc; 1426 $self->alloc;
1427
1428 $self->pre_load;
1429
1345 $self->_load_objects ($self->{load_path}, 1) 1430 $self->_load_objects ($self->{load_path}, 1)
1346 or return; 1431 or return;
1347 1432
1348 $self->set_object_flag (cf::FLAG_OBJ_ORIGINAL, 1) 1433 $self->set_object_flag (cf::FLAG_OBJ_ORIGINAL, 1)
1349 if delete $self->{load_original}; 1434 if delete $self->{load_original};
1371 unless $self->difficulty; 1456 unless $self->difficulty;
1372 Coro::cede; 1457 Coro::cede;
1373 $self->activate; 1458 $self->activate;
1374 } 1459 }
1375 1460
1461 $self->post_load;
1462
1376 $self->in_memory (cf::MAP_IN_MEMORY); 1463 $self->in_memory (cf::MAP_IN_MEMORY);
1377} 1464}
1378 1465
1379sub customise_for { 1466sub customise_for {
1380 my ($self, $ob) = @_; 1467 my ($self, $ob) = @_;
1420 1507
1421 cf::sync_job { $map->load }; 1508 cf::sync_job { $map->load };
1422} 1509}
1423 1510
1424our %MAP_PREFETCH; 1511our %MAP_PREFETCH;
1425our $MAP_PREFETCHER = Coro::async { 1512our $MAP_PREFETCHER = undef;
1426 while () {
1427 for my $path (keys %MAP_PREFETCH) {
1428 my $map = find $path
1429 or next;
1430 $map->load;
1431
1432 delete $MAP_PREFETCH{$path};
1433 }
1434 Coro::schedule;
1435 }
1436};
1437 1513
1438sub find_async { 1514sub find_async {
1439 my ($path, $origin) = @_; 1515 my ($path, $origin) = @_;
1440 1516
1441 $path = normalise $path, $origin && $origin->{path}; 1517 $path = normalise $path, $origin && $origin->{path};
1442 1518
1443 if (my $map = $cf::MAP{$path}) { 1519 if (my $map = $cf::MAP{$path}) {
1444 return $map if $map->in_memory == cf::MAP_IN_MEMORY; 1520 return $map if $map->in_memory == cf::MAP_IN_MEMORY;
1445 } 1521 }
1446 1522
1447 $MAP_PREFETCH{$path} = 0; 1523 undef $MAP_PREFETCH{$path};
1524 $MAP_PREFETCHER ||= cf::async {
1525 while (%MAP_PREFETCH) {
1526 for my $path (keys %MAP_PREFETCH) {
1527 my $map = find $path
1528 or next;
1529 $map->load;
1530
1531 delete $MAP_PREFETCH{$path};
1532 }
1533 }
1534 undef $MAP_PREFETCHER;
1535 };
1448 $MAP_PREFETCHER->ready; 1536 $MAP_PREFETCHER->prio (6);
1449 1537
1450 () 1538 ()
1451} 1539}
1452 1540
1453sub save { 1541sub save {
1498 1586
1499sub reset_at { 1587sub reset_at {
1500 my ($self) = @_; 1588 my ($self) = @_;
1501 1589
1502 # TODO: safety, remove and allow resettable per-player maps 1590 # TODO: safety, remove and allow resettable per-player maps
1503 return 1e99 if $self->isa ("ext::map_per_player"); 1591 return 1e99 if $self->isa ("ext::map_per_player");#d#
1504 return 1e99 if $self->{deny_reset}; 1592 return 1e99 if $self->{deny_reset};
1505 1593
1506 my $time = $self->fixed_resettime ? $self->{instantiate_time} : $self->last_access; 1594 my $time = $self->fixed_resettime ? $self->{instantiate_time} : $self->last_access;
1507 my $to = List::Util::min $MAX_RESET, $self->reset_timeout || $DEFAULT_RESET; 1595 my $to = List::Util::min $MAX_RESET, $self->reset_timeout || $DEFAULT_RESET;
1508 1596
1513 my ($self) = @_; 1601 my ($self) = @_;
1514 1602
1515 $self->reset_at <= $cf::RUNTIME 1603 $self->reset_at <= $cf::RUNTIME
1516} 1604}
1517 1605
1518sub rename {
1519 my ($self, $new_path) = @_;
1520
1521 normalise $new_path;
1522
1523 $self->unlink_save;
1524
1525 delete $cf::MAP{$self->path};
1526 $self->{path} = $new_path; $self->path ($self->{path});
1527 $cf::MAP{$self->path} = $self;
1528
1529 $self->save;
1530}
1531
1532sub reset { 1606sub reset {
1533 my ($self) = @_; 1607 my ($self) = @_;
1534 1608
1535 my $lock = cf::lock_acquire "map_data:$self->{path}"; 1609 my $lock = cf::lock_acquire "map_data:$self->{path}";
1536 1610
1537 return if $self->players; 1611 return if $self->players;
1538 return if $self->isa ("ext::map_per_player");#d# 1612 return if $self->isa ("ext::map_per_player");#d#
1539 1613
1540 warn "resetting map ", $self->path;#d# 1614 warn "resetting map ", $self->path;#d#
1541 1615
1616 $self->in_memory (cf::MAP_SWAPPED);
1617
1618 # need to save uniques path
1619 unless ($self->{deny_save}) {
1620 my $uniq = $self->uniq_path; utf8::encode $uniq;
1621
1622 $self->_save_objects ($uniq, cf::IO_UNIQUES)
1623 if $uniq;
1624 }
1625
1542 delete $cf::MAP{$self->path}; 1626 delete $cf::MAP{$self->path};
1543 1627
1544 $self->in_memory (cf::MAP_SWAPPED);
1545 $self->clear; 1628 $self->clear;
1546 1629
1547 $_->clear_links_to ($self) for values %cf::MAP; 1630 $_->clear_links_to ($self) for values %cf::MAP;
1548 1631
1549 $self->unlink_save; 1632 $self->unlink_save;
1553my $nuke_counter = "aaaa"; 1636my $nuke_counter = "aaaa";
1554 1637
1555sub nuke { 1638sub nuke {
1556 my ($self) = @_; 1639 my ($self) = @_;
1557 1640
1641 delete $cf::MAP{$self->path};
1642
1643 $self->unlink_save;
1644
1645 bless $self, "cf::map";
1646 delete $self->{deny_reset};
1558 $self->{deny_save} = 1; 1647 $self->{deny_save} = 1;
1559 $self->reset_timeout (1); 1648 $self->reset_timeout (1);
1560 $self->rename ("{nuke}/" . ($nuke_counter++)); 1649 $self->path ($self->{path} = "{nuke}/" . ($nuke_counter++));
1650
1651 $cf::MAP{$self->path} = $self;
1652
1561 $self->reset; # polite request, might not happen 1653 $self->reset; # polite request, might not happen
1562} 1654}
1563 1655
1564=item cf::map::unique_maps 1656=item cf::map::unique_maps
1565 1657
1577 for (@$files) { 1669 for (@$files) {
1578 utf8::decode $_; 1670 utf8::decode $_;
1579 next if /\.pst$/; 1671 next if /\.pst$/;
1580 next unless /^$PATH_SEP/o; 1672 next unless /^$PATH_SEP/o;
1581 1673
1582 s/\.map$//; 1674 push @paths, cf::map::normalise $_;
1583 push @paths, $_;
1584 } 1675 }
1585 1676
1586 \@paths 1677 \@paths
1587} 1678}
1588 1679
1682=cut 1773=cut
1683 1774
1684sub link_map { 1775sub link_map {
1685 unless ($LINK_MAP) { 1776 unless ($LINK_MAP) {
1686 $LINK_MAP = cf::map::find "{link}" 1777 $LINK_MAP = cf::map::find "{link}"
1687 or do { warn "FATAL: unable to provide {link} map, exiting."; exit 1 }; 1778 or cf::cleanup "FATAL: unable to provide {link} map, exiting.";
1688 $LINK_MAP->load; 1779 $LINK_MAP->load;
1689 } 1780 }
1690 1781
1691 $LINK_MAP 1782 $LINK_MAP
1692} 1783}
1699 return if UNIVERSAL::isa $self->map, "ext::map_link"; 1790 return if UNIVERSAL::isa $self->map, "ext::map_link";
1700 1791
1701 $self->{_link_pos} ||= [$self->map->{path}, $self->x, $self->y] 1792 $self->{_link_pos} ||= [$self->map->{path}, $self->x, $self->y]
1702 if $self->map; 1793 if $self->map;
1703 1794
1704 $self->enter_map ($LINK_MAP || link_map, 20, 20); 1795 $self->enter_map ($LINK_MAP || link_map, 10, 10);
1705} 1796}
1706 1797
1707sub cf::object::player::leave_link { 1798sub cf::object::player::leave_link {
1708 my ($self, $map, $x, $y) = @_; 1799 my ($self, $map, $x, $y) = @_;
1709 1800
1776 my ($self, $path, $x, $y) = @_; 1867 my ($self, $path, $x, $y) = @_;
1777 1868
1778 $self->enter_link; 1869 $self->enter_link;
1779 1870
1780 (async { 1871 (async {
1872 my $map = eval {
1781 my $map = cf::map::find $path; 1873 my $map = cf::map::find $path;
1782 $map = $map->customise_for ($self) if $map; 1874 $map = $map->customise_for ($self) if $map;
1783 1875 $map
1784# warn "entering ", $map->path, " at ($x, $y)\n" 1876 } or
1785# if $map;
1786
1787 $map or $self->message ("The exit to '" . ($path->visible_name) . "' is closed", cf::NDI_UNIQUE | cf::NDI_RED); 1877 $self->message ("The exit to '$path' is closed", cf::NDI_UNIQUE | cf::NDI_RED);
1788 1878
1789 $self->leave_link ($map, $x, $y); 1879 $self->leave_link ($map, $x, $y);
1790 })->prio (1); 1880 })->prio (1);
1791} 1881}
1792 1882
1796 1886
1797sub parse_random_map_params { 1887sub parse_random_map_params {
1798 my ($spec) = @_; 1888 my ($spec) = @_;
1799 1889
1800 my $rmp = { # defaults 1890 my $rmp = { # defaults
1801 xsize => 10, 1891 xsize => (cf::rndm 15, 40),
1802 ysize => 10, 1892 ysize => (cf::rndm 15, 40),
1893 symmetry => (cf::rndm 1, cf::SYMMETRY_XY),
1894 #layout => string,
1803 }; 1895 };
1804 1896
1805 for (split /\n/, $spec) { 1897 for (split /\n/, $spec) {
1806 my ($k, $v) = split /\s+/, $_, 2; 1898 my ($k, $v) = split /\s+/, $_, 2;
1807 1899
1811 $rmp 1903 $rmp
1812} 1904}
1813 1905
1814sub prepare_random_map { 1906sub prepare_random_map {
1815 my ($exit) = @_; 1907 my ($exit) = @_;
1908
1909 my $guard = cf::lock_acquire "exit_prepare:$exit";
1816 1910
1817 # all this does is basically replace the /! path by 1911 # all this does is basically replace the /! path by
1818 # a new random map path (?random/...) with a seed 1912 # a new random map path (?random/...) with a seed
1819 # that depends on the exit object 1913 # that depends on the exit object
1820 1914
1821 my $rmp = parse_random_map_params $exit->msg; 1915 my $rmp = parse_random_map_params $exit->msg;
1822 1916
1823 if ($exit->map) { 1917 if ($exit->map) {
1824 $rmp->{region} = $exit->map->region_name; 1918 $rmp->{region} = $exit->region->name;
1825 $rmp->{origin_map} = $exit->map->path; 1919 $rmp->{origin_map} = $exit->map->path;
1826 $rmp->{origin_x} = $exit->x; 1920 $rmp->{origin_x} = $exit->x;
1827 $rmp->{origin_y} = $exit->y; 1921 $rmp->{origin_y} = $exit->y;
1828 } 1922 }
1829 1923
1830 $rmp->{random_seed} ||= $exit->random_seed; 1924 $rmp->{random_seed} ||= $exit->random_seed;
1831 1925
1832 my $data = cf::to_json $rmp; 1926 my $data = cf::to_json $rmp;
1833 my $md5 = Digest::MD5::md5_hex $data; 1927 my $md5 = Digest::MD5::md5_hex $data;
1928 my $meta = "$cf::RANDOM_MAPS/$md5.meta";
1834 1929
1835 if (my $fh = aio_open "$cf::RANDOM_MAPS/$md5.meta", O_WRONLY | O_CREAT, 0666) { 1930 if (my $fh = aio_open "$meta~", O_WRONLY | O_CREAT, 0666) {
1836 aio_write $fh, 0, (length $data), $data, 0; 1931 aio_write $fh, 0, (length $data), $data, 0;
1932 undef $fh;
1933 aio_rename "$meta~", $meta;
1837 1934
1838 $exit->slaying ("?random/$md5"); 1935 $exit->slaying ("?random/$md5");
1839 $exit->msg (undef); 1936 $exit->msg (undef);
1840 } 1937 }
1841} 1938}
1842 1939
1843sub cf::object::player::enter_exit { 1940sub cf::object::player::enter_exit {
1844 my ($self, $exit) = @_; 1941 my ($self, $exit) = @_;
1845 1942
1846 return unless $self->type == cf::PLAYER; 1943 return unless $self->type == cf::PLAYER;
1944
1945 if ($exit->slaying eq "/!") {
1946 #TODO: this should de-fi-ni-te-ly not be a sync-job
1947 cf::sync_job { prepare_random_map $exit };
1948 }
1949
1950 my $slaying = cf::map::normalise $exit->slaying, $exit->map && $exit->map->path;
1951 my $hp = $exit->stats->hp;
1952 my $sp = $exit->stats->sp;
1847 1953
1848 $self->enter_link; 1954 $self->enter_link;
1849 1955
1850 (async { 1956 (async {
1851 $self->deactivate_recursive; # just to be sure 1957 $self->deactivate_recursive; # just to be sure
1852 unless (eval { 1958 unless (eval {
1853 prepare_random_map $exit 1959 $self->goto ($slaying, $hp, $sp);
1854 if $exit->slaying eq "/!";
1855
1856 my $path = new_from_path cf::map $exit->slaying, $exit->map && $exit->map->path;
1857 $self->goto ($path, $exit->stats->hp, $exit->stats->sp);
1858 1960
1859 1; 1961 1;
1860 }) { 1962 }) {
1861 $self->message ("Something went wrong deep within the crossfire server. " 1963 $self->message ("Something went wrong deep within the crossfire server. "
1862 . "I'll try to bring you back to the map you were before. " 1964 . "I'll try to bring you back to the map you were before. "
1923 # get handled first 2025 # get handled first
1924 my $queue = delete $ns->{query_queue} 2026 my $queue = delete $ns->{query_queue}
1925 or return; # be conservative, not sure how that can happen, but we saw a crash here 2027 or return; # be conservative, not sure how that can happen, but we saw a crash here
1926 2028
1927 (shift @$queue)->[1]->($msg); 2029 (shift @$queue)->[1]->($msg);
2030 return unless $ns->valid; # temporary(?) workaround for callback destroying socket
1928 2031
1929 push @{ $ns->{query_queue} }, @$queue; 2032 push @{ $ns->{query_queue} }, @$queue;
1930 2033
1931 if (@{ $ns->{query_queue} } == @$queue) { 2034 if (@{ $ns->{query_queue} } == @$queue) {
1932 if (@$queue) { 2035 if (@$queue) {
2093The parameter C<$family> should best start with the name of the extension 2196The parameter C<$family> should best start with the name of the extension
2094using it, it should be unique. 2197using it, it should be unique.
2095 2198
2096=over 4 2199=over 4
2097 2200
2098=item $hashref = cf::db_get $family
2099
2100Return a hashref for use by the extension C<$family>, which can be
2101modified. After modifications, you have to call C<cf::db_dirty> or
2102C<cf::db_sync>.
2103
2104=item $value = cf::db_get $family => $key 2201=item $value = cf::db_get $family => $key
2105 2202
2106Returns a single value from the database 2203Returns a single value from the database.
2107
2108=item cf::db_put $family => $hashref
2109
2110Stores the given family hashref into the database. Updates are delayed, if
2111you want the data to be synced to disk immediately, use C<cf::db_sync>.
2112 2204
2113=item cf::db_put $family => $key => $value 2205=item cf::db_put $family => $key => $value
2114 2206
2115Stores the given C<$value> in the family hash. Updates are delayed, if you 2207Stores the given C<$value> in the family.
2116want the data to be synced to disk immediately, use C<cf::db_sync>.
2117
2118=item cf::db_dirty
2119
2120Marks the database as dirty, to be updated at a later time.
2121
2122=item cf::db_sync
2123
2124Immediately write the database to disk I<if it is dirty>.
2125 2208
2126=cut 2209=cut
2127 2210
2128our $DB; 2211our $DB;
2129 2212
2130{ 2213sub db_init {
2214 unless ($DB) {
2215 $DB = BDB::db_create $DB_ENV;
2216
2217 cf::sync_job {
2218 eval {
2219 $DB->set_flags (BDB::CHKSUM);
2220
2221 BDB::db_open $DB, undef, "db", undef, BDB::BTREE,
2222 BDB::CREATE | BDB::AUTO_COMMIT, 0666;
2223 cf::cleanup "db_open(db): $!" if $!;
2224 };
2225 cf::cleanup "db_open(db): $@" if $@;
2226 };
2227
2131 my $path = cf::localdir . "/database.pst"; 2228 my $path = cf::localdir . "/database.pst";
2229 if (stat $path) {
2230 cf::sync_job {
2231 my $pst = Storable::retrieve $path;
2132 2232
2133 sub db_load() { 2233 cf::db_put (board => data => $pst->{board});
2134 $DB = stat $path ? Storable::retrieve $path : { }; 2234 cf::db_put (guildrules => data => $pst->{guildrules});
2135 } 2235 cf::db_put (rent => balance => $pst->{rent}{balance});
2236 BDB::db_env_txn_checkpoint $DB_ENV;
2136 2237
2137 my $pid; 2238 unlink $path;
2138
2139 sub db_save() {
2140 waitpid $pid, 0 if $pid;
2141 if (0 == ($pid = fork)) {
2142 $DB->{_meta}{version} = 1;
2143 Storable::nstore $DB, "$path~";
2144 rename "$path~", $path;
2145 cf::_exit 0 if defined $pid;
2146 } 2239 };
2147 }
2148
2149 my $dirty;
2150
2151 sub db_sync() {
2152 db_save if $dirty;
2153 undef $dirty;
2154 }
2155
2156 my $idle = Event->idle (min => $TICK * 2.8, max => 10, repeat => 0, data => WF_AUTOCANCEL, cb => sub {
2157 db_sync;
2158 });
2159
2160 sub db_dirty() {
2161 $dirty = 1;
2162 $idle->start;
2163 }
2164
2165 sub db_get($;$) {
2166 @_ >= 2
2167 ? $DB->{$_[0]}{$_[1]}
2168 : ($DB->{$_[0]} ||= { })
2169 }
2170
2171 sub db_put($$;$) {
2172 if (@_ >= 3) {
2173 $DB->{$_[0]}{$_[1]} = $_[2];
2174 } else {
2175 $DB->{$_[0]} = $_[1];
2176 }
2177 db_dirty;
2178 }
2179
2180 cf::global->attach (
2181 prio => 10000,
2182 on_cleanup => sub {
2183 db_sync;
2184 }, 2240 }
2185 ); 2241 }
2242}
2243
2244sub db_get($$) {
2245 my $key = "$_[0]/$_[1]";
2246
2247 cf::sync_job {
2248 BDB::db_get $DB, undef, $key, my $data;
2249
2250 $! ? ()
2251 : Compress::LZF::sthaw $data
2252 }
2253}
2254
2255sub db_put($$$) {
2256 BDB::dbreq_pri 4;
2257 BDB::db_put $DB, undef, "$_[0]/$_[1]", Compress::LZF::sfreeze_cr $_[2], 0, sub { };
2186} 2258}
2187 2259
2188############################################################################# 2260#############################################################################
2189# the server's main() 2261# the server's init and main functions
2262
2263sub load_resources {
2264 load_regions sprintf "%s/%s/regions", cf::datadir, cf::mapdir
2265 or die "unable to load regions file\n";#d#
2266}
2190 2267
2191sub cfg_load { 2268sub cfg_load {
2192 open my $fh, "<:utf8", cf::confdir . "/config" 2269 open my $fh, "<:utf8", cf::confdir . "/config"
2193 or return; 2270 or return;
2194 2271
2207 }; 2284 };
2208 warn $@ if $@; 2285 warn $@ if $@;
2209 } 2286 }
2210} 2287}
2211 2288
2289sub init {
2290 load_resources;
2291}
2292
2212sub main { 2293sub main {
2213 # we must not ever block the main coroutine 2294 # we must not ever block the main coroutine
2214 local $Coro::idle = sub { 2295 local $Coro::idle = sub {
2215 Carp::cluck "FATAL: Coro::idle was called, major BUG, use cf::sync_job!\n";#d# 2296 Carp::cluck "FATAL: Coro::idle was called, major BUG, use cf::sync_job!\n";#d#
2297 (async {
2216 async { Event::one_event }; 2298 Event::one_event;
2299 })->prio (Coro::PRIO_MAX);
2217 }; 2300 };
2218 2301
2219 cfg_load; 2302 cfg_load;
2220 db_load; 2303 db_init;
2221 load_extensions; 2304 load_extensions;
2305
2306 $TICK_WATCHER->start;
2222 Event::loop; 2307 Event::loop;
2223} 2308}
2224 2309
2225############################################################################# 2310#############################################################################
2226# initialisation and cleanup 2311# initialisation and cleanup
2227 2312
2228# install some emergency cleanup handlers 2313# install some emergency cleanup handlers
2229BEGIN { 2314BEGIN {
2230 for my $signal (qw(INT HUP TERM)) { 2315 for my $signal (qw(INT HUP TERM)) {
2231 Event->signal ( 2316 Event->signal (
2317 reentrant => 0,
2232 data => WF_AUTOCANCEL, 2318 data => WF_AUTOCANCEL,
2233 signal => $signal, 2319 signal => $signal,
2320 prio => 0,
2234 cb => sub { 2321 cb => sub {
2235 cf::cleanup "SIG$signal"; 2322 cf::cleanup "SIG$signal";
2236 }, 2323 },
2237 ); 2324 );
2238 } 2325 }
2239} 2326}
2260 my $map = $cf::MAP{$path} or next; 2347 my $map = $cf::MAP{$path} or next;
2261 $map->valid or next; 2348 $map->valid or next;
2262 $map->save; 2349 $map->save;
2263 } 2350 }
2264 warn "end emergency map save\n"; 2351 warn "end emergency map save\n";
2352
2353 warn "begin emergency database checkpoint\n";
2354 BDB::db_env_txn_checkpoint $DB_ENV;
2355 warn "end emergency database checkpoint\n";
2265 }; 2356 };
2266 2357
2267 warn "leave emergency perl save\n"; 2358 warn "leave emergency perl save\n";
2359}
2360
2361sub post_cleanup {
2362 my ($make_core) = @_;
2363
2364 warn Carp::longmess "post_cleanup backtrace"
2365 if $make_core;
2268} 2366}
2269 2367
2270sub reload() { 2368sub reload() {
2271 # can/must only be called in main 2369 # can/must only be called in main
2272 if ($Coro::current != $Coro::main) { 2370 if ($Coro::current != $Coro::main) {
2273 warn "can only reload from main coroutine\n"; 2371 warn "can only reload from main coroutine";
2274 return; 2372 return;
2275 } 2373 }
2276 2374
2277 warn "reloading..."; 2375 warn "reloading...";
2278 2376
2279 warn "freezing server"; 2377 warn "cancelling server ticker";
2280 my $guard = freeze_mainloop; 2378 $TICK_WATCHER->cancel;
2379
2281 cf::emergency_save; 2380 cf::emergency_save;
2282
2283 warn "sync database to disk";
2284 cf::db_sync;
2285 IO::AIO::flush;
2286 2381
2287 eval { 2382 eval {
2288 # if anything goes wrong in here, we should simply crash as we already saved 2383 # if anything goes wrong in here, we should simply crash as we already saved
2289 2384
2290 warn "cancel all watchers"; 2385 warn "cancelling all WF_AUTOCANCEL watchers";
2291 for (Event::all_watchers) { 2386 for (Event::all_watchers) {
2292 $_->cancel if $_->data & WF_AUTOCANCEL; 2387 $_->cancel if $_->data & WF_AUTOCANCEL;
2293 } 2388 }
2294 2389
2390 warn "syncing database to disk";
2391 BDB::db_env_txn_checkpoint $DB_ENV, 0, 0, 0, sub { };
2392
2393 warn "flushing outstanding aio requests";
2394 for (;;) {
2395 BDB::flush;
2396 IO::AIO::flush;
2397 Coro::cede;
2398 last unless IO::AIO::nreqs || BDB::nreqs;
2399 warn "iterate...";
2400 }
2401
2295 warn "cancel all extension coros"; 2402 warn "cancelling all extension coros";
2296 $_->cancel for values %EXT_CORO; 2403 $_->cancel for values %EXT_CORO;
2297 %EXT_CORO = (); 2404 %EXT_CORO = ();
2298 2405
2299 warn "remove commands"; 2406 warn "removing commands";
2300 %COMMAND = (); 2407 %COMMAND = ();
2301 2408
2302 warn "remove ext commands"; 2409 warn "removing ext commands";
2303 %EXTCMD = (); 2410 %EXTCMD = ();
2304 2411
2305 warn "unload/nuke all extensions"; 2412 warn "unloading/nuking all extensions";
2306 for my $pkg (@EXTS) { 2413 for my $pkg (@EXTS) {
2307 warn "... unloading $pkg"; 2414 warn "... unloading $pkg";
2308 2415
2309 if (my $cb = $pkg->can ("unload")) { 2416 if (my $cb = $pkg->can ("unload")) {
2310 eval { 2417 eval {
2315 2422
2316 warn "... nuking $pkg"; 2423 warn "... nuking $pkg";
2317 Symbol::delete_package $pkg; 2424 Symbol::delete_package $pkg;
2318 } 2425 }
2319 2426
2320 warn "unload all perl modules loaded from $LIBDIR"; 2427 warn "unloading all perl modules loaded from $LIBDIR";
2321 while (my ($k, $v) = each %INC) { 2428 while (my ($k, $v) = each %INC) {
2322 next unless $v =~ /^\Q$LIBDIR\E\/.*\.pm$/; 2429 next unless $v =~ /^\Q$LIBDIR\E\/.*\.pm$/;
2323 2430
2324 warn "removing <$k>"; 2431 warn "... unloading $k";
2325 delete $INC{$k}; 2432 delete $INC{$k};
2326 2433
2327 $k =~ s/\.pm$//; 2434 $k =~ s/\.pm$//;
2328 $k =~ s/\//::/g; 2435 $k =~ s/\//::/g;
2329 2436
2332 } 2439 }
2333 2440
2334 Symbol::delete_package $k; 2441 Symbol::delete_package $k;
2335 } 2442 }
2336 2443
2337 warn "get rid of safe::, as good as possible"; 2444 warn "getting rid of safe::, as good as possible";
2338 Symbol::delete_package "safe::$_" 2445 Symbol::delete_package "safe::$_"
2339 for qw(cf::attachable cf::object cf::object::player cf::client cf::player cf::map cf::party cf::region); 2446 for qw(cf::attachable cf::object cf::object::player cf::client cf::player cf::map cf::party cf::region);
2340 2447
2341 warn "unload cf.pm \"a bit\""; 2448 warn "unloading cf.pm \"a bit\"";
2342 delete $INC{"cf.pm"}; 2449 delete $INC{"cf.pm"};
2343 2450
2344 # don't, removes xs symbols, too, 2451 # don't, removes xs symbols, too,
2345 # and global variables created in xs 2452 # and global variables created in xs
2346 #Symbol::delete_package __PACKAGE__; 2453 #Symbol::delete_package __PACKAGE__;
2347 2454
2455 warn "unload completed, starting to reload now";
2456
2348 warn "reloading cf.pm"; 2457 warn "reloading cf.pm";
2349 require cf; 2458 require cf;
2350 cf::_connect_to_perl; # nominally unnecessary, but cannot hurt 2459 cf::_connect_to_perl; # nominally unnecessary, but cannot hurt
2351 2460
2352 warn "load config and database again"; 2461 warn "loading config and database again";
2353 cf::cfg_load; 2462 cf::cfg_load;
2354 cf::db_load;
2355 2463
2356 warn "load extensions"; 2464 warn "loading extensions";
2357 cf::load_extensions; 2465 cf::load_extensions;
2358 2466
2359 warn "reattach attachments to objects/players"; 2467 warn "reattaching attachments to objects/players";
2360 _global_reattach; 2468 _global_reattach;
2361 warn "reattach attachments to maps"; 2469 warn "reattaching attachments to maps";
2362 reattach $_ for values %MAP; 2470 reattach $_ for values %MAP;
2471
2472 warn "loading reloadable resources";
2473 load_resources;
2474
2475 warn "restarting server ticker";
2476
2477 $TICK_WATCHER->start;
2363 }; 2478 };
2364 2479
2365 if ($@) { 2480 if ($@) {
2366 warn $@; 2481 warn $@;
2367 warn "error while reloading, exiting."; 2482 warn "error while reloading, exiting.";
2369 } 2484 }
2370 2485
2371 warn "reloaded"; 2486 warn "reloaded";
2372}; 2487};
2373 2488
2489our $RELOAD_WATCHER; # used only during reload
2490
2374register_command "reload" => sub { 2491register_command "reload" => sub {
2375 my ($who, $arg) = @_; 2492 my ($who, $arg) = @_;
2376 2493
2377 if ($who->flag (FLAG_WIZ)) { 2494 if ($who->flag (FLAG_WIZ)) {
2378 $who->message ("start of reload."); 2495 $who->message ("reloading server.");
2496
2497 # doing reload synchronously and two reloads happen back-to-back,
2498 # coro crashes during coro_state_free->destroy here.
2499
2500 $RELOAD_WATCHER ||= Event->timer (
2501 reentrant => 0,
2502 after => 0,
2503 data => WF_AUTOCANCEL,
2504 cb => sub {
2379 reload; 2505 reload;
2380 $who->message ("end of reload."); 2506 undef $RELOAD_WATCHER;
2507 },
2508 );
2381 } 2509 }
2382}; 2510};
2383 2511
2384unshift @INC, $LIBDIR; 2512unshift @INC, $LIBDIR;
2513
2514my $bug_warning = 0;
2385 2515
2386$TICK_WATCHER = Event->timer ( 2516$TICK_WATCHER = Event->timer (
2387 reentrant => 0, 2517 reentrant => 0,
2518 parked => 1,
2388 prio => 0, 2519 prio => 0,
2389 at => $NEXT_TICK || $TICK, 2520 at => $NEXT_TICK || $TICK,
2390 data => WF_AUTOCANCEL, 2521 data => WF_AUTOCANCEL,
2391 cb => sub { 2522 cb => sub {
2523 if ($Coro::current != $Coro::main) {
2524 Carp::cluck "major BUG: server tick called outside of main coro, skipping it"
2525 unless ++$bug_warning > 10;
2526 return;
2527 }
2528
2392 $NOW = Event::time; 2529 $NOW = Event::time;
2393 2530
2394 cf::server_tick; # one server iteration 2531 cf::server_tick; # one server iteration
2395 $RUNTIME += $TICK; 2532 $RUNTIME += $TICK;
2396 $NEXT_TICK += $TICK; 2533 $NEXT_TICK += $TICK;
2397 2534
2398 $WAIT_FOR_TICK->broadcast; 2535 $WAIT_FOR_TICK->broadcast;
2399 $WAIT_FOR_TICK_ONE->send if $WAIT_FOR_TICK_ONE->awaited; 2536 $WAIT_FOR_TICK_ONE->send if $WAIT_FOR_TICK_ONE->awaited;
2537
2538 Event::sweep;
2539 Coro::cede_notself;
2540
2541# my $AFTER = Event::time;
2542# warn $AFTER - $NOW;#d#
2400 2543
2401 # if we are delayed by four ticks or more, skip them all 2544 # if we are delayed by four ticks or more, skip them all
2402 $NEXT_TICK = Event::time if Event::time >= $NEXT_TICK + $TICK * 4; 2545 $NEXT_TICK = Event::time if Event::time >= $NEXT_TICK + $TICK * 4;
2403 2546
2404 $TICK_WATCHER->at ($NEXT_TICK); 2547 $TICK_WATCHER->at ($NEXT_TICK);
2405 $TICK_WATCHER->start; 2548 $TICK_WATCHER->start;
2406 }, 2549 },
2407); 2550);
2408 2551
2552{
2553 BDB::max_poll_time $TICK * 0.1;
2554 $BDB_POLL_WATCHER = Event->io (
2555 reentrant => 0,
2556 fd => BDB::poll_fileno,
2557 poll => 'r',
2558 prio => 0,
2559 data => WF_AUTOCANCEL,
2560 cb => \&BDB::poll_cb,
2561 );
2562 BDB::min_parallel 8;
2563
2564 BDB::set_sync_prepare {
2565 my $status;
2566 my $current = $Coro::current;
2567 (
2568 sub {
2569 $status = $!;
2570 $current->ready; undef $current;
2571 },
2572 sub {
2573 Coro::schedule while defined $current;
2574 $! = $status;
2575 },
2576 )
2577 };
2578
2579 unless ($DB_ENV) {
2580 $DB_ENV = BDB::db_env_create;
2581
2582 cf::sync_job {
2583 eval {
2584 BDB::db_env_open
2585 $DB_ENV,
2586 $BDB_ENV_DIR,
2587 BDB::INIT_LOCK | BDB::INIT_LOG | BDB::INIT_MPOOL | BDB::INIT_TXN
2588 | BDB::RECOVER | BDB::REGISTER | BDB::USE_ENVIRON | BDB::CREATE,
2589 0666;
2590
2591 cf::cleanup "db_env_open($BDB_ENV_DIR): $!" if $!;
2592
2593 $DB_ENV->set_flags (BDB::AUTO_COMMIT | BDB::REGION_INIT | BDB::TXN_NOSYNC, 1);
2594 $DB_ENV->set_lk_detect;
2595 };
2596
2597 cf::cleanup "db_env_open(db): $@" if $@;
2598 };
2599 }
2600}
2601
2602{
2603 IO::AIO::min_parallel 8;
2604
2605 undef $Coro::AIO::WATCHER;
2409IO::AIO::max_poll_time $TICK * 0.2; 2606 IO::AIO::max_poll_time $TICK * 0.1;
2410
2411$AIO_POLL_WATCHER = Event->io ( 2607 $AIO_POLL_WATCHER = Event->io (
2608 reentrant => 0,
2412 fd => IO::AIO::poll_fileno, 2609 fd => IO::AIO::poll_fileno,
2413 poll => 'r', 2610 poll => 'r',
2414 prio => 5, 2611 prio => 6,
2415 data => WF_AUTOCANCEL, 2612 data => WF_AUTOCANCEL,
2416 cb => \&IO::AIO::poll_cb, 2613 cb => \&IO::AIO::poll_cb,
2417); 2614 );
2615}
2418 2616
2419$WRITE_RUNTIME_WATCHER = Event->timer ( 2617$WRITE_RUNTIME_WATCHER = Event->timer (
2618 reentrant => 0,
2420 data => WF_AUTOCANCEL, 2619 data => WF_AUTOCANCEL,
2421 after => 0, 2620 after => 1,
2422 interval => 10, 2621 interval => 10,
2423 cb => sub { 2622 prio => 6, # keep it lowest so it acts like a watchdog
2424 (Coro::unblock_sub { 2623 cb => Coro::unblock_sub {
2425 write_runtime 2624 write_runtime
2426 or warn "ERROR: unable to write runtime file: $!"; 2625 or warn "ERROR: unable to write runtime file: $!";
2427 })->();
2428 }, 2626 },
2429); 2627);
2430 2628
2431END { cf::emergency_save } 2629END { cf::emergency_save }
2432 2630

Diff Legend

Removed lines
+ Added lines
< Changed lines
> Changed lines