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.533 by root, Thu Apr 29 07:59:17 2010 UTC vs.
Revision 1.573 by root, Sun May 8 12:40:42 2011 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 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.
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;
78# strictly for debugging 76# strictly for debugging
79$SIG{QUIT} = sub { Carp::cluck "SIGQUIT" }; 77$SIG{QUIT} = sub { Carp::cluck "SIGQUIT" };
80 78
81sub WF_AUTOCANCEL () { 1 } # automatically cancel this watcher on reload 79sub WF_AUTOCANCEL () { 1 } # automatically cancel this watcher on reload
82 80
81our @ORIG_INC;
82
83our %COMMAND = (); 83our %COMMAND = ();
84our %COMMAND_TIME = (); 84our %COMMAND_TIME = ();
85 85
86our @EXTS = (); # list of extension package names 86our @EXTS = (); # list of extension package names
87our %EXTCMD = (); 87our %EXTCMD = ();
93our @EVENT; 93our @EVENT;
94our @REFLECT; # set by XS 94our @REFLECT; # set by XS
95our %REFLECT; # set by us 95our %REFLECT; # set by us
96 96
97our $CONFDIR = confdir; 97our $CONFDIR = confdir;
98
98our $DATADIR = datadir; 99our $DATADIR = datadir;
99our $LIBDIR = "$DATADIR/ext"; 100our $LIBDIR = "$DATADIR/ext";
100our $PODDIR = "$DATADIR/pod"; 101our $PODDIR = "$DATADIR/pod";
101our $MAPDIR = "$DATADIR/" . mapdir; 102our $MAPDIR = "$DATADIR/" . mapdir;
103
102our $LOCALDIR = localdir; 104our $LOCALDIR = localdir;
103our $TMPDIR = "$LOCALDIR/" . tmpdir; 105our $TMPDIR = "$LOCALDIR/" . tmpdir;
104our $UNIQUEDIR = "$LOCALDIR/" . uniquedir; 106our $UNIQUEDIR = "$LOCALDIR/" . uniquedir;
105our $PLAYERDIR = "$LOCALDIR/" . playerdir; 107our $PLAYERDIR = "$LOCALDIR/" . playerdir;
106our $RANDOMDIR = "$LOCALDIR/random"; 108our $RANDOMDIR = "$LOCALDIR/random";
124our $BDB_DEADLOCK_WATCHER; 126our $BDB_DEADLOCK_WATCHER;
125our $BDB_CHECKPOINT_WATCHER; 127our $BDB_CHECKPOINT_WATCHER;
126our $BDB_TRICKLE_WATCHER; 128our $BDB_TRICKLE_WATCHER;
127our $DB_ENV; 129our $DB_ENV;
128 130
129our @EXTRA_MODULES = qw(pod match mapscript); 131our @EXTRA_MODULES = qw(pod match mapscript incloader);
130 132
131our %CFG; 133our %CFG;
132 134
133our $UPTIME; $UPTIME ||= time; 135our $UPTIME; $UPTIME ||= time;
134our $RUNTIME; 136our $RUNTIME = 0;
137our $SERVER_TICK = 0;
135our $NOW; 138our $NOW;
136 139
137our (%PLAYER, %PLAYER_LOADING); # all users 140our (%PLAYER, %PLAYER_LOADING); # all users
138our (%MAP, %MAP_LOADING ); # all maps 141our (%MAP, %MAP_LOADING ); # all maps
139our $LINK_MAP; # the special {link} map, which is always available 142our $LINK_MAP; # the special {link} map, which is always available
148 151
149our @POST_INIT; 152our @POST_INIT;
150 153
151our $REATTACH_ON_RELOAD; # set to true to force object reattach on reload (slow) 154our $REATTACH_ON_RELOAD; # set to true to force object reattach on reload (slow)
152our $REALLY_UNLOOP; # never set to true, please :) 155our $REALLY_UNLOOP; # never set to true, please :)
156
157our $WAIT_FOR_TICK = new Coro::Signal;
158our @WAIT_FOR_TICK_BEGIN;
153 159
154binmode STDOUT; 160binmode STDOUT;
155binmode STDERR; 161binmode STDERR;
156 162
157# read virtual server time, if available 163# read virtual server time, if available
191 197
192=over 4 198=over 4
193 199
194=item $cf::UPTIME 200=item $cf::UPTIME
195 201
196The timestamp of the server start (so not actually an uptime). 202The timestamp of the server start (so not actually an "uptime").
203
204=item $cf::SERVER_TICK
205
206An unsigned integer that starts at zero when the server is started and is
207incremented on every tick.
208
209=item $cf::NOW
210
211The (real) time of the last (current) server tick - updated before and
212after tick processing, so this is useful only as a rough "what time is it
213now" estimate.
214
215=item $cf::TICK
216
217The interval between each server tick, in seconds.
197 218
198=item $cf::RUNTIME 219=item $cf::RUNTIME
199 220
200The time this server has run, starts at 0 and is increased by $cf::TICK on 221The time this server has run, starts at 0 and is increased by $cf::TICK on
201every server tick. 222every server tick.
207Various directories - "/etc", read-only install directory, perl-library 228Various directories - "/etc", read-only install directory, perl-library
208directory, pod-directory, read-only maps directory, "/var", "/var/tmp", 229directory, pod-directory, read-only maps directory, "/var", "/var/tmp",
209unique-items directory, player file directory, random maps directory and 230unique-items directory, player file directory, random maps directory and
210database environment. 231database environment.
211 232
212=item $cf::NOW
213
214The time of the last (current) server tick.
215
216=item $cf::TICK
217
218The interval between server ticks, in seconds.
219
220=item $cf::LOADAVG 233=item $cf::LOADAVG
221 234
222The current CPU load on the server (alpha-smoothed), as a value between 0 235The current CPU load on the server (alpha-smoothed), as a value between 0
223(none) and 1 (overloaded), indicating how much time is spent on processing 236(none) and 1 (overloaded), indicating how much time is spent on processing
224objects per tick. Healthy values are < 0.5. 237objects per tick. Healthy values are < 0.5.
233from wherever your confdir points to. 246from wherever your confdir points to.
234 247
235=item cf::wait_for_tick, cf::wait_for_tick_begin 248=item cf::wait_for_tick, cf::wait_for_tick_begin
236 249
237These are functions that inhibit the current coroutine one tick. cf::wait_for_tick_begin only 250These are functions that inhibit the current coroutine one tick. cf::wait_for_tick_begin only
238returns directly I<after> the tick processing (and consequently, can only wake one process 251returns directly I<after> the tick processing (and consequently, can only wake one thread
239per tick), while cf::wait_for_tick wakes up all waiters after tick processing. 252per tick), while cf::wait_for_tick wakes up all waiters after tick processing.
253
254Note that cf::Wait_for_tick will immediately return when the server is not
255ticking, making it suitable for small pauses in threads that need to run
256when the server is paused. If that is not applicable (i.e. you I<really>
257want to wait, use C<$cf::WAIT_FOR_TICK>).
258
259=item $cf::WAIT_FOR_TICK
260
261Note that C<cf::wait_for_tick> is probably the correct thing to use. This
262variable contains a L<Coro::Signal> that is broadcats after every server
263tick. Calling C<< ->wait >> on it will suspend the caller until after the
264next server tick.
265
266=cut
267
268sub wait_for_tick();
269sub wait_for_tick_begin();
240 270
241=item @cf::INVOKE_RESULTS 271=item @cf::INVOKE_RESULTS
242 272
243This array contains the results of the last C<invoke ()> call. When 273This array contains the results of the last C<invoke ()> call. When
244C<cf::override> is called C<@cf::INVOKE_RESULTS> is set to the parameters of 274C<cf::override> is called C<@cf::INVOKE_RESULTS> is set to the parameters of
307} 337}
308 338
309$EV::DIED = sub { 339$EV::DIED = sub {
310 Carp::cluck "error in event callback: @_"; 340 Carp::cluck "error in event callback: @_";
311}; 341};
342
343#############################################################################
344
345sub fork_call(&@);
346sub get_slot($;$$);
312 347
313############################################################################# 348#############################################################################
314 349
315=head2 UTILITY FUNCTIONS 350=head2 UTILITY FUNCTIONS
316 351
337 $d =~ s/([\x00-\x07\x09\x0b\x0c\x0e-\x1f])/sprintf "\\x%02x", ord($1)/ge; 372 $d =~ s/([\x00-\x07\x09\x0b\x0c\x0e-\x1f])/sprintf "\\x%02x", ord($1)/ge;
338 $d 373 $d
339 } || "[unable to dump $_[0]: '$@']"; 374 } || "[unable to dump $_[0]: '$@']";
340} 375}
341 376
377=item $scalar = load_file $path
378
379Loads the given file from path and returns its contents. Croaks on error
380and can block.
381
382=cut
383
384sub load_file($) {
385 0 <= aio_load $_[0], my $data
386 or Carp::croak "$_[0]: $!";
387
388 $data
389}
390
342=item $ref = cf::decode_json $json 391=item $ref = cf::decode_json $json
343 392
344Converts a JSON string into the corresponding perl data structure. 393Converts a JSON string into the corresponding perl data structure.
345 394
346=item $json = cf::encode_json $ref 395=item $json = cf::encode_json $ref
352our $json_coder = JSON::XS->new->utf8->max_size (1e6); # accept ~1mb max 401our $json_coder = JSON::XS->new->utf8->max_size (1e6); # accept ~1mb max
353 402
354sub encode_json($) { $json_coder->encode ($_[0]) } 403sub encode_json($) { $json_coder->encode ($_[0]) }
355sub decode_json($) { $json_coder->decode ($_[0]) } 404sub decode_json($) { $json_coder->decode ($_[0]) }
356 405
406=item $ref = cf::decode_storable $scalar
407
408Same as Coro::Storable::thaw, so blocks.
409
410=cut
411
412BEGIN { *decode_storable = \&Coro::Storable::thaw }
413
414=item $ref = cf::decode_yaml $scalar
415
416Same as YAML::XS::Load, but doesn't leak, because it forks (and thus blocks).
417
418=cut
419
420sub decode_yaml($) {
421 fork_call { YAML::XS::Load $_[0] } @_
422}
423
424=item $scalar = cf::unlzf $scalar
425
426Same as Compress::LZF::compress, but takes server ticks into account, so
427blocks.
428
429=cut
430
431sub unlzf($) {
432 # we assume 100mb/s minimum decompression speed (noncompressible data on a ~2ghz machine)
433 cf::get_slot +(length $_[0]) / 100_000_000, 0, "unlzf";
434 Compress::LZF::decompress $_[0]
435}
436
357=item cf::post_init { BLOCK } 437=item cf::post_init { BLOCK }
358 438
359Execute the given codeblock, I<after> all extensions have been (re-)loaded, 439Execute the given codeblock, I<after> all extensions have been (re-)loaded,
360but I<before> the server starts ticking again. 440but I<before> the server starts ticking again.
361 441
362The cdoeblock will have a single boolean argument to indicate whether this 442The codeblock will have a single boolean argument to indicate whether this
363is a reload or not. 443is a reload or not.
364 444
365=cut 445=cut
366 446
367sub post_init(&) { 447sub post_init(&) {
368 push @POST_INIT, shift; 448 push @POST_INIT, shift;
449}
450
451sub _post_init {
452 trace "running post_init jobs";
453
454 # run them in parallel...
455
456 my @join;
457
458 while () {
459 push @join, map &Coro::async ($_, 0), @POST_INIT;
460 @POST_INIT = ();
461
462 @join or last;
463
464 (pop @join)->join;
465 }
369} 466}
370 467
371=item cf::lock_wait $string 468=item cf::lock_wait $string
372 469
373Wait until the given lock is available. See cf::lock_acquire. 470Wait until the given lock is available. See cf::lock_acquire.
426 EV::periodic $start, $interval, 0, $cb 523 EV::periodic $start, $interval, 0, $cb
427} 524}
428 525
429=item cf::get_slot $time[, $priority[, $name]] 526=item cf::get_slot $time[, $priority[, $name]]
430 527
431Allocate $time seconds of blocking CPU time at priority C<$priority>: 528Allocate $time seconds of blocking CPU time at priority C<$priority>
432This call blocks and returns only when you have at least C<$time> seconds 529(default: 0): This call blocks and returns only when you have at least
433of cpu time till the next tick. The slot is only valid till the next cede. 530C<$time> seconds of cpu time till the next tick. The slot is only valid
531till the next cede.
532
533Background jobs should use a priority les than zero, interactive jobs
534should use 100 or more.
434 535
435The optional C<$name> can be used to identify the job to run. It might be 536The optional C<$name> can be used to identify the job to run. It might be
436used for statistical purposes and should identify the same time-class. 537used for statistical purposes and should identify the same time-class.
437 538
438Useful for short background jobs. 539Useful for short background jobs.
467 } 568 }
468 } 569 }
469 570
470 if (@SLOT_QUEUE) { 571 if (@SLOT_QUEUE) {
471 # we do not use wait_for_tick() as it returns immediately when tick is inactive 572 # we do not use wait_for_tick() as it returns immediately when tick is inactive
472 push @cf::WAIT_FOR_TICK, $signal; 573 $WAIT_FOR_TICK->wait;
473 $signal->wait;
474 } else { 574 } else {
475 $busy = 0; 575 $busy = 0;
476 Coro::schedule; 576 Coro::schedule;
477 } 577 }
478 } 578 }
518=cut 618=cut
519 619
520sub sync_job(&) { 620sub sync_job(&) {
521 my ($job) = @_; 621 my ($job) = @_;
522 622
523 if ($Coro::current == $Coro::main) { 623 if (in_main) {
524 my $time = AE::time; 624 my $time = AE::time;
525 625
526 # this is the main coro, too bad, we have to block 626 # this is the main coro, too bad, we have to block
527 # till the operation succeeds, freezing the server :/ 627 # till the operation succeeds, freezing the server :/
528 628
529 LOG llevError, Carp::longmess "sync job";#d# 629 #LOG llevError, Carp::longmess "sync job";#d#
530 630
531 my $freeze_guard = freeze_mainloop; 631 my $freeze_guard = freeze_mainloop;
532 632
533 my $busy = 1; 633 my $busy = 1;
534 my @res; 634 my @res;
578 $EXT_CORO{$coro+0} = $coro; 678 $EXT_CORO{$coro+0} = $coro;
579 679
580 $coro 680 $coro
581} 681}
582 682
583=item fork_call { }, $args 683=item fork_call { }, @args
584 684
585Executes the given code block with the given arguments in a seperate 685Executes the given code block with the given arguments in a seperate
586process, returning the results. Everything must be serialisable with 686process, returning the results. Everything must be serialisable with
587Coro::Storable. May, of course, block. Note that the executed sub may 687Coro::Storable. May, of course, block. Note that the executed sub may
588never block itself or use any form of event handling. 688never block itself or use any form of event handling.
589 689
590=cut 690=cut
591 691
692sub post_fork {
693 reset_signals;
694}
695
592sub fork_call(&@) { 696sub fork_call(&@) {
593 my ($cb, @args) = @_; 697 my ($cb, @args) = @_;
594 698
595 # we seemingly have to make a local copy of the whole thing, 699 # we seemingly have to make a local copy of the whole thing,
596 # otherwise perl prematurely frees the stuff :/ 700 # otherwise perl prematurely frees the stuff :/
597 # TODO: investigate and fix (likely this will be rather laborious) 701 # TODO: investigate and fix (likely this will be rather laborious)
598 702
599 my @res = Coro::Util::fork_eval { 703 my @res = Coro::Util::fork_eval {
600 reset_signals; 704 cf::post_fork;
601 &$cb 705 &$cb
602 }, @args; 706 } @args;
603 707
604 wantarray ? @res : $res[-1] 708 wantarray ? @res : $res[-1]
605} 709}
606 710
607sub objinfo { 711sub objinfo {
657within each server. 761within each server.
658 762
659=cut 763=cut
660 764
661sub db_table($) { 765sub db_table($) {
766 cf::error "db_get called from main context"
767 if $Coro::current == $Coro::main;
768
662 my ($name) = @_; 769 my ($name) = @_;
663 my $db = BDB::db_create $DB_ENV; 770 my $db = BDB::db_create $DB_ENV;
664 771
665 eval { 772 eval {
666 $db->set_flags (BDB::CHKSUM); 773 $db->set_flags (BDB::CHKSUM);
676} 783}
677 784
678our $DB; 785our $DB;
679 786
680sub db_init { 787sub db_init {
681 cf::sync_job {
682 $DB ||= db_table "db"; 788 $DB ||= db_table "db";
683 };
684} 789}
685 790
686sub db_get($$) { 791sub db_get($$) {
687 my $key = "$_[0]/$_[1]"; 792 my $key = "$_[0]/$_[1]";
688 793
689 cf::sync_job { 794 cf::error "db_get called from main context"
795 if $Coro::current == $Coro::main;
796
690 BDB::db_get $DB, undef, $key, my $data; 797 BDB::db_get $DB, undef, $key, my $data;
691 798
692 $! ? () 799 $! ? ()
693 : $data 800 : $data
694 }
695} 801}
696 802
697sub db_put($$$) { 803sub db_put($$$) {
698 BDB::dbreq_pri 4; 804 BDB::dbreq_pri 4;
699 BDB::db_put $DB, undef, "$_[0]/$_[1]", $_[2], 0, sub { }; 805 BDB::db_put $DB, undef, "$_[0]/$_[1]", $_[2], 0, sub { };
727 833
728 my @data; 834 my @data;
729 my $md5; 835 my $md5;
730 836
731 for (0 .. $#$src) { 837 for (0 .. $#$src) {
732 0 <= aio_load $src->[$_], $data[$_] 838 $data[$_] = load_file $src->[$_];
733 or Carp::croak "$src->[$_]: $!";
734 } 839 }
735 840
736 # if processing is expensive, check 841 # if processing is expensive, check
737 # checksum first 842 # checksum first
738 if (1) { 843 if (1) {
1421 1526
1422 $ext{meta} = { map { (split /=/, $_, 2)[0, 1] } split /\s+/, $1 } 1527 $ext{meta} = { map { (split /=/, $_, 2)[0, 1] } split /\s+/, $1 }
1423 if $source =~ /\A#!.*?perl.*?#\s*(.*)$/m; 1528 if $source =~ /\A#!.*?perl.*?#\s*(.*)$/m;
1424 1529
1425 $ext{source} = 1530 $ext{source} =
1426 "package $pkg; use 5.10.0; use strict 'vars', 'subs'; use utf8;\n" 1531 "package $pkg; use common::sense;\n"
1427 . "#line 1 \"$path\"\n{\n" 1532 . "#line 1 \"$path\"\n{\n"
1428 . $source 1533 . $source
1429 . "\n};\n1"; 1534 . "\n};\n1";
1430 1535
1431 $todo{$base} = \%ext; 1536 $todo{$base} = \%ext;
1472 1577
1473 while (my ($k, $v) = each %todo) { 1578 while (my ($k, $v) = each %todo) {
1474 cf::cleanup "mandatory extension '$k' has unresolved dependencies, exiting." 1579 cf::cleanup "mandatory extension '$k' has unresolved dependencies, exiting."
1475 if exists $v->{meta}{mandatory}; 1580 if exists $v->{meta}{mandatory};
1476 } 1581 }
1582
1583 last;
1477 } 1584 }
1478 } 1585 }
1479 }; 1586 };
1480} 1587}
1481 1588
1639 my $name = $pl->ob->name; 1746 my $name = $pl->ob->name;
1640 1747
1641 $pl->{deny_save} = 1; 1748 $pl->{deny_save} = 1;
1642 $pl->password ("*"); # this should lock out the player until we have nuked the dir 1749 $pl->password ("*"); # this should lock out the player until we have nuked the dir
1643 1750
1644 $pl->invoke (cf::EVENT_PLAYER_LOGOUT, 1) if $pl->active; 1751 $pl->invoke (cf::EVENT_PLAYER_LOGOUT, 1) if $pl->ns;
1645 $pl->deactivate; 1752 $pl->deactivate;
1753
1646 my $killer = cf::arch::get "killer_quit"; $pl->killer ($killer); $killer->destroy; 1754 my $killer = cf::arch::get "killer_quit"; $pl->killer ($killer); $killer->destroy;
1647 $pl->invoke (cf::EVENT_PLAYER_QUIT); 1755 $pl->invoke (cf::EVENT_PLAYER_QUIT) if $pl->ns;
1756 ext::highscore::check ($pl->ob);
1757
1648 $pl->ns->destroy if $pl->ns; 1758 $pl->ns->destroy if $pl->ns;
1649 1759
1650 my $path = playerdir $pl; 1760 my $path = playerdir $pl;
1651 my $temp = "$path~$cf::RUNTIME~deleting~"; 1761 my $temp = "$path~$cf::RUNTIME~deleting~";
1652 aio_rename $path, $temp; 1762 aio_rename $path, $temp;
1818sub generate_random_map { 1928sub generate_random_map {
1819 my ($self, $rmp) = @_; 1929 my ($self, $rmp) = @_;
1820 1930
1821 my $lock = cf::lock_acquire "generate_random_map"; # the random map generator is NOT reentrant ATM 1931 my $lock = cf::lock_acquire "generate_random_map"; # the random map generator is NOT reentrant ATM
1822 1932
1823 # mit "rum" bekleckern, nicht
1824 $self->_create_random_map ( 1933 $self->_create_random_map ($rmp);
1825 $rmp->{wallstyle}, $rmp->{wall_name}, $rmp->{floorstyle}, $rmp->{monsterstyle},
1826 $rmp->{treasurestyle}, $rmp->{layoutstyle}, $rmp->{doorstyle}, $rmp->{decorstyle}, $rmp->{miningstyle},
1827 $rmp->{origin_map}, $rmp->{final_map}, $rmp->{exitstyle}, $rmp->{this_map},
1828 $rmp->{exit_on_final_map},
1829 $rmp->{xsize}, $rmp->{ysize},
1830 $rmp->{expand2x}, $rmp->{layoutoptions1}, $rmp->{layoutoptions2}, $rmp->{layoutoptions3},
1831 $rmp->{symmetry}, $rmp->{difficulty}, $rmp->{difficulty_given}, $rmp->{difficulty_increase},
1832 $rmp->{dungeon_level}, $rmp->{dungeon_depth}, $rmp->{decoroptions}, $rmp->{orientation},
1833 $rmp->{origin_y}, $rmp->{origin_x}, $rmp->{random_seed}, $rmp->{total_map_hp},
1834 $rmp->{map_layout_style}, $rmp->{treasureoptions}, $rmp->{symmetry_used},
1835 (cf::region::find $rmp->{region}), $rmp->{custom}
1836 )
1837} 1934}
1838 1935
1839=item cf::map->register ($regex, $prio) 1936=item cf::map->register ($regex, $prio)
1840 1937
1841Register a handler for the map path matching the given regex at the 1938Register a handler for the map path matching the given regex at the
1846 1943
1847sub register { 1944sub register {
1848 my (undef, $regex, $prio) = @_; 1945 my (undef, $regex, $prio) = @_;
1849 my $pkg = caller; 1946 my $pkg = caller;
1850 1947
1851 no strict;
1852 push @{"$pkg\::ISA"}, __PACKAGE__; 1948 push @{"$pkg\::ISA"}, __PACKAGE__;
1853 1949
1854 $EXT_MAP{$pkg} = [$prio, qr<$regex>]; 1950 $EXT_MAP{$pkg} = [$prio, qr<$regex>];
1855} 1951}
1856 1952
1868} 1964}
1869 1965
1870sub normalise { 1966sub normalise {
1871 my ($path, $base) = @_; 1967 my ($path, $base) = @_;
1872 1968
1873 $path = "$path"; # make sure its a string 1969 $path = "$path"; # make sure it's a string
1874 1970
1875 $path =~ s/\.map$//; 1971 $path =~ s/\.map$//;
1876 1972
1877 # map plan: 1973 # map plan:
1878 # 1974 #
1893 $base =~ s{[^/]+/?$}{}; 1989 $base =~ s{[^/]+/?$}{};
1894 $path = "$base/$path"; 1990 $path = "$base/$path";
1895 } 1991 }
1896 1992
1897 for ($path) { 1993 for ($path) {
1898 redo if s{//}{/};
1899 redo if s{/\.?/}{/}; 1994 redo if s{/\.?/}{/};
1900 redo if s{/[^/]+/\.\./}{/}; 1995 redo if s{/[^/]+/\.\./}{/};
1901 } 1996 }
1902 1997
1903 $path 1998 $path
1917 $self->init; # pass $1 etc. 2012 $self->init; # pass $1 etc.
1918 return $self; 2013 return $self;
1919 } 2014 }
1920 } 2015 }
1921 2016
1922 Carp::cluck "unable to resolve path '$path' (base '$base')."; 2017 Carp::cluck "unable to resolve path '$path' (base '$base')";
1923 () 2018 ()
1924} 2019}
1925 2020
2021# may re-bless or do other evil things
1926sub init { 2022sub init {
1927 my ($self) = @_; 2023 my ($self) = @_;
1928 2024
1929 $self 2025 $self
1930} 2026}
1995 $self->{load_path} = $path; 2091 $self->{load_path} = $path;
1996 2092
1997 1 2093 1
1998} 2094}
1999 2095
2096# used to laod the header of an original map
2000sub load_header_orig { 2097sub load_header_orig {
2001 my ($self) = @_; 2098 my ($self) = @_;
2002 2099
2003 $self->load_header_from ($self->load_path) 2100 $self->load_header_from ($self->load_path)
2004} 2101}
2005 2102
2103# used to laod the header of an instantiated map
2006sub load_header_temp { 2104sub load_header_temp {
2007 my ($self) = @_; 2105 my ($self) = @_;
2008 2106
2009 $self->load_header_from ($self->save_path) 2107 $self->load_header_from ($self->save_path)
2010} 2108}
2011 2109
2110# called after loading the header from an instantiated map
2012sub prepare_temp { 2111sub prepare_temp {
2013 my ($self) = @_; 2112 my ($self) = @_;
2014 2113
2015 $self->last_access ((delete $self->{last_access}) 2114 $self->last_access ((delete $self->{last_access})
2016 || $cf::RUNTIME); #d# 2115 || $cf::RUNTIME); #d#
2017 # safety 2116 # safety
2018 $self->{instantiate_time} = $cf::RUNTIME 2117 $self->{instantiate_time} = $cf::RUNTIME
2019 if $self->{instantiate_time} > $cf::RUNTIME; 2118 if $self->{instantiate_time} > $cf::RUNTIME;
2020} 2119}
2021 2120
2121# called after loading the header from an original map
2022sub prepare_orig { 2122sub prepare_orig {
2023 my ($self) = @_; 2123 my ($self) = @_;
2024 2124
2025 $self->{load_original} = 1; 2125 $self->{load_original} = 1;
2026 $self->{instantiate_time} = $cf::RUNTIME; 2126 $self->{instantiate_time} = $cf::RUNTIME;
2050 2150
2051sub find; 2151sub find;
2052sub find { 2152sub find {
2053 my ($path, $origin) = @_; 2153 my ($path, $origin) = @_;
2054 2154
2155 cf::cede_to_tick;
2156
2055 $path = normalise $path, $origin && $origin->path; 2157 $path = normalise $path, $origin;
2056 2158
2057 my $guard1 = cf::lock_acquire "map_data:$path";#d#remove 2159 my $guard1 = cf::lock_acquire "map_data:$path";#d#remove
2058 my $guard2 = cf::lock_acquire "map_find:$path"; 2160 my $guard2 = cf::lock_acquire "map_find:$path";
2059 2161
2060 $cf::MAP{$path} || do { 2162 $cf::MAP{$path} || do {
2091 2193
2092 { 2194 {
2093 my $guard = cf::lock_acquire "map_data:$path"; 2195 my $guard = cf::lock_acquire "map_data:$path";
2094 2196
2095 return unless $self->valid; 2197 return unless $self->valid;
2096 return unless $self->in_memory == cf::MAP_SWAPPED; 2198 return unless $self->state == cf::MAP_SWAPPED;
2097
2098 $self->in_memory (cf::MAP_LOADING);
2099 2199
2100 $self->alloc; 2200 $self->alloc;
2101 2201
2102 $self->pre_load; 2202 $self->pre_load;
2103 cf::cede_to_tick; 2203 cf::cede_to_tick;
2104 2204
2205 if (exists $self->{load_path}) {
2105 my $f = new_from_file cf::object::thawer $self->{load_path}; 2206 my $f = new_from_file cf::object::thawer $self->{load_path};
2106 $f->skip_block; 2207 $f->skip_block;
2107 $self->_load_objects ($f) 2208 $self->_load_objects ($f)
2108 or return; 2209 or return;
2109 2210
2110 $self->post_load_original 2211 $self->post_load_original
2111 if delete $self->{load_original}; 2212 if delete $self->{load_original};
2112 2213
2113 if (my $uniq = $self->uniq_path) { 2214 if (my $uniq = $self->uniq_path) {
2114 utf8::encode $uniq; 2215 utf8::encode $uniq;
2115 unless (aio_stat $uniq) { 2216 unless (aio_stat $uniq) {
2116 if (my $f = new_from_file cf::object::thawer $uniq) { 2217 if (my $f = new_from_file cf::object::thawer $uniq) {
2117 $self->clear_unique_items; 2218 $self->clear_unique_items;
2118 $self->_load_objects ($f); 2219 $self->_load_objects ($f);
2119 $f->resolve_delayed_derefs; 2220 $f->resolve_delayed_derefs;
2221 }
2120 } 2222 }
2121 } 2223 }
2122 }
2123 2224
2124 $f->resolve_delayed_derefs; 2225 $f->resolve_delayed_derefs;
2226 } else {
2227 $self->post_load_original
2228 if delete $self->{load_original};
2229 }
2230
2231 $self->state (cf::MAP_INACTIVE);
2125 2232
2126 cf::cede_to_tick; 2233 cf::cede_to_tick;
2127 # now do the right thing for maps 2234 # now do the right thing for maps
2128 $self->link_multipart_objects; 2235 $self->link_multipart_objects;
2129 $self->difficulty ($self->estimate_difficulty) 2236 $self->difficulty ($self->estimate_difficulty)
2133 unless ($self->{deny_activate}) { 2240 unless ($self->{deny_activate}) {
2134 $self->decay_objects; 2241 $self->decay_objects;
2135 $self->fix_auto_apply; 2242 $self->fix_auto_apply;
2136 $self->update_buttons; 2243 $self->update_buttons;
2137 cf::cede_to_tick; 2244 cf::cede_to_tick;
2138 $self->activate; 2245 #$self->activate; # no longer activate maps automatically
2139 } 2246 }
2140 2247
2141 $self->{last_save} = $cf::RUNTIME; 2248 $self->{last_save} = $cf::RUNTIME;
2142 $self->last_access ($cf::RUNTIME); 2249 $self->last_access ($cf::RUNTIME);
2143
2144 $self->in_memory (cf::MAP_ACTIVE);
2145 } 2250 }
2146 2251
2147 $self->post_load; 2252 $self->post_load;
2253
2254 1
2148} 2255}
2149 2256
2150# customize the map for a given player, i.e. 2257# customize the map for a given player, i.e.
2151# return the _real_ map. used by e.g. per-player 2258# return the _real_ map. used by e.g. per-player
2152# maps to change the path to ~playername/mappath 2259# maps to change the path to ~playername/mappath
2190} 2297}
2191 2298
2192sub find_sync { 2299sub find_sync {
2193 my ($path, $origin) = @_; 2300 my ($path, $origin) = @_;
2194 2301
2195 cf::sync_job { find $path, $origin } 2302 # it's a bug to call this from the main context
2303 return cf::LOG cf::llevError | cf::logBacktrace, "do_find_sync"
2304 if $Coro::current == $Coro::main;
2305
2306 find $path, $origin
2196} 2307}
2197 2308
2198sub do_load_sync { 2309sub do_load_sync {
2199 my ($map) = @_; 2310 my ($map) = @_;
2200 2311
2312 # it's a bug to call this from the main context
2201 cf::LOG cf::llevDebug | cf::logBacktrace, "do_load_sync" 2313 return cf::LOG cf::llevError | cf::logBacktrace, "do_load_sync"
2202 if $Coro::current == $Coro::main; 2314 if $Coro::current == $Coro::main;
2203 2315
2204 cf::sync_job { $map->load }; 2316 $map->load;
2205} 2317}
2206 2318
2207our %MAP_PREFETCH; 2319our %MAP_PREFETCH;
2208our $MAP_PREFETCHER = undef; 2320our $MAP_PREFETCHER = undef;
2209 2321
2210sub find_async { 2322sub find_async {
2211 my ($path, $origin, $load) = @_; 2323 my ($path, $origin, $load) = @_;
2212 2324
2213 $path = normalise $path, $origin && $origin->{path}; 2325 $path = normalise $path, $origin;
2214 2326
2215 if (my $map = $cf::MAP{$path}) { 2327 if (my $map = $cf::MAP{$path}) {
2216 return $map if !$load || $map->in_memory == cf::MAP_ACTIVE; 2328 return $map if !$load || $map->linkable;
2217 } 2329 }
2218 2330
2219 $MAP_PREFETCH{$path} |= $load; 2331 $MAP_PREFETCH{$path} |= $load;
2220 2332
2221 $MAP_PREFETCHER ||= cf::async { 2333 $MAP_PREFETCHER ||= cf::async {
2280sub swap_out { 2392sub swap_out {
2281 my ($self) = @_; 2393 my ($self) = @_;
2282 2394
2283 my $lock = cf::lock_acquire "map_data:$self->{path}"; 2395 my $lock = cf::lock_acquire "map_data:$self->{path}";
2284 2396
2285 return if $self->in_memory != cf::MAP_ACTIVE; 2397 return if !$self->linkable;
2286 return if $self->{deny_save}; 2398 return if $self->{deny_save};
2287 return if $self->players; 2399 return if $self->players;
2288 2400
2289 # first deactivate the map and "unlink" it from the core 2401 # first deactivate the map and "unlink" it from the core
2290 $self->deactivate; 2402 $self->deactivate;
2291 $_->clear_links_to ($self) for values %cf::MAP; 2403 $_->clear_links_to ($self) for values %cf::MAP;
2292 $self->in_memory (cf::MAP_SWAPPED); 2404 $self->state (cf::MAP_SWAPPED);
2293 2405
2294 # then atomically save 2406 # then atomically save
2295 $self->_save; 2407 $self->_save;
2296 2408
2297 # then free the map 2409 # then free the map
2323 2435
2324 return if $self->players; 2436 return if $self->players;
2325 2437
2326 cf::trace "resetting map ", $self->path, "\n"; 2438 cf::trace "resetting map ", $self->path, "\n";
2327 2439
2328 $self->in_memory (cf::MAP_SWAPPED); 2440 $self->state (cf::MAP_SWAPPED);
2329 2441
2330 # need to save uniques path 2442 # need to save uniques path
2331 unless ($self->{deny_save}) { 2443 unless ($self->{deny_save}) {
2332 my $uniq = $self->uniq_path; utf8::encode $uniq; 2444 my $uniq = $self->uniq_path; utf8::encode $uniq;
2333 2445
2729 ($path, $x, $y) = (undef, undef, undef); 2841 ($path, $x, $y) = (undef, undef, undef);
2730 } 2842 }
2731 } 2843 }
2732 2844
2733 my $map = eval { 2845 my $map = eval {
2734 my $map = defined $path ? cf::map::find $path : undef; 2846 my $map = defined $path ? cf::map::find $path, $self->map : undef;
2735 2847
2736 if ($map) { 2848 if ($map) {
2737 $map = $map->customise_for ($self); 2849 $map = $map->customise_for ($self);
2738 $map = $check->($map, $x, $y, $self) if $check && $map; 2850 $map = $check->($map, $x, $y, $self) if $check && $map;
2739 } else { 2851 } else {
2829 $Coro::current->{desc} = "enter_exit"; 2941 $Coro::current->{desc} = "enter_exit";
2830 2942
2831 unless (eval { 2943 unless (eval {
2832 $self->deactivate_recursive; # just to be sure 2944 $self->deactivate_recursive; # just to be sure
2833 2945
2834 # random map handling
2835 {
2836 my $guard = cf::lock_acquire "exit_prepare:$exit";
2837
2838 prepare_random_map $exit
2839 if $exit->slaying eq "/!";
2840 }
2841
2842 my $map = cf::map::normalise $exit->slaying, $exit->map && $exit->map->path; 2946 my $map = cf::map::normalise $exit->slaying, $exit->map;
2843 my $x = $exit->stats->hp; 2947 my $x = $exit->stats->hp;
2844 my $y = $exit->stats->sp; 2948 my $y = $exit->stats->sp;
2949
2950 # special map handling
2951 my $slaying = $exit->slaying;
2952
2953 # special map handling
2954 if ($slaying eq "/!") {
2955 my $guard = cf::lock_acquire "exit_prepare:$exit";
2956
2957 prepare_random_map $exit
2958 if $exit->slaying eq "/!"; # need to re-check after getting the lock
2959
2960 $map = $exit->slaying;
2961
2962 } elsif ($slaying eq '!up') {
2963 $map = $exit->map->tile_path (cf::TILE_UP);
2964 $x = $exit->x;
2965 $y = $exit->y;
2966
2967 } elsif ($slaying eq '!down') {
2968 $map = $exit->map->tile_path (cf::TILE_DOWN);
2969 $x = $exit->x;
2970 $y = $exit->y;
2971 }
2845 2972
2846 $self->goto ($map, $x, $y); 2973 $self->goto ($map, $x, $y);
2847 2974
2848 # if exit is damned, update players death & WoR home-position 2975 # if exit is damned, update players death & WoR home-position
2849 $self->contr->savebed ($map, $x, $y) 2976 $self->contr->savebed ($map, $x, $y)
3268 decrease split destroy change_exp value msg lore send_msg)], 3395 decrease split destroy change_exp value msg lore send_msg)],
3269 ["cf::object::player" => qw(player)], 3396 ["cf::object::player" => qw(player)],
3270 ["cf::player" => qw(peaceful send_msg)], 3397 ["cf::player" => qw(peaceful send_msg)],
3271 ["cf::map" => qw(trigger)], 3398 ["cf::map" => qw(trigger)],
3272) { 3399) {
3273 no strict 'refs';
3274 my ($pkg, @funs) = @$_; 3400 my ($pkg, @funs) = @$_;
3275 *{"safe::$pkg\::$_"} = $safe_hole->wrap (\&{"$pkg\::$_"}) 3401 *{"safe::$pkg\::$_"} = $safe_hole->wrap (\&{"$pkg\::$_"})
3276 for @funs; 3402 for @funs;
3277} 3403}
3278 3404
3365 3491
3366 my $enc = JSON::XS->new->utf8->canonical->relaxed; 3492 my $enc = JSON::XS->new->utf8->canonical->relaxed;
3367 3493
3368 trace "loading facedata from $path\n"; 3494 trace "loading facedata from $path\n";
3369 3495
3370 my $facedata; 3496 my $facedata = decode_storable load_file $path;
3371 0 < aio_load $path, $facedata
3372 or die "$path: $!";
3373
3374 $facedata = Coro::Storable::thaw $facedata;
3375 3497
3376 $facedata->{version} == 2 3498 $facedata->{version} == 2
3377 or cf::cleanup "$path: version mismatch, cannot proceed."; 3499 or cf::cleanup "$path: version mismatch, cannot proceed.";
3378 3500
3379 # patch in the exptable 3501 # patch in the exptable
3393 3515
3394 cf::face::set_visibility $idx, $info->{visibility}; 3516 cf::face::set_visibility $idx, $info->{visibility};
3395 cf::face::set_magicmap $idx, $info->{magicmap}; 3517 cf::face::set_magicmap $idx, $info->{magicmap};
3396 cf::face::set_data $idx, 0, $info->{data32}, $info->{hash32}; 3518 cf::face::set_data $idx, 0, $info->{data32}, $info->{hash32};
3397 cf::face::set_data $idx, 1, $info->{data64}, $info->{hash64}; 3519 cf::face::set_data $idx, 1, $info->{data64}, $info->{hash64};
3520 cf::face::set_data $idx, 2, $info->{glyph} , $info->{glyph} ;
3398 3521
3399 cf::cede_to_tick; 3522 cf::cede_to_tick;
3400 } 3523 }
3401 3524
3402 while (my ($face, $info) = each %$faces) { 3525 while (my ($face, $info) = each %$faces) {
3497} 3620}
3498 3621
3499sub reload_sound { 3622sub reload_sound {
3500 trace "loading sound config from $DATADIR/sound\n"; 3623 trace "loading sound config from $DATADIR/sound\n";
3501 3624
3502 0 < Coro::AIO::aio_load "$DATADIR/sound", my $data
3503 or die "$DATADIR/sound $!";
3504
3505 my $soundconf = JSON::XS->new->utf8->relaxed->decode ($data); 3625 my $soundconf = JSON::XS->new->utf8->relaxed->decode (load_file "$DATADIR/sound");
3506 3626
3507 for (0 .. SOUND_CAST_SPELL_0 - 1) { 3627 for (0 .. SOUND_CAST_SPELL_0 - 1) {
3508 my $sound = $soundconf->{compat}[$_] 3628 my $sound = $soundconf->{compat}[$_]
3509 or next; 3629 or next;
3510 3630
3520} 3640}
3521 3641
3522sub reload_resources { 3642sub reload_resources {
3523 trace "reloading resource files...\n"; 3643 trace "reloading resource files...\n";
3524 3644
3645 reload_exp_table;
3646 reload_materials;
3525 reload_facedata; 3647 reload_facedata;
3526 reload_sound; 3648 reload_sound;
3527 reload_archetypes; 3649 reload_archetypes;
3528 reload_regions; 3650 reload_regions;
3529 reload_treasures; 3651 reload_treasures;
3532} 3654}
3533 3655
3534sub reload_config { 3656sub reload_config {
3535 trace "reloading config file...\n"; 3657 trace "reloading config file...\n";
3536 3658
3537 open my $fh, "<:utf8", "$CONFDIR/config" 3659 my $config = load_file "$CONFDIR/config";
3538 or return; 3660 utf8::decode $config;
3539 3661 *CFG = decode_yaml $config;
3540 local $/;
3541 *CFG = YAML::XS::Load scalar <$fh>;
3542 3662
3543 $EMERGENCY_POSITION = $CFG{emergency_position} || ["/world/world_104_115", 49, 38]; 3663 $EMERGENCY_POSITION = $CFG{emergency_position} || ["/world/world_104_115", 49, 38];
3544 3664
3545 $cf::map::MAX_RESET = $CFG{map_max_reset} if exists $CFG{map_max_reset}; 3665 $cf::map::MAX_RESET = $CFG{map_max_reset} if exists $CFG{map_max_reset};
3546 $cf::map::DEFAULT_RESET = $CFG{map_default_reset} if exists $CFG{map_default_reset}; 3666 $cf::map::DEFAULT_RESET = $CFG{map_default_reset} if exists $CFG{map_default_reset};
3550 $CFG{mlockall} ? eval "mlockall()" : eval "munlockall()" 3670 $CFG{mlockall} ? eval "mlockall()" : eval "munlockall()"
3551 and die "WARNING: m(un)lockall failed: $!\n"; 3671 and die "WARNING: m(un)lockall failed: $!\n";
3552 }; 3672 };
3553 warn $@ if $@; 3673 warn $@ if $@;
3554 } 3674 }
3555
3556 trace "finished reloading resource files\n";
3557} 3675}
3558 3676
3559sub pidfile() { 3677sub pidfile() {
3560 sysopen my $fh, $PIDFILE, O_RDWR | O_CREAT 3678 sysopen my $fh, $PIDFILE, O_RDWR | O_CREAT
3561 or die "$PIDFILE: $!"; 3679 or die "$PIDFILE: $!";
3586 3704
3587sub main { 3705sub main {
3588 cf::init_globals; # initialise logging 3706 cf::init_globals; # initialise logging
3589 3707
3590 LOG llevInfo, "Welcome to Deliantra, v" . VERSION; 3708 LOG llevInfo, "Welcome to Deliantra, v" . VERSION;
3591 LOG llevInfo, "Copyright (C) 2005-2008 Marc Alexander Lehmann / Robin Redeker / the Deliantra team."; 3709 LOG llevInfo, "Copyright (C) 2005-2011 Marc Alexander Lehmann / Robin Redeker / the Deliantra team.";
3592 LOG llevInfo, "Copyright (C) 1994 Mark Wedel."; 3710 LOG llevInfo, "Copyright (C) 1994 Mark Wedel.";
3593 LOG llevInfo, "Copyright (C) 1992 Frank Tore Johansen."; 3711 LOG llevInfo, "Copyright (C) 1992 Frank Tore Johansen.";
3594 3712
3595 $Coro::current->prio (Coro::PRIO_MAX); # give the main loop max. priority 3713 $Coro::current->prio (Coro::PRIO_MAX); # give the main loop max. priority
3596 3714
3604 }; 3722 };
3605 3723
3606 evthread_start IO::AIO::poll_fileno; 3724 evthread_start IO::AIO::poll_fileno;
3607 3725
3608 cf::sync_job { 3726 cf::sync_job {
3609 cf::init_experience; 3727 cf::incloader::init ();
3728
3610 cf::init_anim; 3729 cf::init_anim;
3611 cf::init_attackmess; 3730 cf::init_attackmess;
3612 cf::init_dynamic; 3731 cf::init_dynamic;
3613 3732
3614 cf::load_settings; 3733 cf::load_settings;
3615 cf::load_materials;
3616 3734
3617 reload_resources; 3735 reload_resources;
3618 reload_config; 3736 reload_config;
3619 db_init; 3737 db_init;
3620 3738
3632 3750
3633 # no (long-running) fork's whatsoever before this point(!) 3751 # no (long-running) fork's whatsoever before this point(!)
3634 use POSIX (); 3752 use POSIX ();
3635 POSIX::close delete $ENV{LOCKUTIL_LOCK_FD} if exists $ENV{LOCKUTIL_LOCK_FD}; 3753 POSIX::close delete $ENV{LOCKUTIL_LOCK_FD} if exists $ENV{LOCKUTIL_LOCK_FD};
3636 3754
3637 (pop @POST_INIT)->(0) while @POST_INIT; 3755 cf::_post_init 0;
3638 }; 3756 };
3639 3757
3640 cf::object::thawer::errors_are_fatal 0; 3758 cf::object::thawer::errors_are_fatal 0;
3641 info "parse errors in files are no longer fatal from this point on.\n"; 3759 info "parse errors in files are no longer fatal from this point on.\n";
3642 3760
3761 my $free_main; $free_main = EV::idle sub {
3762 undef $free_main;
3763 undef &main; # free gobs of memory :)
3764 };
3765
3643 main_loop; 3766 goto &main_loop;
3644} 3767}
3645 3768
3646############################################################################# 3769#############################################################################
3647# initialisation and cleanup 3770# initialisation and cleanup
3648 3771
3747sub emergency_save() { 3870sub emergency_save() {
3748 my $freeze_guard = cf::freeze_mainloop; 3871 my $freeze_guard = cf::freeze_mainloop;
3749 3872
3750 info "emergency_perl_save: enter\n"; 3873 info "emergency_perl_save: enter\n";
3751 3874
3875 # this is a trade-off: we want to be very quick here, so
3876 # save all maps without fsync, and later call a global sync
3877 # (which in turn might be very very slow)
3878 local $USE_FSYNC = 0;
3879
3752 cf::sync_job { 3880 cf::sync_job {
3753 # this is a trade-off: we want to be very quick here, so 3881 cf::write_runtime_sync; # external watchdog should not bark
3754 # save all maps without fsync, and later call a global sync
3755 # (which in turn might be very very slow)
3756 local $USE_FSYNC = 0;
3757 3882
3758 # use a peculiar iteration method to avoid tripping on perl 3883 # use a peculiar iteration method to avoid tripping on perl
3759 # refcount bugs in for. also avoids problems with players 3884 # refcount bugs in for. also avoids problems with players
3760 # and maps saved/destroyed asynchronously. 3885 # and maps saved/destroyed asynchronously.
3761 info "emergency_perl_save: begin player save\n"; 3886 info "emergency_perl_save: begin player save\n";
3765 delete $pl->{unclean_save}; # not strictly necessary, but cannot hurt 3890 delete $pl->{unclean_save}; # not strictly necessary, but cannot hurt
3766 $pl->save; 3891 $pl->save;
3767 } 3892 }
3768 info "emergency_perl_save: end player save\n"; 3893 info "emergency_perl_save: end player save\n";
3769 3894
3895 cf::write_runtime_sync; # external watchdog should not bark
3896
3770 info "emergency_perl_save: begin map save\n"; 3897 info "emergency_perl_save: begin map save\n";
3771 for my $path (keys %cf::MAP) { 3898 for my $path (keys %cf::MAP) {
3772 my $map = $cf::MAP{$path} or next; 3899 my $map = $cf::MAP{$path} or next;
3773 $map->valid or next; 3900 $map->valid or next;
3774 $map->save; 3901 $map->save;
3775 } 3902 }
3776 info "emergency_perl_save: end map save\n"; 3903 info "emergency_perl_save: end map save\n";
3777 3904
3905 cf::write_runtime_sync; # external watchdog should not bark
3906
3778 info "emergency_perl_save: begin database checkpoint\n"; 3907 info "emergency_perl_save: begin database checkpoint\n";
3779 BDB::db_env_txn_checkpoint $DB_ENV; 3908 BDB::db_env_txn_checkpoint $DB_ENV;
3780 info "emergency_perl_save: end database checkpoint\n"; 3909 info "emergency_perl_save: end database checkpoint\n";
3781 3910
3782 info "emergency_perl_save: begin write uuid\n"; 3911 info "emergency_perl_save: begin write uuid\n";
3783 write_uuid_sync 1; 3912 write_uuid_sync 1;
3784 info "emergency_perl_save: end write uuid\n"; 3913 info "emergency_perl_save: end write uuid\n";
3785 };
3786 3914
3915 cf::write_runtime_sync; # external watchdog should not bark
3916
3917 trace "emergency_perl_save: syncing database to disk";
3918 BDB::db_env_txn_checkpoint $DB_ENV;
3919
3787 info "emergency_perl_save: starting sync()\n"; 3920 info "emergency_perl_save: starting sync\n";
3788 IO::AIO::aio_sync sub { 3921 IO::AIO::aio_sync sub {
3789 info "emergency_perl_save: finished sync()\n"; 3922 info "emergency_perl_save: finished sync\n";
3923 };
3924
3925 cf::write_runtime_sync; # external watchdog should not bark
3926
3927 trace "emergency_perl_save: flushing outstanding aio requests";
3928 while (IO::AIO::nreqs || BDB::nreqs) {
3929 Coro::EV::timer_once 0.01; # let the sync_job do it's thing
3930 }
3931
3932 cf::write_runtime_sync; # external watchdog should not bark
3790 }; 3933 };
3791 3934
3792 info "emergency_perl_save: leave\n"; 3935 info "emergency_perl_save: leave\n";
3793} 3936}
3794 3937
3795sub post_cleanup { 3938sub post_cleanup {
3796 my ($make_core) = @_; 3939 my ($make_core) = @_;
3940
3941 IO::AIO::flush;
3797 3942
3798 error Carp::longmess "post_cleanup backtrace" 3943 error Carp::longmess "post_cleanup backtrace"
3799 if $make_core; 3944 if $make_core;
3800 3945
3801 my $fh = pidfile; 3946 my $fh = pidfile;
3827 } 3972 }
3828} 3973}
3829 3974
3830sub do_reload_perl() { 3975sub do_reload_perl() {
3831 # can/must only be called in main 3976 # can/must only be called in main
3832 if (in_main) { 3977 unless (in_main) {
3833 error "can only reload from main coroutine"; 3978 error "can only reload from main coroutine";
3834 return; 3979 return;
3835 } 3980 }
3836 3981
3837 return if $RELOAD++; 3982 return if $RELOAD++;
3838 3983
3839 my $t1 = AE::time; 3984 my $t1 = AE::time;
3840 3985
3841 while ($RELOAD) { 3986 while ($RELOAD) {
3987 cf::get_slot 0.1, -1, "reload_perl";
3842 info "reloading..."; 3988 info "perl_reload: reloading...";
3843 3989
3844 trace "entering sync_job"; 3990 trace "perl_reload: entering sync_job";
3845 3991
3846 cf::sync_job { 3992 cf::sync_job {
3847 cf::write_runtime_sync; # external watchdog should not bark
3848 cf::emergency_save; 3993 #cf::emergency_save;
3849 cf::write_runtime_sync; # external watchdog should not bark
3850 3994
3851 trace "syncing database to disk";
3852 BDB::db_env_txn_checkpoint $DB_ENV;
3853
3854 # if anything goes wrong in here, we should simply crash as we already saved
3855
3856 trace "flushing outstanding aio requests";
3857 while (IO::AIO::nreqs || BDB::nreqs) {
3858 Coro::EV::timer_once 0.01; # let the sync_job do it's thing
3859 }
3860
3861 trace "cancelling all extension coros"; 3995 trace "perl_reload: cancelling all extension coros";
3862 $_->cancel for values %EXT_CORO; 3996 $_->cancel for values %EXT_CORO;
3863 %EXT_CORO = (); 3997 %EXT_CORO = ();
3864 3998
3865 trace "removing commands"; 3999 trace "perl_reload: removing commands";
3866 %COMMAND = (); 4000 %COMMAND = ();
3867 4001
3868 trace "removing ext/exti commands"; 4002 trace "perl_reload: removing ext/exti commands";
3869 %EXTCMD = (); 4003 %EXTCMD = ();
3870 %EXTICMD = (); 4004 %EXTICMD = ();
3871 4005
3872 trace "unloading/nuking all extensions"; 4006 trace "perl_reload: unloading/nuking all extensions";
3873 for my $pkg (@EXTS) { 4007 for my $pkg (@EXTS) {
3874 trace "... unloading $pkg"; 4008 trace "... unloading $pkg";
3875 4009
3876 if (my $cb = $pkg->can ("unload")) { 4010 if (my $cb = $pkg->can ("unload")) {
3877 eval { 4011 eval {
3882 4016
3883 trace "... clearing $pkg"; 4017 trace "... clearing $pkg";
3884 clear_package $pkg; 4018 clear_package $pkg;
3885 } 4019 }
3886 4020
3887 trace "unloading all perl modules loaded from $LIBDIR"; 4021 trace "perl_reload: unloading all perl modules loaded from $LIBDIR";
3888 while (my ($k, $v) = each %INC) { 4022 while (my ($k, $v) = each %INC) {
3889 next unless $v =~ /^\Q$LIBDIR\E\/.*\.pm$/; 4023 next unless $v =~ /^\Q$LIBDIR\E\/.*\.pm$/;
3890 4024
3891 trace "... unloading $k"; 4025 trace "... unloading $k";
3892 delete $INC{$k}; 4026 delete $INC{$k};
3899 } 4033 }
3900 4034
3901 clear_package $k; 4035 clear_package $k;
3902 } 4036 }
3903 4037
3904 trace "getting rid of safe::, as good as possible"; 4038 trace "perl_reload: getting rid of safe::, as good as possible";
3905 clear_package "safe::$_" 4039 clear_package "safe::$_"
3906 for qw(cf::attachable cf::object cf::object::player cf::client cf::player cf::map cf::party cf::region); 4040 for qw(cf::attachable cf::object cf::object::player cf::client cf::player cf::map cf::party cf::region);
3907 4041
3908 trace "unloading cf.pm \"a bit\""; 4042 trace "perl_reload: unloading cf.pm \"a bit\"";
3909 delete $INC{"cf.pm"}; 4043 delete $INC{"cf.pm"};
3910 delete $INC{"cf/$_.pm"} for @EXTRA_MODULES; 4044 delete $INC{"cf/$_.pm"} for @EXTRA_MODULES;
3911 4045
3912 # don't, removes xs symbols, too, 4046 # don't, removes xs symbols, too,
3913 # and global variables created in xs 4047 # and global variables created in xs
3914 #clear_package __PACKAGE__; 4048 #clear_package __PACKAGE__;
3915 4049
3916 info "unload completed, starting to reload now"; 4050 info "perl_reload: unload completed, starting to reload now";
3917 4051
3918 trace "reloading cf.pm"; 4052 trace "perl_reload: reloading cf.pm";
3919 require cf; 4053 require cf;
3920 cf::_connect_to_perl_1; 4054 cf::_connect_to_perl_1;
3921 4055
3922 trace "loading config and database again"; 4056 trace "perl_reload: loading config and database again";
3923 cf::reload_config; 4057 cf::reload_config;
3924 4058
3925 trace "loading extensions"; 4059 trace "perl_reload: loading extensions";
3926 cf::load_extensions; 4060 cf::load_extensions;
3927 4061
3928 if ($REATTACH_ON_RELOAD) { 4062 if ($REATTACH_ON_RELOAD) {
3929 trace "reattaching attachments to objects/players"; 4063 trace "perl_reload: reattaching attachments to objects/players";
3930 _global_reattach; # objects, sockets 4064 _global_reattach; # objects, sockets
3931 trace "reattaching attachments to maps"; 4065 trace "perl_reload: reattaching attachments to maps";
3932 reattach $_ for values %MAP; 4066 reattach $_ for values %MAP;
3933 trace "reattaching attachments to players"; 4067 trace "perl_reload: reattaching attachments to players";
3934 reattach $_ for values %PLAYER; 4068 reattach $_ for values %PLAYER;
3935 } 4069 }
3936 4070
3937 trace "running post_init jobs"; 4071 cf::_post_init 1;
3938 (pop @POST_INIT)->(1) while @POST_INIT;
3939 4072
3940 trace "leaving sync_job"; 4073 trace "perl_reload: leaving sync_job";
3941 4074
3942 1 4075 1
3943 } or do { 4076 } or do {
3944 error $@; 4077 error $@;
3945 cf::cleanup "error while reloading, exiting."; 4078 cf::cleanup "perl_reload: error, exiting.";
3946 }; 4079 };
3947 4080
3948 info "reloaded";
3949 --$RELOAD; 4081 --$RELOAD;
3950 } 4082 }
3951 4083
3952 $t1 = AE::time - $t1; 4084 $t1 = AE::time - $t1;
3953 info "reload completed in ${t1}s\n"; 4085 info "perl_reload: completed in ${t1}s\n";
3954}; 4086};
3955 4087
3956our $RELOAD_WATCHER; # used only during reload 4088our $RELOAD_WATCHER; # used only during reload
3957 4089
3958sub reload_perl() { 4090sub reload_perl() {
3979 reload_perl; 4111 reload_perl;
3980 }; 4112 };
3981 } 4113 }
3982}; 4114};
3983 4115
3984unshift @INC, $LIBDIR; 4116#############################################################################
3985 4117
3986my $bug_warning = 0; 4118my $bug_warning = 0;
3987 4119
3988our @WAIT_FOR_TICK;
3989our @WAIT_FOR_TICK_BEGIN;
3990
3991sub wait_for_tick { 4120sub wait_for_tick() {
3992 return Coro::cede if tick_inhibit || $Coro::current == $Coro::main; 4121 return Coro::AnyEvent::poll if tick_inhibit || $Coro::current == $Coro::main;
3993 4122
3994 my $signal = new Coro::Signal; 4123 $WAIT_FOR_TICK->wait;
3995 push @WAIT_FOR_TICK, $signal;
3996 $signal->wait;
3997} 4124}
3998 4125
3999sub wait_for_tick_begin { 4126sub wait_for_tick_begin() {
4000 return Coro::cede if tick_inhibit || $Coro::current == $Coro::main; 4127 return Coro::AnyEvent::poll if tick_inhibit || $Coro::current == $Coro::main;
4001 4128
4002 my $signal = new Coro::Signal; 4129 my $signal = new Coro::Signal;
4003 push @WAIT_FOR_TICK_BEGIN, $signal; 4130 push @WAIT_FOR_TICK_BEGIN, $signal;
4004 $signal->wait; 4131 $signal->wait;
4005} 4132}
4009 Carp::cluck "major BUG: server tick called outside of main coro, skipping it" 4136 Carp::cluck "major BUG: server tick called outside of main coro, skipping it"
4010 unless ++$bug_warning > 10; 4137 unless ++$bug_warning > 10;
4011 return; 4138 return;
4012 } 4139 }
4013 4140
4014 cf::server_tick; # one server iteration 4141 cf::one_tick; # one server iteration
4015 4142
4016 #for(1..3e6){} AE::now_update; $NOW=AE::now; # generate load #d# 4143 #for(1..3e6){} AE::now_update; $NOW=AE::now; # generate load #d#
4017 4144
4018 if ($NOW >= $NEXT_RUNTIME_WRITE) { 4145 if ($NOW >= $NEXT_RUNTIME_WRITE) {
4019 $NEXT_RUNTIME_WRITE = List::Util::max $NEXT_RUNTIME_WRITE + 10, $NOW + 5.; 4146 $NEXT_RUNTIME_WRITE = List::Util::max $NEXT_RUNTIME_WRITE + 10, $NOW + 5.;
4025 } 4152 }
4026 4153
4027 if (my $sig = shift @WAIT_FOR_TICK_BEGIN) { 4154 if (my $sig = shift @WAIT_FOR_TICK_BEGIN) {
4028 $sig->send; 4155 $sig->send;
4029 } 4156 }
4030 while (my $sig = shift @WAIT_FOR_TICK) { 4157 $WAIT_FOR_TICK->broadcast;
4031 $sig->send;
4032 }
4033 4158
4034 $LOAD = ($NOW - $TICK_START) / $TICK; 4159 $LOAD = ($NOW - $TICK_START) / $TICK;
4035 $LOADAVG = $LOADAVG * 0.75 + $LOAD * 0.25; 4160 $LOADAVG = $LOADAVG * 0.75 + $LOAD * 0.25;
4036 4161
4037 if (0) { 4162 if (0) {
4056 $DB_ENV->set_flags (&BDB::LOG_AUTOREMOVE ) if BDB::VERSION v0, v4.7; 4181 $DB_ENV->set_flags (&BDB::LOG_AUTOREMOVE ) if BDB::VERSION v0, v4.7;
4057 $DB_ENV->log_set_config (&BDB::LOG_AUTO_REMOVE) if BDB::VERSION v4.7; 4182 $DB_ENV->log_set_config (&BDB::LOG_AUTO_REMOVE) if BDB::VERSION v4.7;
4058 $DB_ENV->set_timeout (30, BDB::SET_TXN_TIMEOUT); 4183 $DB_ENV->set_timeout (30, BDB::SET_TXN_TIMEOUT);
4059 $DB_ENV->set_timeout (30, BDB::SET_LOCK_TIMEOUT); 4184 $DB_ENV->set_timeout (30, BDB::SET_LOCK_TIMEOUT);
4060 4185
4061 (Coro::async { # async to keep sync_job from complaining
4062 cf::sync_job { 4186 cf::sync_job {
4063 eval { 4187 eval {
4064 BDB::db_env_open 4188 BDB::db_env_open
4065 $DB_ENV, 4189 $DB_ENV,
4066 $BDBDIR, 4190 $BDBDIR,
4067 BDB::INIT_LOCK | BDB::INIT_LOG | BDB::INIT_MPOOL | BDB::INIT_TXN 4191 BDB::INIT_LOCK | BDB::INIT_LOG | BDB::INIT_MPOOL | BDB::INIT_TXN
4068 | BDB::RECOVER | BDB::REGISTER | BDB::USE_ENVIRON | BDB::CREATE, 4192 | BDB::RECOVER | BDB::REGISTER | BDB::USE_ENVIRON | BDB::CREATE,
4069 0666; 4193 0666;
4070 4194
4071 cf::cleanup "db_env_open($BDBDIR): $!" if $!; 4195 cf::cleanup "db_env_open($BDBDIR): $!" if $!;
4072 };
4073
4074 cf::cleanup "db_env_open(db): $@" if $@;
4075 }; 4196 };
4076 })->join; 4197
4198 cf::cleanup "db_env_open(db): $@" if $@;
4199 };
4077 } 4200 }
4078 4201
4079 $BDB_DEADLOCK_WATCHER = EV::periodic 0, 3, 0, sub { 4202 $BDB_DEADLOCK_WATCHER = EV::periodic 0, 3, 0, sub {
4080 BDB::db_env_lock_detect $DB_ENV, 0, BDB::LOCK_DEFAULT, 0, sub { }; 4203 BDB::db_env_lock_detect $DB_ENV, 0, BDB::LOCK_DEFAULT, 0, sub { };
4081 }; 4204 };
4093 IO::AIO::min_parallel 8; 4216 IO::AIO::min_parallel 8;
4094 IO::AIO::max_poll_time $TICK * 0.1; 4217 IO::AIO::max_poll_time $TICK * 0.1;
4095 undef $AnyEvent::AIO::WATCHER; 4218 undef $AnyEvent::AIO::WATCHER;
4096} 4219}
4097 4220
4098my $_log_backtrace; 4221our $_log_backtrace;
4222our $_log_backtrace_last;
4099 4223
4100sub _log_backtrace { 4224sub _log_backtrace {
4101 my ($msg, @addr) = @_; 4225 my ($msg, @addr) = @_;
4102 4226
4103 $msg =~ s/\n//; 4227 $msg =~ s/\n$//;
4104 4228
4229 if ($_log_backtrace_last eq $msg) {
4230 LOG llevInfo, "[ABT] $msg\n";
4231 LOG llevInfo, "[ABT] [duplicate, suppressed]\n";
4105 # limit the # of concurrent backtraces 4232 # limit the # of concurrent backtraces
4106 if ($_log_backtrace < 2) { 4233 } elsif ($_log_backtrace < 2) {
4234 $_log_backtrace_last = $msg;
4107 ++$_log_backtrace; 4235 ++$_log_backtrace;
4108 my $perl_bt = Carp::longmess $msg; 4236 my $perl_bt = Carp::longmess $msg;
4109 async { 4237 async {
4110 $Coro::current->{desc} = "abt $msg"; 4238 $Coro::current->{desc} = "abt $msg";
4111 4239
4131 LOG llevInfo, "[ABT] $_\n" for @bt; 4259 LOG llevInfo, "[ABT] $_\n" for @bt;
4132 --$_log_backtrace; 4260 --$_log_backtrace;
4133 }; 4261 };
4134 } else { 4262 } else {
4135 LOG llevInfo, "[ABT] $msg\n"; 4263 LOG llevInfo, "[ABT] $msg\n";
4136 LOG llevInfo, "[ABT] [suppressed]\n"; 4264 LOG llevInfo, "[ABT] [overload, suppressed]\n";
4137 } 4265 }
4138} 4266}
4139 4267
4140# load additional modules 4268# load additional modules
4141require "cf/$_.pm" for @EXTRA_MODULES; 4269require "cf/$_.pm" for @EXTRA_MODULES;

Diff Legend

Removed lines
+ Added lines
< Changed lines
> Changed lines