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.522 by root, Sat Apr 17 02:22:14 2010 UTC vs.
Revision 1.622 by root, Wed Nov 23 06:05:33 2016 UTC

1# 1#
2# This file is part of Deliantra, the Roguelike Realtime MMORPG. 2# This file is part of Deliantra, the Roguelike Realtime MMORPG.
3# 3#
4# Copyright (©) 2006,2007,2008,2009,2010 Marc Alexander Lehmann / Robin Redeker / the Deliantra team 4# Copyright (©) 2006,2007,2008,2009,2010,2011,2012 Marc Alexander Lehmann / Robin Redeker / the Deliantra team
5# 5#
6# Deliantra is free software: you can redistribute it and/or modify it under 6# Deliantra is free software: you can redistribute it and/or modify it under
7# the terms of the Affero GNU General Public License as published by the 7# the terms of the Affero GNU General Public License as published by the
8# Free Software Foundation, either version 3 of the License, or (at your 8# Free Software Foundation, either version 3 of the License, or (at your
9# option) any later version. 9# option) any later version.
10# 10#
11# This program is distributed in the hope that it will be useful, 11# This program is distributed in the hope that it will be useful,
12# but WITHOUT ANY WARRANTY; without even the implied warranty of 12# but WITHOUT ANY WARRANTY; without even the implied warranty of
13# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 13# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
14# GNU General Public License for more details. 14# GNU General Public License for more details.
15# 15#
16# You should have received a copy of the Affero GNU General Public License 16# You should have received a copy of the Affero GNU General Public License
17# and the GNU General Public License along with this program. If not, see 17# and the GNU General Public License along with this program. If not, see
18# <http://www.gnu.org/licenses/>. 18# <http://www.gnu.org/licenses/>.
19# 19#
20# The authors can be reached via e-mail to <support@deliantra.net> 20# The authors can be reached via e-mail to <support@deliantra.net>
21# 21#
22 22
23package cf; 23package cf;
24 24
25use 5.10.0; 25use common::sense;
26use utf8;
27use strict qw(vars subs);
28 26
29use Symbol; 27use Symbol;
30use List::Util; 28use List::Util;
31use Socket; 29use Socket;
32use EV; 30use EV;
34use Safe; 32use Safe;
35use Safe::Hole; 33use Safe::Hole;
36use Storable (); 34use Storable ();
37use Carp (); 35use Carp ();
38 36
39use Guard (); 37use AnyEvent ();
38use AnyEvent::IO ();
39use AnyEvent::DNS ();
40
40use Coro (); 41use Coro ();
41use Coro::State; 42use Coro::State;
42use Coro::Handle; 43use Coro::Handle;
43use Coro::EV; 44use Coro::EV;
44use Coro::AnyEvent; 45use Coro::AnyEvent;
50use Coro::AIO; 51use Coro::AIO;
51use Coro::BDB 1.6; 52use Coro::BDB 1.6;
52use Coro::Storable; 53use Coro::Storable;
53use Coro::Util (); 54use Coro::Util ();
54 55
56use Guard ();
55use JSON::XS 2.01 (); 57use JSON::XS 2.01 ();
56use BDB (); 58use BDB ();
57use Data::Dumper; 59use Data::Dumper;
58use Fcntl; 60use Fcntl;
59use YAML::XS (); 61use YAML::XS ();
62use CBOR::XS ();
60use IO::AIO (); 63use IO::AIO ();
61use Time::HiRes;
62use Compress::LZF; 64use Compress::LZF;
63use Digest::MD5 (); 65use Digest::MD5 ();
64 66
65AnyEvent::detect; 67AnyEvent::detect;
66 68
78# strictly for debugging 80# strictly for debugging
79$SIG{QUIT} = sub { Carp::cluck "SIGQUIT" }; 81$SIG{QUIT} = sub { Carp::cluck "SIGQUIT" };
80 82
81sub WF_AUTOCANCEL () { 1 } # automatically cancel this watcher on reload 83sub WF_AUTOCANCEL () { 1 } # automatically cancel this watcher on reload
82 84
85our @ORIG_INC;
86
83our %COMMAND = (); 87our %COMMAND = ();
84our %COMMAND_TIME = (); 88our %COMMAND_TIME = ();
85 89
86our @EXTS = (); # list of extension package names 90our @EXTS = (); # list of extension package names
87our %EXTCMD = (); 91our %EXTCMD = ();
92our %EXTACMD = ();
88our %EXTICMD = (); 93our %EXTICMD = ();
94our %EXTIACMD = ();
89our %EXT_CORO = (); # coroutines bound to extensions 95our %EXT_CORO = (); # coroutines bound to extensions
90our %EXT_MAP = (); # pluggable maps 96our %EXT_MAP = (); # pluggable maps
91 97
92our $RELOAD; # number of reloads so far, non-zero while in reload 98our $RELOAD; # number of reloads so far, non-zero while in reload
93our @EVENT; 99our @EVENT;
94our @REFLECT; # set by XS 100our @REFLECT; # set by XS
95our %REFLECT; # set by us 101our %REFLECT; # set by us
96 102
97our $CONFDIR = confdir; 103our $CONFDIR = confdir;
104
98our $DATADIR = datadir; 105our $DATADIR = datadir;
99our $LIBDIR = "$DATADIR/ext"; 106our $LIBDIR = "$DATADIR/ext";
100our $PODDIR = "$DATADIR/pod"; 107our $PODDIR = "$DATADIR/pod";
101our $MAPDIR = "$DATADIR/" . mapdir; 108our $MAPDIR = "$DATADIR/" . mapdir;
109
102our $LOCALDIR = localdir; 110our $LOCALDIR = localdir;
103our $TMPDIR = "$LOCALDIR/" . tmpdir; 111our $TMPDIR = "$LOCALDIR/" . tmpdir;
104our $UNIQUEDIR = "$LOCALDIR/" . uniquedir; 112our $UNIQUEDIR = "$LOCALDIR/" . uniquedir;
105our $PLAYERDIR = "$LOCALDIR/" . playerdir; 113our $PLAYERDIR = "$LOCALDIR/" . playerdir;
106our $RANDOMDIR = "$LOCALDIR/random"; 114our $RANDOMDIR = "$LOCALDIR/random";
107our $BDBDIR = "$LOCALDIR/db"; 115our $BDBDIR = "$LOCALDIR/db";
108our $PIDFILE = "$LOCALDIR/pid"; 116our $PIDFILE = "$LOCALDIR/pid";
109our $RUNTIMEFILE = "$LOCALDIR/runtime"; 117our $RUNTIMEFILE = "$LOCALDIR/runtime";
110 118
111our %RESOURCE; 119#our %RESOURCE; # unused
112 120
113our $OUTPUT_RATE_MIN = 4000; 121our $OUTPUT_RATE_MIN = 3000;
114our $OUTPUT_RATE_MAX = 100000; 122our $OUTPUT_RATE_MAX = 1000000;
123
124our $MAX_LINKS = 32; # how many chained exits to follow
125our $VERBOSE_IO = 1;
115 126
116our $TICK = MAX_TIME * 1e-6; # this is a CONSTANT(!) 127our $TICK = MAX_TIME * 1e-6; # this is a CONSTANT(!)
117our $NEXT_RUNTIME_WRITE; # when should the runtime file be written 128our $NEXT_RUNTIME_WRITE; # when should the runtime file be written
118our $NEXT_TICK; 129our $NEXT_TICK;
119our $USE_FSYNC = 1; # use fsync to write maps - default on 130our $USE_FSYNC = 1; # use fsync to write maps - default on
121our $BDB_DEADLOCK_WATCHER; 132our $BDB_DEADLOCK_WATCHER;
122our $BDB_CHECKPOINT_WATCHER; 133our $BDB_CHECKPOINT_WATCHER;
123our $BDB_TRICKLE_WATCHER; 134our $BDB_TRICKLE_WATCHER;
124our $DB_ENV; 135our $DB_ENV;
125 136
126our @EXTRA_MODULES = qw(pod match mapscript); 137our @EXTRA_MODULES = qw(pod match mapscript incloader);
127 138
128our %CFG; 139our %CFG;
140our %EXT_CFG; # cfgkeyname => [var-ref, defaultvalue]
129 141
130our $UPTIME; $UPTIME ||= time; 142our $UPTIME; $UPTIME ||= time;
131our $RUNTIME; 143our $RUNTIME = 0;
144our $SERVER_TICK = 0;
132our $NOW; 145our $NOW;
133 146
134our (%PLAYER, %PLAYER_LOADING); # all users 147our (%PLAYER, %PLAYER_LOADING); # all users
135our (%MAP, %MAP_LOADING ); # all maps 148our (%MAP, %MAP_LOADING ); # all maps
136our $LINK_MAP; # the special {link} map, which is always available 149our $LINK_MAP; # the special {link} map, which is always available
145 158
146our @POST_INIT; 159our @POST_INIT;
147 160
148our $REATTACH_ON_RELOAD; # set to true to force object reattach on reload (slow) 161our $REATTACH_ON_RELOAD; # set to true to force object reattach on reload (slow)
149our $REALLY_UNLOOP; # never set to true, please :) 162our $REALLY_UNLOOP; # never set to true, please :)
163
164our $WAIT_FOR_TICK = new Coro::Signal;
165our @WAIT_FOR_TICK_BEGIN;
150 166
151binmode STDOUT; 167binmode STDOUT;
152binmode STDERR; 168binmode STDERR;
153 169
154# read virtual server time, if available 170# read virtual server time, if available
188 204
189=over 4 205=over 4
190 206
191=item $cf::UPTIME 207=item $cf::UPTIME
192 208
193The timestamp of the server start (so not actually an uptime). 209The timestamp of the server start (so not actually an "uptime").
210
211=item $cf::SERVER_TICK
212
213An unsigned integer that starts at zero when the server is started and is
214incremented on every tick.
215
216=item $cf::NOW
217
218The (real) time of the last (current) server tick - updated before and
219after tick processing, so this is useful only as a rough "what time is it
220now" estimate.
221
222=item $cf::TICK
223
224The interval between each server tick, in seconds.
194 225
195=item $cf::RUNTIME 226=item $cf::RUNTIME
196 227
197The time this server has run, starts at 0 and is increased by $cf::TICK on 228The time this server has run, starts at 0 and is increased by $cf::TICK on
198every server tick. 229every server tick.
199 230
200=item $cf::CONFDIR $cf::DATADIR $cf::LIBDIR $cf::PODDIR 231=item $cf::CONFDIR $cf::DATADIR $cf::LIBDIR $cf::PODDIR
201$cf::MAPDIR $cf::LOCALDIR $cf::TMPDIR $cf::UNIQUEDIR 232$cf::MAPDIR $cf::LOCALDIR $cf::TMPDIR $cf::UNIQUEDIR
202$cf::PLAYERDIR $cf::RANDOMDIR $cf::BDBDIR 233$cf::PLAYERDIR $cf::RANDOMDIR $cf::BDBDIR
203 234
204Various directories - "/etc", read-only install directory, perl-library 235Various directories - "/etc", read-only install directory, perl-library
205directory, pod-directory, read-only maps directory, "/var", "/var/tmp", 236directory, pod-directory, read-only maps directory, "/var", "/var/tmp",
206unique-items directory, player file directory, random maps directory and 237unique-items directory, player file directory, random maps directory and
207database environment. 238database environment.
208 239
209=item $cf::NOW
210
211The time of the last (current) server tick.
212
213=item $cf::TICK
214
215The interval between server ticks, in seconds.
216
217=item $cf::LOADAVG 240=item $cf::LOADAVG
218 241
219The current CPU load on the server (alpha-smoothed), as a value between 0 242The current CPU load on the server (alpha-smoothed), as a value between 0
220(none) and 1 (overloaded), indicating how much time is spent on processing 243(none) and 1 (overloaded), indicating how much time is spent on processing
221objects per tick. Healthy values are < 0.5. 244objects per tick. Healthy values are < 0.5.
229Configuration for the server, loaded from C</etc/deliantra-server/config>, or 252Configuration for the server, loaded from C</etc/deliantra-server/config>, or
230from wherever your confdir points to. 253from wherever your confdir points to.
231 254
232=item cf::wait_for_tick, cf::wait_for_tick_begin 255=item cf::wait_for_tick, cf::wait_for_tick_begin
233 256
234These are functions that inhibit the current coroutine one tick. cf::wait_for_tick_begin only 257These are functions that inhibit the current coroutine one tick.
235returns directly I<after> the tick processing (and consequently, can only wake one process 258cf::wait_for_tick_begin only returns directly I<after> the tick
259processing (and consequently, can only wake one thread per tick), while
236per tick), while cf::wait_for_tick wakes up all waiters after tick processing. 260cf::wait_for_tick wakes up all waiters after tick processing.
261
262Note that cf::wait_for_tick will immediately return when the server is not
263ticking, making it suitable for small pauses in threads that need to run
264when the server is paused. If that is not applicable (i.e. you I<really>
265want to wait, use C<$cf::WAIT_FOR_TICK>).
266
267=item $cf::WAIT_FOR_TICK
268
269Note that C<cf::wait_for_tick> is probably the correct thing to use. This
270variable contains a L<Coro::Signal> that is broadcats after every server
271tick. Calling C<< ->wait >> on it will suspend the caller until after the
272next server tick.
273
274=cut
275
276sub wait_for_tick();
277sub wait_for_tick_begin();
237 278
238=item @cf::INVOKE_RESULTS 279=item @cf::INVOKE_RESULTS
239 280
240This array contains the results of the last C<invoke ()> call. When 281This array contains the results of the last C<invoke ()> call. When
241C<cf::override> is called C<@cf::INVOKE_RESULTS> is set to the parameters of 282C<cf::override> is called C<@cf::INVOKE_RESULTS> is set to the parameters of
249 290
250=back 291=back
251 292
252=cut 293=cut
253 294
295sub error(@) { LOG llevError, join "", @_ }
296sub warn (@) { LOG llevWarn , join "", @_ }
297sub info (@) { LOG llevInfo , join "", @_ }
298sub debug(@) { LOG llevDebug, join "", @_ }
299sub trace(@) { LOG llevTrace, join "", @_ }
300
254$Coro::State::WARNHOOK = sub { 301$Coro::State::WARNHOOK = sub {
255 my $msg = join "", @_; 302 my $msg = join "", @_;
256 303
257 $msg .= "\n" 304 $msg .= "\n"
258 unless $msg =~ /\n$/; 305 unless $msg =~ /\n$/;
259 306
260 $msg =~ s/([\x00-\x08\x0b-\x1f])/sprintf "\\x%02x", ord $1/ge; 307 $msg =~ s/([\x00-\x08\x0b-\x1f])/sprintf "\\x%02x", ord $1/ge;
261 308
262 LOG llevError, $msg; 309 LOG llevWarn, $msg;
263}; 310};
264 311
265$Coro::State::DIEHOOK = sub { 312$Coro::State::DIEHOOK = sub {
266 return unless $^S eq 0; # "eq", not "==" 313 return unless $^S eq 0; # "eq", not "=="
267 314
268 warn Carp::longmess $_[0]; 315 error Carp::longmess $_[0];
269 316
270 if (in_main) {#d# 317 if (in_main) {#d#
271 warn "DIEHOOK called in main context, Coro bug?\n";#d# 318 error "DIEHOOK called in main context, Coro bug?\n";#d#
272 return;#d# 319 return;#d#
273 }#d# 320 }#d#
274 321
275 # kill coroutine otherwise 322 # kill coroutine otherwise
276 Coro::terminate 323 Coro::terminate
296)) { 343)) {
297 @{"safe::$pkg\::wrap::ISA"} = @{"$pkg\::wrap::ISA"} = $pkg; 344 @{"safe::$pkg\::wrap::ISA"} = @{"$pkg\::wrap::ISA"} = $pkg;
298} 345}
299 346
300$EV::DIED = sub { 347$EV::DIED = sub {
301 Carp::cluck "error in event callback: @_"; 348 warn "error in event callback: $@";
302}; 349};
350
351#############################################################################
352
353sub fork_call(&@);
354sub get_slot($;$$);
303 355
304############################################################################# 356#############################################################################
305 357
306=head2 UTILITY FUNCTIONS 358=head2 UTILITY FUNCTIONS
307 359
328 $d =~ s/([\x00-\x07\x09\x0b\x0c\x0e-\x1f])/sprintf "\\x%02x", ord($1)/ge; 380 $d =~ s/([\x00-\x07\x09\x0b\x0c\x0e-\x1f])/sprintf "\\x%02x", ord($1)/ge;
329 $d 381 $d
330 } || "[unable to dump $_[0]: '$@']"; 382 } || "[unable to dump $_[0]: '$@']";
331} 383}
332 384
385=item $scalar = cf::load_file $path
386
387Loads the given file from path and returns its contents. Croaks on error
388and can block.
389
390=cut
391
392sub load_file($) {
393 0 <= aio_load $_[0], my $data
394 or Carp::croak "$_[0]: $!";
395
396 $data
397}
398
399=item $success = cf::replace_file $path, $data, $sync
400
401Atomically replaces the file at the given $path with new $data, and
402optionally $sync the data to disk before replacing the file.
403
404=cut
405
406sub replace_file($$;$) {
407 my ($path, $data, $sync) = @_;
408
409 my $lock = cf::lock_acquire ("replace_file:$path");
410
411 my $fh = aio_open "$path~", Fcntl::O_WRONLY | Fcntl::O_CREAT | Fcntl::O_TRUNC, 0644
412 or return;
413
414 $data = $data->() if ref $data;
415
416 length $data == aio_write $fh, 0, (length $data), $data, 0
417 or return;
418
419 !$sync
420 or !aio_fsync $fh
421 or return;
422
423 aio_close $fh
424 and return;
425
426 aio_rename "$path~", $path
427 and return;
428
429 if ($sync) {
430 $path =~ s%/[^/]*$%%;
431 aio_pathsync $path;
432 }
433
434 1
435}
436
333=item $ref = cf::decode_json $json 437=item $ref = cf::decode_json $json
334 438
335Converts a JSON string into the corresponding perl data structure. 439Converts a JSON string into the corresponding perl data structure.
336 440
337=item $json = cf::encode_json $ref 441=item $json = cf::encode_json $ref
343our $json_coder = JSON::XS->new->utf8->max_size (1e6); # accept ~1mb max 447our $json_coder = JSON::XS->new->utf8->max_size (1e6); # accept ~1mb max
344 448
345sub encode_json($) { $json_coder->encode ($_[0]) } 449sub encode_json($) { $json_coder->encode ($_[0]) }
346sub decode_json($) { $json_coder->decode ($_[0]) } 450sub decode_json($) { $json_coder->decode ($_[0]) }
347 451
452=item $ref = cf::decode_storable $scalar
453
454Same as Coro::Storable::thaw, so blocks.
455
456=cut
457
458BEGIN { *decode_storable = \&Coro::Storable::thaw }
459
460=item $ref = cf::decode_yaml $scalar
461
462Same as YAML::XS::Load, but doesn't leak, because it forks (and thus blocks).
463
464=cut
465
466sub decode_yaml($) {
467 fork_call { YAML::XS::Load $_[0] } @_
468}
469
470=item $scalar = cf::decode_cbor $scalar
471
472Same as CBOR::XS::decode_cbor, but takes server ticks into account, so
473blocks. For small amounts of data, C<CBOR::XS::decode_cbor> is the better
474alternative.
475
476=cut
477
478sub decode_cbor($) {
479 # we assume 10mb/s minimum decoding speed (on a ~2ghz machine)
480 cf::get_slot +(length $_[0]) / 10_000_000, 0, "decode_cbor";
481 CBOR::XS::decode_cbor $_[0]
482}
483
484=item $scalar = cf::unlzf $scalar
485
486Same as Compress::LZF::compress, but takes server ticks into account, so
487blocks.
488
489=cut
490
491sub unlzf($) {
492 # we assume 100mb/s minimum decompression speed (noncompressible data on a ~2ghz machine)
493 cf::get_slot +(length $_[0]) / 100_000_000, 0, "unlzf";
494 Compress::LZF::decompress $_[0]
495}
496
348=item cf::post_init { BLOCK } 497=item cf::post_init { BLOCK }
349 498
350Execute the given codeblock, I<after> all extensions have been (re-)loaded, 499Execute the given codeblock, I<after> all extensions have been (re-)loaded,
351but I<before> the server starts ticking again. 500but I<before> the server starts ticking again.
352 501
353The cdoeblock will have a single boolean argument to indicate whether this 502The codeblock will have a single boolean argument to indicate whether this
354is a reload or not. 503is a reload or not.
355 504
356=cut 505=cut
357 506
358sub post_init(&) { 507sub post_init(&) {
359 push @POST_INIT, shift; 508 push @POST_INIT, shift;
360} 509}
361 510
511sub _post_init {
512 trace "running post_init jobs";
513
514 # run them in parallel...
515
516 my @join;
517
518 while () {
519 push @join, map &Coro::async ($_, 0), @POST_INIT;
520 @POST_INIT = ();
521
522 @join or last;
523
524 (pop @join)->join;
525 }
526}
527
362=item cf::lock_wait $string 528=item cf::lock_wait $string
363 529
364Wait until the given lock is available. See cf::lock_acquire. 530Wait until the given lock is available. See cf::lock_acquire.
365 531
366=item my $lock = cf::lock_acquire $string 532=item my $lock = cf::lock_acquire $string
367 533
368Wait until the given lock is available and then acquires it and returns 534Wait until the given lock is available and then acquires it and returns
369a L<Guard> object. If the guard object gets destroyed (goes out of scope, 535a L<Guard> object. If the guard object gets destroyed (goes out of scope,
417 EV::periodic $start, $interval, 0, $cb 583 EV::periodic $start, $interval, 0, $cb
418} 584}
419 585
420=item cf::get_slot $time[, $priority[, $name]] 586=item cf::get_slot $time[, $priority[, $name]]
421 587
422Allocate $time seconds of blocking CPU time at priority C<$priority>: 588Allocate $time seconds of blocking CPU time at priority C<$priority>
423This call blocks and returns only when you have at least C<$time> seconds 589(default: 0): This call blocks and returns only when you have at least
424of cpu time till the next tick. The slot is only valid till the next cede. 590C<$time> seconds of cpu time till the next tick. The slot is only valid
591till the next cede.
592
593Background jobs should use a priority less than zero, interactive jobs
594should use 100 or more.
425 595
426The optional C<$name> can be used to identify the job to run. It might be 596The optional C<$name> can be used to identify the job to run. It might be
427used for statistical purposes and should identify the same time-class. 597used for statistical purposes and should identify the same time-class.
428 598
429Useful for short background jobs. 599Useful for short background jobs.
441 my $signal = new Coro::Signal; 611 my $signal = new Coro::Signal;
442 my $busy; 612 my $busy;
443 613
444 while () { 614 while () {
445 next_job: 615 next_job:
616
617 Coro::cede;
446 618
447 my $avail = cf::till_tick; 619 my $avail = cf::till_tick;
448 620
449 for (0 .. $#SLOT_QUEUE) { 621 for (0 .. $#SLOT_QUEUE) {
450 if ($SLOT_QUEUE[$_][0] <= $avail) { 622 if ($SLOT_QUEUE[$_][0] <= $avail) {
451 $busy = 0; 623 $busy = 0;
452 my $job = splice @SLOT_QUEUE, $_, 1, (); 624 my $job = splice @SLOT_QUEUE, $_, 1, ();
453 $job->[2]->send; 625 $job->[2]->send;
454 Coro::cede;
455 goto next_job; 626 goto next_job;
456 } else { 627 } else {
457 $SLOT_QUEUE[$_][0] *= $SLOT_DECAY; 628 $SLOT_QUEUE[$_][0] *= $SLOT_DECAY;
458 } 629 }
459 } 630 }
460 631
461 if (@SLOT_QUEUE) { 632 if (@SLOT_QUEUE) {
462 # we do not use wait_for_tick() as it returns immediately when tick is inactive 633 wait_for_tick;
463 push @cf::WAIT_FOR_TICK, $signal;
464 $signal->wait;
465 } else { 634 } else {
466 $busy = 0; 635 $busy = 0;
467 Coro::schedule; 636 Coro::schedule;
468 } 637 }
469 } 638 }
495BEGIN { *async = \&Coro::async_pool } 664BEGIN { *async = \&Coro::async_pool }
496 665
497=item cf::sync_job { BLOCK } 666=item cf::sync_job { BLOCK }
498 667
499The design of Deliantra requires that the main coroutine ($Coro::main) 668The design of Deliantra requires that the main coroutine ($Coro::main)
500is always able to handle events or runnable, as Deliantra is only 669is always able to handle events or is runnable, as Deliantra is only
501partly reentrant. Thus "blocking" it by e.g. waiting for I/O is not 670partly reentrant. Thus "blocking" it by e.g. waiting for I/O is not
502acceptable. 671acceptable.
503 672
504If it must be done, put the blocking parts into C<sync_job>. This will run 673If it must be done, put the blocking parts into C<sync_job>. This will run
505the given BLOCK in another coroutine while waiting for the result. The 674the given BLOCK in another coroutine while waiting for the result. The
509=cut 678=cut
510 679
511sub sync_job(&) { 680sub sync_job(&) {
512 my ($job) = @_; 681 my ($job) = @_;
513 682
514 if ($Coro::current == $Coro::main) { 683 if (in_main) {
515 my $time = AE::time; 684 my $time = AE::time;
516 685
517 # this is the main coro, too bad, we have to block 686 # this is the main coro, too bad, we have to block
518 # till the operation succeeds, freezing the server :/ 687 # till the operation succeeds, freezing the server :/
519 688
520 LOG llevError, Carp::longmess "sync job";#d# 689 #LOG llevError, Carp::longmess "sync job";#d#
521 690
522 my $freeze_guard = freeze_mainloop; 691 my $freeze_guard = freeze_mainloop;
523 692
524 my $busy = 1; 693 my $busy = 1;
525 my @res; 694 my @res;
526 695
527 (async { 696 (async {
528 $Coro::current->desc ("sync job coro"); 697 $Coro::current->desc ("sync job coro");
529 @res = eval { $job->() }; 698 @res = eval { $job->() };
530 warn $@ if $@; 699 error $@ if $@;
531 undef $busy; 700 undef $busy;
532 })->prio (Coro::PRIO_MAX); 701 })->prio (Coro::PRIO_MAX);
533 702
534 while ($busy) { 703 while ($busy) {
535 if (Coro::nready) { 704 if (Coro::nready) {
536 Coro::cede_notself; 705 Coro::cede_notself;
537 } else { 706 } else {
538 EV::loop EV::LOOP_ONESHOT; 707 EV::run EV::RUN_ONCE;
539 } 708 }
540 } 709 }
541 710
542 my $time = AE::time - $time; 711 my $time = AE::time - $time;
543 712
569 $EXT_CORO{$coro+0} = $coro; 738 $EXT_CORO{$coro+0} = $coro;
570 739
571 $coro 740 $coro
572} 741}
573 742
574=item fork_call { }, $args 743=item fork_call { }, @args
575 744
576Executes the given code block with the given arguments in a seperate 745Executes the given code block with the given arguments in a seperate
577process, returning the results. Everything must be serialisable with 746process, returning the results. Everything must be serialisable with
578Coro::Storable. May, of course, block. Note that the executed sub may 747Coro::Storable. May, of course, block. Note that the executed sub may
579never block itself or use any form of event handling. 748never block itself or use any form of event handling.
580 749
581=cut 750=cut
582 751
752sub post_fork {
753 reset_signals;
754}
755
583sub fork_call(&@) { 756sub fork_call(&@) {
584 my ($cb, @args) = @_; 757 my ($cb, @args) = @_;
585 758
586 # we seemingly have to make a local copy of the whole thing,
587 # otherwise perl prematurely frees the stuff :/
588 # TODO: investigate and fix (likely this will be rather laborious)
589
590 my @res = Coro::Util::fork_eval { 759 my @res = Coro::Util::fork_eval {
591 reset_signals; 760 cf::post_fork;
592 &$cb 761 &$cb
593 }, @args; 762 } @args;
594 763
595 wantarray ? @res : $res[-1] 764 wantarray ? @res : $res[-1]
596} 765}
597 766
598sub objinfo { 767sub objinfo {
648within each server. 817within each server.
649 818
650=cut 819=cut
651 820
652sub db_table($) { 821sub db_table($) {
822 cf::error "db_get called from main context"
823 if $Coro::current == $Coro::main;
824
653 my ($name) = @_; 825 my ($name) = @_;
654 my $db = BDB::db_create $DB_ENV; 826 my $db = BDB::db_create $DB_ENV;
655 827
656 eval { 828 eval {
657 $db->set_flags (BDB::CHKSUM); 829 $db->set_flags (BDB::CHKSUM);
667} 839}
668 840
669our $DB; 841our $DB;
670 842
671sub db_init { 843sub db_init {
672 cf::sync_job {
673 $DB ||= db_table "db"; 844 $DB ||= db_table "db";
674 };
675} 845}
676 846
677sub db_get($$) { 847sub db_get($$) {
678 my $key = "$_[0]/$_[1]"; 848 my $key = "$_[0]/$_[1]";
679 849
680 cf::sync_job { 850 cf::error "db_get called from main context"
851 if $Coro::current == $Coro::main;
852
681 BDB::db_get $DB, undef, $key, my $data; 853 BDB::db_get $DB, undef, $key, my $data;
682 854
683 $! ? () 855 $! ? ()
684 : $data 856 : $data
685 }
686} 857}
687 858
688sub db_put($$$) { 859sub db_put($$$) {
689 BDB::dbreq_pri 4; 860 BDB::dbreq_pri 4;
690 BDB::db_put $DB, undef, "$_[0]/$_[1]", $_[2], 0, sub { }; 861 BDB::db_put $DB, undef, "$_[0]/$_[1]", $_[2], 0, sub { };
718 889
719 my @data; 890 my @data;
720 my $md5; 891 my $md5;
721 892
722 for (0 .. $#$src) { 893 for (0 .. $#$src) {
723 0 <= aio_load $src->[$_], $data[$_] 894 $data[$_] = load_file $src->[$_];
724 or Carp::croak "$src->[$_]: $!";
725 } 895 }
726 896
727 # if processing is expensive, check 897 # if processing is expensive, check
728 # checksum first 898 # checksum first
729 if (1) { 899 if (1) {
742 912
743 return db_get cache => "$id/data"; 913 return db_get cache => "$id/data";
744 } 914 }
745 } 915 }
746 916
747 my $t1 = Time::HiRes::time; 917 my $t1 = EV::time;
748 my $data = $process->(\@data); 918 my $data = $process->(\@data);
749 my $t2 = Time::HiRes::time; 919 my $t2 = EV::time;
750 920
751 warn "cache: '$id' processed in ", $t2 - $t1, "s\n"; 921 info "cache: '$id' processed in ", $t2 - $t1, "s\n";
752 922
753 db_put cache => "$id/data", $data; 923 db_put cache => "$id/data", $data;
754 db_put cache => "$id/md5" , $md5; 924 db_put cache => "$id/md5" , $md5;
755 db_put cache => "$id/meta", $meta; 925 db_put cache => "$id/meta", $meta;
756 926
766 936
767=cut 937=cut
768 938
769sub datalog($@) { 939sub datalog($@) {
770 my ($type, %kv) = @_; 940 my ($type, %kv) = @_;
771 warn "DATALOG ", JSON::XS->new->ascii->encode ({ %kv, type => $type }); 941 info "DATALOG ", JSON::XS->new->ascii->encode ({ %kv, type => $type });
772} 942}
773 943
774=back 944=back
775 945
776=cut 946=cut
971 1141
972 } elsif (exists $cb_id{$type}) { 1142 } elsif (exists $cb_id{$type}) {
973 _attach_cb $registry, $cb_id{$type}, $prio, shift @arg; 1143 _attach_cb $registry, $cb_id{$type}, $prio, shift @arg;
974 1144
975 } elsif (ref $type) { 1145 } elsif (ref $type) {
976 warn "attaching objects not supported, ignoring.\n"; 1146 error "attaching objects not supported, ignoring.\n";
977 1147
978 } else { 1148 } else {
979 shift @arg; 1149 shift @arg;
980 warn "attach argument '$type' not supported, ignoring.\n"; 1150 error "attach argument '$type' not supported, ignoring.\n";
981 } 1151 }
982 } 1152 }
983} 1153}
984 1154
985sub _object_attach { 1155sub _object_attach {
995 _attach $registry, $klass, @attach; 1165 _attach $registry, $klass, @attach;
996 } 1166 }
997 1167
998 $obj->{$name} = \%arg; 1168 $obj->{$name} = \%arg;
999 } else { 1169 } else {
1000 warn "object uses attachment '$name' which is not available, postponing.\n"; 1170 info "object uses attachment '$name' which is not available, postponing.\n";
1001 } 1171 }
1002 1172
1003 $obj->{_attachment}{$name} = undef; 1173 $obj->{_attachment}{$name} = undef;
1004} 1174}
1005 1175
1064 1234
1065 for (@$callbacks) { 1235 for (@$callbacks) {
1066 eval { &{$_->[1]} }; 1236 eval { &{$_->[1]} };
1067 1237
1068 if ($@) { 1238 if ($@) {
1069 warn "$@";
1070 warn "... while processing $EVENT[$event][0](@_) event, skipping processing altogether.\n"; 1239 error "$@", "... while processing $EVENT[$event][0](@_) event, skipping processing altogether.\n";
1071 override; 1240 override;
1072 } 1241 }
1073 1242
1074 return 1 if $override; 1243 return 1 if $override;
1075 } 1244 }
1154 for (@$attach) { 1323 for (@$attach) {
1155 my ($klass, @attach) = @$_; 1324 my ($klass, @attach) = @$_;
1156 _attach $registry, $klass, @attach; 1325 _attach $registry, $klass, @attach;
1157 } 1326 }
1158 } else { 1327 } else {
1159 warn "object uses attachment '$name' that is not available, postponing.\n"; 1328 info "object uses attachment '$name' that is not available, postponing.\n";
1160 } 1329 }
1161 } 1330 }
1162} 1331}
1163 1332
1164cf::attachable->attach ( 1333cf::attachable->attach (
1191 my ($filename, $rdata, $objs) = @_; 1360 my ($filename, $rdata, $objs) = @_;
1192 1361
1193 sync_job { 1362 sync_job {
1194 if (length $$rdata) { 1363 if (length $$rdata) {
1195 utf8::decode (my $decname = $filename); 1364 utf8::decode (my $decname = $filename);
1196 warn sprintf "saving %s (%d,%d)\n", 1365 trace sprintf "saving %s (%d,%d)\n",
1197 $decname, length $$rdata, scalar @$objs; 1366 $decname, length $$rdata, scalar @$objs
1367 if $VERBOSE_IO;
1198 1368
1199 if (my $fh = aio_open "$filename~", O_WRONLY | O_CREAT, 0600) { 1369 if (my $fh = aio_open "$filename~", O_WRONLY | O_CREAT, 0600) {
1200 aio_chmod $fh, SAVE_MODE; 1370 aio_chmod $fh, SAVE_MODE;
1201 aio_write $fh, 0, (length $$rdata), $$rdata, 0; 1371 aio_write $fh, 0, (length $$rdata), $$rdata, 0;
1202 if ($cf::USE_FSYNC) { 1372 if ($cf::USE_FSYNC) {
1224 aio_rename "$filename~", $filename; 1394 aio_rename "$filename~", $filename;
1225 1395
1226 $filename =~ s%/[^/]+$%%; 1396 $filename =~ s%/[^/]+$%%;
1227 aio_pathsync $filename if $cf::USE_FSYNC; 1397 aio_pathsync $filename if $cf::USE_FSYNC;
1228 } else { 1398 } else {
1229 warn "unable to save objects: $filename~: $!\n"; 1399 error "unable to save objects: $filename~: $!\n";
1230 } 1400 }
1231 } else { 1401 } else {
1232 aio_unlink $filename; 1402 aio_unlink $filename;
1233 aio_unlink "$filename.pst"; 1403 aio_unlink "$filename.pst";
1234 } 1404 }
1258 my $st = eval { Coro::Storable::thaw $av }; 1428 my $st = eval { Coro::Storable::thaw $av };
1259 $av = $st->{objs}; 1429 $av = $st->{objs};
1260 } 1430 }
1261 1431
1262 utf8::decode (my $decname = $filename); 1432 utf8::decode (my $decname = $filename);
1263 warn sprintf "loading %s (%d,%d)\n", 1433 trace sprintf "loading %s (%d,%d)\n",
1264 $decname, length $data, scalar @{$av || []}; 1434 $decname, length $data, scalar @{$av || []}
1435 if $VERBOSE_IO;
1265 1436
1266 ($data, $av) 1437 ($data, $av)
1267} 1438}
1268 1439
1269=head2 COMMAND CALLBACKS 1440=head2 COMMAND CALLBACKS
1273=cut 1444=cut
1274 1445
1275############################################################################# 1446#############################################################################
1276# command handling &c 1447# command handling &c
1277 1448
1278=item cf::register_command $name => \&callback($ob,$args); 1449=item cf::register_command $name => \&callback($ob,$args)
1279 1450
1280Register a callback for execution when the client sends the user command 1451Register a callback for execution when the client sends the user command
1281$name. 1452$name.
1282 1453
1283=cut 1454=cut
1289 #warn "registering command '$name/$time' to '$caller'"; 1460 #warn "registering command '$name/$time' to '$caller'";
1290 1461
1291 push @{ $COMMAND{$name} }, [$caller, $cb]; 1462 push @{ $COMMAND{$name} }, [$caller, $cb];
1292} 1463}
1293 1464
1294=item cf::register_extcmd $name => \&callback($pl,$packet); 1465=item cf::register_extcmd $name => \&callback($pl,@args)
1295 1466
1296Register a callback for execution when the client sends an (synchronous) 1467Register a callback for execution when the client sends an (synchronous)
1297extcmd packet. Ext commands will be processed in the order they are 1468extcmd packet. Ext commands will be processed in the order they are
1298received by the server, like other user commands. The first argument is 1469received by the server, like other user commands. The first argument is
1299the logged-in player. Ext commands can only be processed after a player 1470the logged-in player. Ext commands can only be processed after a player
1300has logged in successfully. 1471has logged in successfully.
1301 1472
1302If the callback returns something, it is sent back as if reply was being 1473The values will be sent back to the client.
1303called.
1304 1474
1475=item cf::register_async_extcmd $name => \&callback($pl,$reply->(...),@args)
1476
1477Same as C<cf::register_extcmd>, but instead of returning values, the
1478callback needs to clal the C<$reply> function.
1479
1305=item cf::register_exticmd $name => \&callback($ns,$packet); 1480=item cf::register_exticmd $name => \&callback($ns,@args)
1306 1481
1307Register a callback for execution when the client sends an (asynchronous) 1482Register a callback for execution when the client sends an (asynchronous)
1308exticmd packet. Exti commands are processed by the server as soon as they 1483exticmd packet. Exti commands are processed by the server as soon as they
1309are received, i.e. out of order w.r.t. other commands. The first argument 1484are received, i.e. out of order w.r.t. other commands. The first argument
1310is a client socket. Exti commands can be received anytime, even before 1485is a client socket. Exti commands can be received anytime, even before
1311log-in. 1486log-in.
1312 1487
1313If the callback returns something, it is sent back as if reply was being 1488The values will be sent back to the client.
1314called.
1315 1489
1316=cut 1490=item cf::register_async_exticmd $name => \&callback($ns,$reply->(...),@args)
1317 1491
1492Same as C<cf::register_extcmd>, but instead of returning values, the
1493callback needs to clal the C<$reply> function.
1494
1495=cut
1496
1318sub register_extcmd { 1497sub register_extcmd($$) {
1319 my ($name, $cb) = @_; 1498 my ($name, $cb) = @_;
1320 1499
1321 $EXTCMD{$name} = $cb; 1500 $EXTCMD{$name} = $cb;
1322} 1501}
1323 1502
1324sub register_exticmd { 1503sub register_async_extcmd($$) {
1325 my ($name, $cb) = @_; 1504 my ($name, $cb) = @_;
1326 1505
1506 $EXTACMD{$name} = $cb;
1507}
1508
1509sub register_exticmd($$) {
1510 my ($name, $cb) = @_;
1511
1327 $EXTICMD{$name} = $cb; 1512 $EXTICMD{$name} = $cb;
1513}
1514
1515sub register_async_exticmd($$) {
1516 my ($name, $cb) = @_;
1517
1518 $EXTIACMD{$name} = $cb;
1328} 1519}
1329 1520
1330use File::Glob (); 1521use File::Glob ();
1331 1522
1332cf::player->attach ( 1523cf::player->attach (
1346 my ($pl, $buf) = @_; 1537 my ($pl, $buf) = @_;
1347 1538
1348 my $msg = eval { $pl->ns->{json_coder}->decode ($buf) }; 1539 my $msg = eval { $pl->ns->{json_coder}->decode ($buf) };
1349 1540
1350 if (ref $msg) { 1541 if (ref $msg) {
1351 my ($type, $reply, @payload) = 1542 my ($type, $reply, @payload) = @$msg; # version 1 used %type, $id, %$hash
1352 "ARRAY" eq ref $msg
1353 ? @$msg
1354 : ($msg->{msgtype}, $msg->{msgid}, %$msg); # TODO: version 1, remove
1355 1543
1356 my @reply;
1357
1358 if (my $cb = $EXTCMD{$type}) { 1544 if (my $cb = $EXTACMD{$type}) {
1545 $cb->(
1546 $pl,
1547 sub {
1548 $pl->ext_msg ("reply-$reply", @_)
1549 if $reply;
1550 },
1551 @payload
1552 );
1553 } else {
1554 my @reply;
1555
1556 if (my $cb = $EXTCMD{$type}) {
1359 @reply = $cb->($pl, @payload); 1557 @reply = $cb->($pl, @payload);
1558 }
1559
1560 $pl->ext_msg ("reply-$reply", @reply)
1561 if $reply;
1360 } 1562 }
1361 1563
1362 $pl->ext_reply ($reply, @reply)
1363 if $reply;
1364
1365 } else { 1564 } else {
1366 warn "player " . ($pl->ob->name) . " sent unparseable ext message: <$buf>\n"; 1565 error "player " . ($pl->ob->name) . " sent unparseable ext message: <$buf>\n";
1367 } 1566 }
1368 1567
1369 cf::override; 1568 cf::override;
1370 }, 1569 },
1371); 1570);
1381 }; 1580 };
1382 1581
1383 $grp 1582 $grp
1384} 1583}
1385 1584
1585sub _ext_cfg_reg($$$$) {
1586 my ($rvar, $varname, $cfgname, $default) = @_;
1587
1588 $cfgname = lc $varname
1589 unless length $cfgname;
1590
1591 $EXT_CFG{$cfgname} = [$rvar, $default];
1592
1593 $$rvar = exists $CFG{$cfgname} ? $CFG{$cfgname} : $default;
1594}
1595
1386sub load_extensions { 1596sub load_extensions {
1597 info "loading extensions...";
1598
1599 %EXT_CFG = ();
1600
1387 cf::sync_job { 1601 cf::sync_job {
1388 my %todo; 1602 my %todo;
1389 1603
1390 for my $path (<$LIBDIR/*.ext>) { 1604 for my $path (<$LIBDIR/*.ext>) {
1391 next unless -r $path; 1605 next unless -r $path;
1409 1623
1410 $ext{meta} = { map { (split /=/, $_, 2)[0, 1] } split /\s+/, $1 } 1624 $ext{meta} = { map { (split /=/, $_, 2)[0, 1] } split /\s+/, $1 }
1411 if $source =~ /\A#!.*?perl.*?#\s*(.*)$/m; 1625 if $source =~ /\A#!.*?perl.*?#\s*(.*)$/m;
1412 1626
1413 $ext{source} = 1627 $ext{source} =
1414 "package $pkg; use 5.10.0; use strict 'vars', 'subs'; use utf8;\n" 1628 "package $pkg; use common::sense;\n"
1415 . "#line 1 \"$path\"\n{\n" 1629 . "#line 1 \"$path\"\n{\n"
1416 . $source 1630 . $source
1417 . "\n};\n1"; 1631 . "\n};\n1";
1418 1632
1419 $todo{$base} = \%ext; 1633 $todo{$base} = \%ext;
1431 for (split /,\s*/, $v->{meta}{depends}) { 1645 for (split /,\s*/, $v->{meta}{depends}) {
1432 next ext 1646 next ext
1433 unless exists $done{$_}; 1647 unless exists $done{$_};
1434 } 1648 }
1435 1649
1436 warn "... pass $pass, loading '$k' into '$v->{pkg}'\n"; 1650 trace "... pass $pass, loading '$k' into '$v->{pkg}'\n";
1437 1651
1652 my $source = $v->{source};
1653
1654 # support "CONF varname :confname = default" pseudo-statements
1655 $source =~ s{
1656 ^ CONF \s+ ([^\s:=]+) \s* (?:: \s* ([^\s:=]+) \s* )? = ([^\n#]+)
1657 }{
1658 "our \$$1; BEGIN { cf::_ext_cfg_reg \\\$$1, q\x00$1\x00, q\x00$2\x00, $3 }";
1659 }gmxe;
1660
1438 my $active = eval $v->{source}; 1661 my $active = eval $source;
1439 1662
1440 if (length $@) { 1663 if (length $@) {
1441 warn "$v->{path}: $@\n"; 1664 error "$v->{path}: $@\n";
1442 1665
1443 cf::cleanup "mandatory extension '$k' failed to load, exiting." 1666 cf::cleanup "mandatory extension '$k' failed to load, exiting."
1444 if exists $v->{meta}{mandatory}; 1667 if exists $v->{meta}{mandatory};
1445 1668
1446 warn "$v->{base}: optional extension cannot be loaded, skipping.\n"; 1669 warn "$v->{base}: optional extension cannot be loaded, skipping.\n";
1448 } else { 1671 } else {
1449 $done{$k} = delete $todo{$k}; 1672 $done{$k} = delete $todo{$k};
1450 push @EXTS, $v->{pkg}; 1673 push @EXTS, $v->{pkg};
1451 $progress = 1; 1674 $progress = 1;
1452 1675
1453 warn "$v->{base}: extension inactive.\n" 1676 info "$v->{base}: extension inactive.\n"
1454 unless $active; 1677 unless $active;
1455 } 1678 }
1456 } 1679 }
1457 1680
1458 unless ($progress) { 1681 unless ($progress) {
1460 1683
1461 while (my ($k, $v) = each %todo) { 1684 while (my ($k, $v) = each %todo) {
1462 cf::cleanup "mandatory extension '$k' has unresolved dependencies, exiting." 1685 cf::cleanup "mandatory extension '$k' has unresolved dependencies, exiting."
1463 if exists $v->{meta}{mandatory}; 1686 if exists $v->{meta}{mandatory};
1464 } 1687 }
1688
1689 last;
1465 } 1690 }
1466 } 1691 }
1467 }; 1692 };
1468} 1693}
1469 1694
1627 my $name = $pl->ob->name; 1852 my $name = $pl->ob->name;
1628 1853
1629 $pl->{deny_save} = 1; 1854 $pl->{deny_save} = 1;
1630 $pl->password ("*"); # this should lock out the player until we have nuked the dir 1855 $pl->password ("*"); # this should lock out the player until we have nuked the dir
1631 1856
1632 $pl->invoke (cf::EVENT_PLAYER_LOGOUT, 1) if $pl->active; 1857 $pl->invoke (cf::EVENT_PLAYER_LOGOUT, 1) if $pl->ns;
1633 $pl->deactivate; 1858 $pl->deactivate;
1859
1634 my $killer = cf::arch::get "killer_quit"; $pl->killer ($killer); $killer->destroy; 1860 my $killer = cf::arch::get "killer_quit"; $pl->killer ($killer); $killer->destroy;
1635 $pl->ob->check_score;
1636 $pl->invoke (cf::EVENT_PLAYER_QUIT); 1861 $pl->invoke (cf::EVENT_PLAYER_QUIT) if $pl->ns;
1862 ext::highscore::check ($pl->ob);
1863
1637 $pl->ns->destroy if $pl->ns; 1864 $pl->ns->destroy if $pl->ns;
1638 1865
1639 my $path = playerdir $pl; 1866 my $path = playerdir $pl;
1640 my $temp = "$path~$cf::RUNTIME~deleting~"; 1867 my $temp = "$path~$cf::RUNTIME~deleting~";
1641 aio_rename $path, $temp; 1868 aio_rename $path, $temp;
1695 \@logins 1922 \@logins
1696} 1923}
1697 1924
1698=item $player->maps 1925=item $player->maps
1699 1926
1927=item cf::player::maps $login
1928
1700Returns an arrayref of map paths that are private for this 1929Returns an arrayref of map paths that are private for this
1701player. May block. 1930player. May block.
1702 1931
1703=cut 1932=cut
1704 1933
1725 1954
1726=item $protocol_xml = $player->expand_cfpod ($cfpod) 1955=item $protocol_xml = $player->expand_cfpod ($cfpod)
1727 1956
1728Expand deliantra pod fragments into protocol xml. 1957Expand deliantra pod fragments into protocol xml.
1729 1958
1730=item $player->ext_reply ($msgid, @msg)
1731
1732Sends an ext reply to the player.
1733
1734=cut
1735
1736sub ext_reply($$@) {
1737 my ($self, $id, @msg) = @_;
1738
1739 $self->ns->ext_reply ($id, @msg)
1740}
1741
1742=item $player->ext_msg ($type, @msg) 1959=item $player->ext_msg ($type, @msg)
1743 1960
1744Sends an ext event to the client. 1961Sends an ext event to the client.
1745 1962
1746=cut 1963=cut
1765 1982
1766=cut 1983=cut
1767 1984
1768sub find_by_path($) { 1985sub find_by_path($) {
1769 my ($path) = @_; 1986 my ($path) = @_;
1987
1988 $path =~ s/^~[^\/]*//; # skip ~login
1770 1989
1771 my ($match, $specificity); 1990 my ($match, $specificity);
1772 1991
1773 for my $region (list) { 1992 for my $region (list) {
1774 if ($region->{match} && $path =~ $region->{match}) { 1993 if ($region->{match} && $path =~ $region->{match}) {
1803sub generate_random_map { 2022sub generate_random_map {
1804 my ($self, $rmp) = @_; 2023 my ($self, $rmp) = @_;
1805 2024
1806 my $lock = cf::lock_acquire "generate_random_map"; # the random map generator is NOT reentrant ATM 2025 my $lock = cf::lock_acquire "generate_random_map"; # the random map generator is NOT reentrant ATM
1807 2026
1808 # mit "rum" bekleckern, nicht
1809 $self->_create_random_map ( 2027 $self->_create_random_map ($rmp);
1810 $rmp->{wallstyle}, $rmp->{wall_name}, $rmp->{floorstyle}, $rmp->{monsterstyle},
1811 $rmp->{treasurestyle}, $rmp->{layoutstyle}, $rmp->{doorstyle}, $rmp->{decorstyle}, $rmp->{miningstyle},
1812 $rmp->{origin_map}, $rmp->{final_map}, $rmp->{exitstyle}, $rmp->{this_map},
1813 $rmp->{exit_on_final_map},
1814 $rmp->{xsize}, $rmp->{ysize},
1815 $rmp->{expand2x}, $rmp->{layoutoptions1}, $rmp->{layoutoptions2}, $rmp->{layoutoptions3},
1816 $rmp->{symmetry}, $rmp->{difficulty}, $rmp->{difficulty_given}, $rmp->{difficulty_increase},
1817 $rmp->{dungeon_level}, $rmp->{dungeon_depth}, $rmp->{decoroptions}, $rmp->{orientation},
1818 $rmp->{origin_y}, $rmp->{origin_x}, $rmp->{random_seed}, $rmp->{total_map_hp},
1819 $rmp->{map_layout_style}, $rmp->{treasureoptions}, $rmp->{symmetry_used},
1820 (cf::region::find $rmp->{region}), $rmp->{custom}
1821 )
1822} 2028}
1823 2029
1824=item cf::map->register ($regex, $prio) 2030=item cf::map->register ($regex, $prio)
1825 2031
1826Register a handler for the map path matching the given regex at the 2032Register a handler for the map path matching the given regex at the
1831 2037
1832sub register { 2038sub register {
1833 my (undef, $regex, $prio) = @_; 2039 my (undef, $regex, $prio) = @_;
1834 my $pkg = caller; 2040 my $pkg = caller;
1835 2041
1836 no strict;
1837 push @{"$pkg\::ISA"}, __PACKAGE__; 2042 push @{"$pkg\::ISA"}, __PACKAGE__;
1838 2043
1839 $EXT_MAP{$pkg} = [$prio, qr<$regex>]; 2044 $EXT_MAP{$pkg} = [$prio, qr<$regex>];
1840} 2045}
1841 2046
1842# also paths starting with '/' 2047# also paths starting with '/'
1843$EXT_MAP{"cf::map"} = [0, qr{^(?=/)}]; 2048$EXT_MAP{"cf::map::wrap"} = [0, qr{^(?=/)}];
1844 2049
1845sub thawer_merge { 2050sub thawer_merge {
1846 my ($self, $merge) = @_; 2051 my ($self, $merge) = @_;
1847 2052
1848 # we have to keep some variables in memory intact 2053 # we have to keep some variables in memory intact
1853} 2058}
1854 2059
1855sub normalise { 2060sub normalise {
1856 my ($path, $base) = @_; 2061 my ($path, $base) = @_;
1857 2062
1858 $path = "$path"; # make sure its a string 2063 $path = "$path"; # make sure it's a string
1859 2064
1860 $path =~ s/\.map$//; 2065 $path =~ s/\.map$//;
1861 2066
1862 # map plan: 2067 # map plan:
1863 # 2068 #
1878 $base =~ s{[^/]+/?$}{}; 2083 $base =~ s{[^/]+/?$}{};
1879 $path = "$base/$path"; 2084 $path = "$base/$path";
1880 } 2085 }
1881 2086
1882 for ($path) { 2087 for ($path) {
1883 redo if s{//}{/};
1884 redo if s{/\.?/}{/}; 2088 redo if s{/\.?/}{/};
1885 redo if s{/[^/]+/\.\./}{/}; 2089 redo if s{/[^/]+/\.\./}{/};
1886 } 2090 }
1887 2091
1888 $path 2092 $path
1902 $self->init; # pass $1 etc. 2106 $self->init; # pass $1 etc.
1903 return $self; 2107 return $self;
1904 } 2108 }
1905 } 2109 }
1906 2110
1907 Carp::cluck "unable to resolve path '$path' (base '$base')."; 2111 Carp::cluck "unable to resolve path '$path' (base '$base')";
1908 () 2112 ()
1909} 2113}
1910 2114
2115# may re-bless or do other evil things
1911sub init { 2116sub init {
1912 my ($self) = @_; 2117 my ($self) = @_;
1913 2118
1914 $self 2119 $self
1915} 2120}
1980 $self->{load_path} = $path; 2185 $self->{load_path} = $path;
1981 2186
1982 1 2187 1
1983} 2188}
1984 2189
2190# used to laod the header of an original map
1985sub load_header_orig { 2191sub load_header_orig {
1986 my ($self) = @_; 2192 my ($self) = @_;
1987 2193
1988 $self->load_header_from ($self->load_path) 2194 $self->load_header_from ($self->load_path)
1989} 2195}
1990 2196
2197# used to laod the header of an instantiated map
1991sub load_header_temp { 2198sub load_header_temp {
1992 my ($self) = @_; 2199 my ($self) = @_;
1993 2200
1994 $self->load_header_from ($self->save_path) 2201 $self->load_header_from ($self->save_path)
1995} 2202}
1996 2203
2204# called after loading the header from an instantiated map
1997sub prepare_temp { 2205sub prepare_temp {
1998 my ($self) = @_; 2206 my ($self) = @_;
1999 2207
2000 $self->last_access ((delete $self->{last_access}) 2208 $self->last_access ((delete $self->{last_access})
2001 || $cf::RUNTIME); #d# 2209 || $cf::RUNTIME); #d#
2002 # safety 2210 # safety
2003 $self->{instantiate_time} = $cf::RUNTIME 2211 $self->{instantiate_time} = $cf::RUNTIME
2004 if $self->{instantiate_time} > $cf::RUNTIME; 2212 if $self->{instantiate_time} > $cf::RUNTIME;
2005} 2213}
2006 2214
2215# called after loading the header from an original map
2007sub prepare_orig { 2216sub prepare_orig {
2008 my ($self) = @_; 2217 my ($self) = @_;
2009 2218
2010 $self->{load_original} = 1; 2219 $self->{load_original} = 1;
2011 $self->{instantiate_time} = $cf::RUNTIME; 2220 $self->{instantiate_time} = $cf::RUNTIME;
2035 2244
2036sub find; 2245sub find;
2037sub find { 2246sub find {
2038 my ($path, $origin) = @_; 2247 my ($path, $origin) = @_;
2039 2248
2249 cf::cede_to_tick;
2250
2040 $path = normalise $path, $origin && $origin->path; 2251 $path = normalise $path, $origin;
2041 2252
2042 my $guard1 = cf::lock_acquire "map_data:$path";#d#remove 2253 my $guard1 = cf::lock_acquire "map_data:$path";#d#remove
2043 my $guard2 = cf::lock_acquire "map_find:$path"; 2254 my $guard2 = cf::lock_acquire "map_find:$path";
2044 2255
2045 $cf::MAP{$path} || do { 2256 $cf::MAP{$path} || do {
2076 2287
2077 { 2288 {
2078 my $guard = cf::lock_acquire "map_data:$path"; 2289 my $guard = cf::lock_acquire "map_data:$path";
2079 2290
2080 return unless $self->valid; 2291 return unless $self->valid;
2081 return unless $self->in_memory == cf::MAP_SWAPPED; 2292 return unless $self->state == cf::MAP_SWAPPED;
2082
2083 $self->in_memory (cf::MAP_LOADING);
2084 2293
2085 $self->alloc; 2294 $self->alloc;
2086 2295
2087 $self->pre_load; 2296 $self->pre_load;
2088 cf::cede_to_tick; 2297 cf::cede_to_tick;
2089 2298
2299 if (exists $self->{load_path}) {
2090 my $f = new_from_file cf::object::thawer $self->{load_path}; 2300 my $f = new_from_file cf::object::thawer $self->{load_path};
2091 $f->skip_block; 2301 $f->skip_block;
2092 $self->_load_objects ($f) 2302 $self->_load_objects ($f)
2093 or return; 2303 or return;
2094 2304
2095 $self->post_load_original 2305 $self->post_load_original
2096 if delete $self->{load_original}; 2306 if delete $self->{load_original};
2097 2307
2098 if (my $uniq = $self->uniq_path) { 2308 if (my $uniq = $self->uniq_path) {
2099 utf8::encode $uniq; 2309 utf8::encode $uniq;
2100 unless (aio_stat $uniq) { 2310 unless (aio_stat $uniq) {
2101 if (my $f = new_from_file cf::object::thawer $uniq) { 2311 if (my $f = new_from_file cf::object::thawer $uniq) {
2102 $self->clear_unique_items; 2312 $self->clear_unique_items;
2103 $self->_load_objects ($f); 2313 $self->_load_objects ($f);
2104 $f->resolve_delayed_derefs; 2314 $f->resolve_delayed_derefs;
2315 }
2105 } 2316 }
2106 } 2317 }
2107 }
2108 2318
2109 $f->resolve_delayed_derefs; 2319 $f->resolve_delayed_derefs;
2320 } else {
2321 $self->post_load_original
2322 if delete $self->{load_original};
2323 }
2324
2325 $self->state (cf::MAP_INACTIVE);
2110 2326
2111 cf::cede_to_tick; 2327 cf::cede_to_tick;
2112 # now do the right thing for maps 2328 # now do the right thing for maps
2113 $self->link_multipart_objects; 2329 $self->link_multipart_objects;
2114 $self->difficulty ($self->estimate_difficulty) 2330 $self->difficulty ($self->estimate_difficulty)
2118 unless ($self->{deny_activate}) { 2334 unless ($self->{deny_activate}) {
2119 $self->decay_objects; 2335 $self->decay_objects;
2120 $self->fix_auto_apply; 2336 $self->fix_auto_apply;
2121 $self->update_buttons; 2337 $self->update_buttons;
2122 cf::cede_to_tick; 2338 cf::cede_to_tick;
2123 $self->activate; 2339 #$self->activate; # no longer activate maps automatically
2124 } 2340 }
2125 2341
2126 $self->{last_save} = $cf::RUNTIME; 2342 $self->{last_save} = $cf::RUNTIME;
2127 $self->last_access ($cf::RUNTIME); 2343 $self->last_access ($cf::RUNTIME);
2128
2129 $self->in_memory (cf::MAP_ACTIVE);
2130 } 2344 }
2131 2345
2132 $self->post_load; 2346 $self->post_load;
2347
2348 1
2133} 2349}
2134 2350
2135# customize the map for a given player, i.e. 2351# customize the map for a given player, i.e.
2136# return the _real_ map. used by e.g. per-player 2352# return the _real_ map. used by e.g. per-player
2137# maps to change the path to ~playername/mappath 2353# maps to change the path to ~playername/mappath
2145# if $self->per_party; 2361# if $self->per_party;
2146 2362
2147 $self 2363 $self
2148} 2364}
2149 2365
2150# find and load all maps in the 3x3 area around a map
2151sub load_neighbours {
2152 my ($map) = @_;
2153
2154 my @neigh; # diagonal neighbours
2155
2156 for (0 .. 3) {
2157 my $neigh = $map->tile_path ($_)
2158 or next;
2159 $neigh = find $neigh, $map
2160 or next;
2161 $neigh->load;
2162
2163 push @neigh,
2164 [$neigh->tile_path (($_ + 3) % 4), $neigh],
2165 [$neigh->tile_path (($_ + 1) % 4), $neigh];
2166 }
2167
2168 for (grep defined $_->[0], @neigh) {
2169 my ($path, $origin) = @$_;
2170 my $neigh = find $path, $origin
2171 or next;
2172 $neigh->load;
2173 }
2174}
2175
2176sub find_sync { 2366sub find_sync {
2177 my ($path, $origin) = @_; 2367 my ($path, $origin) = @_;
2178 2368
2179 cf::sync_job { find $path, $origin } 2369 # it's a bug to call this from the main context
2370 return cf::LOG cf::llevError | cf::logBacktrace, "do_find_sync"
2371 if $Coro::current == $Coro::main;
2372
2373 find $path, $origin
2180} 2374}
2181 2375
2182sub do_load_sync { 2376sub do_load_sync {
2183 my ($map) = @_; 2377 my ($map) = @_;
2184 2378
2379 # it's a bug to call this from the main context
2185 cf::LOG cf::llevDebug | cf::logBacktrace, "do_load_sync" 2380 return cf::LOG cf::llevError | cf::logBacktrace, "do_load_sync"
2186 if $Coro::current == $Coro::main; 2381 if $Coro::current == $Coro::main;
2187 2382
2188 cf::sync_job { $map->load }; 2383 $map->load;
2189} 2384}
2190 2385
2191our %MAP_PREFETCH; 2386our %MAP_PREFETCH;
2192our $MAP_PREFETCHER = undef; 2387our $MAP_PREFETCHER = undef;
2193 2388
2194sub find_async { 2389sub find_async {
2195 my ($path, $origin, $load) = @_; 2390 my ($path, $origin, $load) = @_;
2196 2391
2197 $path = normalise $path, $origin && $origin->{path}; 2392 $path = normalise $path, $origin;
2198 2393
2199 if (my $map = $cf::MAP{$path}) { 2394 if (my $map = $cf::MAP{$path}) {
2200 return $map if !$load || $map->in_memory == cf::MAP_ACTIVE; 2395 return $map if !$load || $map->linkable;
2201 } 2396 }
2202 2397
2203 $MAP_PREFETCH{$path} |= $load; 2398 $MAP_PREFETCH{$path} |= $load;
2204 2399
2205 $MAP_PREFETCHER ||= cf::async { 2400 $MAP_PREFETCHER ||= cf::async {
2206 $Coro::current->{desc} = "map prefetcher"; 2401 $Coro::current->{desc} = "map prefetcher";
2207 2402
2208 while (%MAP_PREFETCH) { 2403 while (%MAP_PREFETCH) {
2209 while (my ($k, $v) = each %MAP_PREFETCH) { 2404 for my $k (keys %MAP_PREFETCH) {
2210 if (my $map = find $k) { 2405 if (my $map = find $k) {
2211 $map->load if $v; 2406 $map->load if $MAP_PREFETCH{$k};
2212 } 2407 }
2213 2408
2214 delete $MAP_PREFETCH{$k}; 2409 delete $MAP_PREFETCH{$k};
2215 } 2410 }
2216 } 2411 }
2264sub swap_out { 2459sub swap_out {
2265 my ($self) = @_; 2460 my ($self) = @_;
2266 2461
2267 my $lock = cf::lock_acquire "map_data:$self->{path}"; 2462 my $lock = cf::lock_acquire "map_data:$self->{path}";
2268 2463
2269 return if $self->in_memory != cf::MAP_ACTIVE; 2464 return if !$self->linkable;
2270 return if $self->{deny_save}; 2465 return if $self->{deny_save};
2271 return if $self->players; 2466 return if $self->players;
2272 2467
2273 # first deactivate the map and "unlink" it from the core 2468 # first deactivate the map and "unlink" it from the core
2274 $self->deactivate; 2469 $self->deactivate;
2275 $_->clear_links_to ($self) for values %cf::MAP; 2470 $_->clear_links_to ($self) for values %cf::MAP;
2276 $self->in_memory (cf::MAP_SWAPPED); 2471 $self->state (cf::MAP_SWAPPED);
2277 2472
2278 # then atomically save 2473 # then atomically save
2279 $self->_save; 2474 $self->_save;
2280 2475
2281 # then free the map 2476 # then free the map
2305 2500
2306 my $lock = cf::lock_acquire "map_data:$self->{path}"; 2501 my $lock = cf::lock_acquire "map_data:$self->{path}";
2307 2502
2308 return if $self->players; 2503 return if $self->players;
2309 2504
2310 warn "resetting map ", $self->path, "\n"; 2505 cf::trace "resetting map ", $self->path, "\n";
2311 2506
2312 $self->in_memory (cf::MAP_SWAPPED); 2507 $self->state (cf::MAP_SWAPPED);
2313 2508
2314 # need to save uniques path 2509 # need to save uniques path
2315 unless ($self->{deny_save}) { 2510 unless ($self->{deny_save}) {
2316 my $uniq = $self->uniq_path; utf8::encode $uniq; 2511 my $uniq = $self->uniq_path; utf8::encode $uniq;
2317 2512
2339 2534
2340 delete $cf::MAP{$self->path}; 2535 delete $cf::MAP{$self->path};
2341 2536
2342 $self->unlink_save; 2537 $self->unlink_save;
2343 2538
2344 bless $self, "cf::map"; 2539 bless $self, "cf::map::wrap";
2345 delete $self->{deny_reset}; 2540 delete $self->{deny_reset};
2346 $self->{deny_save} = 1; 2541 $self->{deny_save} = 1;
2347 $self->reset_timeout (1); 2542 $self->reset_timeout (1);
2348 $self->path ($self->{path} = "{nuke}/" . ($nuke_counter++)); 2543 $self->path ($self->{path} = "{nuke}/" . ($nuke_counter++));
2349 2544
2470 2665
2471Creates and returns a persistent reference to an object that can be stored as a string. 2666Creates and returns a persistent reference to an object that can be stored as a string.
2472 2667
2473=item $ob = cf::object::deref ($refstring) 2668=item $ob = cf::object::deref ($refstring)
2474 2669
2475returns the objetc referenced by refstring. may return undef when it cnanot find the object, 2670returns the objetc referenced by refstring. may return undef when it cannot find the object,
2476even if the object actually exists. May block. 2671even if the object actually exists. May block.
2477 2672
2478=cut 2673=cut
2479 2674
2480sub deref { 2675sub deref {
2562=item $player_object->may ("access") 2757=item $player_object->may ("access")
2563 2758
2564Returns wether the given player is authorized to access resource "access" 2759Returns wether the given player is authorized to access resource "access"
2565(e.g. "command_wizcast"). 2760(e.g. "command_wizcast").
2566 2761
2762This is implemented by checking a config setting of C<may_access> where
2763C<access> is replaced by the access string. The following alternatives are
2764possible (and are tested in order):
2765
2766=over 4
2767
2768=item * Player is DM
2769
2770The request will succeed.
2771
2772=item * may_access is an array reference
2773
2774If either the player nickname or UUID is in the array, the request will
2775succeed, otherwise it will fail.
2776
2777=item * may_access is a true value
2778
2779The request will succeed.
2780
2781=item * may_access is missing or false
2782
2783The request will fail.
2784
2785=back
2786
2567=cut 2787=cut
2568 2788
2569sub cf::object::player::may { 2789sub cf::object::player::may {
2570 my ($self, $access) = @_; 2790 my ($self, $access) = @_;
2571 2791
2572 $self->flag (cf::FLAG_WIZ) || 2792 $self->flag (cf::FLAG_WIZ) ||
2573 (ref $cf::CFG{"may_$access"} 2793 (ref $cf::CFG{"may_$access"}
2574 ? scalar grep $self->name eq $_, @{$cf::CFG{"may_$access"}} 2794 ? scalar grep $self->name eq $_ || $self->uuid eq $_, @{$cf::CFG{"may_$access"}}
2575 : $cf::CFG{"may_$access"}) 2795 : $cf::CFG{"may_$access"})
2576} 2796}
2577 2797
2578=item $player_object->enter_link 2798=item $player_object->enter_link
2579 2799
2580Freezes the player and moves him/her to a special map (C<{link}>). 2800Freezes the player and moves him/her to a special map (C<{link}>).
2581 2801
2582The player should be reasonably safe there for short amounts of time (e.g. 2802The player should be reasonably safe there for short amounts of time (e.g.
2583for loading a map). You I<MUST> call C<leave_link> as soon as possible, 2803for loading a map). You I<MUST> call C<leave_link> as soon as possible,
2584though, as the palyer cannot control the character while it is on the link 2804though, as the player cannot control the character while it is on the link
2585map. 2805map.
2586 2806
2587Will never block. 2807This method will never block, which is the whole reaosn for it's
2808existance: you can I<always> put a player onto the link map, which is the
2809only place to put objects that is guaranteed to exist.
2810
2811A typical usage pattern is to call C<enter_link> synchronously from the
2812server, then start a new thread, do your blocking stuff there and then
2813call C<leave_link> from that thread.
2588 2814
2589=item $player_object->leave_link ($map, $x, $y) 2815=item $player_object->leave_link ($map, $x, $y)
2590 2816
2591Moves the player out of the special C<{link}> map onto the specified 2817Moves the player out of the special C<{link}> map onto the specified
2592map. If the map is not valid (or omitted), the player will be moved back 2818map. If the map is not valid (or omitted), the player will be moved back
2610sub cf::object::player::enter_link { 2836sub cf::object::player::enter_link {
2611 my ($self) = @_; 2837 my ($self) = @_;
2612 2838
2613 $self->deactivate_recursive; 2839 $self->deactivate_recursive;
2614 2840
2841 ++$self->{_link_recursion};
2842
2615 return if UNIVERSAL::isa $self->map, "ext::map_link"; 2843 return if UNIVERSAL::isa $self->map, "ext::map_link";
2616 2844
2617 $self->{_link_pos} ||= [$self->map->{path}, $self->x, $self->y] 2845 $self->{_link_pos} ||= [$self->map->{path}, $self->x, $self->y]
2618 if $self->map && $self->map->{path} ne "{link}"; 2846 if $self->map && $self->map->{path} ne "{link}";
2619 2847
2645 # use -1 or undef as default coordinates, not 0, 0 2873 # use -1 or undef as default coordinates, not 0, 0
2646 ($x, $y) = ($map->enter_x, $map->enter_y) 2874 ($x, $y) = ($map->enter_x, $map->enter_y)
2647 if $x <= 0 && $y <= 0; 2875 if $x <= 0 && $y <= 0;
2648 2876
2649 $map->load; 2877 $map->load;
2650 $map->load_neighbours;
2651 2878
2652 return unless $self->contr->active; 2879 return unless $self->contr->active;
2653 2880
2654 local $self->{_prev_pos} = $link_pos; # ugly hack for rent.ext 2881 local $self->{_prev_pos} = $link_pos; # ugly hack for rent.ext
2655 $self->enter_map ($map, $x, $y); 2882 if ($self->enter_map ($map, $x, $y)) {
2656 2883 # entering was successful
2884 delete $self->{_link_recursion};
2657 # only activate afterwards, to support waiting in hooks 2885 # only activate afterwards, to support waiting in hooks
2658 $self->activate_recursive; 2886 $self->activate_recursive;
2659} 2887 }
2660 2888
2889}
2890
2661=item $player_object->goto ($path, $x, $y[, $check->($map)[, $done->()]]) 2891=item $player_object->goto ($path, $x, $y[, $check->($map, $x, $y, $player)[, $done->($player)]])
2662 2892
2663Moves the player to the given map-path and coordinates by first freezing 2893Moves the player to the given map-path and coordinates by first freezing
2664her, loading and preparing them map, calling the provided $check callback 2894her, loading and preparing them map, calling the provided $check callback
2665that has to return the map if sucecssful, and then unfreezes the player on 2895that has to return the map if sucecssful, and then unfreezes the player on
2666the new (success) or old (failed) map position. In either case, $done will 2896the new (success) or old (failed) map position. In either case, $done will
2673 2903
2674our $GOTOGEN; 2904our $GOTOGEN;
2675 2905
2676sub cf::object::player::goto { 2906sub cf::object::player::goto {
2677 my ($self, $path, $x, $y, $check, $done) = @_; 2907 my ($self, $path, $x, $y, $check, $done) = @_;
2908
2909 if ($self->{_link_recursion} >= $MAX_LINKS) {
2910 error "FATAL: link recursion exceeded, ", $self->name, " goto $path $x $y, redirecting.";
2911 $self->failmsg ("Something went wrong inside the server - please contact an administrator!");
2912 ($path, $x, $y) = @$EMERGENCY_POSITION;
2913 }
2678 2914
2679 # do generation counting so two concurrent goto's will be executed in-order 2915 # do generation counting so two concurrent goto's will be executed in-order
2680 my $gen = $self->{_goto_generation} = ++$GOTOGEN; 2916 my $gen = $self->{_goto_generation} = ++$GOTOGEN;
2681 2917
2682 $self->enter_link; 2918 $self->enter_link;
2702 ($path, $x, $y) = (undef, undef, undef); 2938 ($path, $x, $y) = (undef, undef, undef);
2703 } 2939 }
2704 } 2940 }
2705 2941
2706 my $map = eval { 2942 my $map = eval {
2707 my $map = defined $path ? cf::map::find $path : undef; 2943 my $map = defined $path ? cf::map::find $path, $self->map : undef;
2708 2944
2709 if ($map) { 2945 if ($map) {
2710 $map = $map->customise_for ($self); 2946 $map = $map->customise_for ($self);
2711 $map = $check->($map) if $check && $map; 2947 $map = $check->($map, $x, $y, $self) if $check && $map;
2712 } else { 2948 } else {
2713 $self->message ("The exit to '$path' is closed.", cf::NDI_UNIQUE | cf::NDI_RED); 2949 $self->message ("The exit to '$path' is closed.", cf::NDI_UNIQUE | cf::NDI_RED);
2714 } 2950 }
2715 2951
2716 $map 2952 $map
2724 if ($gen == $self->{_goto_generation}) { 2960 if ($gen == $self->{_goto_generation}) {
2725 delete $self->{_goto_generation}; 2961 delete $self->{_goto_generation};
2726 $self->leave_link ($map, $x, $y); 2962 $self->leave_link ($map, $x, $y);
2727 } 2963 }
2728 2964
2729 $done->() if $done; 2965 $done->($self) if $done;
2730 })->prio (1); 2966 })->prio (1);
2731} 2967}
2732 2968
2733=item $player_object->enter_exit ($exit_object) 2969=item $player_object->enter_exit ($exit_object)
2734 2970
2802 $Coro::current->{desc} = "enter_exit"; 3038 $Coro::current->{desc} = "enter_exit";
2803 3039
2804 unless (eval { 3040 unless (eval {
2805 $self->deactivate_recursive; # just to be sure 3041 $self->deactivate_recursive; # just to be sure
2806 3042
2807 # random map handling
2808 {
2809 my $guard = cf::lock_acquire "exit_prepare:$exit";
2810
2811 prepare_random_map $exit
2812 if $exit->slaying eq "/!";
2813 }
2814
2815 my $map = cf::map::normalise $exit->slaying, $exit->map && $exit->map->path; 3043 my $map = cf::map::normalise $exit->slaying, $exit->map;
2816 my $x = $exit->stats->hp; 3044 my $x = $exit->stats->hp;
2817 my $y = $exit->stats->sp; 3045 my $y = $exit->stats->sp;
3046
3047 # special map handling
3048 my $slaying = $exit->slaying;
3049
3050 # special map handling
3051 if ($slaying eq "/!") {
3052 my $guard = cf::lock_acquire "exit_prepare:$exit";
3053
3054 prepare_random_map $exit
3055 if $exit->slaying eq "/!"; # need to re-check after getting the lock
3056
3057 $map = $exit->slaying;
3058
3059 } elsif ($slaying eq '!up') {
3060 $map = $exit->map->tile_path (cf::TILE_UP);
3061 $x = $exit->x;
3062 $y = $exit->y;
3063
3064 } elsif ($slaying eq '!down') {
3065 $map = $exit->map->tile_path (cf::TILE_DOWN);
3066 $x = $exit->x;
3067 $y = $exit->y;
3068 }
2818 3069
2819 $self->goto ($map, $x, $y); 3070 $self->goto ($map, $x, $y);
2820 3071
2821 # if exit is damned, update players death & WoR home-position 3072 # if exit is damned, update players death & WoR home-position
2822 $self->contr->savebed ($map, $x, $y) 3073 $self->contr->savebed ($map, $x, $y)
2827 $self->message ("Something went wrong deep within the deliantra server. " 3078 $self->message ("Something went wrong deep within the deliantra server. "
2828 . "I'll try to bring you back to the map you were before. " 3079 . "I'll try to bring you back to the map you were before. "
2829 . "Please report this to the dungeon master!", 3080 . "Please report this to the dungeon master!",
2830 cf::NDI_UNIQUE | cf::NDI_RED); 3081 cf::NDI_UNIQUE | cf::NDI_RED);
2831 3082
2832 warn "ERROR in enter_exit: $@"; 3083 error "ERROR in enter_exit: $@";
2833 $self->leave_link; 3084 $self->leave_link;
2834 } 3085 }
2835 })->prio (1); 3086 })->prio (1);
2836} 3087}
2837 3088
2838=head3 cf::client 3089=head3 cf::client
2839 3090
2840=over 4 3091=over 4
2841
2842=item $client->send_drawinfo ($text, $flags)
2843
2844Sends a drawinfo packet to the client. Circumvents output buffering so
2845should not be used under normal circumstances.
2846
2847=cut
2848
2849sub cf::client::send_drawinfo {
2850 my ($self, $text, $flags) = @_;
2851
2852 utf8::encode $text;
2853 $self->send_packet (sprintf "drawinfo %d %s", $flags || cf::NDI_BLACK, $text);
2854}
2855 3092
2856=item $client->send_big_packet ($pkt) 3093=item $client->send_big_packet ($pkt)
2857 3094
2858Like C<send_packet>, but tries to compress large packets, and fragments 3095Like C<send_packet>, but tries to compress large packets, and fragments
2859them as required. 3096them as required.
2878 $self->send_packet ($pkt); 3115 $self->send_packet ($pkt);
2879} 3116}
2880 3117
2881=item $client->send_msg ($channel, $msg, $color, [extra...]) 3118=item $client->send_msg ($channel, $msg, $color, [extra...])
2882 3119
2883Send a drawinfo or msg packet to the client, formatting the msg for the 3120Send a msg packet to the client, formatting the msg for the client if
2884client if neccessary. C<$type> should be a string identifying the type of 3121necessary. C<$type> should be a string identifying the type of the
2885the message, with C<log> being the default. If C<$color> is negative, suppress 3122message, with C<log> being the default. If C<$color> is negative, suppress
2886the message unless the client supports the msg packet. 3123the message unless the client supports the msg packet.
2887 3124
2888=cut 3125=cut
2889 3126
2890# non-persistent channels (usually the info channel) 3127# non-persistent channels (usually the info channel)
2995 id => "death", 3232 id => "death",
2996 title => "Death", 3233 title => "Death",
2997 reply => undef, 3234 reply => undef,
2998 tooltip => "Reason for and more info about your most recent death", 3235 tooltip => "Reason for and more info about your most recent death",
2999 }, 3236 },
3237 "c/fatal" => {
3238 id => "fatal",
3239 title => "Fatal Error",
3240 reply => undef,
3241 tooltip => "Reason for the server disconnect",
3242 },
3000 "c/say" => $SAY_CHANNEL, 3243 "c/say" => $SAY_CHANNEL,
3001 "c/chat" => $CHAT_CHANNEL, 3244 "c/chat" => $CHAT_CHANNEL,
3002); 3245);
3003 3246
3004sub cf::client::send_msg { 3247sub cf::client::send_msg {
3047=cut 3290=cut
3048 3291
3049sub cf::client::ext_msg($$@) { 3292sub cf::client::ext_msg($$@) {
3050 my ($self, $type, @msg) = @_; 3293 my ($self, $type, @msg) = @_;
3051 3294
3052 if ($self->extcmd == 2) {
3053 $self->send_big_packet ("ext " . $self->{json_coder}->encode ([$type, @msg])); 3295 $self->send_big_packet ("ext " . $self->{json_coder}->encode ([$type, @msg]));
3054 } elsif ($self->extcmd == 1) { # TODO: remove
3055 push @msg, msgtype => "event_$type";
3056 $self->send_big_packet ("ext " . $self->{json_coder}->encode ({@msg}));
3057 }
3058}
3059
3060=item $client->ext_reply ($msgid, @msg)
3061
3062Sends an ext reply to the client.
3063
3064=cut
3065
3066sub cf::client::ext_reply($$@) {
3067 my ($self, $id, @msg) = @_;
3068
3069 if ($self->extcmd == 2) {
3070 $self->send_big_packet ("ext " . $self->{json_coder}->encode (["reply-$id", @msg]));
3071 } elsif ($self->extcmd == 1) {
3072 #TODO: version 1, remove
3073 unshift @msg, msgtype => "reply", msgid => $id;
3074 $self->send_big_packet ("ext " . $self->{json_coder}->encode ({@msg}));
3075 }
3076} 3296}
3077 3297
3078=item $success = $client->query ($flags, "text", \&cb) 3298=item $success = $client->query ($flags, "text", \&cb)
3079 3299
3080Queues a query to the client, calling the given callback with 3300Queues a query to the client, calling the given callback with
3100 3320
3101 $self->send_packet ($self->{query_queue}[0][0]) 3321 $self->send_packet ($self->{query_queue}[0][0])
3102 if @{ $self->{query_queue} } == 1; 3322 if @{ $self->{query_queue} } == 1;
3103 3323
3104 1 3324 1
3325}
3326
3327=item $client->update_command_faces
3328
3329=cut
3330
3331our %COMMAND_FACE;
3332
3333sub cf::client::update_command_faces {
3334 my ($self) = @_;
3335
3336 my @faces = grep $_,
3337 $COMMAND_FACE{preferred},
3338 $COMMAND_FACE{standard},
3339 $COMMAND_FACE{skill},
3340 $self->pl->ob->flag (cf::FLAG_WIZ) ? $COMMAND_FACE{dm} : (),
3341 $COMMAND_FACE{emote},
3342 ;
3343
3344 $self->send_face ($_)
3345 for @faces;
3346 $self->flush_fx;
3347
3348 $self->ext_msg (command_list => @faces);
3349}
3350
3351=item cf::client::set_command_face $type, $commands
3352
3353=cut
3354
3355sub cf::client::set_command_face {
3356 my ($type, $list) = @_;
3357
3358 my $idx = &cf::face::set ( #d# ugly forward reference
3359 "command_list/$type" => cf::FT_RSRC,
3360 JSON::XS->new->utf8->encode ([ sort @$list ])
3361 );
3362
3363 $COMMAND_FACE{$type} = $idx;
3105} 3364}
3106 3365
3107cf::client->attach ( 3366cf::client->attach (
3108 on_connect => sub { 3367 on_connect => sub {
3109 my ($ns) = @_; 3368 my ($ns) = @_;
3135 my ($ns, $buf) = @_; 3394 my ($ns, $buf) = @_;
3136 3395
3137 my $msg = eval { $ns->{json_coder}->decode ($buf) }; 3396 my $msg = eval { $ns->{json_coder}->decode ($buf) };
3138 3397
3139 if (ref $msg) { 3398 if (ref $msg) {
3140 my ($type, $reply, @payload) = 3399 my ($type, $reply, @payload) = @$msg; # version 1 used %type, $id, %$hash
3141 "ARRAY" eq ref $msg
3142 ? @$msg
3143 : ($msg->{msgtype}, $msg->{msgid}, %$msg); # TODO: version 1, remove
3144 3400
3145 my @reply;
3146
3147 if (my $cb = $EXTICMD{$type}) { 3401 if (my $cb = $EXTIACMD{$type}) {
3402 $cb->(
3403 $ns,
3404 sub {
3405 $ns->ext_msg ("reply-$reply", @_)
3406 if $reply;
3407 },
3408 @payload
3409 );
3410 } else {
3411 my @reply;
3412
3413 if (my $cb = $EXTICMD{$type}) {
3148 @reply = $cb->($ns, @payload); 3414 @reply = $cb->($ns, @payload);
3415 }
3416
3417 $ns->ext_msg ("reply-$reply", @reply)
3418 if $reply;
3149 } 3419 }
3150
3151 $ns->ext_reply ($reply, @reply)
3152 if $reply;
3153
3154 } else { 3420 } else {
3155 warn "client " . ($ns->pl ? $ns->pl->ob->name : $ns->host) . " sent unparseable exti message: <$buf>\n"; 3421 error "client " . ($ns->pl ? $ns->pl->ob->name : $ns->host) . " sent unparseable exti message: <$buf>\n";
3156 } 3422 }
3157 3423
3158 cf::override; 3424 cf::override;
3159 }, 3425 },
3160); 3426);
3241 decrease split destroy change_exp value msg lore send_msg)], 3507 decrease split destroy change_exp value msg lore send_msg)],
3242 ["cf::object::player" => qw(player)], 3508 ["cf::object::player" => qw(player)],
3243 ["cf::player" => qw(peaceful send_msg)], 3509 ["cf::player" => qw(peaceful send_msg)],
3244 ["cf::map" => qw(trigger)], 3510 ["cf::map" => qw(trigger)],
3245) { 3511) {
3246 no strict 'refs';
3247 my ($pkg, @funs) = @$_; 3512 my ($pkg, @funs) = @$_;
3248 *{"safe::$pkg\::$_"} = $safe_hole->wrap (\&{"$pkg\::$_"}) 3513 *{"safe::$pkg\::$_"} = $safe_hole->wrap (\&{"$pkg\::$_"})
3249 for @funs; 3514 for @funs;
3250} 3515}
3251 3516
3290 local @cf::_safe_eval_args = values %vars; 3555 local @cf::_safe_eval_args = values %vars;
3291 @res = wantarray ? eval eval : scalar eval $eval; 3556 @res = wantarray ? eval eval : scalar eval $eval;
3292 } 3557 }
3293 3558
3294 if ($@) { 3559 if ($@) {
3295 warn "$@"; 3560 warn "$@",
3296 warn "while executing safe code '$code'\n"; 3561 "while executing safe code '$code'\n",
3297 warn "with arguments " . (join " ", %vars) . "\n"; 3562 "with arguments " . (join " ", %vars) . "\n";
3298 } 3563 }
3299 3564
3300 wantarray ? @res : $res[0] 3565 wantarray ? @res : $res[0]
3301} 3566}
3302 3567
3327=cut 3592=cut
3328 3593
3329############################################################################# 3594#############################################################################
3330# the server's init and main functions 3595# the server's init and main functions
3331 3596
3597{
3598 package cf::face;
3599
3600 our %HASH; # hash => idx
3601 our @DATA; # dynamically-created facedata, only faceste 0 used
3602 our @FOFS; # file offset, if > 0
3603 our @SIZE; # size of face, in octets
3604 our @META; # meta hash of face, if any
3605 our $DATAFH; # facedata filehandle
3606
3607 # internal api, not finalised
3608 sub set {
3609 my ($name, $type, $data) = @_;
3610
3611 my $idx = cf::face::find $name;
3612
3613 if ($idx) {
3614 delete $HASH{cf::face::get_csum $idx};
3615 } else {
3616 $idx = cf::face::alloc $name;
3617 }
3618
3619 my $hash = cf::face::mangle_csum Digest::MD5::md5 $data;
3620
3621 cf::face::set_type $idx, $type;
3622 cf::face::set_csum $idx, 0, $hash;
3623
3624 # we need to destroy the SV itself, not just modify it, as a running ix
3625 # might hold a reference to it: "delete" achieves that.
3626 delete $FOFS[0][$idx];
3627 delete $DATA[0][$idx];
3628 $DATA[0][$idx] = $data;
3629 $SIZE[0][$idx] = length $data;
3630 delete $META[$idx];
3631 $HASH{$hash} = $idx;#d#
3632
3633 $idx
3634 }
3635
3636 sub _get_data($$$) {
3637 my ($idx, $set, $cb) = @_;
3638
3639 if (defined $DATA[$set][$idx]) {
3640 $cb->($DATA[$set][$idx]);
3641 } elsif (my $fofs = $FOFS[$set][$idx]) {
3642 my $size = $SIZE[$set][$idx];
3643 my $buf;
3644 IO::AIO::aio_read $DATAFH, $fofs, $size, $buf, 0, sub {
3645 if ($_[0] == $size) {
3646 #cf::debug "read face $idx, $size from $fofs as ", length $buf;#d#
3647 $cb->($buf);
3648 } else {
3649 cf::error "INTERNAL ERROR: unable to read facedata for face $idx#$set ($size, $fofs), ignoring request.";
3650 }
3651 };
3652 } else {
3653 cf::error "requested facedata for unknown face $idx#$set, ignoring.";
3654 }
3655 }
3656
3657 # rather ineffient
3658 sub cf::face::get_data($;$) {
3659 my ($idx, $set) = @_;
3660
3661 _get_data $idx, $set, Coro::rouse_cb;
3662 Coro::rouse_wait
3663 }
3664
3665 sub cf::face::ix {
3666 my ($ns, $set, $idx, $pri) = @_;
3667
3668 _get_data $idx, $set, sub {
3669 $ns->ix_send ($idx, $pri, $_[0]);
3670 };
3671 }
3672}
3673
3332sub load_facedata($) { 3674sub load_facedata($) {
3333 my ($path) = @_; 3675 my ($path) = @_;
3334 3676
3335 # HACK to clear player env face cache, we need some signal framework
3336 # for this (global event?)
3337 %ext::player_env::MUSIC_FACE_CACHE = ();
3338
3339 my $enc = JSON::XS->new->utf8->canonical->relaxed; 3677 my $enc = JSON::XS->new->utf8->canonical->relaxed;
3340 3678
3341 warn "loading facedata from $path\n"; 3679 trace "loading facedata from $path\n";
3342 3680
3343 my $facedata; 3681 my $facedata = decode_storable load_file "$path/faceinfo";
3344 0 < aio_load $path, $facedata
3345 or die "$path: $!";
3346
3347 $facedata = Coro::Storable::thaw $facedata;
3348 3682
3349 $facedata->{version} == 2 3683 $facedata->{version} == 2
3350 or cf::cleanup "$path: version mismatch, cannot proceed."; 3684 or cf::cleanup "$path/faceinfo: version mismatch, cannot proceed.";
3351 3685
3352 # patch in the exptable 3686 my $fh = aio_open "$DATADIR/facedata", IO::AIO::O_RDONLY, 0
3353 my $exp_table = $enc->encode ([map cf::level_to_min_exp $_, 1 .. cf::settings->max_level]); 3687 or cf::cleanup "$path/facedata: $!, cannot proceed.";
3354 $facedata->{resource}{"res/exp_table"} = { 3688
3355 type => FT_RSRC, 3689 get_slot 1, -100, "load_facedata"; # make sure we get a very big slot
3356 data => $exp_table, 3690
3357 hash => (Digest::MD5::md5 $exp_table), 3691 # BEGIN ATOMIC
3358 }; 3692 # from here on, everything must be atomic - no thread switch allowed
3359 cf::cede_to_tick; 3693 my $t1 = EV::time;
3360 3694
3361 { 3695 {
3362 my $faces = $facedata->{faceinfo}; 3696 my $faces = $facedata->{faceinfo};
3363 3697
3364 while (my ($face, $info) = each %$faces) { 3698 for my $face (sort keys %$faces) {
3699 my $info = $faces->{$face};
3365 my $idx = (cf::face::find $face) || cf::face::alloc $face; 3700 my $idx = (cf::face::find $face) || cf::face::alloc $face;
3366 3701
3367 cf::face::set_visibility $idx, $info->{visibility}; 3702 cf::face::set_visibility $idx, $info->{visibility};
3368 cf::face::set_magicmap $idx, $info->{magicmap}; 3703 cf::face::set_magicmap $idx, $info->{magicmap};
3369 cf::face::set_data $idx, 0, $info->{data32}, $info->{hash32}; 3704 cf::face::set_csum $idx, 0, $info->{hash64}; $cf::face::SIZE[0][$idx] = $info->{size64}; $cf::face::FOFS[0][$idx] = $info->{fofs64};
3370 cf::face::set_data $idx, 1, $info->{data64}, $info->{hash64}; 3705 cf::face::set_csum $idx, 1, $info->{hash32}; $cf::face::SIZE[1][$idx] = $info->{size32}; $cf::face::FOFS[1][$idx] = $info->{fofs32};
3371 3706 cf::face::set_csum $idx, 2, $info->{glyph}; $cf::face::DATA[2][$idx] = $info->{glyph};
3372 cf::cede_to_tick; 3707 $cf::face::HASH{$info->{hash64}} = $idx;
3708 delete $cf::face::META[$idx];
3373 } 3709 }
3374 3710
3375 while (my ($face, $info) = each %$faces) { 3711 while (my ($face, $info) = each %$faces) {
3376 next unless $info->{smooth}; 3712 next unless $info->{smooth};
3377 3713
3380 3716
3381 if (my $smooth = cf::face::find $info->{smooth}) { 3717 if (my $smooth = cf::face::find $info->{smooth}) {
3382 cf::face::set_smooth $idx, $smooth; 3718 cf::face::set_smooth $idx, $smooth;
3383 cf::face::set_smoothlevel $idx, $info->{smoothlevel}; 3719 cf::face::set_smoothlevel $idx, $info->{smoothlevel};
3384 } else { 3720 } else {
3385 warn "smooth face '$info->{smooth}' not found for face '$face'"; 3721 error "smooth face '$info->{smooth}' not found for face '$face'";
3386 } 3722 }
3387
3388 cf::cede_to_tick;
3389 } 3723 }
3390 } 3724 }
3391 3725
3392 { 3726 {
3393 my $anims = $facedata->{animinfo}; 3727 my $anims = $facedata->{animinfo};
3394 3728
3395 while (my ($anim, $info) = each %$anims) { 3729 while (my ($anim, $info) = each %$anims) {
3396 cf::anim::set $anim, $info->{frames}, $info->{facings}; 3730 cf::anim::set $anim, $info->{frames}, $info->{facings};
3397 cf::cede_to_tick;
3398 } 3731 }
3399 3732
3400 cf::anim::invalidate_all; # d'oh 3733 cf::anim::invalidate_all; # d'oh
3401 } 3734 }
3402 3735
3403 { 3736 {
3404 my $res = $facedata->{resource}; 3737 my $res = $facedata->{resource};
3405 3738
3406 while (my ($name, $info) = each %$res) { 3739 while (my ($name, $info) = each %$res) {
3407 if (defined $info->{type}) { 3740 if (defined (my $type = $info->{type})) {
3741 # TODO: different hash - must free and use new index, or cache ixface data queue
3408 my $idx = (cf::face::find $name) || cf::face::alloc $name; 3742 my $idx = (cf::face::find $name) || cf::face::alloc $name;
3409 3743
3410 cf::face::set_data $idx, 0, $info->{data}, $info->{hash};
3411 cf::face::set_type $idx, $info->{type}; 3744 cf::face::set_type $idx, $type;
3745 cf::face::set_csum $idx, 0, $info->{hash};
3746 $cf::face::SIZE[0][$idx] = $info->{size};
3747 $cf::face::FOFS[0][$idx] = $info->{fofs};
3748 $cf::face::META[$idx] = $type & 1 ? undef : $info->{meta}; # preserve meta unless prepended already
3749 $cf::face::HASH{$info->{hash}} = $idx;
3412 } else { 3750 } else {
3413 $RESOURCE{$name} = $info; 3751# $RESOURCE{$name} = $info; # unused
3414 } 3752 }
3415
3416 cf::cede_to_tick;
3417 } 3753 }
3418 } 3754 }
3755
3756 ($fh, $cf::face::DATAFH) = ($cf::face::DATAFH, $fh);
3757
3758 # HACK to clear player env face cache, we need some signal framework
3759 # for this (global event?)
3760 %ext::player_env::MUSIC_FACE_CACHE = ();
3761
3762 # END ATOMIC
3763
3764 cf::debug "facedata atomic update time ", EV::time - $t1;
3419 3765
3420 cf::global->invoke (EVENT_GLOBAL_RESOURCE_UPDATE); 3766 cf::global->invoke (EVENT_GLOBAL_RESOURCE_UPDATE);
3421 3767
3768 aio_close $fh if $fh; # close old facedata
3769
3422 1 3770 1
3423} 3771}
3424
3425cf::global->attach (on_resource_update => sub {
3426 if (my $soundconf = $RESOURCE{"res/sound.conf"}) {
3427 $soundconf = JSON::XS->new->utf8->relaxed->decode ($soundconf->{data});
3428
3429 for (0 .. SOUND_CAST_SPELL_0 - 1) {
3430 my $sound = $soundconf->{compat}[$_]
3431 or next;
3432
3433 my $face = cf::face::find "sound/$sound->[1]";
3434 cf::sound::set $sound->[0] => $face;
3435 cf::sound::old_sound_index $_, $face; # gcfclient-compat
3436 }
3437
3438 while (my ($k, $v) = each %{$soundconf->{event}}) {
3439 my $face = cf::face::find "sound/$v";
3440 cf::sound::set $k => $face;
3441 }
3442 }
3443});
3444 3772
3445register_exticmd fx_want => sub { 3773register_exticmd fx_want => sub {
3446 my ($ns, $want) = @_; 3774 my ($ns, $want) = @_;
3447 3775
3448 while (my ($k, $v) = each %$want) { 3776 while (my ($k, $v) = each %$want) {
3456 my $status = load_resource_file_ $_[0]; 3784 my $status = load_resource_file_ $_[0];
3457 get_slot 0.1, 100; 3785 get_slot 0.1, 100;
3458 cf::arch::commit_load; 3786 cf::arch::commit_load;
3459 3787
3460 $status 3788 $status
3789}
3790
3791sub reload_exp_table {
3792 _reload_exp_table;
3793
3794 cf::face::set
3795 "res/exp_table" => FT_RSRC,
3796 JSON::XS->new->utf8->canonical->encode (
3797 [map cf::level_to_min_exp $_, 1 .. cf::settings->max_level]
3798 );
3799}
3800
3801sub reload_materials {
3802 _reload_materials;
3461} 3803}
3462 3804
3463sub reload_regions { 3805sub reload_regions {
3464 # HACK to clear player env face cache, we need some signal framework 3806 # HACK to clear player env face cache, we need some signal framework
3465 # for this (global event?) 3807 # for this (global event?)
3473 if exists $_->{match}; 3815 if exists $_->{match};
3474 } 3816 }
3475} 3817}
3476 3818
3477sub reload_facedata { 3819sub reload_facedata {
3478 load_facedata "$DATADIR/facedata" 3820 load_facedata $DATADIR
3479 or die "unable to load facedata\n"; 3821 or die "unable to load facedata\n";
3480} 3822}
3481 3823
3482sub reload_archetypes { 3824sub reload_archetypes {
3483 load_resource_file "$DATADIR/archetypes" 3825 load_resource_file "$DATADIR/archetypes"
3484 or die "unable to load archetypes\n"; 3826 or die "unable to load archetypes\n";
3827
3828 cf::face::set
3829 "res/skill_info" => FT_RSRC,
3830 JSON::XS->new->utf8->canonical->encode (
3831 [map [cf::arch::skillvec ($_)->name], 0 .. cf::arch::skillvec_size - 1]
3832 );
3833
3834 cf::face::set
3835 "res/spell_paths" => FT_RSRC,
3836 JSON::XS->new->utf8->canonical->encode (
3837 [map [cf::spellpathnames ($_)], 0 .. NRSPELLPATHS - 1]
3838 );
3839
3840 # command completion
3841 my @commands;
3842
3843 for (0..cf::arch::skillvec_size - 1) {
3844 my $skill = cf::arch::skillvec $_;
3845 my $name = $skill->name;
3846 my $flags = cf::skill_flags $skill->subtype;
3847
3848 push @commands, "ready_skill $name" if $flags & (SF_COMBAT | SF_RANGED | SF_GRACE);
3849 push @commands, "use_skill $name" if $flags & (SF_USE | SF_AUTARK | SF_GRACE);
3850 }
3851
3852 cf::client::set_command_face skill => \@commands;
3485} 3853}
3486 3854
3487sub reload_treasures { 3855sub reload_treasures {
3488 load_resource_file "$DATADIR/treasures" 3856 load_resource_file "$DATADIR/treasures"
3489 or die "unable to load treasurelists\n"; 3857 or die "unable to load treasurelists\n";
3490} 3858}
3491 3859
3860sub reload_sound {
3861 trace "loading sound config from $DATADIR/sound\n";
3862
3863 my $soundconf = JSON::XS->new->utf8->relaxed->decode (load_file "$DATADIR/sound");
3864
3865 for (0 .. SOUND_CAST_SPELL_0 - 1) {
3866 my $sound = $soundconf->{compat}[$_]
3867 or next;
3868
3869 my $face = cf::face::find "sound/$sound->[1]";
3870 cf::sound::set $sound->[0] => $face;
3871 cf::sound::old_sound_index $_, $face; # gcfclient-compat
3872 }
3873
3874 while (my ($k, $v) = each %{$soundconf->{event}}) {
3875 my $face = cf::face::find "sound/$v";
3876 cf::sound::set $k => $face;
3877 }
3878}
3879
3492sub reload_resources { 3880sub reload_resources {
3493 warn "reloading resource files...\n"; 3881 trace "reloading resource files...\n";
3494 3882
3883 reload_materials;
3495 reload_facedata; 3884 reload_facedata;
3885 reload_exp_table;
3886 reload_sound;
3496 reload_archetypes; 3887 reload_archetypes;
3497 reload_regions; 3888 reload_regions;
3498 reload_treasures; 3889 reload_treasures;
3499 3890
3500 warn "finished reloading resource files\n"; 3891 trace "finished reloading resource files\n";
3501} 3892}
3502 3893
3503sub reload_config { 3894sub reload_config {
3504 warn "reloading config file...\n"; 3895 trace "reloading config file...\n";
3505 3896
3506 open my $fh, "<:utf8", "$CONFDIR/config" 3897 my $config = load_file "$CONFDIR/config";
3507 or return; 3898 utf8::decode $config;
3899 *CFG = decode_yaml $config;
3508 3900
3509 local $/;
3510 *CFG = YAML::XS::Load scalar <$fh>;
3511
3512 $EMERGENCY_POSITION = $CFG{emergency_position} || ["/world/world_105_115", 5, 37]; 3901 $EMERGENCY_POSITION = $CFG{emergency_position} || ["/world/world_104_115", 49, 38];
3513 3902
3514 $cf::map::MAX_RESET = $CFG{map_max_reset} if exists $CFG{map_max_reset}; 3903 $cf::map::MAX_RESET = $CFG{map_max_reset} if exists $CFG{map_max_reset};
3515 $cf::map::DEFAULT_RESET = $CFG{map_default_reset} if exists $CFG{map_default_reset}; 3904 $cf::map::DEFAULT_RESET = $CFG{map_default_reset} if exists $CFG{map_default_reset};
3516 3905
3517 if (exists $CFG{mlockall}) { 3906 if (exists $CFG{mlockall}) {
3519 $CFG{mlockall} ? eval "mlockall()" : eval "munlockall()" 3908 $CFG{mlockall} ? eval "mlockall()" : eval "munlockall()"
3520 and die "WARNING: m(un)lockall failed: $!\n"; 3909 and die "WARNING: m(un)lockall failed: $!\n";
3521 }; 3910 };
3522 warn $@ if $@; 3911 warn $@ if $@;
3523 } 3912 }
3524
3525 warn "finished reloading resource files\n";
3526} 3913}
3527 3914
3528sub pidfile() { 3915sub pidfile() {
3529 sysopen my $fh, $PIDFILE, O_RDWR | O_CREAT 3916 sysopen my $fh, $PIDFILE, O_RDWR | O_CREAT
3530 or die "$PIDFILE: $!"; 3917 or die "$PIDFILE: $!";
3543 seek $fh, 0, 0; 3930 seek $fh, 0, 0;
3544 print $fh $$; 3931 print $fh $$;
3545} 3932}
3546 3933
3547sub main_loop { 3934sub main_loop {
3548 warn "EV::loop starting\n"; 3935 trace "EV::run starting\n";
3549 if (1) { 3936 if (1) {
3550 EV::loop; 3937 EV::run;
3551 } 3938 }
3552 warn "EV::loop returned\n"; 3939 trace "EV::run returned\n";
3553 goto &main_loop unless $REALLY_UNLOOP; 3940 goto &main_loop unless $REALLY_UNLOOP;
3554} 3941}
3555 3942
3556sub main { 3943sub main {
3557 cf::init_globals; # initialise logging 3944 cf::init_globals; # initialise logging
3558 3945
3559 LOG llevInfo, "Welcome to Deliantra, v" . VERSION; 3946 LOG llevInfo, "Welcome to Deliantra, v" . VERSION;
3560 LOG llevInfo, "Copyright (C) 2005-2008 Marc Alexander Lehmann / Robin Redeker / the Deliantra team."; 3947 LOG llevInfo, "Copyright (C) 2005-2012 Marc Alexander Lehmann / Robin Redeker / the Deliantra team.";
3561 LOG llevInfo, "Copyright (C) 1994 Mark Wedel."; 3948 LOG llevInfo, "Copyright (C) 1994 Mark Wedel.";
3562 LOG llevInfo, "Copyright (C) 1992 Frank Tore Johansen."; 3949 LOG llevInfo, "Copyright (C) 1992 Frank Tore Johansen.";
3563 3950
3564 $Coro::current->prio (Coro::PRIO_MAX); # give the main loop max. priority 3951 $Coro::current->prio (Coro::PRIO_MAX); # give the main loop max. priority
3565 3952
3566 # we must not ever block the main coroutine 3953 # we must not ever block the main coroutine
3567 local $Coro::idle = sub { 3954 $Coro::idle = sub {
3568 Carp::cluck "FATAL: Coro::idle was called, major BUG, use cf::sync_job!\n";#d# 3955 Carp::cluck "FATAL: Coro::idle was called, major BUG, use cf::sync_job!\n";#d#
3569 (async { 3956 (async {
3570 $Coro::current->{desc} = "IDLE BUG HANDLER"; 3957 $Coro::current->{desc} = "IDLE BUG HANDLER";
3571 EV::loop EV::LOOP_ONESHOT; 3958 EV::run EV::RUN_ONCE;
3572 })->prio (Coro::PRIO_MAX); 3959 })->prio (Coro::PRIO_MAX);
3573 }; 3960 };
3574 3961
3575 evthread_start IO::AIO::poll_fileno; 3962 evthread_start IO::AIO::poll_fileno;
3576 3963
3577 cf::sync_job { 3964 cf::sync_job {
3578 cf::init_experience; 3965 cf::incloader::init ();
3966
3967 db_init;
3968
3579 cf::init_anim; 3969 cf::init_anim;
3580 cf::init_attackmess; 3970 cf::init_attackmess;
3581 cf::init_dynamic; 3971 cf::init_dynamic;
3582 3972
3583 cf::load_settings; 3973 cf::load_settings;
3584 cf::load_materials;
3585 3974
3586 reload_resources; 3975 reload_resources;
3587 reload_config; 3976 reload_config;
3588 db_init;
3589 3977
3590 cf::init_uuid; 3978 cf::init_uuid;
3591 cf::init_signals; 3979 cf::init_signals;
3592 cf::init_skills; 3980 cf::init_skills;
3593 3981
3601 3989
3602 # no (long-running) fork's whatsoever before this point(!) 3990 # no (long-running) fork's whatsoever before this point(!)
3603 use POSIX (); 3991 use POSIX ();
3604 POSIX::close delete $ENV{LOCKUTIL_LOCK_FD} if exists $ENV{LOCKUTIL_LOCK_FD}; 3992 POSIX::close delete $ENV{LOCKUTIL_LOCK_FD} if exists $ENV{LOCKUTIL_LOCK_FD};
3605 3993
3606 (pop @POST_INIT)->(0) while @POST_INIT; 3994 cf::_post_init 0;
3607 }; 3995 };
3608 3996
3609 cf::object::thawer::errors_are_fatal 0; 3997 cf::object::thawer::errors_are_fatal 0;
3610 warn "parse errors in files are no longer fatal from this point on.\n"; 3998 info "parse errors in files are no longer fatal from this point on.\n";
3611 3999
4000 AE::postpone {
4001 undef &main; # free gobs of memory :)
4002 };
4003
3612 main_loop; 4004 goto &main_loop;
3613} 4005}
3614 4006
3615############################################################################# 4007#############################################################################
3616# initialisation and cleanup 4008# initialisation and cleanup
3617 4009
3656 or return; 4048 or return;
3657 4049
3658 aio_rename "$RUNTIMEFILE~", $RUNTIMEFILE 4050 aio_rename "$RUNTIMEFILE~", $RUNTIMEFILE
3659 and return; 4051 and return;
3660 4052
3661 warn sprintf "runtime file written (%gs).\n", AE::time - $t0; 4053 trace sprintf "runtime file written (%gs).\n", AE::time - $t0;
3662 4054
3663 1 4055 1
3664} 4056}
3665 4057
3666our $uuid_lock; 4058our $uuid_lock;
3678 or return; 4070 or return;
3679 4071
3680 my $value = uuid_seq uuid_cur; 4072 my $value = uuid_seq uuid_cur;
3681 4073
3682 unless ($value) { 4074 unless ($value) {
3683 warn "cowardly refusing to write zero uuid value!\n"; 4075 info "cowardly refusing to write zero uuid value!\n";
3684 return; 4076 return;
3685 } 4077 }
3686 4078
3687 my $value = uuid_str $value + $uuid_skip; 4079 my $value = uuid_str $value + $uuid_skip;
3688 $uuid_skip = 0; 4080 $uuid_skip = 0;
3698 or return; 4090 or return;
3699 4091
3700 aio_rename "$uuid~", $uuid 4092 aio_rename "$uuid~", $uuid
3701 and return; 4093 and return;
3702 4094
3703 warn "uuid file written ($value).\n"; 4095 trace "uuid file written ($value).\n";
3704 4096
3705 1 4097 1
3706 4098
3707} 4099}
3708 4100
3714} 4106}
3715 4107
3716sub emergency_save() { 4108sub emergency_save() {
3717 my $freeze_guard = cf::freeze_mainloop; 4109 my $freeze_guard = cf::freeze_mainloop;
3718 4110
3719 warn "emergency_perl_save: enter\n"; 4111 info "emergency_perl_save: enter\n";
4112
4113 # this is a trade-off: we want to be very quick here, so
4114 # save all maps without fsync, and later call a global sync
4115 # (which in turn might be very very slow)
4116 local $USE_FSYNC = 0;
3720 4117
3721 cf::sync_job { 4118 cf::sync_job {
3722 # this is a trade-off: we want to be very quick here, so 4119 cf::write_runtime_sync; # external watchdog should not bark
3723 # save all maps without fsync, and later call a global sync
3724 # (which in turn might be very very slow)
3725 local $USE_FSYNC = 0;
3726 4120
3727 # use a peculiar iteration method to avoid tripping on perl 4121 # use a peculiar iteration method to avoid tripping on perl
3728 # refcount bugs in for. also avoids problems with players 4122 # refcount bugs in for. also avoids problems with players
3729 # and maps saved/destroyed asynchronously. 4123 # and maps saved/destroyed asynchronously.
3730 warn "emergency_perl_save: begin player save\n"; 4124 info "emergency_perl_save: begin player save\n";
3731 for my $login (keys %cf::PLAYER) { 4125 for my $login (keys %cf::PLAYER) {
3732 my $pl = $cf::PLAYER{$login} or next; 4126 my $pl = $cf::PLAYER{$login} or next;
3733 $pl->valid or next; 4127 $pl->valid or next;
3734 delete $pl->{unclean_save}; # not strictly necessary, but cannot hurt 4128 delete $pl->{unclean_save}; # not strictly necessary, but cannot hurt
3735 $pl->save; 4129 $pl->save;
3736 } 4130 }
3737 warn "emergency_perl_save: end player save\n"; 4131 info "emergency_perl_save: end player save\n";
3738 4132
4133 cf::write_runtime_sync; # external watchdog should not bark
4134
3739 warn "emergency_perl_save: begin map save\n"; 4135 info "emergency_perl_save: begin map save\n";
3740 for my $path (keys %cf::MAP) { 4136 for my $path (keys %cf::MAP) {
3741 my $map = $cf::MAP{$path} or next; 4137 my $map = $cf::MAP{$path} or next;
3742 $map->valid or next; 4138 $map->valid or next;
3743 $map->save; 4139 $map->save;
3744 } 4140 }
3745 warn "emergency_perl_save: end map save\n"; 4141 info "emergency_perl_save: end map save\n";
3746 4142
4143 cf::write_runtime_sync; # external watchdog should not bark
4144
3747 warn "emergency_perl_save: begin database checkpoint\n"; 4145 info "emergency_perl_save: begin database checkpoint\n";
3748 BDB::db_env_txn_checkpoint $DB_ENV; 4146 BDB::db_env_txn_checkpoint $DB_ENV;
3749 warn "emergency_perl_save: end database checkpoint\n"; 4147 info "emergency_perl_save: end database checkpoint\n";
3750 4148
3751 warn "emergency_perl_save: begin write uuid\n"; 4149 info "emergency_perl_save: begin write uuid\n";
3752 write_uuid_sync 1; 4150 write_uuid_sync 1;
3753 warn "emergency_perl_save: end write uuid\n"; 4151 info "emergency_perl_save: end write uuid\n";
4152
4153 cf::write_runtime_sync; # external watchdog should not bark
4154
4155 trace "emergency_perl_save: syncing database to disk";
4156 BDB::db_env_txn_checkpoint $DB_ENV;
4157
4158 info "emergency_perl_save: starting sync\n";
4159 IO::AIO::aio_sync sub {
4160 info "emergency_perl_save: finished sync\n";
4161 };
4162
4163 cf::write_runtime_sync; # external watchdog should not bark
4164
4165 trace "emergency_perl_save: flushing outstanding aio requests";
4166 while (IO::AIO::nreqs || BDB::nreqs) {
4167 Coro::AnyEvent::sleep 0.01; # let the sync_job do it's thing
4168 }
4169
4170 cf::write_runtime_sync; # external watchdog should not bark
3754 }; 4171 };
3755 4172
3756 warn "emergency_perl_save: starting sync()\n";
3757 IO::AIO::aio_sync sub {
3758 warn "emergency_perl_save: finished sync()\n";
3759 };
3760
3761 warn "emergency_perl_save: leave\n"; 4173 info "emergency_perl_save: leave\n";
3762} 4174}
3763 4175
3764sub post_cleanup { 4176sub post_cleanup {
3765 my ($make_core) = @_; 4177 my ($make_core) = @_;
3766 4178
4179 IO::AIO::flush;
4180
3767 warn Carp::longmess "post_cleanup backtrace" 4181 error Carp::longmess "post_cleanup backtrace"
3768 if $make_core; 4182 if $make_core;
3769 4183
3770 my $fh = pidfile; 4184 my $fh = pidfile;
3771 unlink $PIDFILE if <$fh> == $$; 4185 unlink $PIDFILE if <$fh> == $$;
3772} 4186}
3796 } 4210 }
3797} 4211}
3798 4212
3799sub do_reload_perl() { 4213sub do_reload_perl() {
3800 # can/must only be called in main 4214 # can/must only be called in main
3801 if (in_main) { 4215 unless (in_main) {
3802 warn "can only reload from main coroutine"; 4216 error "can only reload from main coroutine";
3803 return; 4217 return;
3804 } 4218 }
3805 4219
3806 return if $RELOAD++; 4220 return if $RELOAD++;
3807 4221
3808 my $t1 = AE::time; 4222 my $t1 = AE::time;
3809 4223
3810 while ($RELOAD) { 4224 while ($RELOAD) {
3811 warn "reloading..."; 4225 cf::get_slot 0.1, -1, "reload_perl";
4226 info "perl_reload: reloading...";
3812 4227
3813 warn "entering sync_job"; 4228 trace "perl_reload: entering sync_job";
3814 4229
3815 cf::sync_job { 4230 cf::sync_job {
3816 cf::write_runtime_sync; # external watchdog should not bark
3817 cf::emergency_save; 4231 #cf::emergency_save;
3818 cf::write_runtime_sync; # external watchdog should not bark
3819 4232
3820 warn "syncing database to disk";
3821 BDB::db_env_txn_checkpoint $DB_ENV;
3822
3823 # if anything goes wrong in here, we should simply crash as we already saved
3824
3825 warn "flushing outstanding aio requests";
3826 while (IO::AIO::nreqs || BDB::nreqs) {
3827 Coro::EV::timer_once 0.01; # let the sync_job do it's thing
3828 }
3829
3830 warn "cancelling all extension coros"; 4233 trace "perl_reload: cancelling all extension coros";
3831 $_->cancel for values %EXT_CORO; 4234 $_->cancel for values %EXT_CORO;
3832 %EXT_CORO = (); 4235 %EXT_CORO = ();
3833 4236
3834 warn "removing commands"; 4237 trace "perl_reload: removing commands";
3835 %COMMAND = (); 4238 %COMMAND = ();
3836 4239
3837 warn "removing ext/exti commands"; 4240 trace "perl_reload: removing ext/exti commands";
3838 %EXTCMD = (); 4241 %EXTCMD = ();
3839 %EXTICMD = (); 4242 %EXTICMD = ();
3840 4243
3841 warn "unloading/nuking all extensions"; 4244 trace "perl_reload: unloading/nuking all extensions";
3842 for my $pkg (@EXTS) { 4245 for my $pkg (@EXTS) {
3843 warn "... unloading $pkg"; 4246 trace "... unloading $pkg";
3844 4247
3845 if (my $cb = $pkg->can ("unload")) { 4248 if (my $cb = $pkg->can ("unload")) {
3846 eval { 4249 eval {
3847 $cb->($pkg); 4250 $cb->($pkg);
3848 1 4251 1
3849 } or warn "$pkg unloaded, but with errors: $@"; 4252 } or error "$pkg unloaded, but with errors: $@";
3850 } 4253 }
3851 4254
3852 warn "... clearing $pkg"; 4255 trace "... clearing $pkg";
3853 clear_package $pkg; 4256 clear_package $pkg;
3854 } 4257 }
3855 4258
3856 warn "unloading all perl modules loaded from $LIBDIR"; 4259 trace "perl_reload: unloading all perl modules loaded from $LIBDIR";
3857 while (my ($k, $v) = each %INC) { 4260 while (my ($k, $v) = each %INC) {
3858 next unless $v =~ /^\Q$LIBDIR\E\/.*\.pm$/; 4261 next unless $v =~ /^\Q$LIBDIR\E\/.*\.pm$/;
3859 4262
3860 warn "... unloading $k"; 4263 trace "... unloading $k";
3861 delete $INC{$k}; 4264 delete $INC{$k};
3862 4265
3863 $k =~ s/\.pm$//; 4266 $k =~ s/\.pm$//;
3864 $k =~ s/\//::/g; 4267 $k =~ s/\//::/g;
3865 4268
3868 } 4271 }
3869 4272
3870 clear_package $k; 4273 clear_package $k;
3871 } 4274 }
3872 4275
3873 warn "getting rid of safe::, as good as possible"; 4276 trace "perl_reload: getting rid of safe::, as good as possible";
3874 clear_package "safe::$_" 4277 clear_package "safe::$_"
3875 for qw(cf::attachable cf::object cf::object::player cf::client cf::player cf::map cf::party cf::region); 4278 for qw(cf::attachable cf::object cf::object::player cf::client cf::player cf::map cf::party cf::region);
3876 4279
3877 warn "unloading cf.pm \"a bit\""; 4280 trace "perl_reload: unloading cf.pm \"a bit\"";
3878 delete $INC{"cf.pm"}; 4281 delete $INC{"cf.pm"};
3879 delete $INC{"cf/$_.pm"} for @EXTRA_MODULES; 4282 delete $INC{"cf/$_.pm"} for @EXTRA_MODULES;
3880 4283
3881 # don't, removes xs symbols, too, 4284 # don't, removes xs symbols, too,
3882 # and global variables created in xs 4285 # and global variables created in xs
3883 #clear_package __PACKAGE__; 4286 #clear_package __PACKAGE__;
3884 4287
3885 warn "unload completed, starting to reload now"; 4288 info "perl_reload: unload completed, starting to reload now";
3886 4289
3887 warn "reloading cf.pm"; 4290 trace "perl_reload: reloading cf.pm";
3888 require cf; 4291 require cf;
3889 cf::_connect_to_perl_1; 4292 cf::_connect_to_perl_1;
3890 4293
3891 warn "loading config and database again"; 4294 trace "perl_reload: loading config and database again";
3892 cf::reload_config; 4295 cf::reload_config;
3893 4296
3894 warn "loading extensions"; 4297 trace "perl_reload: loading extensions";
3895 cf::load_extensions; 4298 cf::load_extensions;
3896 4299
3897 if ($REATTACH_ON_RELOAD) { 4300 if ($REATTACH_ON_RELOAD) {
3898 warn "reattaching attachments to objects/players"; 4301 trace "perl_reload: reattaching attachments to objects/players";
3899 _global_reattach; # objects, sockets 4302 _global_reattach; # objects, sockets
3900 warn "reattaching attachments to maps"; 4303 trace "perl_reload: reattaching attachments to maps";
3901 reattach $_ for values %MAP; 4304 reattach $_ for values %MAP;
3902 warn "reattaching attachments to players"; 4305 trace "perl_reload: reattaching attachments to players";
3903 reattach $_ for values %PLAYER; 4306 reattach $_ for values %PLAYER;
3904 } 4307 }
3905 4308
3906 warn "running post_init jobs"; 4309 cf::_post_init 1;
3907 (pop @POST_INIT)->(1) while @POST_INIT;
3908 4310
3909 warn "leaving sync_job"; 4311 trace "perl_reload: leaving sync_job";
3910 4312
3911 1 4313 1
3912 } or do { 4314 } or do {
3913 warn $@; 4315 error $@;
3914 cf::cleanup "error while reloading, exiting."; 4316 cf::cleanup "perl_reload: error, exiting.";
3915 }; 4317 };
3916 4318
3917 warn "reloaded";
3918 --$RELOAD; 4319 --$RELOAD;
3919 } 4320 }
3920 4321
3921 $t1 = AE::time - $t1; 4322 $t1 = AE::time - $t1;
3922 warn "reload completed in ${t1}s\n"; 4323 info "perl_reload: completed in ${t1}s\n";
3923}; 4324};
3924 4325
3925our $RELOAD_WATCHER; # used only during reload 4326our $RELOAD_WATCHER; # used only during reload
3926 4327
3927sub reload_perl() { 4328sub reload_perl() {
3948 reload_perl; 4349 reload_perl;
3949 }; 4350 };
3950 } 4351 }
3951}; 4352};
3952 4353
3953unshift @INC, $LIBDIR; 4354#############################################################################
3954 4355
3955my $bug_warning = 0; 4356my $bug_warning = 0;
3956 4357
3957our @WAIT_FOR_TICK;
3958our @WAIT_FOR_TICK_BEGIN;
3959
3960sub wait_for_tick { 4358sub wait_for_tick() {
3961 return Coro::cede if tick_inhibit || $Coro::current == $Coro::main; 4359 return Coro::AnyEvent::poll if tick_inhibit || $Coro::current == $Coro::main;
3962 4360
3963 my $signal = new Coro::Signal; 4361 $WAIT_FOR_TICK->wait;
3964 push @WAIT_FOR_TICK, $signal;
3965 $signal->wait;
3966} 4362}
3967 4363
3968sub wait_for_tick_begin { 4364sub wait_for_tick_begin() {
3969 return Coro::cede if tick_inhibit || $Coro::current == $Coro::main; 4365 return Coro::AnyEvent::poll if tick_inhibit || $Coro::current == $Coro::main;
3970 4366
3971 my $signal = new Coro::Signal; 4367 my $signal = new Coro::Signal;
3972 push @WAIT_FOR_TICK_BEGIN, $signal; 4368 push @WAIT_FOR_TICK_BEGIN, $signal;
3973 $signal->wait; 4369 $signal->wait;
3974} 4370}
3978 Carp::cluck "major BUG: server tick called outside of main coro, skipping it" 4374 Carp::cluck "major BUG: server tick called outside of main coro, skipping it"
3979 unless ++$bug_warning > 10; 4375 unless ++$bug_warning > 10;
3980 return; 4376 return;
3981 } 4377 }
3982 4378
3983 cf::server_tick; # one server iteration 4379 cf::one_tick; # one server iteration
3984 4380
3985 #for(1..3e6){} AE::now_update; $NOW=AE::now; # generate load #d# 4381 #for(1..3e6){} AE::now_update; $NOW=AE::now; # generate load #d#
3986 4382
3987 if ($NOW >= $NEXT_RUNTIME_WRITE) { 4383 if ($NOW >= $NEXT_RUNTIME_WRITE) {
3988 $NEXT_RUNTIME_WRITE = List::Util::max $NEXT_RUNTIME_WRITE + 10, $NOW + 5.; 4384 $NEXT_RUNTIME_WRITE = List::Util::max $NEXT_RUNTIME_WRITE + 10, $NOW + 5.;
3989 Coro::async_pool { 4385 Coro::async_pool {
3990 $Coro::current->{desc} = "runtime saver"; 4386 $Coro::current->{desc} = "runtime saver";
3991 write_runtime_sync 4387 write_runtime_sync
3992 or warn "ERROR: unable to write runtime file: $!"; 4388 or error "ERROR: unable to write runtime file: $!";
3993 }; 4389 };
3994 } 4390 }
3995 4391
3996 if (my $sig = shift @WAIT_FOR_TICK_BEGIN) { 4392 if (my $sig = shift @WAIT_FOR_TICK_BEGIN) {
3997 $sig->send; 4393 $sig->send;
3998 } 4394 }
3999 while (my $sig = shift @WAIT_FOR_TICK) { 4395 $WAIT_FOR_TICK->broadcast;
4000 $sig->send;
4001 }
4002 4396
4003 $LOAD = ($NOW - $TICK_START) / $TICK; 4397 $LOAD = ($NOW - $TICK_START) / $TICK;
4004 $LOADAVG = $LOADAVG * 0.75 + $LOAD * 0.25; 4398 $LOADAVG = $LOADAVG * 0.75 + $LOAD * 0.25;
4005 4399
4006 if (0) { 4400 if (0) {
4007 if ($NEXT_TICK) { 4401 if ($NEXT_TICK) {
4008 my $jitter = $TICK_START - $NEXT_TICK; 4402 my $jitter = $TICK_START - $NEXT_TICK;
4009 $JITTER = $JITTER * 0.75 + $jitter * 0.25; 4403 $JITTER = $JITTER * 0.75 + $jitter * 0.25;
4010 warn "jitter $JITTER\n";#d# 4404 debug "jitter $JITTER\n";#d#
4011 } 4405 }
4012 } 4406 }
4013} 4407}
4014 4408
4015{ 4409{
4016 # configure BDB 4410 # configure BDB
4411 info "initialising database";
4017 4412
4018 BDB::min_parallel 16; 4413 BDB::min_parallel 16;
4019 BDB::max_poll_reqs $TICK * 0.1; 4414 BDB::max_poll_reqs $TICK * 0.1;
4020 $AnyEvent::BDB::WATCHER->priority (1); 4415 #$AnyEvent::BDB::WATCHER->priority (1);
4021 4416
4022 unless ($DB_ENV) { 4417 unless ($DB_ENV) {
4023 $DB_ENV = BDB::db_env_create; 4418 $DB_ENV = BDB::db_env_create;
4024 $DB_ENV->set_flags (BDB::AUTO_COMMIT | BDB::REGION_INIT); 4419 $DB_ENV->set_flags (BDB::AUTO_COMMIT | BDB::REGION_INIT);
4025 $DB_ENV->set_flags (&BDB::LOG_AUTOREMOVE ) if BDB::VERSION v0, v4.7; 4420 $DB_ENV->set_flags (&BDB::LOG_AUTOREMOVE ) if BDB::VERSION v0, v4.7;
4050 BDB::db_env_txn_checkpoint $DB_ENV, 0, 0, 0, sub { }; 4445 BDB::db_env_txn_checkpoint $DB_ENV, 0, 0, 0, sub { };
4051 }; 4446 };
4052 $BDB_TRICKLE_WATCHER = EV::periodic 0, 10, 0, sub { 4447 $BDB_TRICKLE_WATCHER = EV::periodic 0, 10, 0, sub {
4053 BDB::db_env_memp_trickle $DB_ENV, 20, 0, sub { }; 4448 BDB::db_env_memp_trickle $DB_ENV, 20, 0, sub { };
4054 }; 4449 };
4450
4451 info "database initialised";
4055} 4452}
4056 4453
4057{ 4454{
4058 # configure IO::AIO 4455 # configure IO::AIO
4059 4456
4457 info "initialising aio";
4060 IO::AIO::min_parallel 8; 4458 IO::AIO::min_parallel 8;
4061 IO::AIO::max_poll_time $TICK * 0.1; 4459 IO::AIO::max_poll_time $TICK * 0.1;
4062 undef $AnyEvent::AIO::WATCHER; 4460 undef $AnyEvent::AIO::WATCHER;
4461 info "aio initialised";
4063} 4462}
4064 4463
4065my $_log_backtrace; 4464our $_log_backtrace;
4465our $_log_backtrace_last;
4066 4466
4067sub _log_backtrace { 4467sub _log_backtrace {
4068 my ($msg, @addr) = @_; 4468 my ($msg, @addr) = @_;
4069 4469
4070 $msg =~ s/\n//; 4470 $msg =~ s/\n$//;
4071 4471
4472 if ($_log_backtrace_last eq $msg) {
4473 LOG llevInfo, "[ABT] $msg\n";
4474 LOG llevInfo, "[ABT] [duplicate, suppressed]\n";
4072 # limit the # of concurrent backtraces 4475 # limit the # of concurrent backtraces
4073 if ($_log_backtrace < 2) { 4476 } elsif ($_log_backtrace < 2) {
4477 $_log_backtrace_last = $msg;
4074 ++$_log_backtrace; 4478 ++$_log_backtrace;
4075 my $perl_bt = Carp::longmess $msg; 4479 my $perl_bt = Carp::longmess $msg;
4076 async { 4480 async {
4077 $Coro::current->{desc} = "abt $msg"; 4481 $Coro::current->{desc} = "abt $msg";
4078 4482
4098 LOG llevInfo, "[ABT] $_\n" for @bt; 4502 LOG llevInfo, "[ABT] $_\n" for @bt;
4099 --$_log_backtrace; 4503 --$_log_backtrace;
4100 }; 4504 };
4101 } else { 4505 } else {
4102 LOG llevInfo, "[ABT] $msg\n"; 4506 LOG llevInfo, "[ABT] $msg\n";
4103 LOG llevInfo, "[ABT] [suppressed]\n"; 4507 LOG llevInfo, "[ABT] [overload, suppressed]\n";
4104 } 4508 }
4105} 4509}
4106 4510
4107# load additional modules 4511# load additional modules
4108require "cf/$_.pm" for @EXTRA_MODULES; 4512require "cf/$_.pm" for @EXTRA_MODULES;

Diff Legend

Removed lines
+ Added lines
< Changed lines
> Changed lines