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

Diff Legend

Removed lines
+ Added lines
< Changed lines
> Changed lines