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.553 by root, Tue May 18 21:30:16 2010 UTC

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 = ();
124our $BDB_DEADLOCK_WATCHER; 124our $BDB_DEADLOCK_WATCHER;
125our $BDB_CHECKPOINT_WATCHER; 125our $BDB_CHECKPOINT_WATCHER;
126our $BDB_TRICKLE_WATCHER; 126our $BDB_TRICKLE_WATCHER;
127our $DB_ENV; 127our $DB_ENV;
128 128
129our @EXTRA_MODULES = qw(pod match mapscript); 129our @EXTRA_MODULES = qw(pod match mapscript incloader);
130 130
131our %CFG; 131our %CFG;
132 132
133our $UPTIME; $UPTIME ||= time; 133our $UPTIME; $UPTIME ||= time;
134our $RUNTIME; 134our $RUNTIME;
233from wherever your confdir points to. 233from wherever your confdir points to.
234 234
235=item cf::wait_for_tick, cf::wait_for_tick_begin 235=item cf::wait_for_tick, cf::wait_for_tick_begin
236 236
237These are functions that inhibit the current coroutine one tick. cf::wait_for_tick_begin only 237These 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 238returns 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. 239per tick), while cf::wait_for_tick wakes up all waiters after tick processing.
240
241=cut
242
243sub wait_for_tick();
244sub wait_for_tick_begin();
240 245
241=item @cf::INVOKE_RESULTS 246=item @cf::INVOKE_RESULTS
242 247
243This array contains the results of the last C<invoke ()> call. When 248This 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 249C<cf::override> is called C<@cf::INVOKE_RESULTS> is set to the parameters of
352our $json_coder = JSON::XS->new->utf8->max_size (1e6); # accept ~1mb max 357our $json_coder = JSON::XS->new->utf8->max_size (1e6); # accept ~1mb max
353 358
354sub encode_json($) { $json_coder->encode ($_[0]) } 359sub encode_json($) { $json_coder->encode ($_[0]) }
355sub decode_json($) { $json_coder->decode ($_[0]) } 360sub decode_json($) { $json_coder->decode ($_[0]) }
356 361
362=item $ref = cf::yaml_load $scalar
363
364Same as YAML::XS::Load, but doesn't leak, because it forks (and thus blocks).
365
366=cut
367
368sub fork_call(&@);
369
370sub yaml_load($) {
371 fork_call { YAML::XS::Load $_[0] } @_
372}
373
357=item cf::post_init { BLOCK } 374=item cf::post_init { BLOCK }
358 375
359Execute the given codeblock, I<after> all extensions have been (re-)loaded, 376Execute the given codeblock, I<after> all extensions have been (re-)loaded,
360but I<before> the server starts ticking again. 377but I<before> the server starts ticking again.
361 378
362The cdoeblock will have a single boolean argument to indicate whether this 379The codeblock will have a single boolean argument to indicate whether this
363is a reload or not. 380is a reload or not.
364 381
365=cut 382=cut
366 383
367sub post_init(&) { 384sub post_init(&) {
368 push @POST_INIT, shift; 385 push @POST_INIT, shift;
386}
387
388sub _post_init {
389 trace "running post_init jobs";
390
391 # run them in parallel...
392
393 my @join;
394
395 while () {
396 push @join, map &Coro::async ($_, 0), @POST_INIT;
397 @POST_INIT = ();
398
399 @join or last;
400
401 (pop @join)->join;
402 }
369} 403}
370 404
371=item cf::lock_wait $string 405=item cf::lock_wait $string
372 406
373Wait until the given lock is available. See cf::lock_acquire. 407Wait until the given lock is available. See cf::lock_acquire.
518=cut 552=cut
519 553
520sub sync_job(&) { 554sub sync_job(&) {
521 my ($job) = @_; 555 my ($job) = @_;
522 556
523 if ($Coro::current == $Coro::main) { 557 if (in_main) {
524 my $time = AE::time; 558 my $time = AE::time;
525 559
526 # this is the main coro, too bad, we have to block 560 # this is the main coro, too bad, we have to block
527 # till the operation succeeds, freezing the server :/ 561 # till the operation succeeds, freezing the server :/
528 562
529 LOG llevError, Carp::longmess "sync job";#d# 563 #LOG llevError, Carp::longmess "sync job";#d#
530 564
531 my $freeze_guard = freeze_mainloop; 565 my $freeze_guard = freeze_mainloop;
532 566
533 my $busy = 1; 567 my $busy = 1;
534 my @res; 568 my @res;
578 $EXT_CORO{$coro+0} = $coro; 612 $EXT_CORO{$coro+0} = $coro;
579 613
580 $coro 614 $coro
581} 615}
582 616
583=item fork_call { }, $args 617=item fork_call { }, @args
584 618
585Executes the given code block with the given arguments in a seperate 619Executes the given code block with the given arguments in a seperate
586process, returning the results. Everything must be serialisable with 620process, returning the results. Everything must be serialisable with
587Coro::Storable. May, of course, block. Note that the executed sub may 621Coro::Storable. May, of course, block. Note that the executed sub may
588never block itself or use any form of event handling. 622never block itself or use any form of event handling.
589 623
590=cut 624=cut
591 625
626sub post_fork {
627 reset_signals;
628}
629
592sub fork_call(&@) { 630sub fork_call(&@) {
593 my ($cb, @args) = @_; 631 my ($cb, @args) = @_;
594 632
595 # we seemingly have to make a local copy of the whole thing, 633 # we seemingly have to make a local copy of the whole thing,
596 # otherwise perl prematurely frees the stuff :/ 634 # otherwise perl prematurely frees the stuff :/
597 # TODO: investigate and fix (likely this will be rather laborious) 635 # TODO: investigate and fix (likely this will be rather laborious)
598 636
599 my @res = Coro::Util::fork_eval { 637 my @res = Coro::Util::fork_eval {
600 reset_signals; 638 cf::post_fork;
601 &$cb 639 &$cb
602 }, @args; 640 } @args;
603 641
604 wantarray ? @res : $res[-1] 642 wantarray ? @res : $res[-1]
605} 643}
606 644
607sub objinfo { 645sub objinfo {
657within each server. 695within each server.
658 696
659=cut 697=cut
660 698
661sub db_table($) { 699sub db_table($) {
700 cf::error "db_get called from main context"
701 if $Coro::current == $Coro::main;
702
662 my ($name) = @_; 703 my ($name) = @_;
663 my $db = BDB::db_create $DB_ENV; 704 my $db = BDB::db_create $DB_ENV;
664 705
665 eval { 706 eval {
666 $db->set_flags (BDB::CHKSUM); 707 $db->set_flags (BDB::CHKSUM);
676} 717}
677 718
678our $DB; 719our $DB;
679 720
680sub db_init { 721sub db_init {
681 cf::sync_job {
682 $DB ||= db_table "db"; 722 $DB ||= db_table "db";
683 };
684} 723}
685 724
686sub db_get($$) { 725sub db_get($$) {
687 my $key = "$_[0]/$_[1]"; 726 my $key = "$_[0]/$_[1]";
688 727
689 cf::sync_job { 728 cf::error "db_get called from main context"
729 if $Coro::current == $Coro::main;
730
690 BDB::db_get $DB, undef, $key, my $data; 731 BDB::db_get $DB, undef, $key, my $data;
691 732
692 $! ? () 733 $! ? ()
693 : $data 734 : $data
694 }
695} 735}
696 736
697sub db_put($$$) { 737sub db_put($$$) {
698 BDB::dbreq_pri 4; 738 BDB::dbreq_pri 4;
699 BDB::db_put $DB, undef, "$_[0]/$_[1]", $_[2], 0, sub { }; 739 BDB::db_put $DB, undef, "$_[0]/$_[1]", $_[2], 0, sub { };
1421 1461
1422 $ext{meta} = { map { (split /=/, $_, 2)[0, 1] } split /\s+/, $1 } 1462 $ext{meta} = { map { (split /=/, $_, 2)[0, 1] } split /\s+/, $1 }
1423 if $source =~ /\A#!.*?perl.*?#\s*(.*)$/m; 1463 if $source =~ /\A#!.*?perl.*?#\s*(.*)$/m;
1424 1464
1425 $ext{source} = 1465 $ext{source} =
1426 "package $pkg; use 5.10.0; use strict 'vars', 'subs'; use utf8;\n" 1466 "package $pkg; use common::sense;\n"
1427 . "#line 1 \"$path\"\n{\n" 1467 . "#line 1 \"$path\"\n{\n"
1428 . $source 1468 . $source
1429 . "\n};\n1"; 1469 . "\n};\n1";
1430 1470
1431 $todo{$base} = \%ext; 1471 $todo{$base} = \%ext;
1639 my $name = $pl->ob->name; 1679 my $name = $pl->ob->name;
1640 1680
1641 $pl->{deny_save} = 1; 1681 $pl->{deny_save} = 1;
1642 $pl->password ("*"); # this should lock out the player until we have nuked the dir 1682 $pl->password ("*"); # this should lock out the player until we have nuked the dir
1643 1683
1644 $pl->invoke (cf::EVENT_PLAYER_LOGOUT, 1) if $pl->active; 1684 $pl->invoke (cf::EVENT_PLAYER_LOGOUT, 1) if $pl->ns;
1645 $pl->deactivate; 1685 $pl->deactivate;
1686
1646 my $killer = cf::arch::get "killer_quit"; $pl->killer ($killer); $killer->destroy; 1687 my $killer = cf::arch::get "killer_quit"; $pl->killer ($killer); $killer->destroy;
1647 $pl->invoke (cf::EVENT_PLAYER_QUIT); 1688 $pl->invoke (cf::EVENT_PLAYER_QUIT) if $pl->ns;
1689 ext::highscore::check ($pl->ob);
1690
1648 $pl->ns->destroy if $pl->ns; 1691 $pl->ns->destroy if $pl->ns;
1649 1692
1650 my $path = playerdir $pl; 1693 my $path = playerdir $pl;
1651 my $temp = "$path~$cf::RUNTIME~deleting~"; 1694 my $temp = "$path~$cf::RUNTIME~deleting~";
1652 aio_rename $path, $temp; 1695 aio_rename $path, $temp;
1846 1889
1847sub register { 1890sub register {
1848 my (undef, $regex, $prio) = @_; 1891 my (undef, $regex, $prio) = @_;
1849 my $pkg = caller; 1892 my $pkg = caller;
1850 1893
1851 no strict;
1852 push @{"$pkg\::ISA"}, __PACKAGE__; 1894 push @{"$pkg\::ISA"}, __PACKAGE__;
1853 1895
1854 $EXT_MAP{$pkg} = [$prio, qr<$regex>]; 1896 $EXT_MAP{$pkg} = [$prio, qr<$regex>];
1855} 1897}
1856 1898
1868} 1910}
1869 1911
1870sub normalise { 1912sub normalise {
1871 my ($path, $base) = @_; 1913 my ($path, $base) = @_;
1872 1914
1873 $path = "$path"; # make sure its a string 1915 $path = "$path"; # make sure it's a string
1874 1916
1875 $path =~ s/\.map$//; 1917 $path =~ s/\.map$//;
1876 1918
1877 # map plan: 1919 # map plan:
1878 # 1920 #
1893 $base =~ s{[^/]+/?$}{}; 1935 $base =~ s{[^/]+/?$}{};
1894 $path = "$base/$path"; 1936 $path = "$base/$path";
1895 } 1937 }
1896 1938
1897 for ($path) { 1939 for ($path) {
1898 redo if s{//}{/};
1899 redo if s{/\.?/}{/}; 1940 redo if s{/\.?/}{/};
1900 redo if s{/[^/]+/\.\./}{/}; 1941 redo if s{/[^/]+/\.\./}{/};
1901 } 1942 }
1902 1943
1903 $path 1944 $path
1917 $self->init; # pass $1 etc. 1958 $self->init; # pass $1 etc.
1918 return $self; 1959 return $self;
1919 } 1960 }
1920 } 1961 }
1921 1962
1922 Carp::cluck "unable to resolve path '$path' (base '$base')."; 1963 Carp::cluck "unable to resolve path '$path' (base '$base')";
1923 () 1964 ()
1924} 1965}
1925 1966
1926sub init { 1967sub init {
1927 my ($self) = @_; 1968 my ($self) = @_;
2049} 2090}
2050 2091
2051sub find; 2092sub find;
2052sub find { 2093sub find {
2053 my ($path, $origin) = @_; 2094 my ($path, $origin) = @_;
2095
2096 cf::cede_to_tick;
2054 2097
2055 $path = normalise $path, $origin && $origin->path; 2098 $path = normalise $path, $origin && $origin->path;
2056 2099
2057 my $guard1 = cf::lock_acquire "map_data:$path";#d#remove 2100 my $guard1 = cf::lock_acquire "map_data:$path";#d#remove
2058 my $guard2 = cf::lock_acquire "map_find:$path"; 2101 my $guard2 = cf::lock_acquire "map_find:$path";
2143 2186
2144 $self->in_memory (cf::MAP_ACTIVE); 2187 $self->in_memory (cf::MAP_ACTIVE);
2145 } 2188 }
2146 2189
2147 $self->post_load; 2190 $self->post_load;
2191
2192 1
2148} 2193}
2149 2194
2150# customize the map for a given player, i.e. 2195# customize the map for a given player, i.e.
2151# return the _real_ map. used by e.g. per-player 2196# return the _real_ map. used by e.g. per-player
2152# maps to change the path to ~playername/mappath 2197# maps to change the path to ~playername/mappath
2190} 2235}
2191 2236
2192sub find_sync { 2237sub find_sync {
2193 my ($path, $origin) = @_; 2238 my ($path, $origin) = @_;
2194 2239
2195 cf::sync_job { find $path, $origin } 2240 return cf::LOG cf::llevError | cf::logBacktrace, "do_find_sync"
2241 if $Coro::current == $Coro::main;
2242
2243 find $path, $origin
2196} 2244}
2197 2245
2198sub do_load_sync { 2246sub do_load_sync {
2199 my ($map) = @_; 2247 my ($map) = @_;
2200 2248
2201 cf::LOG cf::llevDebug | cf::logBacktrace, "do_load_sync" 2249 return cf::LOG cf::llevError | cf::logBacktrace, "do_load_sync"
2202 if $Coro::current == $Coro::main; 2250 if $Coro::current == $Coro::main;
2203 2251
2204 cf::sync_job { $map->load }; 2252 $map->load;
2205} 2253}
2206 2254
2207our %MAP_PREFETCH; 2255our %MAP_PREFETCH;
2208our $MAP_PREFETCHER = undef; 2256our $MAP_PREFETCHER = undef;
2209 2257
3268 decrease split destroy change_exp value msg lore send_msg)], 3316 decrease split destroy change_exp value msg lore send_msg)],
3269 ["cf::object::player" => qw(player)], 3317 ["cf::object::player" => qw(player)],
3270 ["cf::player" => qw(peaceful send_msg)], 3318 ["cf::player" => qw(peaceful send_msg)],
3271 ["cf::map" => qw(trigger)], 3319 ["cf::map" => qw(trigger)],
3272) { 3320) {
3273 no strict 'refs';
3274 my ($pkg, @funs) = @$_; 3321 my ($pkg, @funs) = @$_;
3275 *{"safe::$pkg\::$_"} = $safe_hole->wrap (\&{"$pkg\::$_"}) 3322 *{"safe::$pkg\::$_"} = $safe_hole->wrap (\&{"$pkg\::$_"})
3276 for @funs; 3323 for @funs;
3277} 3324}
3278 3325
3365 3412
3366 my $enc = JSON::XS->new->utf8->canonical->relaxed; 3413 my $enc = JSON::XS->new->utf8->canonical->relaxed;
3367 3414
3368 trace "loading facedata from $path\n"; 3415 trace "loading facedata from $path\n";
3369 3416
3370 my $facedata;
3371 0 < aio_load $path, $facedata 3417 0 < aio_load $path, my $facedata
3372 or die "$path: $!"; 3418 or die "$path: $!";
3373 3419
3374 $facedata = Coro::Storable::thaw $facedata; 3420 $facedata = Coro::Storable::thaw $facedata;
3375 3421
3376 $facedata->{version} == 2 3422 $facedata->{version} == 2
3520} 3566}
3521 3567
3522sub reload_resources { 3568sub reload_resources {
3523 trace "reloading resource files...\n"; 3569 trace "reloading resource files...\n";
3524 3570
3571 reload_exp_table;
3572 reload_materials;
3525 reload_facedata; 3573 reload_facedata;
3526 reload_sound; 3574 reload_sound;
3527 reload_archetypes; 3575 reload_archetypes;
3528 reload_regions; 3576 reload_regions;
3529 reload_treasures; 3577 reload_treasures;
3532} 3580}
3533 3581
3534sub reload_config { 3582sub reload_config {
3535 trace "reloading config file...\n"; 3583 trace "reloading config file...\n";
3536 3584
3537 open my $fh, "<:utf8", "$CONFDIR/config" 3585 0 < aio_load "$CONFDIR/config", my $config
3538 or return; 3586 or die "$CONFDIR/config: $!";
3539 3587
3540 local $/; 3588 utf8::decode $config;
3541 *CFG = YAML::XS::Load scalar <$fh>; 3589 *CFG = yaml_load $config;
3542 3590
3543 $EMERGENCY_POSITION = $CFG{emergency_position} || ["/world/world_104_115", 49, 38]; 3591 $EMERGENCY_POSITION = $CFG{emergency_position} || ["/world/world_104_115", 49, 38];
3544 3592
3545 $cf::map::MAX_RESET = $CFG{map_max_reset} if exists $CFG{map_max_reset}; 3593 $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}; 3594 $cf::map::DEFAULT_RESET = $CFG{map_default_reset} if exists $CFG{map_default_reset};
3550 $CFG{mlockall} ? eval "mlockall()" : eval "munlockall()" 3598 $CFG{mlockall} ? eval "mlockall()" : eval "munlockall()"
3551 and die "WARNING: m(un)lockall failed: $!\n"; 3599 and die "WARNING: m(un)lockall failed: $!\n";
3552 }; 3600 };
3553 warn $@ if $@; 3601 warn $@ if $@;
3554 } 3602 }
3555
3556 trace "finished reloading resource files\n";
3557} 3603}
3558 3604
3559sub pidfile() { 3605sub pidfile() {
3560 sysopen my $fh, $PIDFILE, O_RDWR | O_CREAT 3606 sysopen my $fh, $PIDFILE, O_RDWR | O_CREAT
3561 or die "$PIDFILE: $!"; 3607 or die "$PIDFILE: $!";
3586 3632
3587sub main { 3633sub main {
3588 cf::init_globals; # initialise logging 3634 cf::init_globals; # initialise logging
3589 3635
3590 LOG llevInfo, "Welcome to Deliantra, v" . VERSION; 3636 LOG llevInfo, "Welcome to Deliantra, v" . VERSION;
3591 LOG llevInfo, "Copyright (C) 2005-2008 Marc Alexander Lehmann / Robin Redeker / the Deliantra team."; 3637 LOG llevInfo, "Copyright (C) 2005-2010 Marc Alexander Lehmann / Robin Redeker / the Deliantra team.";
3592 LOG llevInfo, "Copyright (C) 1994 Mark Wedel."; 3638 LOG llevInfo, "Copyright (C) 1994 Mark Wedel.";
3593 LOG llevInfo, "Copyright (C) 1992 Frank Tore Johansen."; 3639 LOG llevInfo, "Copyright (C) 1992 Frank Tore Johansen.";
3594 3640
3595 $Coro::current->prio (Coro::PRIO_MAX); # give the main loop max. priority 3641 $Coro::current->prio (Coro::PRIO_MAX); # give the main loop max. priority
3596 3642
3604 }; 3650 };
3605 3651
3606 evthread_start IO::AIO::poll_fileno; 3652 evthread_start IO::AIO::poll_fileno;
3607 3653
3608 cf::sync_job { 3654 cf::sync_job {
3609 cf::init_experience; 3655 cf::incloader::init ();
3656
3610 cf::init_anim; 3657 cf::init_anim;
3611 cf::init_attackmess; 3658 cf::init_attackmess;
3612 cf::init_dynamic; 3659 cf::init_dynamic;
3613 3660
3614 cf::load_settings; 3661 cf::load_settings;
3615 cf::load_materials;
3616 3662
3617 reload_resources; 3663 reload_resources;
3618 reload_config; 3664 reload_config;
3619 db_init; 3665 db_init;
3620 3666
3632 3678
3633 # no (long-running) fork's whatsoever before this point(!) 3679 # no (long-running) fork's whatsoever before this point(!)
3634 use POSIX (); 3680 use POSIX ();
3635 POSIX::close delete $ENV{LOCKUTIL_LOCK_FD} if exists $ENV{LOCKUTIL_LOCK_FD}; 3681 POSIX::close delete $ENV{LOCKUTIL_LOCK_FD} if exists $ENV{LOCKUTIL_LOCK_FD};
3636 3682
3637 (pop @POST_INIT)->(0) while @POST_INIT; 3683 cf::_post_init 0;
3638 }; 3684 };
3639 3685
3640 cf::object::thawer::errors_are_fatal 0; 3686 cf::object::thawer::errors_are_fatal 0;
3641 info "parse errors in files are no longer fatal from this point on.\n"; 3687 info "parse errors in files are no longer fatal from this point on.\n";
3642 3688
3689 my $free_main; $free_main = EV::idle sub {
3690 undef $free_main;
3691 undef &main; # free gobs of memory :)
3692 };
3693
3643 main_loop; 3694 goto &main_loop;
3644} 3695}
3645 3696
3646############################################################################# 3697#############################################################################
3647# initialisation and cleanup 3698# initialisation and cleanup
3648 3699
3747sub emergency_save() { 3798sub emergency_save() {
3748 my $freeze_guard = cf::freeze_mainloop; 3799 my $freeze_guard = cf::freeze_mainloop;
3749 3800
3750 info "emergency_perl_save: enter\n"; 3801 info "emergency_perl_save: enter\n";
3751 3802
3803 # this is a trade-off: we want to be very quick here, so
3804 # save all maps without fsync, and later call a global sync
3805 # (which in turn might be very very slow)
3806 local $USE_FSYNC = 0;
3807
3752 cf::sync_job { 3808 cf::sync_job {
3753 # this is a trade-off: we want to be very quick here, so 3809 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 3810
3758 # use a peculiar iteration method to avoid tripping on perl 3811 # use a peculiar iteration method to avoid tripping on perl
3759 # refcount bugs in for. also avoids problems with players 3812 # refcount bugs in for. also avoids problems with players
3760 # and maps saved/destroyed asynchronously. 3813 # and maps saved/destroyed asynchronously.
3761 info "emergency_perl_save: begin player save\n"; 3814 info "emergency_perl_save: begin player save\n";
3765 delete $pl->{unclean_save}; # not strictly necessary, but cannot hurt 3818 delete $pl->{unclean_save}; # not strictly necessary, but cannot hurt
3766 $pl->save; 3819 $pl->save;
3767 } 3820 }
3768 info "emergency_perl_save: end player save\n"; 3821 info "emergency_perl_save: end player save\n";
3769 3822
3823 cf::write_runtime_sync; # external watchdog should not bark
3824
3770 info "emergency_perl_save: begin map save\n"; 3825 info "emergency_perl_save: begin map save\n";
3771 for my $path (keys %cf::MAP) { 3826 for my $path (keys %cf::MAP) {
3772 my $map = $cf::MAP{$path} or next; 3827 my $map = $cf::MAP{$path} or next;
3773 $map->valid or next; 3828 $map->valid or next;
3774 $map->save; 3829 $map->save;
3775 } 3830 }
3776 info "emergency_perl_save: end map save\n"; 3831 info "emergency_perl_save: end map save\n";
3777 3832
3833 cf::write_runtime_sync; # external watchdog should not bark
3834
3778 info "emergency_perl_save: begin database checkpoint\n"; 3835 info "emergency_perl_save: begin database checkpoint\n";
3779 BDB::db_env_txn_checkpoint $DB_ENV; 3836 BDB::db_env_txn_checkpoint $DB_ENV;
3780 info "emergency_perl_save: end database checkpoint\n"; 3837 info "emergency_perl_save: end database checkpoint\n";
3781 3838
3782 info "emergency_perl_save: begin write uuid\n"; 3839 info "emergency_perl_save: begin write uuid\n";
3783 write_uuid_sync 1; 3840 write_uuid_sync 1;
3784 info "emergency_perl_save: end write uuid\n"; 3841 info "emergency_perl_save: end write uuid\n";
3785 };
3786 3842
3843 cf::write_runtime_sync; # external watchdog should not bark
3844
3845 trace "emergency_perl_save: syncing database to disk";
3846 BDB::db_env_txn_checkpoint $DB_ENV;
3847
3787 info "emergency_perl_save: starting sync()\n"; 3848 info "emergency_perl_save: starting sync\n";
3788 IO::AIO::aio_sync sub { 3849 IO::AIO::aio_sync sub {
3789 info "emergency_perl_save: finished sync()\n"; 3850 info "emergency_perl_save: finished sync\n";
3851 };
3852
3853 cf::write_runtime_sync; # external watchdog should not bark
3854
3855 trace "emergency_perl_save: flushing outstanding aio requests";
3856 while (IO::AIO::nreqs || BDB::nreqs) {
3857 Coro::EV::timer_once 0.01; # let the sync_job do it's thing
3858 }
3859
3860 cf::write_runtime_sync; # external watchdog should not bark
3790 }; 3861 };
3791 3862
3792 info "emergency_perl_save: leave\n"; 3863 info "emergency_perl_save: leave\n";
3793} 3864}
3794 3865
3795sub post_cleanup { 3866sub post_cleanup {
3796 my ($make_core) = @_; 3867 my ($make_core) = @_;
3868
3869 IO::AIO::flush;
3797 3870
3798 error Carp::longmess "post_cleanup backtrace" 3871 error Carp::longmess "post_cleanup backtrace"
3799 if $make_core; 3872 if $make_core;
3800 3873
3801 my $fh = pidfile; 3874 my $fh = pidfile;
3827 } 3900 }
3828} 3901}
3829 3902
3830sub do_reload_perl() { 3903sub do_reload_perl() {
3831 # can/must only be called in main 3904 # can/must only be called in main
3832 if (in_main) { 3905 unless (in_main) {
3833 error "can only reload from main coroutine"; 3906 error "can only reload from main coroutine";
3834 return; 3907 return;
3835 } 3908 }
3836 3909
3837 return if $RELOAD++; 3910 return if $RELOAD++;
3838 3911
3839 my $t1 = AE::time; 3912 my $t1 = AE::time;
3840 3913
3841 while ($RELOAD) { 3914 while ($RELOAD) {
3915 cf::get_slot 0.1, -1, "reload_perl";
3842 info "reloading..."; 3916 info "perl_reload: reloading...";
3843 3917
3844 trace "entering sync_job"; 3918 trace "perl_reload: entering sync_job";
3845 3919
3846 cf::sync_job { 3920 cf::sync_job {
3847 cf::write_runtime_sync; # external watchdog should not bark
3848 cf::emergency_save; 3921 #cf::emergency_save;
3849 cf::write_runtime_sync; # external watchdog should not bark
3850 3922
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"; 3923 trace "perl_reload: cancelling all extension coros";
3862 $_->cancel for values %EXT_CORO; 3924 $_->cancel for values %EXT_CORO;
3863 %EXT_CORO = (); 3925 %EXT_CORO = ();
3864 3926
3865 trace "removing commands"; 3927 trace "perl_reload: removing commands";
3866 %COMMAND = (); 3928 %COMMAND = ();
3867 3929
3868 trace "removing ext/exti commands"; 3930 trace "perl_reload: removing ext/exti commands";
3869 %EXTCMD = (); 3931 %EXTCMD = ();
3870 %EXTICMD = (); 3932 %EXTICMD = ();
3871 3933
3872 trace "unloading/nuking all extensions"; 3934 trace "perl_reload: unloading/nuking all extensions";
3873 for my $pkg (@EXTS) { 3935 for my $pkg (@EXTS) {
3874 trace "... unloading $pkg"; 3936 trace "... unloading $pkg";
3875 3937
3876 if (my $cb = $pkg->can ("unload")) { 3938 if (my $cb = $pkg->can ("unload")) {
3877 eval { 3939 eval {
3882 3944
3883 trace "... clearing $pkg"; 3945 trace "... clearing $pkg";
3884 clear_package $pkg; 3946 clear_package $pkg;
3885 } 3947 }
3886 3948
3887 trace "unloading all perl modules loaded from $LIBDIR"; 3949 trace "perl_reload: unloading all perl modules loaded from $LIBDIR";
3888 while (my ($k, $v) = each %INC) { 3950 while (my ($k, $v) = each %INC) {
3889 next unless $v =~ /^\Q$LIBDIR\E\/.*\.pm$/; 3951 next unless $v =~ /^\Q$LIBDIR\E\/.*\.pm$/;
3890 3952
3891 trace "... unloading $k"; 3953 trace "... unloading $k";
3892 delete $INC{$k}; 3954 delete $INC{$k};
3899 } 3961 }
3900 3962
3901 clear_package $k; 3963 clear_package $k;
3902 } 3964 }
3903 3965
3904 trace "getting rid of safe::, as good as possible"; 3966 trace "perl_reload: getting rid of safe::, as good as possible";
3905 clear_package "safe::$_" 3967 clear_package "safe::$_"
3906 for qw(cf::attachable cf::object cf::object::player cf::client cf::player cf::map cf::party cf::region); 3968 for qw(cf::attachable cf::object cf::object::player cf::client cf::player cf::map cf::party cf::region);
3907 3969
3908 trace "unloading cf.pm \"a bit\""; 3970 trace "perl_reload: unloading cf.pm \"a bit\"";
3909 delete $INC{"cf.pm"}; 3971 delete $INC{"cf.pm"};
3910 delete $INC{"cf/$_.pm"} for @EXTRA_MODULES; 3972 delete $INC{"cf/$_.pm"} for @EXTRA_MODULES;
3911 3973
3912 # don't, removes xs symbols, too, 3974 # don't, removes xs symbols, too,
3913 # and global variables created in xs 3975 # and global variables created in xs
3914 #clear_package __PACKAGE__; 3976 #clear_package __PACKAGE__;
3915 3977
3916 info "unload completed, starting to reload now"; 3978 info "perl_reload: unload completed, starting to reload now";
3917 3979
3918 trace "reloading cf.pm"; 3980 trace "perl_reload: reloading cf.pm";
3919 require cf; 3981 require cf;
3920 cf::_connect_to_perl_1; 3982 cf::_connect_to_perl_1;
3921 3983
3922 trace "loading config and database again"; 3984 trace "perl_reload: loading config and database again";
3923 cf::reload_config; 3985 cf::reload_config;
3924 3986
3925 trace "loading extensions"; 3987 trace "perl_reload: loading extensions";
3926 cf::load_extensions; 3988 cf::load_extensions;
3927 3989
3928 if ($REATTACH_ON_RELOAD) { 3990 if ($REATTACH_ON_RELOAD) {
3929 trace "reattaching attachments to objects/players"; 3991 trace "perl_reload: reattaching attachments to objects/players";
3930 _global_reattach; # objects, sockets 3992 _global_reattach; # objects, sockets
3931 trace "reattaching attachments to maps"; 3993 trace "perl_reload: reattaching attachments to maps";
3932 reattach $_ for values %MAP; 3994 reattach $_ for values %MAP;
3933 trace "reattaching attachments to players"; 3995 trace "perl_reload: reattaching attachments to players";
3934 reattach $_ for values %PLAYER; 3996 reattach $_ for values %PLAYER;
3935 } 3997 }
3936 3998
3937 trace "running post_init jobs"; 3999 cf::_post_init 1;
3938 (pop @POST_INIT)->(1) while @POST_INIT;
3939 4000
3940 trace "leaving sync_job"; 4001 trace "perl_reload: leaving sync_job";
3941 4002
3942 1 4003 1
3943 } or do { 4004 } or do {
3944 error $@; 4005 error $@;
3945 cf::cleanup "error while reloading, exiting."; 4006 cf::cleanup "perl_reload: error, exiting.";
3946 }; 4007 };
3947 4008
3948 info "reloaded";
3949 --$RELOAD; 4009 --$RELOAD;
3950 } 4010 }
3951 4011
3952 $t1 = AE::time - $t1; 4012 $t1 = AE::time - $t1;
3953 info "reload completed in ${t1}s\n"; 4013 info "perl_reload: completed in ${t1}s\n";
3954}; 4014};
3955 4015
3956our $RELOAD_WATCHER; # used only during reload 4016our $RELOAD_WATCHER; # used only during reload
3957 4017
3958sub reload_perl() { 4018sub reload_perl() {
3979 reload_perl; 4039 reload_perl;
3980 }; 4040 };
3981 } 4041 }
3982}; 4042};
3983 4043
3984unshift @INC, $LIBDIR; 4044#############################################################################
3985 4045
3986my $bug_warning = 0; 4046my $bug_warning = 0;
3987 4047
3988our @WAIT_FOR_TICK; 4048our @WAIT_FOR_TICK;
3989our @WAIT_FOR_TICK_BEGIN; 4049our @WAIT_FOR_TICK_BEGIN;
3990 4050
3991sub wait_for_tick { 4051sub wait_for_tick() {
3992 return Coro::cede if tick_inhibit || $Coro::current == $Coro::main; 4052 return Coro::cede if tick_inhibit || $Coro::current == $Coro::main;
3993 4053
3994 my $signal = new Coro::Signal; 4054 my $signal = new Coro::Signal;
3995 push @WAIT_FOR_TICK, $signal; 4055 push @WAIT_FOR_TICK, $signal;
3996 $signal->wait; 4056 $signal->wait;
3997} 4057}
3998 4058
3999sub wait_for_tick_begin { 4059sub wait_for_tick_begin() {
4000 return Coro::cede if tick_inhibit || $Coro::current == $Coro::main; 4060 return Coro::cede if tick_inhibit || $Coro::current == $Coro::main;
4001 4061
4002 my $signal = new Coro::Signal; 4062 my $signal = new Coro::Signal;
4003 push @WAIT_FOR_TICK_BEGIN, $signal; 4063 push @WAIT_FOR_TICK_BEGIN, $signal;
4004 $signal->wait; 4064 $signal->wait;
4056 $DB_ENV->set_flags (&BDB::LOG_AUTOREMOVE ) if BDB::VERSION v0, v4.7; 4116 $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; 4117 $DB_ENV->log_set_config (&BDB::LOG_AUTO_REMOVE) if BDB::VERSION v4.7;
4058 $DB_ENV->set_timeout (30, BDB::SET_TXN_TIMEOUT); 4118 $DB_ENV->set_timeout (30, BDB::SET_TXN_TIMEOUT);
4059 $DB_ENV->set_timeout (30, BDB::SET_LOCK_TIMEOUT); 4119 $DB_ENV->set_timeout (30, BDB::SET_LOCK_TIMEOUT);
4060 4120
4061 (Coro::async { # async to keep sync_job from complaining
4062 cf::sync_job { 4121 cf::sync_job {
4063 eval { 4122 eval {
4064 BDB::db_env_open 4123 BDB::db_env_open
4065 $DB_ENV, 4124 $DB_ENV,
4066 $BDBDIR, 4125 $BDBDIR,
4067 BDB::INIT_LOCK | BDB::INIT_LOG | BDB::INIT_MPOOL | BDB::INIT_TXN 4126 BDB::INIT_LOCK | BDB::INIT_LOG | BDB::INIT_MPOOL | BDB::INIT_TXN
4068 | BDB::RECOVER | BDB::REGISTER | BDB::USE_ENVIRON | BDB::CREATE, 4127 | BDB::RECOVER | BDB::REGISTER | BDB::USE_ENVIRON | BDB::CREATE,
4069 0666; 4128 0666;
4070 4129
4071 cf::cleanup "db_env_open($BDBDIR): $!" if $!; 4130 cf::cleanup "db_env_open($BDBDIR): $!" if $!;
4072 };
4073
4074 cf::cleanup "db_env_open(db): $@" if $@;
4075 }; 4131 };
4076 })->join; 4132
4133 cf::cleanup "db_env_open(db): $@" if $@;
4134 };
4077 } 4135 }
4078 4136
4079 $BDB_DEADLOCK_WATCHER = EV::periodic 0, 3, 0, sub { 4137 $BDB_DEADLOCK_WATCHER = EV::periodic 0, 3, 0, sub {
4080 BDB::db_env_lock_detect $DB_ENV, 0, BDB::LOCK_DEFAULT, 0, sub { }; 4138 BDB::db_env_lock_detect $DB_ENV, 0, BDB::LOCK_DEFAULT, 0, sub { };
4081 }; 4139 };
4093 IO::AIO::min_parallel 8; 4151 IO::AIO::min_parallel 8;
4094 IO::AIO::max_poll_time $TICK * 0.1; 4152 IO::AIO::max_poll_time $TICK * 0.1;
4095 undef $AnyEvent::AIO::WATCHER; 4153 undef $AnyEvent::AIO::WATCHER;
4096} 4154}
4097 4155
4098my $_log_backtrace; 4156our $_log_backtrace;
4157our $_log_backtrace_last;
4099 4158
4100sub _log_backtrace { 4159sub _log_backtrace {
4101 my ($msg, @addr) = @_; 4160 my ($msg, @addr) = @_;
4102 4161
4103 $msg =~ s/\n//; 4162 $msg =~ s/\n$//;
4104 4163
4164 if ($_log_backtrace_last eq $msg) {
4165 LOG llevInfo, "[ABT] $msg\n";
4166 LOG llevInfo, "[ABT] [duplicate, suppressed]\n";
4105 # limit the # of concurrent backtraces 4167 # limit the # of concurrent backtraces
4106 if ($_log_backtrace < 2) { 4168 } elsif ($_log_backtrace < 2) {
4169 $_log_backtrace_last = $msg;
4107 ++$_log_backtrace; 4170 ++$_log_backtrace;
4108 my $perl_bt = Carp::longmess $msg; 4171 my $perl_bt = Carp::longmess $msg;
4109 async { 4172 async {
4110 $Coro::current->{desc} = "abt $msg"; 4173 $Coro::current->{desc} = "abt $msg";
4111 4174
4131 LOG llevInfo, "[ABT] $_\n" for @bt; 4194 LOG llevInfo, "[ABT] $_\n" for @bt;
4132 --$_log_backtrace; 4195 --$_log_backtrace;
4133 }; 4196 };
4134 } else { 4197 } else {
4135 LOG llevInfo, "[ABT] $msg\n"; 4198 LOG llevInfo, "[ABT] $msg\n";
4136 LOG llevInfo, "[ABT] [suppressed]\n"; 4199 LOG llevInfo, "[ABT] [overload, suppressed]\n";
4137 } 4200 }
4138} 4201}
4139 4202
4140# load additional modules 4203# load additional modules
4141require "cf/$_.pm" for @EXTRA_MODULES; 4204require "cf/$_.pm" for @EXTRA_MODULES;

Diff Legend

Removed lines
+ Added lines
< Changed lines
> Changed lines