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.205 by root, Mon Feb 5 18:29:20 2007 UTC vs.
Revision 1.264 by root, Sun May 6 05:44:48 2007 UTC

3use utf8; 3use utf8;
4use strict; 4use strict;
5 5
6use Symbol; 6use Symbol;
7use List::Util; 7use List::Util;
8use Socket;
8use Storable; 9use Storable;
10use Event;
9use Opcode; 11use Opcode;
10use Safe; 12use Safe;
11use Safe::Hole; 13use Safe::Hole;
12 14
13use Coro 3.5 (); 15use Coro 3.61 ();
16use Coro::State;
17use Coro::Handle;
14use Coro::Event; 18use Coro::Event;
15use Coro::Timer; 19use Coro::Timer;
16use Coro::Signal; 20use Coro::Signal;
17use Coro::Semaphore; 21use Coro::Semaphore;
18use Coro::AIO; 22use Coro::AIO;
23use Coro::Storable;
19 24
25use BDB ();
20use Data::Dumper; 26use Data::Dumper;
21use Digest::MD5; 27use Digest::MD5;
22use Fcntl; 28use Fcntl;
29use YAML::Syck ();
23use IO::AIO 2.32 (); 30use IO::AIO 2.32 ();
24use YAML::Syck ();
25use Time::HiRes; 31use Time::HiRes;
32use Compress::LZF;
26 33
34# configure various modules to our taste
35#
36$Storable::canonical = 1; # reduce rsync transfers
37Coro::State::cctx_stacksize 256000; # 1-2MB stack, for deep recursions in maze generator
38Compress::LZF::sfreeze_cr { }; # prime Compress::LZF so it does not use require later
39
27use Event; $Event::Eval = 1; # no idea why this is required, but it is 40$Event::Eval = 1; # no idea why this is required, but it is
28
29sub WF_AUTOCANCEL () { 1 } # automatically cancel this watcher on reload
30 41
31# work around bug in YAML::Syck - bad news for perl6, will it be as broken wrt. unicode? 42# work around bug in YAML::Syck - bad news for perl6, will it be as broken wrt. unicode?
32$YAML::Syck::ImplicitUnicode = 1; 43$YAML::Syck::ImplicitUnicode = 1;
33 44
34$Coro::main->prio (Coro::PRIO_MAX); # run main coroutine ("the server") with very high priority 45$Coro::main->prio (Coro::PRIO_MAX); # run main coroutine ("the server") with very high priority
46
47sub WF_AUTOCANCEL () { 1 } # automatically cancel this watcher on reload
35 48
36our %COMMAND = (); 49our %COMMAND = ();
37our %COMMAND_TIME = (); 50our %COMMAND_TIME = ();
38 51
39our @EXTS = (); # list of extension package names 52our @EXTS = (); # list of extension package names
40our %EXTCMD = (); 53our %EXTCMD = ();
41our %EXT_CORO = (); # coroutines bound to extensions 54our %EXT_CORO = (); # coroutines bound to extensions
42our %EXT_MAP = (); # pluggable maps 55our %EXT_MAP = (); # pluggable maps
43 56
57our $RELOAD; # number of reloads so far
44our @EVENT; 58our @EVENT;
45our $LIBDIR = datadir . "/ext";
46 59
47our $TICK = MAX_TIME * 1e-6; 60our $CONFDIR = confdir;
61our $DATADIR = datadir;
62our $LIBDIR = "$DATADIR/ext";
63our $PODDIR = "$DATADIR/pod";
64our $MAPDIR = "$DATADIR/" . mapdir;
65our $LOCALDIR = localdir;
66our $TMPDIR = "$LOCALDIR/" . tmpdir;
67our $UNIQUEDIR = "$LOCALDIR/" . uniquedir;
68our $PLAYERDIR = "$LOCALDIR/" . playerdir;
69our $RANDOMDIR = "$LOCALDIR/random";
70our $BDBDIR = "$LOCALDIR/db";
71
72our $TICK = MAX_TIME * 1e-6; # this is a CONSTANT(!)
48our $TICK_WATCHER; 73our $TICK_WATCHER;
49our $AIO_POLL_WATCHER; 74our $AIO_POLL_WATCHER;
50our $WRITE_RUNTIME_WATCHER; 75our $NEXT_RUNTIME_WRITE; # when should the runtime file be written
51our $NEXT_TICK; 76our $NEXT_TICK;
52our $NOW; 77our $NOW;
53our $USE_FSYNC = 1; # use fsync to write maps - default off 78our $USE_FSYNC = 1; # use fsync to write maps - default off
54 79
80our $BDB_POLL_WATCHER;
81our $DB_ENV;
82
55our %CFG; 83our %CFG;
56 84
57our $UPTIME; $UPTIME ||= time; 85our $UPTIME; $UPTIME ||= time;
58our $RUNTIME; 86our $RUNTIME;
59 87
60our %PLAYER; # all users 88our %PLAYER; # all users
61our %MAP; # all maps 89our %MAP; # all maps
62our $LINK_MAP; # the special {link} map, which is always available 90our $LINK_MAP; # the special {link} map, which is always available
63our $RANDOM_MAPS = cf::localdir . "/random";
64
65our $WAIT_FOR_TICK; $WAIT_FOR_TICK ||= new Coro::Signal;
66our $WAIT_FOR_TICK_ONE; $WAIT_FOR_TICK_ONE ||= new Coro::Signal;
67 91
68# used to convert map paths into valid unix filenames by replacing / by ∕ 92# used to convert map paths into valid unix filenames by replacing / by ∕
69our $PATH_SEP = "∕"; # U+2215, chosen purely for visual reasons 93our $PATH_SEP = "∕"; # U+2215, chosen purely for visual reasons
70 94
71binmode STDOUT; 95binmode STDOUT;
72binmode STDERR; 96binmode STDERR;
73 97
74# read virtual server time, if available 98# read virtual server time, if available
75unless ($RUNTIME || !-e cf::localdir . "/runtime") { 99unless ($RUNTIME || !-e "$LOCALDIR/runtime") {
76 open my $fh, "<", cf::localdir . "/runtime" 100 open my $fh, "<", "$LOCALDIR/runtime"
77 or die "unable to read runtime file: $!"; 101 or die "unable to read runtime file: $!";
78 $RUNTIME = <$fh> + 0.; 102 $RUNTIME = <$fh> + 0.;
79} 103}
80 104
81mkdir cf::localdir; 105mkdir $_
82mkdir cf::localdir . "/" . cf::playerdir; 106 for $LOCALDIR, $TMPDIR, $UNIQUEDIR, $PLAYERDIR, $RANDOMDIR, $BDBDIR;
83mkdir cf::localdir . "/" . cf::tmpdir;
84mkdir cf::localdir . "/" . cf::uniquedir;
85mkdir $RANDOM_MAPS;
86 107
87our $EMERGENCY_POSITION; 108our $EMERGENCY_POSITION;
88 109
89sub cf::map::normalise; 110sub cf::map::normalise;
90 111
101=item $cf::RUNTIME 122=item $cf::RUNTIME
102 123
103The time this server has run, starts at 0 and is increased by $cf::TICK on 124The time this server has run, starts at 0 and is increased by $cf::TICK on
104every server tick. 125every server tick.
105 126
106=item $cf::LIBDIR 127=item $cf::CONFDIR $cf::DATADIR $cf::LIBDIR $cf::PODDIR
128$cf::MAPDIR $cf::LOCALDIR $cf::TMPDIR $cf::UNIQUEDIR
129$cf::PLAYERDIR $cf::RANDOMDIR $cf::BDBDIR
107 130
108The perl library directory, where extensions and cf-specific modules can 131Various directories - "/etc", read-only install directory, perl-library
109be found. It will be added to C<@INC> automatically. 132directory, pod-directory, read-only maps directory, "/var", "/var/tmp",
133unique-items directory, player file directory, random maps directory and
134database environment.
110 135
111=item $cf::NOW 136=item $cf::NOW
112 137
113The time of the last (current) server tick. 138The time of the last (current) server tick.
114 139
119=item %cf::CFG 144=item %cf::CFG
120 145
121Configuration for the server, loaded from C</etc/crossfire/config>, or 146Configuration for the server, loaded from C</etc/crossfire/config>, or
122from wherever your confdir points to. 147from wherever your confdir points to.
123 148
124=item $cf::WAIT_FOR_TICK, $cf::WAIT_FOR_TICK_ONE 149=item cf::wait_for_tick, cf::wait_for_tick_begin
125 150
126These are Coro::Signal objects that are C<< ->broadcast >> (WAIT_FOR_TICK) 151These are functions that inhibit the current coroutine one tick. cf::wait_for_tick_begin only
127or C<< ->send >> (WAIT_FOR_TICK_ONE) on after normal server tick 152returns directly I<after> the tick processing (and consequently, can only wake one process
128processing has been done. Call C<< ->wait >> on them to maximise the 153per tick), while cf::wait_for_tick wakes up all waiters after tick processing.
129window of cpu time available, or simply to synchronise to the server tick.
130 154
131=back 155=back
132 156
133=cut 157=cut
134 158
135BEGIN { 159BEGIN {
136 *CORE::GLOBAL::warn = sub { 160 *CORE::GLOBAL::warn = sub {
137 my $msg = join "", @_; 161 my $msg = join "", @_;
138 utf8::encode $msg;
139 162
140 $msg .= "\n" 163 $msg .= "\n"
141 unless $msg =~ /\n$/; 164 unless $msg =~ /\n$/;
142 165
166 $msg =~ s/([\x00-\x08\x0b-\x1f])/sprintf "\\x%02x", ord $1/ge;
167
168 utf8::encode $msg;
143 LOG llevError, $msg; 169 LOG llevError, $msg;
144 }; 170 };
145} 171}
146 172
147@safe::cf::global::ISA = @cf::global::ISA = 'cf::attachable'; 173@safe::cf::global::ISA = @cf::global::ISA = 'cf::attachable';
193 $d =~ s/([\x00-\x07\x09\x0b\x0c\x0e-\x1f])/sprintf "\\x%02x", ord($1)/ge; 219 $d =~ s/([\x00-\x07\x09\x0b\x0c\x0e-\x1f])/sprintf "\\x%02x", ord($1)/ge;
194 $d 220 $d
195 } || "[unable to dump $_[0]: '$@']"; 221 } || "[unable to dump $_[0]: '$@']";
196} 222}
197 223
198use JSON::Syck (); # TODO# replace by JSON::PC once working 224use JSON::XS qw(to_json from_json); # TODO# replace by JSON::PC once working
199 225
200=item $ref = cf::from_json $json 226=item $ref = cf::from_json $json
201 227
202Converts a JSON string into the corresponding perl data structure. 228Converts a JSON string into the corresponding perl data structure.
203 229
204=cut
205
206sub from_json($) {
207 $JSON::Syck::ImplicitUnicode = 1; # work around JSON::Syck bugs
208 JSON::Syck::Load $_[0]
209}
210
211=item $json = cf::to_json $ref 230=item $json = cf::to_json $ref
212 231
213Converts a perl data structure into its JSON representation. 232Converts a perl data structure into its JSON representation.
214
215=cut
216
217sub to_json($) {
218 $JSON::Syck::ImplicitUnicode = 0; # work around JSON::Syck bugs
219 JSON::Syck::Dump $_[0]
220}
221 233
222=item cf::lock_wait $string 234=item cf::lock_wait $string
223 235
224Wait until the given lock is available. See cf::lock_acquire. 236Wait until the given lock is available. See cf::lock_acquire.
225 237
231returned. 243returned.
232 244
233Lock names should begin with a unique identifier (for example, cf::map::find 245Lock names should begin with a unique identifier (for example, cf::map::find
234uses map_find and cf::map::load uses map_load). 246uses map_find and cf::map::load uses map_load).
235 247
248=item $locked = cf::lock_active $string
249
250Return true if the lock is currently active, i.e. somebody has locked it.
251
236=cut 252=cut
237 253
238our %LOCK; 254our %LOCK;
239 255
240sub lock_wait($) { 256sub lock_wait($) {
259 # wake up all waiters, to be on the safe side 275 # wake up all waiters, to be on the safe side
260 $_->ready for @{ delete $LOCK{$key} }; 276 $_->ready for @{ delete $LOCK{$key} };
261 } 277 }
262} 278}
263 279
280sub lock_active($) {
281 my ($key) = @_;
282
283 ! ! $LOCK{$key}
284}
285
264sub freeze_mainloop { 286sub freeze_mainloop {
265 return unless $TICK_WATCHER->is_active; 287 return unless $TICK_WATCHER->is_active;
266 288
267 my $guard = Coro::guard { 289 my $guard = Coro::guard {
268 $TICK_WATCHER->start; 290 $TICK_WATCHER->start;
269 $WRITE_RUNTIME_WATCHER->start;
270 }; 291 };
271 $WRITE_RUNTIME_WATCHER->stop;
272 $TICK_WATCHER->stop; 292 $TICK_WATCHER->stop;
273 $guard 293 $guard
274} 294}
275 295
276=item cf::async { BLOCK } 296=item cf::async { BLOCK }
347 367
348 $coro 368 $coro
349} 369}
350 370
351sub write_runtime { 371sub write_runtime {
352 my $runtime = cf::localdir . "/runtime"; 372 my $runtime = "$LOCALDIR/runtime";
353 373
374 # first touch the runtime file to show we are still running:
375 # the fsync below can take a very very long time.
376
377 warn "touching runtime...\n";#d#
378 if (my $fh = aio_open $runtime, O_WRONLY, 0) {
379 utime undef, undef, $fh;
380 }
381
382 my $guard = cf::lock_acquire "write_runtime";
383
384 warn "starting to write runtime...\n";#d#
354 my $fh = aio_open "$runtime~", O_WRONLY | O_CREAT, 0644 385 my $fh = aio_open "$runtime~", O_WRONLY | O_CREAT, 0644
355 or return; 386 or return;
356 387
357 my $value = $cf::RUNTIME + 90 + 10; 388 my $value = $cf::RUNTIME + 90 + 10;
358 # 10 is the runtime save interval, for a monotonic clock 389 # 10 is the runtime save interval, for a monotonic clock
363 394
364 # always fsync - this file is important 395 # always fsync - this file is important
365 aio_fsync $fh 396 aio_fsync $fh
366 and return; 397 and return;
367 398
399 # touch it again to show we are up-to-date
400 utime undef, undef, $fh;
401
368 close $fh 402 close $fh
369 or return; 403 or return;
370 404
371 aio_rename "$runtime~", $runtime 405 aio_rename "$runtime~", $runtime
372 and return; 406 and return;
373 407
408 warn "... done writing runtime.\n";#d#
409
374 1 410 1
411}
412
413=item cf::datalog type => key => value, ...
414
415Log a datalog packet of the given type with the given key-value pairs.
416
417=cut
418
419sub datalog($@) {
420 my ($type, %kv) = @_;
421 warn "DATALOG ", JSON::XS->new->ascii->encode ({ %kv, type => $type });
375} 422}
376 423
377=back 424=back
378 425
379=cut 426=cut
778 } 825 }
779 } else { 826 } else {
780 aio_unlink $filename; 827 aio_unlink $filename;
781 aio_unlink "$filename.pst"; 828 aio_unlink "$filename.pst";
782 } 829 }
783
784 #d##TODO# nuke non .map-files if exist
785 if ($filename =~ s/\.map$//) {
786 aio_unlink $filename;
787 aio_unlink "$filename.pst";
788 }
789 } 830 }
790} 831}
791 832
792sub object_freezer_as_string { 833sub object_freezer_as_string {
793 my ($rdata, $objs) = @_; 834 my ($rdata, $objs) = @_;
799 840
800sub object_thawer_load { 841sub object_thawer_load {
801 my ($filename) = @_; 842 my ($filename) = @_;
802 843
803 my ($data, $av); 844 my ($data, $av);
804
805 #d#TODO remove .map if file does not exist
806 aio_stat $filename and $filename =~ s/\.map$//;
807 845
808 (aio_load $filename, $data) >= 0 846 (aio_load $filename, $data) >= 0
809 or return; 847 or return;
810 848
811 unless (aio_stat "$filename.pst") { 849 unless (aio_stat "$filename.pst") {
950Returns the given player object, loading it if necessary (might block). 988Returns the given player object, loading it if necessary (might block).
951 989
952=cut 990=cut
953 991
954sub playerdir($) { 992sub playerdir($) {
955 cf::localdir 993 "$PLAYERDIR/"
956 . "/"
957 . cf::playerdir
958 . "/"
959 . (ref $_[0] ? $_[0]->ob->name : $_[0]) 994 . (ref $_[0] ? $_[0]->ob->name : $_[0])
960} 995}
961 996
962sub path($) { 997sub path($) {
963 my $login = ref $_[0] ? $_[0]->ob->name : $_[0]; 998 my $login = ref $_[0] ? $_[0]->ob->name : $_[0];
964 999
965 (playerdir $login) . "/$login.pl" 1000 (playerdir $login) . "/playerdata"
966} 1001}
967 1002
968sub find_active($) { 1003sub find_active($) {
969 $cf::PLAYER{$_[0]} 1004 $cf::PLAYER{$_[0]}
970 and $cf::PLAYER{$_[0]}->active 1005 and $cf::PLAYER{$_[0]}->active
983 my $login = $_[0]; 1018 my $login = $_[0];
984 1019
985 my $guard = cf::lock_acquire "user_find:$login"; 1020 my $guard = cf::lock_acquire "user_find:$login";
986 1021
987 $cf::PLAYER{$_[0]} || do { 1022 $cf::PLAYER{$_[0]} || do {
1023 # rename old playerfiles to new ones
1024 #TODO: remove when no longer required
1025 aio_link +(playerdir $login) . "/$login.pl.pst", (playerdir $login) . "/playerdata.pst";
1026 aio_link +(playerdir $login) . "/$login.pl" , (playerdir $login) . "/playerdata";
1027 aio_unlink +(playerdir $login) . "/$login.pl.pst";
1028 aio_unlink +(playerdir $login) . "/$login.pl";
1029
988 my $pl = load_pl path $login 1030 my $pl = load_pl path $login
989 or return; 1031 or return;
990 $cf::PLAYER{$login} = $pl 1032 $cf::PLAYER{$login} = $pl
991 } 1033 }
992 } 1034 }
1029 1071
1030=cut 1072=cut
1031 1073
1032sub quit_character { 1074sub quit_character {
1033 my ($pl) = @_; 1075 my ($pl) = @_;
1076
1077 my $name = $pl->ob->name;
1034 1078
1035 $pl->{deny_save} = 1; 1079 $pl->{deny_save} = 1;
1036 $pl->password ("*"); # this should lock out the player until we nuked the dir 1080 $pl->password ("*"); # this should lock out the player until we nuked the dir
1037 1081
1038 $pl->invoke (cf::EVENT_PLAYER_LOGOUT, 1) if $pl->active; 1082 $pl->invoke (cf::EVENT_PLAYER_LOGOUT, 1) if $pl->active;
1043 my $path = playerdir $pl; 1087 my $path = playerdir $pl;
1044 my $temp = "$path~$cf::RUNTIME~deleting~"; 1088 my $temp = "$path~$cf::RUNTIME~deleting~";
1045 aio_rename $path, $temp; 1089 aio_rename $path, $temp;
1046 delete $cf::PLAYER{$pl->ob->name}; 1090 delete $cf::PLAYER{$pl->ob->name};
1047 $pl->destroy; 1091 $pl->destroy;
1092
1093 my $prefix = qr<^~\Q$name\E/>;
1094
1095 # nuke player maps
1096 $cf::MAP{$_}->nuke for grep /$prefix/, keys %cf::MAP;
1097
1048 IO::AIO::aio_rmtree $temp; 1098 IO::AIO::aio_rmtree $temp;
1099}
1100
1101=item $pl->kick
1102
1103Kicks a player out of the game. This destroys the connection.
1104
1105=cut
1106
1107sub kick {
1108 my ($pl, $kicker) = @_;
1109
1110 $pl->invoke (cf::EVENT_PLAYER_KICK, $kicker);
1111 $pl->killer ("kicked");
1112 $pl->ns->destroy;
1049} 1113}
1050 1114
1051=item cf::player::list_logins 1115=item cf::player::list_logins
1052 1116
1053Returns am arrayref of all valid playernames in the system, can take a 1117Returns am arrayref of all valid playernames in the system, can take a
1054while and may block, so not sync_job-capable, ever. 1118while and may block, so not sync_job-capable, ever.
1055 1119
1056=cut 1120=cut
1057 1121
1058sub list_logins { 1122sub list_logins {
1059 my $dirs = aio_readdir cf::localdir . "/" . cf::playerdir 1123 my $dirs = aio_readdir $PLAYERDIR
1060 or return []; 1124 or return [];
1061 1125
1062 my @logins; 1126 my @logins;
1063 1127
1064 for my $login (@$dirs) { 1128 for my $login (@$dirs) {
1099 } 1163 }
1100 1164
1101 \@paths 1165 \@paths
1102} 1166}
1103 1167
1104=item $player->ext_reply ($msgid, $msgtype, %msg) 1168=item $player->ext_reply ($msgid, %msg)
1105 1169
1106Sends an ext reply to the player. 1170Sends an ext reply to the player.
1107 1171
1108=cut 1172=cut
1109 1173
1110sub ext_reply($$$%) { 1174sub ext_reply($$%) {
1111 my ($self, $id, %msg) = @_; 1175 my ($self, $id, %msg) = @_;
1112 1176
1113 $msg{msgid} = $id; 1177 $msg{msgid} = $id;
1114 1178
1115 $self->send ("ext " . cf::to_json \%msg); 1179 $self->send ("ext " . cf::to_json \%msg);
1116} 1180}
1117 1181
1118package cf; 1182=item $player->ext_event ($type, %msg)
1183
1184Sends an ext event to the client.
1185
1186=cut
1187
1188sub ext_event($$%) {
1189 my ($self, $type, %msg) = @_;
1190
1191 $self->ns->ext_event ($type, %msg);
1192}
1193
1194=head3 cf::region
1195
1196=over 4
1197
1198=cut
1199
1200package cf::region;
1201
1202=item cf::region::find_by_path $path
1203
1204Tries to decuce the probable region for a map knowing only its path.
1205
1206=cut
1207
1208sub find_by_path($) {
1209 my ($path) = @_;
1210
1211 my ($match, $specificity);
1212
1213 for my $region (list) {
1214 if ($region->match && $path =~ $region->match) {
1215 ($match, $specificity) = ($region, $region->specificity)
1216 if $region->specificity > $specificity;
1217 }
1218 }
1219
1220 $match
1221}
1119 1222
1120=back 1223=back
1121
1122 1224
1123=head3 cf::map 1225=head3 cf::map
1124 1226
1125=over 4 1227=over 4
1126 1228
1264 1366
1265# the original (read-only) location 1367# the original (read-only) location
1266sub load_path { 1368sub load_path {
1267 my ($self) = @_; 1369 my ($self) = @_;
1268 1370
1269 sprintf "%s/%s/%s.map", cf::datadir, cf::mapdir, $self->{path} 1371 "$MAPDIR/$self->{path}.map"
1270} 1372}
1271 1373
1272# the temporary/swap location 1374# the temporary/swap location
1273sub save_path { 1375sub save_path {
1274 my ($self) = @_; 1376 my ($self) = @_;
1275 1377
1276 (my $path = $_[0]{path}) =~ s/\//$PATH_SEP/g; 1378 (my $path = $_[0]{path}) =~ s/\//$PATH_SEP/g;
1277 sprintf "%s/%s/%s.map", cf::localdir, cf::tmpdir, $path 1379 "$TMPDIR/$path.map"
1278} 1380}
1279 1381
1280# the unique path, undef == no special unique path 1382# the unique path, undef == no special unique path
1281sub uniq_path { 1383sub uniq_path {
1282 my ($self) = @_; 1384 my ($self) = @_;
1283 1385
1284 (my $path = $_[0]{path}) =~ s/\//$PATH_SEP/g; 1386 (my $path = $_[0]{path}) =~ s/\//$PATH_SEP/g;
1285 sprintf "%s/%s/%s", cf::localdir, cf::uniquedir, $path 1387 "$UNIQUEDIR/$path"
1286} 1388}
1287 1389
1288# and all this just because we cannot iterate over 1390# and all this just because we cannot iterate over
1289# all maps in C++... 1391# all maps in C++...
1290sub change_all_map_light { 1392sub change_all_map_light {
1298 my ($self) = @_; 1400 my ($self) = @_;
1299 1401
1300 utf8::encode (my $save = $self->save_path); 1402 utf8::encode (my $save = $self->save_path);
1301 IO::AIO::aioreq_pri 4; Coro::AIO::aio_unlink $save; 1403 IO::AIO::aioreq_pri 4; Coro::AIO::aio_unlink $save;
1302 IO::AIO::aioreq_pri 4; Coro::AIO::aio_unlink "$save.pst"; 1404 IO::AIO::aioreq_pri 4; Coro::AIO::aio_unlink "$save.pst";
1303
1304 #d#TODO remove .map and also nuke
1305 $save =~ s/\.map// or return;#d#
1306 IO::AIO::aioreq_pri 4; Coro::AIO::aio_unlink $save;#d#
1307 IO::AIO::aioreq_pri 4; Coro::AIO::aio_unlink "$save.pst";#d#
1308} 1405}
1309 1406
1310sub load_header_from($) { 1407sub load_header_from($) {
1311 my ($self, $path) = @_; 1408 my ($self, $path) = @_;
1312 1409
1362 $self->load_header_orig 1459 $self->load_header_orig
1363 or return; 1460 or return;
1364 $self->prepare_orig; 1461 $self->prepare_orig;
1365 } 1462 }
1366 1463
1464 $self->default_region (cf::region::find_by_path $self->{path})
1465 unless $self->default_region;
1466
1367 1 1467 1
1368} 1468}
1369 1469
1370sub find; 1470sub find;
1371sub find { 1471sub find {
1404 my ($self) = @_; 1504 my ($self) = @_;
1405 1505
1406 local $self->{deny_reset} = 1; # loading can take a long time 1506 local $self->{deny_reset} = 1; # loading can take a long time
1407 1507
1408 my $path = $self->{path}; 1508 my $path = $self->{path};
1509
1510 {
1409 my $guard = cf::lock_acquire "map_load:$path"; 1511 my $guard = cf::lock_acquire "map_load:$path";
1410 1512
1411 return if $self->in_memory != cf::MAP_SWAPPED; 1513 return if $self->in_memory != cf::MAP_SWAPPED;
1412 1514
1413 $self->in_memory (cf::MAP_LOADING); 1515 $self->in_memory (cf::MAP_LOADING);
1414 1516
1415 $self->alloc; 1517 $self->alloc;
1416 1518
1417 $self->pre_load; 1519 $self->pre_load;
1418
1419 $self->_load_objects ($self->{load_path}, 1)
1420 or return;
1421
1422 $self->set_object_flag (cf::FLAG_OBJ_ORIGINAL, 1)
1423 if delete $self->{load_original};
1424
1425 if (my $uniq = $self->uniq_path) {
1426 utf8::encode $uniq;
1427 if (aio_open $uniq, O_RDONLY, 0) {
1428 $self->clear_unique_items;
1429 $self->_load_objects ($uniq, 0);
1430 }
1431 }
1432
1433 Coro::cede;
1434
1435 # now do the right thing for maps
1436 $self->link_multipart_objects;
1437
1438 unless ($self->{deny_activate}) {
1439 $self->decay_objects;
1440 $self->fix_auto_apply;
1441 $self->update_buttons;
1442 Coro::cede; 1520 Coro::cede;
1443 $self->set_darkness_map; 1521
1522 $self->_load_objects ($self->{load_path}, 1)
1523 or return;
1524
1525 $self->set_object_flag (cf::FLAG_OBJ_ORIGINAL, 1)
1526 if delete $self->{load_original};
1527
1528 if (my $uniq = $self->uniq_path) {
1529 utf8::encode $uniq;
1530 if (aio_open $uniq, O_RDONLY, 0) {
1531 $self->clear_unique_items;
1532 $self->_load_objects ($uniq, 0);
1533 }
1534 }
1535
1536 Coro::cede;
1537 # now do the right thing for maps
1538 $self->link_multipart_objects;
1444 $self->difficulty ($self->estimate_difficulty) 1539 $self->difficulty ($self->estimate_difficulty)
1445 unless $self->difficulty; 1540 unless $self->difficulty;
1446 Coro::cede; 1541 Coro::cede;
1542
1543 unless ($self->{deny_activate}) {
1544 $self->decay_objects;
1545 $self->fix_auto_apply;
1546 $self->update_buttons;
1547 Coro::cede;
1548 $self->set_darkness_map;
1549 Coro::cede;
1447 $self->activate; 1550 $self->activate;
1551 }
1552
1553 $self->in_memory (cf::MAP_IN_MEMORY);
1448 } 1554 }
1449 1555
1450 $self->post_load; 1556 $self->post_load;
1451
1452 $self->in_memory (cf::MAP_IN_MEMORY);
1453} 1557}
1454 1558
1455sub customise_for { 1559sub customise_for {
1456 my ($self, $ob) = @_; 1560 my ($self, $ob) = @_;
1457 1561
1600 return if $self->players; 1704 return if $self->players;
1601 return if $self->isa ("ext::map_per_player");#d# 1705 return if $self->isa ("ext::map_per_player");#d#
1602 1706
1603 warn "resetting map ", $self->path;#d# 1707 warn "resetting map ", $self->path;#d#
1604 1708
1709 $self->in_memory (cf::MAP_SWAPPED);
1710
1711 # need to save uniques path
1712 unless ($self->{deny_save}) {
1713 my $uniq = $self->uniq_path; utf8::encode $uniq;
1714
1715 $self->_save_objects ($uniq, cf::IO_UNIQUES)
1716 if $uniq;
1717 }
1718
1605 delete $cf::MAP{$self->path}; 1719 delete $cf::MAP{$self->path};
1606 1720
1607 $self->in_memory (cf::MAP_SWAPPED);
1608 $self->clear; 1721 $self->clear;
1609 1722
1610 $_->clear_links_to ($self) for values %cf::MAP; 1723 $_->clear_links_to ($self) for values %cf::MAP;
1611 1724
1612 $self->unlink_save; 1725 $self->unlink_save;
1639instantiated unique items. May block. 1752instantiated unique items. May block.
1640 1753
1641=cut 1754=cut
1642 1755
1643sub unique_maps() { 1756sub unique_maps() {
1644 my $files = aio_readdir cf::localdir . "/" . cf::uniquedir 1757 my $files = aio_readdir $UNIQUEDIR
1645 or return; 1758 or return;
1646 1759
1647 my @paths; 1760 my @paths;
1648 1761
1649 for (@$files) { 1762 for (@$files) {
1802 $map->load; 1915 $map->load;
1803 $map->load_diag; 1916 $map->load_diag;
1804 1917
1805 return unless $self->contr->active; 1918 return unless $self->contr->active;
1806 $self->activate_recursive; 1919 $self->activate_recursive;
1920
1921 local $self->{_prev_pos} = $link_pos; # ugly hack for rent.ext
1807 $self->enter_map ($map, $x, $y); 1922 $self->enter_map ($map, $x, $y);
1808} 1923}
1809 1924
1810cf::player->attach ( 1925cf::player->attach (
1811 on_logout => sub { 1926 on_logout => sub {
1824 # try to abort aborted map switching on player login :) 1939 # try to abort aborted map switching on player login :)
1825 # should happen only on crashes 1940 # should happen only on crashes
1826 if ($pl->ob->{_link_pos}) { 1941 if ($pl->ob->{_link_pos}) {
1827 $pl->ob->enter_link; 1942 $pl->ob->enter_link;
1828 (async { 1943 (async {
1829 # we need this sleep as the login has a concurrent enter_exit running
1830 # and this sleep increases chances of the player not ending up in scorn
1831 $pl->ob->reply (undef, 1944 $pl->ob->reply (undef,
1832 "There was an internal problem at your last logout, " 1945 "There was an internal problem at your last logout, "
1833 . "the server will try to bring you to your intended destination in a second.", 1946 . "the server will try to bring you to your intended destination in a second.",
1834 cf::NDI_RED); 1947 cf::NDI_RED);
1948 # we need this sleep as the login has a concurrent enter_exit running
1949 # and this sleep increases chances of the player not ending up in scorn
1835 Coro::Timer::sleep 1; 1950 Coro::Timer::sleep 1;
1836 $pl->ob->leave_link; 1951 $pl->ob->leave_link;
1837 })->prio (2); 1952 })->prio (2);
1838 } 1953 }
1839 }, 1954 },
1903 2018
1904 $rmp->{random_seed} ||= $exit->random_seed; 2019 $rmp->{random_seed} ||= $exit->random_seed;
1905 2020
1906 my $data = cf::to_json $rmp; 2021 my $data = cf::to_json $rmp;
1907 my $md5 = Digest::MD5::md5_hex $data; 2022 my $md5 = Digest::MD5::md5_hex $data;
1908 my $meta = "$cf::RANDOM_MAPS/$md5.meta"; 2023 my $meta = "$RANDOMDIR/$md5.meta";
1909 2024
1910 if (my $fh = aio_open "$meta~", O_WRONLY | O_CREAT, 0666) { 2025 if (my $fh = aio_open "$meta~", O_WRONLY | O_CREAT, 0666) {
1911 aio_write $fh, 0, (length $data), $data, 0; 2026 aio_write $fh, 0, (length $data), $data, 0;
1912 undef $fh; 2027 undef $fh;
1913 aio_rename "$meta~", $meta; 2028 aio_rename "$meta~", $meta;
1922 2037
1923 return unless $self->type == cf::PLAYER; 2038 return unless $self->type == cf::PLAYER;
1924 2039
1925 if ($exit->slaying eq "/!") { 2040 if ($exit->slaying eq "/!") {
1926 #TODO: this should de-fi-ni-te-ly not be a sync-job 2041 #TODO: this should de-fi-ni-te-ly not be a sync-job
2042 # the problem is that $exit might not survive long enough
2043 # so it needs to be done right now, right here
1927 cf::sync_job { prepare_random_map $exit }; 2044 cf::sync_job { prepare_random_map $exit };
1928 } 2045 }
1929 2046
1930 my $slaying = cf::map::normalise $exit->slaying, $exit->map && $exit->map->path; 2047 my $slaying = cf::map::normalise $exit->slaying, $exit->map && $exit->map->path;
1931 my $hp = $exit->stats->hp; 2048 my $hp = $exit->stats->hp;
1939 $self->goto ($slaying, $hp, $sp); 2056 $self->goto ($slaying, $hp, $sp);
1940 2057
1941 1; 2058 1;
1942 }) { 2059 }) {
1943 $self->message ("Something went wrong deep within the crossfire server. " 2060 $self->message ("Something went wrong deep within the crossfire server. "
1944 . "I'll try to bring you back to the map you were before. " 2061 . "I'll try to bring you back to the map you were before. "
1945 . "Please report this to the dungeon master!", 2062 . "Please report this to the dungeon master!",
1946 cf::NDI_UNIQUE | cf::NDI_RED); 2063 cf::NDI_UNIQUE | cf::NDI_RED);
1947 2064
1948 warn "ERROR in enter_exit: $@"; 2065 warn "ERROR in enter_exit: $@";
1949 $self->leave_link; 2066 $self->leave_link;
1950 } 2067 }
1951 })->prio (1); 2068 })->prio (1);
1964 2081
1965sub cf::client::send_drawinfo { 2082sub cf::client::send_drawinfo {
1966 my ($self, $text, $flags) = @_; 2083 my ($self, $text, $flags) = @_;
1967 2084
1968 utf8::encode $text; 2085 utf8::encode $text;
1969 $self->send_packet (sprintf "drawinfo %d %s", $flags, $text); 2086 $self->send_packet (sprintf "drawinfo %d %s", $flags || cf::NDI_BLACK, $text);
1970} 2087}
1971 2088
2089=item $client->ext_event ($type, %msg)
2090
2091Sends an exti event to the client.
2092
2093=cut
2094
2095sub cf::client::ext_event($$%) {
2096 my ($self, $type, %msg) = @_;
2097
2098 $msg{msgtype} = "event_$type";
2099 $self->send_packet ("ext " . cf::to_json \%msg);
2100}
1972 2101
1973=item $success = $client->query ($flags, "text", \&cb) 2102=item $success = $client->query ($flags, "text", \&cb)
1974 2103
1975Queues a query to the client, calling the given callback with 2104Queues a query to the client, calling the given callback with
1976the reply text on a reply. flags can be C<cf::CS_QUERY_YESNO>, 2105the reply text on a reply. flags can be C<cf::CS_QUERY_YESNO>,
2073 2202
2074# here we export the classes and methods available to script code 2203# here we export the classes and methods available to script code
2075 2204
2076=pod 2205=pod
2077 2206
2078The following fucntions and emthods are available within a safe environment: 2207The following functions and methods are available within a safe environment:
2079 2208
2080 cf::object contr pay_amount pay_player map 2209 cf::object contr pay_amount pay_player map
2081 cf::object::player player 2210 cf::object::player player
2082 cf::player peaceful 2211 cf::player peaceful
2083 cf::map trigger 2212 cf::map trigger
2168############################################################################# 2297#############################################################################
2169 2298
2170=head2 EXTENSION DATABASE SUPPORT 2299=head2 EXTENSION DATABASE SUPPORT
2171 2300
2172Crossfire maintains a very simple database for extension use. It can 2301Crossfire maintains a very simple database for extension use. It can
2173currently store anything that can be serialised using Storable, which 2302currently store binary data only (use Compress::LZF::sfreeze_cr/sthaw to
2174excludes objects. 2303convert to/from binary).
2175 2304
2176The parameter C<$family> should best start with the name of the extension 2305The parameter C<$family> should best start with the name of the extension
2177using it, it should be unique. 2306using it, it should be unique.
2178 2307
2179=over 4 2308=over 4
2180 2309
2181=item $hashref = cf::db_get $family
2182
2183Return a hashref for use by the extension C<$family>, which can be
2184modified. After modifications, you have to call C<cf::db_dirty> or
2185C<cf::db_sync>.
2186
2187=item $value = cf::db_get $family => $key 2310=item $value = cf::db_get $family => $key
2188 2311
2189Returns a single value from the database 2312Returns a single value from the database.
2190
2191=item cf::db_put $family => $hashref
2192
2193Stores the given family hashref into the database. Updates are delayed, if
2194you want the data to be synced to disk immediately, use C<cf::db_sync>.
2195 2313
2196=item cf::db_put $family => $key => $value 2314=item cf::db_put $family => $key => $value
2197 2315
2198Stores the given C<$value> in the family hash. Updates are delayed, if you 2316Stores the given C<$value> in the family.
2199want the data to be synced to disk immediately, use C<cf::db_sync>.
2200
2201=item cf::db_dirty
2202
2203Marks the database as dirty, to be updated at a later time.
2204
2205=item cf::db_sync
2206
2207Immediately write the database to disk I<if it is dirty>.
2208 2317
2209=cut 2318=cut
2210 2319
2211our $DB; 2320our $DB;
2212 2321
2213{ 2322sub db_init {
2214 my $path = cf::localdir . "/database.pst"; 2323 unless ($DB) {
2324 $DB = BDB::db_create $DB_ENV;
2215 2325
2216 sub db_load() { 2326 cf::sync_job {
2217 $DB = stat $path ? Storable::retrieve $path : { }; 2327 eval {
2218 } 2328 $DB->set_flags (BDB::CHKSUM);
2219 2329
2220 my $pid; 2330 BDB::db_open $DB, undef, "db", undef, BDB::BTREE,
2221 2331 BDB::CREATE | BDB::AUTO_COMMIT, 0666;
2222 sub db_save() { 2332 cf::cleanup "db_open(db): $!" if $!;
2223 waitpid $pid, 0 if $pid; 2333 };
2224 if (0 == ($pid = fork)) { 2334 cf::cleanup "db_open(db): $@" if $@;
2225 $DB->{_meta}{version} = 1;
2226 Storable::nstore $DB, "$path~";
2227 rename "$path~", $path;
2228 cf::_exit 0 if defined $pid;
2229 } 2335 };
2230 } 2336 }
2337}
2231 2338
2232 my $dirty;
2233
2234 sub db_sync() {
2235 db_save if $dirty;
2236 undef $dirty;
2237 }
2238
2239 my $idle = Event->idle (
2240 reentrant => 0,
2241 min => 10,
2242 max => 20,
2243 repeat => 0,
2244 data => WF_AUTOCANCEL,
2245 cb => \&db_sync,
2246 );
2247
2248 sub db_dirty() {
2249 $dirty = 1;
2250 $idle->start;
2251 }
2252
2253 sub db_get($;$) { 2339sub db_get($$) {
2254 @_ >= 2 2340 my $key = "$_[0]/$_[1]";
2255 ? $DB->{$_[0]}{$_[1]}
2256 : ($DB->{$_[0]} ||= { })
2257 }
2258 2341
2342 cf::sync_job {
2343 BDB::db_get $DB, undef, $key, my $data;
2344
2345 $! ? ()
2346 : $data
2347 }
2348}
2349
2259 sub db_put($$;$) { 2350sub db_put($$$) {
2260 if (@_ >= 3) { 2351 BDB::dbreq_pri 4;
2261 $DB->{$_[0]}{$_[1]} = $_[2]; 2352 BDB::db_put $DB, undef, "$_[0]/$_[1]", $_[2], 0, sub { };
2262 } else { 2353}
2263 $DB->{$_[0]} = $_[1];
2264 }
2265 db_dirty;
2266 }
2267 2354
2268 cf::global->attach ( 2355=item cf::cache $id => [$paths...], $processversion => $process
2269 prio => 10000, 2356
2270 on_cleanup => sub { 2357Generic caching function that returns the value of the resource $id,
2271 db_sync; 2358caching and regenerating as required.
2359
2360This function can block.
2361
2362=cut
2363
2364sub cache {
2365 my ($id, $src, $processversion, $process) = @_;
2366
2367 my $meta =
2368 join "\x00",
2369 $processversion,
2370 map {
2371 aio_stat $_
2372 and Carp::croak "$_: $!";
2373
2374 ($_, (stat _)[7,9])
2375 } @$src;
2376
2377 my $dbmeta = db_get cache => "$id/meta";
2378 if ($dbmeta ne $meta) {
2379 # changed, we may need to process
2380
2381 my @data;
2382 my $md5;
2383
2384 for (0 .. $#$src) {
2385 0 <= aio_load $src->[$_], $data[$_]
2386 or Carp::croak "$src->[$_]: $!";
2272 }, 2387 }
2273 ); 2388
2389 # if processing is expensive, check
2390 # checksum first
2391 if (1) {
2392 $md5 =
2393 join "\x00",
2394 $processversion,
2395 map {
2396 Coro::cede;
2397 ($src->[$_], Digest::MD5::md5_hex $data[$_])
2398 } 0.. $#$src;
2399
2400
2401 my $dbmd5 = db_get cache => "$id/md5";
2402 if ($dbmd5 eq $md5) {
2403 db_put cache => "$id/meta", $meta;
2404
2405 return db_get cache => "$id/data";
2406 }
2407 }
2408
2409 my $t1 = Time::HiRes::time;
2410 my $data = $process->(\@data);
2411 my $t2 = Time::HiRes::time;
2412
2413 warn "cache: '$id' processed in ", $t2 - $t1, "s\n";
2414
2415 db_put cache => "$id/data", $data;
2416 db_put cache => "$id/md5" , $md5;
2417 db_put cache => "$id/meta", $meta;
2418
2419 return $data;
2420 }
2421
2422 db_get cache => "$id/data"
2274} 2423}
2424
2425=item fork_call { }, $args
2426
2427Executes the given code block with the given arguments in a seperate
2428process, returning the results. Everything must be serialisable with
2429Coro::Storable. May, of course, block. Note that the executed sub may
2430never block itself or use any form of Event handling.
2431
2432=cut
2433
2434sub fork_call(&@) {
2435 my ($cb, @args) = @_;
2436
2437# socketpair my $fh1, my $fh2, Socket::AF_UNIX, Socket::SOCK_STREAM, Socket::PF_UNSPEC
2438# or die "socketpair: $!";
2439 pipe my $fh1, my $fh2
2440 or die "pipe: $!";
2441
2442 if (my $pid = fork) {
2443 close $fh2;
2444
2445 my $res = (Coro::Handle::unblock $fh1)->readline (undef);
2446 $res = Coro::Storable::thaw $res;
2447
2448 waitpid $pid, 0; # should not block anymore, we expect the child to simply behave
2449
2450 die $$res unless "ARRAY" eq ref $res;
2451
2452 return wantarray ? @$res : $res->[-1];
2453 } else {
2454 reset_signals;
2455 local $SIG{__WARN__};
2456 local $SIG{__DIE__};
2457 eval {
2458 close $fh1;
2459
2460 my @res = eval { $cb->(@args) };
2461 syswrite $fh2, Coro::Storable::freeze +($@ ? \"$@" : \@res);
2462 };
2463
2464 warn $@ if $@;
2465 _exit 0;
2466 }
2467}
2468
2469
2275 2470
2276############################################################################# 2471#############################################################################
2277# the server's init and main functions 2472# the server's init and main functions
2278 2473
2279sub load_resources { 2474sub load_facedata($) {
2280 load_regions sprintf "%s/%s/regions", cf::datadir, cf::mapdir 2475 my ($path) = @_;
2476
2477 warn "loading facedata from $path\n";
2478
2479 my $facedata;
2480 0 < aio_load $path, $facedata
2481 or die "$path: $!";
2482
2483 $facedata = Coro::Storable::thaw $facedata;
2484
2485 $facedata->{version} == 2
2486 or cf::cleanup "$path: version mismatch, cannot proceed.";
2487
2488 {
2489 my $faces = $facedata->{faceinfo};
2490
2491 while (my ($face, $info) = each %$faces) {
2492 my $idx = (cf::face::find $face) || cf::face::alloc $face;
2493 cf::face::set $idx, $info->{visibility}, $info->{magicmap};
2494 cf::face::set_data $idx, 0, $info->{data32}, $info->{chksum32};
2495 cf::face::set_data $idx, 1, $info->{data64}, $info->{chksum64};
2496 Coro::cede;
2497 }
2498
2499 while (my ($face, $info) = each %$faces) {
2500 next unless $info->{smooth};
2501 my $idx = cf::face::find $face
2502 or next;
2503 if (my $smooth = cf::face::find $info->{smooth}) {
2504 cf::face::set_smooth $idx, $smooth, $info->{smoothlevel};
2505 } else {
2506 warn "smooth face '$info->{smooth}' not found for face '$face'";
2507 }
2508 Coro::cede;
2509 }
2510 }
2511
2512 {
2513 my $anims = $facedata->{animinfo};
2514
2515 while (my ($anim, $info) = each %$anims) {
2516 cf::anim::set $anim, $info->{frames}, $info->{facings};
2517 Coro::cede;
2518 }
2519
2520 cf::anim::invalidate_all; # d'oh
2521 }
2522
2523 1
2524}
2525
2526sub reload_regions {
2527 load_resource_file "$MAPDIR/regions"
2281 or die "unable to load regions file\n";#d# 2528 or die "unable to load regions file\n";
2529}
2530
2531sub reload_facedata {
2532 load_facedata "$DATADIR/facedata"
2533 or die "unable to load facedata\n";
2534}
2535
2536sub reload_archetypes {
2537 load_resource_file "$DATADIR/archetypes"
2538 or die "unable to load archetypes\n";
2539}
2540
2541sub reload_treasures {
2542 load_resource_file "$DATADIR/treasures"
2543 or die "unable to load treasurelists\n";
2544}
2545
2546sub reload_resources {
2547 warn "reloading resource files...\n";
2548
2549 reload_regions;
2550 reload_facedata;
2551 reload_archetypes;
2552 reload_treasures;
2553
2554 warn "finished reloading resource files\n";
2555}
2556
2557sub init {
2558 reload_resources;
2282} 2559}
2283 2560
2284sub cfg_load { 2561sub cfg_load {
2285 open my $fh, "<:utf8", cf::confdir . "/config" 2562 open my $fh, "<:utf8", "$CONFDIR/config"
2286 or return; 2563 or return;
2287 2564
2288 local $/; 2565 local $/;
2289 *CFG = YAML::Syck::Load <$fh>; 2566 *CFG = YAML::Syck::Load <$fh>;
2290 2567
2298 $CFG{mlockall} ? eval "mlockall()" : eval "munlockall()" 2575 $CFG{mlockall} ? eval "mlockall()" : eval "munlockall()"
2299 and die "WARNING: m(un)lockall failed: $!\n"; 2576 and die "WARNING: m(un)lockall failed: $!\n";
2300 }; 2577 };
2301 warn $@ if $@; 2578 warn $@ if $@;
2302 } 2579 }
2303}
2304
2305sub init {
2306 load_resources;
2307} 2580}
2308 2581
2309sub main { 2582sub main {
2310 # we must not ever block the main coroutine 2583 # we must not ever block the main coroutine
2311 local $Coro::idle = sub { 2584 local $Coro::idle = sub {
2314 Event::one_event; 2587 Event::one_event;
2315 })->prio (Coro::PRIO_MAX); 2588 })->prio (Coro::PRIO_MAX);
2316 }; 2589 };
2317 2590
2318 cfg_load; 2591 cfg_load;
2319 db_load; 2592 db_init;
2320 load_extensions; 2593 load_extensions;
2321 2594
2322 $TICK_WATCHER->start; 2595 $TICK_WATCHER->start;
2323 Event::loop; 2596 Event::loop;
2324} 2597}
2363 my $map = $cf::MAP{$path} or next; 2636 my $map = $cf::MAP{$path} or next;
2364 $map->valid or next; 2637 $map->valid or next;
2365 $map->save; 2638 $map->save;
2366 } 2639 }
2367 warn "end emergency map save\n"; 2640 warn "end emergency map save\n";
2641
2642 warn "begin emergency database checkpoint\n";
2643 BDB::db_env_txn_checkpoint $DB_ENV;
2644 warn "end emergency database checkpoint\n";
2368 }; 2645 };
2369 2646
2370 warn "leave emergency perl save\n"; 2647 warn "leave emergency perl save\n";
2371} 2648}
2372 2649
2650sub post_cleanup {
2651 my ($make_core) = @_;
2652
2653 warn Carp::longmess "post_cleanup backtrace"
2654 if $make_core;
2655}
2656
2373sub reload() { 2657sub do_reload_perl() {
2374 # can/must only be called in main 2658 # can/must only be called in main
2375 if ($Coro::current != $Coro::main) { 2659 if ($Coro::current != $Coro::main) {
2376 warn "can only reload from main coroutine"; 2660 warn "can only reload from main coroutine";
2377 return; 2661 return;
2378 } 2662 }
2379 2663
2380 warn "reloading..."; 2664 warn "reloading...";
2381 2665
2382 warn "cancelling server ticker"; 2666 warn "entering sync_job";
2383 $TICK_WATCHER->cancel;
2384 2667
2668 cf::sync_job {
2669 cf::write_runtime; # external watchdog should not bark
2385 cf::emergency_save; 2670 cf::emergency_save;
2671 cf::write_runtime; # external watchdog should not bark
2386 2672
2387 eval { 2673 warn "syncing database to disk";
2674 BDB::db_env_txn_checkpoint $DB_ENV;
2675
2388 # if anything goes wrong in here, we should simply crash as we already saved 2676 # if anything goes wrong in here, we should simply crash as we already saved
2389
2390 warn "syncing database to disk";
2391 cf::db_sync;
2392 2677
2393 warn "cancelling all WF_AUTOCANCEL watchers"; 2678 warn "cancelling all WF_AUTOCANCEL watchers";
2394 for (Event::all_watchers) { 2679 for (Event::all_watchers) {
2395 $_->cancel if $_->data & WF_AUTOCANCEL; 2680 $_->cancel if $_->data & WF_AUTOCANCEL;
2396 } 2681 }
2397 2682
2398 warn "flushing outstanding aio requests"; 2683 warn "flushing outstanding aio requests";
2399 for (;;) { 2684 for (;;) {
2685 BDB::flush;
2400 IO::AIO::flush; 2686 IO::AIO::flush;
2401 Coro::cede; 2687 Coro::cede;
2402 last unless IO::AIO::nreqs; 2688 last unless IO::AIO::nreqs || BDB::nreqs;
2403 warn "iterate..."; 2689 warn "iterate...";
2404 } 2690 }
2691
2692 ++$RELOAD;
2405 2693
2406 warn "cancelling all extension coros"; 2694 warn "cancelling all extension coros";
2407 $_->cancel for values %EXT_CORO; 2695 $_->cancel for values %EXT_CORO;
2408 %EXT_CORO = (); 2696 %EXT_CORO = ();
2409 2697
2449 Symbol::delete_package "safe::$_" 2737 Symbol::delete_package "safe::$_"
2450 for qw(cf::attachable cf::object cf::object::player cf::client cf::player cf::map cf::party cf::region); 2738 for qw(cf::attachable cf::object cf::object::player cf::client cf::player cf::map cf::party cf::region);
2451 2739
2452 warn "unloading cf.pm \"a bit\""; 2740 warn "unloading cf.pm \"a bit\"";
2453 delete $INC{"cf.pm"}; 2741 delete $INC{"cf.pm"};
2742 delete $INC{"cf/pod.pm"};
2454 2743
2455 # don't, removes xs symbols, too, 2744 # don't, removes xs symbols, too,
2456 # and global variables created in xs 2745 # and global variables created in xs
2457 #Symbol::delete_package __PACKAGE__; 2746 #Symbol::delete_package __PACKAGE__;
2458 2747
2462 require cf; 2751 require cf;
2463 cf::_connect_to_perl; # nominally unnecessary, but cannot hurt 2752 cf::_connect_to_perl; # nominally unnecessary, but cannot hurt
2464 2753
2465 warn "loading config and database again"; 2754 warn "loading config and database again";
2466 cf::cfg_load; 2755 cf::cfg_load;
2467 cf::db_load;
2468 2756
2469 warn "loading extensions"; 2757 warn "loading extensions";
2470 cf::load_extensions; 2758 cf::load_extensions;
2471 2759
2472 warn "reattaching attachments to objects/players"; 2760 warn "reattaching attachments to objects/players";
2473 _global_reattach; 2761 _global_reattach; # objects, sockets
2474 warn "reattaching attachments to maps"; 2762 warn "reattaching attachments to maps";
2475 reattach $_ for values %MAP; 2763 reattach $_ for values %MAP;
2764 warn "reattaching attachments to players";
2765 reattach $_ for values %PLAYER;
2476 2766
2477 warn "loading reloadable resources"; 2767 warn "leaving sync_job";
2478 load_resources;
2479 2768
2480 warn "restarting server ticker"; 2769 1
2481 2770 } or do {
2482 $TICK_WATCHER->start;
2483 };
2484
2485 if ($@) {
2486 warn $@; 2771 warn $@;
2487 warn "error while reloading, exiting."; 2772 warn "error while reloading, exiting.";
2488 exit 1; 2773 exit 1;
2489 } 2774 };
2490 2775
2491 warn "reloaded"; 2776 warn "reloaded";
2492}; 2777};
2493 2778
2494our $RELOAD_WATCHER; # used only during reload 2779our $RELOAD_WATCHER; # used only during reload
2495 2780
2781sub reload_perl() {
2782 # doing reload synchronously and two reloads happen back-to-back,
2783 # coro crashes during coro_state_free->destroy here.
2784
2785 $RELOAD_WATCHER ||= Event->timer (
2786 reentrant => 0,
2787 after => 0,
2788 data => WF_AUTOCANCEL,
2789 cb => sub {
2790 do_reload_perl;
2791 undef $RELOAD_WATCHER;
2792 },
2793 );
2794}
2795
2496register_command "reload" => sub { 2796register_command "reload" => sub {
2497 my ($who, $arg) = @_; 2797 my ($who, $arg) = @_;
2498 2798
2499 if ($who->flag (FLAG_WIZ)) { 2799 if ($who->flag (FLAG_WIZ)) {
2500 $who->message ("reloading server."); 2800 $who->message ("reloading server.");
2501 2801 async { reload_perl };
2502 # doing reload synchronously and two reloads happen back-to-back,
2503 # coro crashes during coro_state_free->destroy here.
2504
2505 $RELOAD_WATCHER ||= Event->timer (
2506 reentrant => 0,
2507 after => 0,
2508 data => WF_AUTOCANCEL,
2509 cb => sub {
2510 reload;
2511 undef $RELOAD_WATCHER;
2512 },
2513 );
2514 } 2802 }
2515}; 2803};
2516 2804
2517unshift @INC, $LIBDIR; 2805unshift @INC, $LIBDIR;
2518 2806
2519my $bug_warning = 0; 2807my $bug_warning = 0;
2808
2809our @WAIT_FOR_TICK;
2810our @WAIT_FOR_TICK_BEGIN;
2811
2812sub wait_for_tick {
2813 return unless $TICK_WATCHER->is_active;
2814 return if $Coro::current == $Coro::main;
2815
2816 my $signal = new Coro::Signal;
2817 push @WAIT_FOR_TICK, $signal;
2818 $signal->wait;
2819}
2820
2821sub wait_for_tick_begin {
2822 return unless $TICK_WATCHER->is_active;
2823 return if $Coro::current == $Coro::main;
2824
2825 my $signal = new Coro::Signal;
2826 push @WAIT_FOR_TICK_BEGIN, $signal;
2827 $signal->wait;
2828}
2520 2829
2521$TICK_WATCHER = Event->timer ( 2830$TICK_WATCHER = Event->timer (
2522 reentrant => 0, 2831 reentrant => 0,
2523 parked => 1, 2832 parked => 1,
2524 prio => 0, 2833 prio => 0,
2532 } 2841 }
2533 2842
2534 $NOW = Event::time; 2843 $NOW = Event::time;
2535 2844
2536 cf::server_tick; # one server iteration 2845 cf::server_tick; # one server iteration
2846
2537 $RUNTIME += $TICK; 2847 $RUNTIME += $TICK;
2538 $NEXT_TICK += $TICK; 2848 $NEXT_TICK += $TICK;
2539 2849
2540 $WAIT_FOR_TICK->broadcast; 2850 if ($NOW >= $NEXT_RUNTIME_WRITE) {
2541 $WAIT_FOR_TICK_ONE->send if $WAIT_FOR_TICK_ONE->awaited; 2851 $NEXT_RUNTIME_WRITE = $NOW + 10;
2542 2852 Coro::async_pool {
2543 Event::sweep; 2853 write_runtime
2544 Coro::cede_notself; 2854 or warn "ERROR: unable to write runtime file: $!";
2855 };
2545 2856 }
2857
2546# my $AFTER = Event::time; 2858# my $AFTER = Event::time;
2547# warn $AFTER - $NOW;#d# 2859# warn $AFTER - $NOW;#d#
2548 2860
2549 # if we are delayed by four ticks or more, skip them all 2861 # if we are delayed by four ticks or more, skip them all
2550 $NEXT_TICK = Event::time if Event::time >= $NEXT_TICK + $TICK * 4; 2862 $NEXT_TICK = Event::time if Event::time >= $NEXT_TICK + $TICK * 4;
2551 2863
2552 $TICK_WATCHER->at ($NEXT_TICK); 2864 $TICK_WATCHER->at ($NEXT_TICK);
2553 $TICK_WATCHER->start; 2865 $TICK_WATCHER->start;
2866
2867 if (my $sig = shift @WAIT_FOR_TICK_BEGIN) {
2868 $sig->send;
2869 }
2870 while (my $sig = shift @WAIT_FOR_TICK) {
2871 $sig->send;
2872 }
2873
2874 _post_tick;
2554 }, 2875 },
2555); 2876);
2556 2877
2878{
2879 BDB::max_poll_time $TICK * 0.1;
2880 $BDB_POLL_WATCHER = Event->io (
2881 reentrant => 0,
2882 fd => BDB::poll_fileno,
2883 poll => 'r',
2884 prio => 0,
2885 data => WF_AUTOCANCEL,
2886 cb => \&BDB::poll_cb,
2887 );
2888 BDB::min_parallel 8;
2889
2890 BDB::set_sync_prepare {
2891 my $status;
2892 my $current = $Coro::current;
2893 (
2894 sub {
2895 $status = $!;
2896 $current->ready; undef $current;
2897 },
2898 sub {
2899 Coro::schedule while defined $current;
2900 $! = $status;
2901 },
2902 )
2903 };
2904
2905 unless ($DB_ENV) {
2906 $DB_ENV = BDB::db_env_create;
2907
2908 cf::sync_job {
2909 eval {
2910 BDB::db_env_open
2911 $DB_ENV,
2912 $BDBDIR,
2913 BDB::INIT_LOCK | BDB::INIT_LOG | BDB::INIT_MPOOL | BDB::INIT_TXN
2914 | BDB::RECOVER | BDB::REGISTER | BDB::USE_ENVIRON | BDB::CREATE,
2915 0666;
2916
2917 cf::cleanup "db_env_open($BDBDIR): $!" if $!;
2918
2919 $DB_ENV->set_flags (BDB::AUTO_COMMIT | BDB::REGION_INIT | BDB::TXN_NOSYNC, 1);
2920 $DB_ENV->set_lk_detect;
2921 };
2922
2923 cf::cleanup "db_env_open(db): $@" if $@;
2924 };
2925 }
2926}
2927
2928{
2929 IO::AIO::min_parallel 8;
2930
2931 undef $Coro::AIO::WATCHER;
2557IO::AIO::max_poll_time $TICK * 0.1; 2932 IO::AIO::max_poll_time $TICK * 0.1;
2558
2559undef $Coro::AIO::WATCHER;
2560$AIO_POLL_WATCHER = Event->io ( 2933 $AIO_POLL_WATCHER = Event->io (
2561 reentrant => 0, 2934 reentrant => 0,
2935 data => WF_AUTOCANCEL,
2562 fd => IO::AIO::poll_fileno, 2936 fd => IO::AIO::poll_fileno,
2563 poll => 'r', 2937 poll => 'r',
2564 prio => 6, 2938 prio => 6,
2565 data => WF_AUTOCANCEL,
2566 cb => \&IO::AIO::poll_cb, 2939 cb => \&IO::AIO::poll_cb,
2567); 2940 );
2941}
2568 2942
2569$WRITE_RUNTIME_WATCHER = Event->timer ( 2943my $_log_backtrace;
2570 reentrant => 0, 2944
2571 data => WF_AUTOCANCEL, 2945sub _log_backtrace {
2572 after => 1, 2946 my ($msg, @addr) = @_;
2573 interval => 10, 2947
2574 prio => 6, # keep it lowest so it acts like a watchdog 2948 $msg =~ s/\n//;
2575 cb => Coro::unblock_sub { 2949
2576 write_runtime 2950 # limit the # of concurrent backtraces
2577 or warn "ERROR: unable to write runtime file: $!"; 2951 if ($_log_backtrace < 2) {
2952 ++$_log_backtrace;
2953 async {
2954 my @bt = fork_call {
2955 @addr = map { sprintf "%x", $_ } @addr;
2956 my $self = (-f "/proc/$$/exe") ? "/proc/$$/exe" : $^X;
2957 open my $fh, "exec addr2line -C -f -i -e \Q$self\E @addr 2>&1 |"
2958 or die "addr2line: $!";
2959
2960 my @funcs;
2961 my @res = <$fh>;
2962 chomp for @res;
2963 while (@res) {
2964 my ($func, $line) = splice @res, 0, 2, ();
2965 push @funcs, "[$func] $line";
2966 }
2967
2968 @funcs
2969 };
2970
2971 LOG llevInfo, "[ABT] $msg\n";
2972 LOG llevInfo, "[ABT] $_\n" for @bt;
2973 --$_log_backtrace;
2974 };
2975 } else {
2976 LOG llevInfo, "[ABT] $msg\n";
2977 LOG llevInfo, "[ABT] [suppressed]\n";
2578 }, 2978 }
2579); 2979}
2980
2981# load additional modules
2982use cf::pod;
2580 2983
2581END { cf::emergency_save } 2984END { cf::emergency_save }
2582 2985
25831 29861
2584 2987

Diff Legend

Removed lines
+ Added lines
< Changed lines
> Changed lines