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.559 by root, Sat Feb 26 12:50:27 2011 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 = ();
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;
233from wherever your confdir points to. 235from wherever your confdir points to.
234 236
235=item cf::wait_for_tick, cf::wait_for_tick_begin 237=item cf::wait_for_tick, cf::wait_for_tick_begin
236 238
237These are functions that inhibit the current coroutine one tick. cf::wait_for_tick_begin only 239These 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 240returns 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. 241per tick), while cf::wait_for_tick wakes up all waiters after tick processing.
242
243=cut
244
245sub wait_for_tick();
246sub wait_for_tick_begin();
240 247
241=item @cf::INVOKE_RESULTS 248=item @cf::INVOKE_RESULTS
242 249
243This array contains the results of the last C<invoke ()> call. When 250This 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 251C<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 359our $json_coder = JSON::XS->new->utf8->max_size (1e6); # accept ~1mb max
353 360
354sub encode_json($) { $json_coder->encode ($_[0]) } 361sub encode_json($) { $json_coder->encode ($_[0]) }
355sub decode_json($) { $json_coder->decode ($_[0]) } 362sub decode_json($) { $json_coder->decode ($_[0]) }
356 363
364=item $ref = cf::yaml_load $scalar
365
366Same as YAML::XS::Load, but doesn't leak, because it forks (and thus blocks).
367
368=cut
369
370sub fork_call(&@);
371
372sub yaml_load($) {
373 fork_call { YAML::XS::Load $_[0] } @_
374}
375
357=item cf::post_init { BLOCK } 376=item cf::post_init { BLOCK }
358 377
359Execute the given codeblock, I<after> all extensions have been (re-)loaded, 378Execute the given codeblock, I<after> all extensions have been (re-)loaded,
360but I<before> the server starts ticking again. 379but I<before> the server starts ticking again.
361 380
362The cdoeblock will have a single boolean argument to indicate whether this 381The codeblock will have a single boolean argument to indicate whether this
363is a reload or not. 382is a reload or not.
364 383
365=cut 384=cut
366 385
367sub post_init(&) { 386sub post_init(&) {
368 push @POST_INIT, shift; 387 push @POST_INIT, shift;
388}
389
390sub _post_init {
391 trace "running post_init jobs";
392
393 # run them in parallel...
394
395 my @join;
396
397 while () {
398 push @join, map &Coro::async ($_, 0), @POST_INIT;
399 @POST_INIT = ();
400
401 @join or last;
402
403 (pop @join)->join;
404 }
369} 405}
370 406
371=item cf::lock_wait $string 407=item cf::lock_wait $string
372 408
373Wait until the given lock is available. See cf::lock_acquire. 409Wait until the given lock is available. See cf::lock_acquire.
518=cut 554=cut
519 555
520sub sync_job(&) { 556sub sync_job(&) {
521 my ($job) = @_; 557 my ($job) = @_;
522 558
523 if ($Coro::current == $Coro::main) { 559 if (in_main) {
524 my $time = AE::time; 560 my $time = AE::time;
525 561
526 # this is the main coro, too bad, we have to block 562 # this is the main coro, too bad, we have to block
527 # till the operation succeeds, freezing the server :/ 563 # till the operation succeeds, freezing the server :/
528 564
529 LOG llevError, Carp::longmess "sync job";#d# 565 #LOG llevError, Carp::longmess "sync job";#d#
530 566
531 my $freeze_guard = freeze_mainloop; 567 my $freeze_guard = freeze_mainloop;
532 568
533 my $busy = 1; 569 my $busy = 1;
534 my @res; 570 my @res;
578 $EXT_CORO{$coro+0} = $coro; 614 $EXT_CORO{$coro+0} = $coro;
579 615
580 $coro 616 $coro
581} 617}
582 618
583=item fork_call { }, $args 619=item fork_call { }, @args
584 620
585Executes the given code block with the given arguments in a seperate 621Executes the given code block with the given arguments in a seperate
586process, returning the results. Everything must be serialisable with 622process, returning the results. Everything must be serialisable with
587Coro::Storable. May, of course, block. Note that the executed sub may 623Coro::Storable. May, of course, block. Note that the executed sub may
588never block itself or use any form of event handling. 624never block itself or use any form of event handling.
589 625
590=cut 626=cut
591 627
628sub post_fork {
629 reset_signals;
630}
631
592sub fork_call(&@) { 632sub fork_call(&@) {
593 my ($cb, @args) = @_; 633 my ($cb, @args) = @_;
594 634
595 # we seemingly have to make a local copy of the whole thing, 635 # we seemingly have to make a local copy of the whole thing,
596 # otherwise perl prematurely frees the stuff :/ 636 # otherwise perl prematurely frees the stuff :/
597 # TODO: investigate and fix (likely this will be rather laborious) 637 # TODO: investigate and fix (likely this will be rather laborious)
598 638
599 my @res = Coro::Util::fork_eval { 639 my @res = Coro::Util::fork_eval {
600 reset_signals; 640 cf::post_fork;
601 &$cb 641 &$cb
602 }, @args; 642 } @args;
603 643
604 wantarray ? @res : $res[-1] 644 wantarray ? @res : $res[-1]
605} 645}
606 646
607sub objinfo { 647sub objinfo {
657within each server. 697within each server.
658 698
659=cut 699=cut
660 700
661sub db_table($) { 701sub db_table($) {
702 cf::error "db_get called from main context"
703 if $Coro::current == $Coro::main;
704
662 my ($name) = @_; 705 my ($name) = @_;
663 my $db = BDB::db_create $DB_ENV; 706 my $db = BDB::db_create $DB_ENV;
664 707
665 eval { 708 eval {
666 $db->set_flags (BDB::CHKSUM); 709 $db->set_flags (BDB::CHKSUM);
676} 719}
677 720
678our $DB; 721our $DB;
679 722
680sub db_init { 723sub db_init {
681 cf::sync_job {
682 $DB ||= db_table "db"; 724 $DB ||= db_table "db";
683 };
684} 725}
685 726
686sub db_get($$) { 727sub db_get($$) {
687 my $key = "$_[0]/$_[1]"; 728 my $key = "$_[0]/$_[1]";
688 729
689 cf::sync_job { 730 cf::error "db_get called from main context"
731 if $Coro::current == $Coro::main;
732
690 BDB::db_get $DB, undef, $key, my $data; 733 BDB::db_get $DB, undef, $key, my $data;
691 734
692 $! ? () 735 $! ? ()
693 : $data 736 : $data
694 }
695} 737}
696 738
697sub db_put($$$) { 739sub db_put($$$) {
698 BDB::dbreq_pri 4; 740 BDB::dbreq_pri 4;
699 BDB::db_put $DB, undef, "$_[0]/$_[1]", $_[2], 0, sub { }; 741 BDB::db_put $DB, undef, "$_[0]/$_[1]", $_[2], 0, sub { };
1421 1463
1422 $ext{meta} = { map { (split /=/, $_, 2)[0, 1] } split /\s+/, $1 } 1464 $ext{meta} = { map { (split /=/, $_, 2)[0, 1] } split /\s+/, $1 }
1423 if $source =~ /\A#!.*?perl.*?#\s*(.*)$/m; 1465 if $source =~ /\A#!.*?perl.*?#\s*(.*)$/m;
1424 1466
1425 $ext{source} = 1467 $ext{source} =
1426 "package $pkg; use 5.10.0; use strict 'vars', 'subs'; use utf8;\n" 1468 "package $pkg; use common::sense;\n"
1427 . "#line 1 \"$path\"\n{\n" 1469 . "#line 1 \"$path\"\n{\n"
1428 . $source 1470 . $source
1429 . "\n};\n1"; 1471 . "\n};\n1";
1430 1472
1431 $todo{$base} = \%ext; 1473 $todo{$base} = \%ext;
1639 my $name = $pl->ob->name; 1681 my $name = $pl->ob->name;
1640 1682
1641 $pl->{deny_save} = 1; 1683 $pl->{deny_save} = 1;
1642 $pl->password ("*"); # this should lock out the player until we have nuked the dir 1684 $pl->password ("*"); # this should lock out the player until we have nuked the dir
1643 1685
1644 $pl->invoke (cf::EVENT_PLAYER_LOGOUT, 1) if $pl->active; 1686 $pl->invoke (cf::EVENT_PLAYER_LOGOUT, 1) if $pl->ns;
1645 $pl->deactivate; 1687 $pl->deactivate;
1688
1646 my $killer = cf::arch::get "killer_quit"; $pl->killer ($killer); $killer->destroy; 1689 my $killer = cf::arch::get "killer_quit"; $pl->killer ($killer); $killer->destroy;
1647 $pl->invoke (cf::EVENT_PLAYER_QUIT); 1690 $pl->invoke (cf::EVENT_PLAYER_QUIT) if $pl->ns;
1691 ext::highscore::check ($pl->ob);
1692
1648 $pl->ns->destroy if $pl->ns; 1693 $pl->ns->destroy if $pl->ns;
1649 1694
1650 my $path = playerdir $pl; 1695 my $path = playerdir $pl;
1651 my $temp = "$path~$cf::RUNTIME~deleting~"; 1696 my $temp = "$path~$cf::RUNTIME~deleting~";
1652 aio_rename $path, $temp; 1697 aio_rename $path, $temp;
1818sub generate_random_map { 1863sub generate_random_map {
1819 my ($self, $rmp) = @_; 1864 my ($self, $rmp) = @_;
1820 1865
1821 my $lock = cf::lock_acquire "generate_random_map"; # the random map generator is NOT reentrant ATM 1866 my $lock = cf::lock_acquire "generate_random_map"; # the random map generator is NOT reentrant ATM
1822 1867
1823 # mit "rum" bekleckern, nicht
1824 $self->_create_random_map ( 1868 $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} 1869}
1838 1870
1839=item cf::map->register ($regex, $prio) 1871=item cf::map->register ($regex, $prio)
1840 1872
1841Register a handler for the map path matching the given regex at the 1873Register a handler for the map path matching the given regex at the
1846 1878
1847sub register { 1879sub register {
1848 my (undef, $regex, $prio) = @_; 1880 my (undef, $regex, $prio) = @_;
1849 my $pkg = caller; 1881 my $pkg = caller;
1850 1882
1851 no strict;
1852 push @{"$pkg\::ISA"}, __PACKAGE__; 1883 push @{"$pkg\::ISA"}, __PACKAGE__;
1853 1884
1854 $EXT_MAP{$pkg} = [$prio, qr<$regex>]; 1885 $EXT_MAP{$pkg} = [$prio, qr<$regex>];
1855} 1886}
1856 1887
1868} 1899}
1869 1900
1870sub normalise { 1901sub normalise {
1871 my ($path, $base) = @_; 1902 my ($path, $base) = @_;
1872 1903
1873 $path = "$path"; # make sure its a string 1904 $path = "$path"; # make sure it's a string
1874 1905
1875 $path =~ s/\.map$//; 1906 $path =~ s/\.map$//;
1876 1907
1877 # map plan: 1908 # map plan:
1878 # 1909 #
1893 $base =~ s{[^/]+/?$}{}; 1924 $base =~ s{[^/]+/?$}{};
1894 $path = "$base/$path"; 1925 $path = "$base/$path";
1895 } 1926 }
1896 1927
1897 for ($path) { 1928 for ($path) {
1898 redo if s{//}{/};
1899 redo if s{/\.?/}{/}; 1929 redo if s{/\.?/}{/};
1900 redo if s{/[^/]+/\.\./}{/}; 1930 redo if s{/[^/]+/\.\./}{/};
1901 } 1931 }
1902 1932
1903 $path 1933 $path
1917 $self->init; # pass $1 etc. 1947 $self->init; # pass $1 etc.
1918 return $self; 1948 return $self;
1919 } 1949 }
1920 } 1950 }
1921 1951
1922 Carp::cluck "unable to resolve path '$path' (base '$base')."; 1952 Carp::cluck "unable to resolve path '$path' (base '$base')";
1923 () 1953 ()
1924} 1954}
1925 1955
1926sub init { 1956sub init {
1927 my ($self) = @_; 1957 my ($self) = @_;
2049} 2079}
2050 2080
2051sub find; 2081sub find;
2052sub find { 2082sub find {
2053 my ($path, $origin) = @_; 2083 my ($path, $origin) = @_;
2084
2085 cf::cede_to_tick;
2054 2086
2055 $path = normalise $path, $origin && $origin->path; 2087 $path = normalise $path, $origin && $origin->path;
2056 2088
2057 my $guard1 = cf::lock_acquire "map_data:$path";#d#remove 2089 my $guard1 = cf::lock_acquire "map_data:$path";#d#remove
2058 my $guard2 = cf::lock_acquire "map_find:$path"; 2090 my $guard2 = cf::lock_acquire "map_find:$path";
2143 2175
2144 $self->in_memory (cf::MAP_ACTIVE); 2176 $self->in_memory (cf::MAP_ACTIVE);
2145 } 2177 }
2146 2178
2147 $self->post_load; 2179 $self->post_load;
2180
2181 1
2148} 2182}
2149 2183
2150# customize the map for a given player, i.e. 2184# customize the map for a given player, i.e.
2151# return the _real_ map. used by e.g. per-player 2185# return the _real_ map. used by e.g. per-player
2152# maps to change the path to ~playername/mappath 2186# maps to change the path to ~playername/mappath
2190} 2224}
2191 2225
2192sub find_sync { 2226sub find_sync {
2193 my ($path, $origin) = @_; 2227 my ($path, $origin) = @_;
2194 2228
2195 cf::sync_job { find $path, $origin } 2229 return cf::LOG cf::llevError | cf::logBacktrace, "do_find_sync"
2230 if $Coro::current == $Coro::main;
2231
2232 find $path, $origin
2196} 2233}
2197 2234
2198sub do_load_sync { 2235sub do_load_sync {
2199 my ($map) = @_; 2236 my ($map) = @_;
2200 2237
2201 cf::LOG cf::llevDebug | cf::logBacktrace, "do_load_sync" 2238 return cf::LOG cf::llevError | cf::logBacktrace, "do_load_sync"
2202 if $Coro::current == $Coro::main; 2239 if $Coro::current == $Coro::main;
2203 2240
2204 cf::sync_job { $map->load }; 2241 $map->load;
2205} 2242}
2206 2243
2207our %MAP_PREFETCH; 2244our %MAP_PREFETCH;
2208our $MAP_PREFETCHER = undef; 2245our $MAP_PREFETCHER = undef;
2209 2246
3268 decrease split destroy change_exp value msg lore send_msg)], 3305 decrease split destroy change_exp value msg lore send_msg)],
3269 ["cf::object::player" => qw(player)], 3306 ["cf::object::player" => qw(player)],
3270 ["cf::player" => qw(peaceful send_msg)], 3307 ["cf::player" => qw(peaceful send_msg)],
3271 ["cf::map" => qw(trigger)], 3308 ["cf::map" => qw(trigger)],
3272) { 3309) {
3273 no strict 'refs';
3274 my ($pkg, @funs) = @$_; 3310 my ($pkg, @funs) = @$_;
3275 *{"safe::$pkg\::$_"} = $safe_hole->wrap (\&{"$pkg\::$_"}) 3311 *{"safe::$pkg\::$_"} = $safe_hole->wrap (\&{"$pkg\::$_"})
3276 for @funs; 3312 for @funs;
3277} 3313}
3278 3314
3365 3401
3366 my $enc = JSON::XS->new->utf8->canonical->relaxed; 3402 my $enc = JSON::XS->new->utf8->canonical->relaxed;
3367 3403
3368 trace "loading facedata from $path\n"; 3404 trace "loading facedata from $path\n";
3369 3405
3370 my $facedata;
3371 0 < aio_load $path, $facedata 3406 0 < aio_load $path, my $facedata
3372 or die "$path: $!"; 3407 or die "$path: $!";
3373 3408
3374 $facedata = Coro::Storable::thaw $facedata; 3409 $facedata = Coro::Storable::thaw $facedata;
3375 3410
3376 $facedata->{version} == 2 3411 $facedata->{version} == 2
3393 3428
3394 cf::face::set_visibility $idx, $info->{visibility}; 3429 cf::face::set_visibility $idx, $info->{visibility};
3395 cf::face::set_magicmap $idx, $info->{magicmap}; 3430 cf::face::set_magicmap $idx, $info->{magicmap};
3396 cf::face::set_data $idx, 0, $info->{data32}, $info->{hash32}; 3431 cf::face::set_data $idx, 0, $info->{data32}, $info->{hash32};
3397 cf::face::set_data $idx, 1, $info->{data64}, $info->{hash64}; 3432 cf::face::set_data $idx, 1, $info->{data64}, $info->{hash64};
3433 cf::face::set_data $idx, 2, $info->{glyph} , $info->{glyph} ;
3398 3434
3399 cf::cede_to_tick; 3435 cf::cede_to_tick;
3400 } 3436 }
3401 3437
3402 while (my ($face, $info) = each %$faces) { 3438 while (my ($face, $info) = each %$faces) {
3520} 3556}
3521 3557
3522sub reload_resources { 3558sub reload_resources {
3523 trace "reloading resource files...\n"; 3559 trace "reloading resource files...\n";
3524 3560
3561 reload_exp_table;
3562 reload_materials;
3525 reload_facedata; 3563 reload_facedata;
3526 reload_sound; 3564 reload_sound;
3527 reload_archetypes; 3565 reload_archetypes;
3528 reload_regions; 3566 reload_regions;
3529 reload_treasures; 3567 reload_treasures;
3532} 3570}
3533 3571
3534sub reload_config { 3572sub reload_config {
3535 trace "reloading config file...\n"; 3573 trace "reloading config file...\n";
3536 3574
3537 open my $fh, "<:utf8", "$CONFDIR/config" 3575 0 < aio_load "$CONFDIR/config", my $config
3538 or return; 3576 or die "$CONFDIR/config: $!";
3539 3577
3540 local $/; 3578 utf8::decode $config;
3541 *CFG = YAML::XS::Load scalar <$fh>; 3579 *CFG = yaml_load $config;
3542 3580
3543 $EMERGENCY_POSITION = $CFG{emergency_position} || ["/world/world_104_115", 49, 38]; 3581 $EMERGENCY_POSITION = $CFG{emergency_position} || ["/world/world_104_115", 49, 38];
3544 3582
3545 $cf::map::MAX_RESET = $CFG{map_max_reset} if exists $CFG{map_max_reset}; 3583 $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}; 3584 $cf::map::DEFAULT_RESET = $CFG{map_default_reset} if exists $CFG{map_default_reset};
3550 $CFG{mlockall} ? eval "mlockall()" : eval "munlockall()" 3588 $CFG{mlockall} ? eval "mlockall()" : eval "munlockall()"
3551 and die "WARNING: m(un)lockall failed: $!\n"; 3589 and die "WARNING: m(un)lockall failed: $!\n";
3552 }; 3590 };
3553 warn $@ if $@; 3591 warn $@ if $@;
3554 } 3592 }
3555
3556 trace "finished reloading resource files\n";
3557} 3593}
3558 3594
3559sub pidfile() { 3595sub pidfile() {
3560 sysopen my $fh, $PIDFILE, O_RDWR | O_CREAT 3596 sysopen my $fh, $PIDFILE, O_RDWR | O_CREAT
3561 or die "$PIDFILE: $!"; 3597 or die "$PIDFILE: $!";
3586 3622
3587sub main { 3623sub main {
3588 cf::init_globals; # initialise logging 3624 cf::init_globals; # initialise logging
3589 3625
3590 LOG llevInfo, "Welcome to Deliantra, v" . VERSION; 3626 LOG llevInfo, "Welcome to Deliantra, v" . VERSION;
3591 LOG llevInfo, "Copyright (C) 2005-2008 Marc Alexander Lehmann / Robin Redeker / the Deliantra team."; 3627 LOG llevInfo, "Copyright (C) 2005-2010 Marc Alexander Lehmann / Robin Redeker / the Deliantra team.";
3592 LOG llevInfo, "Copyright (C) 1994 Mark Wedel."; 3628 LOG llevInfo, "Copyright (C) 1994 Mark Wedel.";
3593 LOG llevInfo, "Copyright (C) 1992 Frank Tore Johansen."; 3629 LOG llevInfo, "Copyright (C) 1992 Frank Tore Johansen.";
3594 3630
3595 $Coro::current->prio (Coro::PRIO_MAX); # give the main loop max. priority 3631 $Coro::current->prio (Coro::PRIO_MAX); # give the main loop max. priority
3596 3632
3604 }; 3640 };
3605 3641
3606 evthread_start IO::AIO::poll_fileno; 3642 evthread_start IO::AIO::poll_fileno;
3607 3643
3608 cf::sync_job { 3644 cf::sync_job {
3609 cf::init_experience; 3645 cf::incloader::init ();
3646
3610 cf::init_anim; 3647 cf::init_anim;
3611 cf::init_attackmess; 3648 cf::init_attackmess;
3612 cf::init_dynamic; 3649 cf::init_dynamic;
3613 3650
3614 cf::load_settings; 3651 cf::load_settings;
3615 cf::load_materials;
3616 3652
3617 reload_resources; 3653 reload_resources;
3618 reload_config; 3654 reload_config;
3619 db_init; 3655 db_init;
3620 3656
3632 3668
3633 # no (long-running) fork's whatsoever before this point(!) 3669 # no (long-running) fork's whatsoever before this point(!)
3634 use POSIX (); 3670 use POSIX ();
3635 POSIX::close delete $ENV{LOCKUTIL_LOCK_FD} if exists $ENV{LOCKUTIL_LOCK_FD}; 3671 POSIX::close delete $ENV{LOCKUTIL_LOCK_FD} if exists $ENV{LOCKUTIL_LOCK_FD};
3636 3672
3637 (pop @POST_INIT)->(0) while @POST_INIT; 3673 cf::_post_init 0;
3638 }; 3674 };
3639 3675
3640 cf::object::thawer::errors_are_fatal 0; 3676 cf::object::thawer::errors_are_fatal 0;
3641 info "parse errors in files are no longer fatal from this point on.\n"; 3677 info "parse errors in files are no longer fatal from this point on.\n";
3642 3678
3679 my $free_main; $free_main = EV::idle sub {
3680 undef $free_main;
3681 undef &main; # free gobs of memory :)
3682 };
3683
3643 main_loop; 3684 goto &main_loop;
3644} 3685}
3645 3686
3646############################################################################# 3687#############################################################################
3647# initialisation and cleanup 3688# initialisation and cleanup
3648 3689
3747sub emergency_save() { 3788sub emergency_save() {
3748 my $freeze_guard = cf::freeze_mainloop; 3789 my $freeze_guard = cf::freeze_mainloop;
3749 3790
3750 info "emergency_perl_save: enter\n"; 3791 info "emergency_perl_save: enter\n";
3751 3792
3793 # this is a trade-off: we want to be very quick here, so
3794 # save all maps without fsync, and later call a global sync
3795 # (which in turn might be very very slow)
3796 local $USE_FSYNC = 0;
3797
3752 cf::sync_job { 3798 cf::sync_job {
3753 # this is a trade-off: we want to be very quick here, so 3799 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 3800
3758 # use a peculiar iteration method to avoid tripping on perl 3801 # use a peculiar iteration method to avoid tripping on perl
3759 # refcount bugs in for. also avoids problems with players 3802 # refcount bugs in for. also avoids problems with players
3760 # and maps saved/destroyed asynchronously. 3803 # and maps saved/destroyed asynchronously.
3761 info "emergency_perl_save: begin player save\n"; 3804 info "emergency_perl_save: begin player save\n";
3765 delete $pl->{unclean_save}; # not strictly necessary, but cannot hurt 3808 delete $pl->{unclean_save}; # not strictly necessary, but cannot hurt
3766 $pl->save; 3809 $pl->save;
3767 } 3810 }
3768 info "emergency_perl_save: end player save\n"; 3811 info "emergency_perl_save: end player save\n";
3769 3812
3813 cf::write_runtime_sync; # external watchdog should not bark
3814
3770 info "emergency_perl_save: begin map save\n"; 3815 info "emergency_perl_save: begin map save\n";
3771 for my $path (keys %cf::MAP) { 3816 for my $path (keys %cf::MAP) {
3772 my $map = $cf::MAP{$path} or next; 3817 my $map = $cf::MAP{$path} or next;
3773 $map->valid or next; 3818 $map->valid or next;
3774 $map->save; 3819 $map->save;
3775 } 3820 }
3776 info "emergency_perl_save: end map save\n"; 3821 info "emergency_perl_save: end map save\n";
3777 3822
3823 cf::write_runtime_sync; # external watchdog should not bark
3824
3778 info "emergency_perl_save: begin database checkpoint\n"; 3825 info "emergency_perl_save: begin database checkpoint\n";
3779 BDB::db_env_txn_checkpoint $DB_ENV; 3826 BDB::db_env_txn_checkpoint $DB_ENV;
3780 info "emergency_perl_save: end database checkpoint\n"; 3827 info "emergency_perl_save: end database checkpoint\n";
3781 3828
3782 info "emergency_perl_save: begin write uuid\n"; 3829 info "emergency_perl_save: begin write uuid\n";
3783 write_uuid_sync 1; 3830 write_uuid_sync 1;
3784 info "emergency_perl_save: end write uuid\n"; 3831 info "emergency_perl_save: end write uuid\n";
3785 };
3786 3832
3833 cf::write_runtime_sync; # external watchdog should not bark
3834
3835 trace "emergency_perl_save: syncing database to disk";
3836 BDB::db_env_txn_checkpoint $DB_ENV;
3837
3787 info "emergency_perl_save: starting sync()\n"; 3838 info "emergency_perl_save: starting sync\n";
3788 IO::AIO::aio_sync sub { 3839 IO::AIO::aio_sync sub {
3789 info "emergency_perl_save: finished sync()\n"; 3840 info "emergency_perl_save: finished sync\n";
3841 };
3842
3843 cf::write_runtime_sync; # external watchdog should not bark
3844
3845 trace "emergency_perl_save: flushing outstanding aio requests";
3846 while (IO::AIO::nreqs || BDB::nreqs) {
3847 Coro::EV::timer_once 0.01; # let the sync_job do it's thing
3848 }
3849
3850 cf::write_runtime_sync; # external watchdog should not bark
3790 }; 3851 };
3791 3852
3792 info "emergency_perl_save: leave\n"; 3853 info "emergency_perl_save: leave\n";
3793} 3854}
3794 3855
3795sub post_cleanup { 3856sub post_cleanup {
3796 my ($make_core) = @_; 3857 my ($make_core) = @_;
3858
3859 IO::AIO::flush;
3797 3860
3798 error Carp::longmess "post_cleanup backtrace" 3861 error Carp::longmess "post_cleanup backtrace"
3799 if $make_core; 3862 if $make_core;
3800 3863
3801 my $fh = pidfile; 3864 my $fh = pidfile;
3827 } 3890 }
3828} 3891}
3829 3892
3830sub do_reload_perl() { 3893sub do_reload_perl() {
3831 # can/must only be called in main 3894 # can/must only be called in main
3832 if (in_main) { 3895 unless (in_main) {
3833 error "can only reload from main coroutine"; 3896 error "can only reload from main coroutine";
3834 return; 3897 return;
3835 } 3898 }
3836 3899
3837 return if $RELOAD++; 3900 return if $RELOAD++;
3838 3901
3839 my $t1 = AE::time; 3902 my $t1 = AE::time;
3840 3903
3841 while ($RELOAD) { 3904 while ($RELOAD) {
3905 cf::get_slot 0.1, -1, "reload_perl";
3842 info "reloading..."; 3906 info "perl_reload: reloading...";
3843 3907
3844 trace "entering sync_job"; 3908 trace "perl_reload: entering sync_job";
3845 3909
3846 cf::sync_job { 3910 cf::sync_job {
3847 cf::write_runtime_sync; # external watchdog should not bark
3848 cf::emergency_save; 3911 #cf::emergency_save;
3849 cf::write_runtime_sync; # external watchdog should not bark
3850 3912
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"; 3913 trace "perl_reload: cancelling all extension coros";
3862 $_->cancel for values %EXT_CORO; 3914 $_->cancel for values %EXT_CORO;
3863 %EXT_CORO = (); 3915 %EXT_CORO = ();
3864 3916
3865 trace "removing commands"; 3917 trace "perl_reload: removing commands";
3866 %COMMAND = (); 3918 %COMMAND = ();
3867 3919
3868 trace "removing ext/exti commands"; 3920 trace "perl_reload: removing ext/exti commands";
3869 %EXTCMD = (); 3921 %EXTCMD = ();
3870 %EXTICMD = (); 3922 %EXTICMD = ();
3871 3923
3872 trace "unloading/nuking all extensions"; 3924 trace "perl_reload: unloading/nuking all extensions";
3873 for my $pkg (@EXTS) { 3925 for my $pkg (@EXTS) {
3874 trace "... unloading $pkg"; 3926 trace "... unloading $pkg";
3875 3927
3876 if (my $cb = $pkg->can ("unload")) { 3928 if (my $cb = $pkg->can ("unload")) {
3877 eval { 3929 eval {
3882 3934
3883 trace "... clearing $pkg"; 3935 trace "... clearing $pkg";
3884 clear_package $pkg; 3936 clear_package $pkg;
3885 } 3937 }
3886 3938
3887 trace "unloading all perl modules loaded from $LIBDIR"; 3939 trace "perl_reload: unloading all perl modules loaded from $LIBDIR";
3888 while (my ($k, $v) = each %INC) { 3940 while (my ($k, $v) = each %INC) {
3889 next unless $v =~ /^\Q$LIBDIR\E\/.*\.pm$/; 3941 next unless $v =~ /^\Q$LIBDIR\E\/.*\.pm$/;
3890 3942
3891 trace "... unloading $k"; 3943 trace "... unloading $k";
3892 delete $INC{$k}; 3944 delete $INC{$k};
3899 } 3951 }
3900 3952
3901 clear_package $k; 3953 clear_package $k;
3902 } 3954 }
3903 3955
3904 trace "getting rid of safe::, as good as possible"; 3956 trace "perl_reload: getting rid of safe::, as good as possible";
3905 clear_package "safe::$_" 3957 clear_package "safe::$_"
3906 for qw(cf::attachable cf::object cf::object::player cf::client cf::player cf::map cf::party cf::region); 3958 for qw(cf::attachable cf::object cf::object::player cf::client cf::player cf::map cf::party cf::region);
3907 3959
3908 trace "unloading cf.pm \"a bit\""; 3960 trace "perl_reload: unloading cf.pm \"a bit\"";
3909 delete $INC{"cf.pm"}; 3961 delete $INC{"cf.pm"};
3910 delete $INC{"cf/$_.pm"} for @EXTRA_MODULES; 3962 delete $INC{"cf/$_.pm"} for @EXTRA_MODULES;
3911 3963
3912 # don't, removes xs symbols, too, 3964 # don't, removes xs symbols, too,
3913 # and global variables created in xs 3965 # and global variables created in xs
3914 #clear_package __PACKAGE__; 3966 #clear_package __PACKAGE__;
3915 3967
3916 info "unload completed, starting to reload now"; 3968 info "perl_reload: unload completed, starting to reload now";
3917 3969
3918 trace "reloading cf.pm"; 3970 trace "perl_reload: reloading cf.pm";
3919 require cf; 3971 require cf;
3920 cf::_connect_to_perl_1; 3972 cf::_connect_to_perl_1;
3921 3973
3922 trace "loading config and database again"; 3974 trace "perl_reload: loading config and database again";
3923 cf::reload_config; 3975 cf::reload_config;
3924 3976
3925 trace "loading extensions"; 3977 trace "perl_reload: loading extensions";
3926 cf::load_extensions; 3978 cf::load_extensions;
3927 3979
3928 if ($REATTACH_ON_RELOAD) { 3980 if ($REATTACH_ON_RELOAD) {
3929 trace "reattaching attachments to objects/players"; 3981 trace "perl_reload: reattaching attachments to objects/players";
3930 _global_reattach; # objects, sockets 3982 _global_reattach; # objects, sockets
3931 trace "reattaching attachments to maps"; 3983 trace "perl_reload: reattaching attachments to maps";
3932 reattach $_ for values %MAP; 3984 reattach $_ for values %MAP;
3933 trace "reattaching attachments to players"; 3985 trace "perl_reload: reattaching attachments to players";
3934 reattach $_ for values %PLAYER; 3986 reattach $_ for values %PLAYER;
3935 } 3987 }
3936 3988
3937 trace "running post_init jobs"; 3989 cf::_post_init 1;
3938 (pop @POST_INIT)->(1) while @POST_INIT;
3939 3990
3940 trace "leaving sync_job"; 3991 trace "perl_reload: leaving sync_job";
3941 3992
3942 1 3993 1
3943 } or do { 3994 } or do {
3944 error $@; 3995 error $@;
3945 cf::cleanup "error while reloading, exiting."; 3996 cf::cleanup "perl_reload: error, exiting.";
3946 }; 3997 };
3947 3998
3948 info "reloaded";
3949 --$RELOAD; 3999 --$RELOAD;
3950 } 4000 }
3951 4001
3952 $t1 = AE::time - $t1; 4002 $t1 = AE::time - $t1;
3953 info "reload completed in ${t1}s\n"; 4003 info "perl_reload: completed in ${t1}s\n";
3954}; 4004};
3955 4005
3956our $RELOAD_WATCHER; # used only during reload 4006our $RELOAD_WATCHER; # used only during reload
3957 4007
3958sub reload_perl() { 4008sub reload_perl() {
3979 reload_perl; 4029 reload_perl;
3980 }; 4030 };
3981 } 4031 }
3982}; 4032};
3983 4033
3984unshift @INC, $LIBDIR; 4034#############################################################################
3985 4035
3986my $bug_warning = 0; 4036my $bug_warning = 0;
3987 4037
3988our @WAIT_FOR_TICK; 4038our @WAIT_FOR_TICK;
3989our @WAIT_FOR_TICK_BEGIN; 4039our @WAIT_FOR_TICK_BEGIN;
3990 4040
3991sub wait_for_tick { 4041sub wait_for_tick() {
3992 return Coro::cede if tick_inhibit || $Coro::current == $Coro::main; 4042 return Coro::cede if tick_inhibit || $Coro::current == $Coro::main;
3993 4043
3994 my $signal = new Coro::Signal; 4044 my $signal = new Coro::Signal;
3995 push @WAIT_FOR_TICK, $signal; 4045 push @WAIT_FOR_TICK, $signal;
3996 $signal->wait; 4046 $signal->wait;
3997} 4047}
3998 4048
3999sub wait_for_tick_begin { 4049sub wait_for_tick_begin() {
4000 return Coro::cede if tick_inhibit || $Coro::current == $Coro::main; 4050 return Coro::cede if tick_inhibit || $Coro::current == $Coro::main;
4001 4051
4002 my $signal = new Coro::Signal; 4052 my $signal = new Coro::Signal;
4003 push @WAIT_FOR_TICK_BEGIN, $signal; 4053 push @WAIT_FOR_TICK_BEGIN, $signal;
4004 $signal->wait; 4054 $signal->wait;
4056 $DB_ENV->set_flags (&BDB::LOG_AUTOREMOVE ) if BDB::VERSION v0, v4.7; 4106 $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; 4107 $DB_ENV->log_set_config (&BDB::LOG_AUTO_REMOVE) if BDB::VERSION v4.7;
4058 $DB_ENV->set_timeout (30, BDB::SET_TXN_TIMEOUT); 4108 $DB_ENV->set_timeout (30, BDB::SET_TXN_TIMEOUT);
4059 $DB_ENV->set_timeout (30, BDB::SET_LOCK_TIMEOUT); 4109 $DB_ENV->set_timeout (30, BDB::SET_LOCK_TIMEOUT);
4060 4110
4061 (Coro::async { # async to keep sync_job from complaining
4062 cf::sync_job { 4111 cf::sync_job {
4063 eval { 4112 eval {
4064 BDB::db_env_open 4113 BDB::db_env_open
4065 $DB_ENV, 4114 $DB_ENV,
4066 $BDBDIR, 4115 $BDBDIR,
4067 BDB::INIT_LOCK | BDB::INIT_LOG | BDB::INIT_MPOOL | BDB::INIT_TXN 4116 BDB::INIT_LOCK | BDB::INIT_LOG | BDB::INIT_MPOOL | BDB::INIT_TXN
4068 | BDB::RECOVER | BDB::REGISTER | BDB::USE_ENVIRON | BDB::CREATE, 4117 | BDB::RECOVER | BDB::REGISTER | BDB::USE_ENVIRON | BDB::CREATE,
4069 0666; 4118 0666;
4070 4119
4071 cf::cleanup "db_env_open($BDBDIR): $!" if $!; 4120 cf::cleanup "db_env_open($BDBDIR): $!" if $!;
4072 };
4073
4074 cf::cleanup "db_env_open(db): $@" if $@;
4075 }; 4121 };
4076 })->join; 4122
4123 cf::cleanup "db_env_open(db): $@" if $@;
4124 };
4077 } 4125 }
4078 4126
4079 $BDB_DEADLOCK_WATCHER = EV::periodic 0, 3, 0, sub { 4127 $BDB_DEADLOCK_WATCHER = EV::periodic 0, 3, 0, sub {
4080 BDB::db_env_lock_detect $DB_ENV, 0, BDB::LOCK_DEFAULT, 0, sub { }; 4128 BDB::db_env_lock_detect $DB_ENV, 0, BDB::LOCK_DEFAULT, 0, sub { };
4081 }; 4129 };
4093 IO::AIO::min_parallel 8; 4141 IO::AIO::min_parallel 8;
4094 IO::AIO::max_poll_time $TICK * 0.1; 4142 IO::AIO::max_poll_time $TICK * 0.1;
4095 undef $AnyEvent::AIO::WATCHER; 4143 undef $AnyEvent::AIO::WATCHER;
4096} 4144}
4097 4145
4098my $_log_backtrace; 4146our $_log_backtrace;
4147our $_log_backtrace_last;
4099 4148
4100sub _log_backtrace { 4149sub _log_backtrace {
4101 my ($msg, @addr) = @_; 4150 my ($msg, @addr) = @_;
4102 4151
4103 $msg =~ s/\n//; 4152 $msg =~ s/\n$//;
4104 4153
4154 if ($_log_backtrace_last eq $msg) {
4155 LOG llevInfo, "[ABT] $msg\n";
4156 LOG llevInfo, "[ABT] [duplicate, suppressed]\n";
4105 # limit the # of concurrent backtraces 4157 # limit the # of concurrent backtraces
4106 if ($_log_backtrace < 2) { 4158 } elsif ($_log_backtrace < 2) {
4159 $_log_backtrace_last = $msg;
4107 ++$_log_backtrace; 4160 ++$_log_backtrace;
4108 my $perl_bt = Carp::longmess $msg; 4161 my $perl_bt = Carp::longmess $msg;
4109 async { 4162 async {
4110 $Coro::current->{desc} = "abt $msg"; 4163 $Coro::current->{desc} = "abt $msg";
4111 4164
4131 LOG llevInfo, "[ABT] $_\n" for @bt; 4184 LOG llevInfo, "[ABT] $_\n" for @bt;
4132 --$_log_backtrace; 4185 --$_log_backtrace;
4133 }; 4186 };
4134 } else { 4187 } else {
4135 LOG llevInfo, "[ABT] $msg\n"; 4188 LOG llevInfo, "[ABT] $msg\n";
4136 LOG llevInfo, "[ABT] [suppressed]\n"; 4189 LOG llevInfo, "[ABT] [overload, suppressed]\n";
4137 } 4190 }
4138} 4191}
4139 4192
4140# load additional modules 4193# load additional modules
4141require "cf/$_.pm" for @EXTRA_MODULES; 4194require "cf/$_.pm" for @EXTRA_MODULES;

Diff Legend

Removed lines
+ Added lines
< Changed lines
> Changed lines