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.443 by root, Sun Aug 31 10:05:26 2008 UTC vs.
Revision 1.458 by root, Sat Dec 13 20:34:37 2008 UTC

32use Opcode; 32use Opcode;
33use Safe; 33use Safe;
34use Safe::Hole; 34use Safe::Hole;
35use Storable (); 35use Storable ();
36 36
37use Guard ();
37use Coro (); 38use Coro ();
38use Coro::State; 39use Coro::State;
39use Coro::Handle; 40use Coro::Handle;
40use Coro::EV; 41use Coro::EV;
41use Coro::AnyEvent; 42use Coro::AnyEvent;
63 64
64# configure various modules to our taste 65# configure various modules to our taste
65# 66#
66$Storable::canonical = 1; # reduce rsync transfers 67$Storable::canonical = 1; # reduce rsync transfers
67Coro::State::cctx_stacksize 256000; # 1-2MB stack, for deep recursions in maze generator 68Coro::State::cctx_stacksize 256000; # 1-2MB stack, for deep recursions in maze generator
69
70$Coro::main->prio (Coro::PRIO_MAX); # run main coroutine ("the server") with very high priority
71
72# make sure c-lzf reinitialises itself
73Compress::LZF::set_serializer "Storable", "Storable::net_mstore", "Storable::mretrieve";
68Compress::LZF::sfreeze_cr { }; # prime Compress::LZF so it does not use require later 74Compress::LZF::sfreeze_cr { }; # prime Compress::LZF so it does not use require later
69
70$Coro::main->prio (Coro::PRIO_MAX); # run main coroutine ("the server") with very high priority
71 75
72sub WF_AUTOCANCEL () { 1 } # automatically cancel this watcher on reload 76sub WF_AUTOCANCEL () { 1 } # automatically cancel this watcher on reload
73 77
74our %COMMAND = (); 78our %COMMAND = ();
75our %COMMAND_TIME = (); 79our %COMMAND_TIME = ();
78our %EXTCMD = (); 82our %EXTCMD = ();
79our %EXTICMD = (); 83our %EXTICMD = ();
80our %EXT_CORO = (); # coroutines bound to extensions 84our %EXT_CORO = (); # coroutines bound to extensions
81our %EXT_MAP = (); # pluggable maps 85our %EXT_MAP = (); # pluggable maps
82 86
83our $RELOAD; # number of reloads so far 87our $RELOAD; # number of reloads so far, non-zero while in reload
84our @EVENT; 88our @EVENT;
85 89
86our $CONFDIR = confdir; 90our $CONFDIR = confdir;
87our $DATADIR = datadir; 91our $DATADIR = datadir;
88our $LIBDIR = "$DATADIR/ext"; 92our $LIBDIR = "$DATADIR/ext";
89our $PODDIR = "$DATADIR/pod"; 93our $PODDIR = "$DATADIR/pod";
90our $MAPDIR = "$DATADIR/" . mapdir; 94our $MAPDIR = "$DATADIR/" . mapdir;
91our $LOCALDIR = localdir; 95our $LOCALDIR = localdir;
92our $TMPDIR = "$LOCALDIR/" . tmpdir; 96our $TMPDIR = "$LOCALDIR/" . tmpdir;
93our $UNIQUEDIR = "$LOCALDIR/" . uniquedir; 97our $UNIQUEDIR = "$LOCALDIR/" . uniquedir;
94our $PLAYERDIR = "$LOCALDIR/" . playerdir; 98our $PLAYERDIR = "$LOCALDIR/" . playerdir;
95our $RANDOMDIR = "$LOCALDIR/random"; 99our $RANDOMDIR = "$LOCALDIR/random";
96our $BDBDIR = "$LOCALDIR/db"; 100our $BDBDIR = "$LOCALDIR/db";
101our $PIDFILE = "$LOCALDIR/pid";
102our $RUNTIMEFILE = "$LOCALDIR/runtime";
103
97our %RESOURCE; 104our %RESOURCE;
98 105
99our $TICK = MAX_TIME * 1e-6; # this is a CONSTANT(!) 106our $TICK = MAX_TIME * 1e-6; # this is a CONSTANT(!)
100our $NEXT_RUNTIME_WRITE; # when should the runtime file be written 107our $NEXT_RUNTIME_WRITE; # when should the runtime file be written
101our $NEXT_TICK; 108our $NEXT_TICK;
122our $LOAD; # a number between 0 (idle) and 1 (too many objects) 129our $LOAD; # a number between 0 (idle) and 1 (too many objects)
123our $LOADAVG; # same thing, but with alpha-smoothing 130our $LOADAVG; # same thing, but with alpha-smoothing
124our $JITTER; # average jitter 131our $JITTER; # average jitter
125our $TICK_START; # for load detecting purposes 132our $TICK_START; # for load detecting purposes
126 133
134our @POST_INIT;
135
136our $REATTACH_ON_RELOAD; # ste to true to force object reattach on reload (slow)
137
127binmode STDOUT; 138binmode STDOUT;
128binmode STDERR; 139binmode STDERR;
129 140
130# read virtual server time, if available 141# read virtual server time, if available
131unless ($RUNTIME || !-e "$LOCALDIR/runtime") { 142unless ($RUNTIME || !-e $RUNTIMEFILE) {
132 open my $fh, "<", "$LOCALDIR/runtime" 143 open my $fh, "<", $RUNTIMEFILE
133 or die "unable to read runtime file: $!"; 144 or die "unable to read $RUNTIMEFILE file: $!";
134 $RUNTIME = <$fh> + 0.; 145 $RUNTIME = <$fh> + 0.;
135} 146}
136 147
137mkdir $_ 148mkdir $_
138 for $LOCALDIR, $TMPDIR, $UNIQUEDIR, $PLAYERDIR, $RANDOMDIR, $BDBDIR; 149 for $LOCALDIR, $TMPDIR, $UNIQUEDIR, $PLAYERDIR, $RANDOMDIR, $BDBDIR;
299our $json_coder = JSON::XS->new->utf8->max_size (1e6); # accept ~1mb max 310our $json_coder = JSON::XS->new->utf8->max_size (1e6); # accept ~1mb max
300 311
301sub encode_json($) { $json_coder->encode ($_[0]) } 312sub encode_json($) { $json_coder->encode ($_[0]) }
302sub decode_json($) { $json_coder->decode ($_[0]) } 313sub decode_json($) { $json_coder->decode ($_[0]) }
303 314
315=item cf::post_init { BLOCK }
316
317Execute the given codeblock, I<after> all extensions have been (re-)loaded,
318but I<before> the server starts ticking again.
319
320The cdoeblock will have a single boolean argument to indicate whether this
321is a reload or not.
322
323=cut
324
325sub post_init(&) {
326 push @POST_INIT, shift;
327}
328
304=item cf::lock_wait $string 329=item cf::lock_wait $string
305 330
306Wait until the given lock is available. See cf::lock_acquire. 331Wait until the given lock is available. See cf::lock_acquire.
307 332
308=item my $lock = cf::lock_acquire $string 333=item my $lock = cf::lock_acquire $string
309 334
310Wait until the given lock is available and then acquires it and returns 335Wait until the given lock is available and then acquires it and returns
311a Coro::guard object. If the guard object gets destroyed (goes out of scope, 336a L<Guard> object. If the guard object gets destroyed (goes out of scope,
312for example when the coroutine gets canceled), the lock is automatically 337for example when the coroutine gets canceled), the lock is automatically
313returned. 338returned.
314 339
315Locks are *not* recursive, locking from the same coro twice results in a 340Locks are *not* recursive, locking from the same coro twice results in a
316deadlocked coro. 341deadlocked coro.
335 return;#d# 360 return;#d#
336 }#d# 361 }#d#
337 362
338 # wait for lock, if any 363 # wait for lock, if any
339 while ($LOCK{$key}) { 364 while ($LOCK{$key}) {
365 #local $Coro::current->{desc} = "$Coro::current->{desc} <waiting for lock $key>";
340 push @{ $LOCK{$key} }, $Coro::current; 366 push @{ $LOCK{$key} }, $Coro::current;
341 Coro::schedule; 367 Coro::schedule;
342 } 368 }
343} 369}
344 370
349 lock_wait $key; 375 lock_wait $key;
350 376
351 $LOCK{$key} = []; 377 $LOCK{$key} = [];
352 $LOCKER{$key} = $Coro::current;#d# 378 $LOCKER{$key} = $Coro::current;#d#
353 379
354 Coro::guard { 380 Guard::guard {
355 delete $LOCKER{$key};#d# 381 delete $LOCKER{$key};#d#
356 # wake up all waiters, to be on the safe side 382 # wake up all waiters, to be on the safe side
357 $_->ready for @{ delete $LOCK{$key} }; 383 $_->ready for @{ delete $LOCK{$key} };
358 } 384 }
359} 385}
365} 391}
366 392
367sub freeze_mainloop { 393sub freeze_mainloop {
368 tick_inhibit_inc; 394 tick_inhibit_inc;
369 395
370 Coro::guard \&tick_inhibit_dec; 396 &Guard::guard (\&tick_inhibit_dec);
371} 397}
372 398
373=item cf::periodic $interval, $cb 399=item cf::periodic $interval, $cb
374 400
375Like EV::periodic, but randomly selects a starting point so that the actions 401Like EV::periodic, but randomly selects a starting point so that the actions
727 753
728############################################################################# 754#############################################################################
729 755
730=head2 ATTACHABLE OBJECTS 756=head2 ATTACHABLE OBJECTS
731 757
732Many objects in crossfire are so-called attachable objects. That means you can 758Many objects in deliantra are so-called attachable objects. That means you can
733attach callbacks/event handlers (a collection of which is called an "attachment") 759attach callbacks/event handlers (a collection of which is called an "attachment")
734to it. All such attachable objects support the following methods. 760to it. All such attachable objects support the following methods.
735 761
736In the following description, CLASS can be any of C<global>, C<object> 762In the following description, CLASS can be any of C<global>, C<object>
737C<player>, C<client> or C<map> (i.e. the attachable objects in 763C<player>, C<client> or C<map> (i.e. the attachable objects in
787=item cf::CLASS::attachment $name, ... 813=item cf::CLASS::attachment $name, ...
788 814
789Register an attachment by C<$name> through which attachable objects of the 815Register an attachment by C<$name> through which attachable objects of the
790given CLASS can refer to this attachment. 816given CLASS can refer to this attachment.
791 817
792Some classes such as crossfire maps and objects can specify attachments 818Some classes such as deliantra maps and objects can specify attachments
793that are attached at load/instantiate time, thus the need for a name. 819that are attached at load/instantiate time, thus the need for a name.
794 820
795These calls expect any number of the following handler/hook descriptions: 821These calls expect any number of the following handler/hook descriptions:
796 822
797=over 4 823=over 4
1164 } else { 1190 } else {
1165 aio_unlink "$filename.pst"; 1191 aio_unlink "$filename.pst";
1166 } 1192 }
1167 1193
1168 aio_rename "$filename~", $filename; 1194 aio_rename "$filename~", $filename;
1195
1196 $filename =~ s%/[^/]+$%%;
1197 aio_pathsync $filename if $cf::USE_FSYNC;
1169 } else { 1198 } else {
1170 warn "FATAL: $filename~: $!\n"; 1199 warn "FATAL: $filename~: $!\n";
1171 } 1200 }
1172 } else { 1201 } else {
1173 aio_unlink $filename; 1202 aio_unlink $filename;
1266 my ($name, $cb) = @_; 1295 my ($name, $cb) = @_;
1267 1296
1268 $EXTICMD{$name} = $cb; 1297 $EXTICMD{$name} = $cb;
1269} 1298}
1270 1299
1300use File::Glob ();
1301
1271cf::player->attach ( 1302cf::player->attach (
1272 on_command => sub { 1303 on_command => sub {
1273 my ($pl, $name, $params) = @_; 1304 my ($pl, $name, $params) = @_;
1274 1305
1275 my $cb = $COMMAND{$name} 1306 my $cb = $COMMAND{$name}
1306 } 1337 }
1307 1338
1308 cf::override; 1339 cf::override;
1309 }, 1340 },
1310); 1341);
1342
1343# "readahead" all extensions
1344sub cache_extensions {
1345 my $grp = IO::AIO::aio_group;
1346
1347 add $grp IO::AIO::aio_readdir $LIBDIR, sub {
1348 for (grep /\.ext$/, @{$_[0]}) {
1349 add $grp IO::AIO::aio_load "$LIBDIR/$_", my $data;
1350 }
1351 };
1352
1353 $grp
1354}
1311 1355
1312sub load_extensions { 1356sub load_extensions {
1313 cf::sync_job { 1357 cf::sync_job {
1314 my %todo; 1358 my %todo;
1315 1359
1385 1429
1386=back 1430=back
1387 1431
1388=head2 CORE EXTENSIONS 1432=head2 CORE EXTENSIONS
1389 1433
1390Functions and methods that extend core crossfire objects. 1434Functions and methods that extend core deliantra objects.
1391 1435
1392=cut 1436=cut
1393 1437
1394package cf::player; 1438package cf::player;
1395 1439
1438 1482
1439sub exists($) { 1483sub exists($) {
1440 my ($login) = @_; 1484 my ($login) = @_;
1441 1485
1442 $cf::PLAYER{$login} 1486 $cf::PLAYER{$login}
1443 or cf::sync_job { !aio_stat path $login } 1487 or !aio_stat path $login
1444} 1488}
1445 1489
1446sub find($) { 1490sub find($) {
1447 return $cf::PLAYER{$_[0]} || do { 1491 return $cf::PLAYER{$_[0]} || do {
1448 my $login = $_[0]; 1492 my $login = $_[0];
1619 } 1663 }
1620 1664
1621 \@paths 1665 \@paths
1622} 1666}
1623 1667
1624=item $protocol_xml = $player->expand_cfpod ($crossfire_pod) 1668=item $protocol_xml = $player->expand_cfpod ($cfpod)
1625 1669
1626Expand crossfire pod fragments into protocol xml. 1670Expand deliantra pod fragments into protocol xml.
1627
1628=cut
1629
1630sub expand_cfpod {
1631 my ($self, $pod) = @_;
1632
1633 my @nest = [qr<\G$>, undef, ""];
1634 my $xml;
1635
1636 for ($pod) {
1637 while () {
1638 if (/\G( (?: [^BCEGHITUZ&>\n\ ]+ | [BCEGHITUZ](?!<) | \ (?!>) )+ )/xgcs) {
1639 $xml .= $1;
1640 } elsif (/\G\n(?=\S)/xgcs) {
1641 $xml .= " ";
1642 } elsif (/\G\n/xgcs) {
1643 $xml .= "\n";
1644 } elsif (/\G ([BCEGHITUZ]) (< (?: <+\ | (?!<) ) )/xgcs) {
1645 my ($code, $delim) = ($1, scalar reverse $2);
1646 $delim =~ y/</>/; # delim now contains the stop sequence
1647 $delim = qr{\G\Q$delim};
1648
1649 my $cb;
1650
1651 if ($code eq "B") {
1652 $cb = sub { "<b>$_[0]</b>" };
1653 } elsif ($code eq "C") {
1654 $cb = sub { "<tt>$_[0]</tt>" };
1655 } elsif ($code eq "E") {
1656 $cb = sub { warn "E<$_[0]>\n";"&$_[0];" };
1657 } elsif ($code eq "G") {
1658 $cb = sub {
1659 my ($male, $female) = split /\|/, $_[0];
1660 $self->gender ? $female : $male
1661 };
1662 } elsif ($code eq "H") {
1663 $cb = sub {
1664 (
1665 "<fg name=\"lightblue\">[$_[0] (Use hintmode to suppress hints)]</fg>",
1666 "<fg name=\"lightblue\">[Hint suppressed, see hintmode]</fg>",
1667 "",
1668 )[$self->{hintmode}];
1669 };
1670 } elsif ($code eq "I") {
1671 $cb = sub { "<i>$_[0]</i>" };
1672 } elsif ($code eq "T") {
1673 $cb = sub { "<big><b>$_[0]</b></big>" };
1674 } elsif ($code eq "U") {
1675 $cb = sub { "<u>$_[0]</u>" };
1676 } elsif ($code eq "Z") {
1677 $cb = sub { };
1678 } else {
1679 die "FATAL error in expand_cfpod";
1680 }
1681
1682 push @nest, [$delim, $cb, $xml];
1683 undef $xml;
1684
1685 } elsif ($_ =~ /$nest[-1][0]/gcs) {
1686 my $nest = pop @nest;
1687
1688 if ($nest->[1]) {
1689 $xml = $nest->[2] . $nest->[1]->($xml);
1690 } else {
1691 last;
1692 }
1693 } elsif (/\G</xgcs) {
1694 $xml .= "&lt;";
1695 } elsif (/\G&/xgcs) {
1696 $xml .= "&amp;";
1697 } elsif (/\G>/xgcs) {
1698 $xml .= ">";
1699 } else {
1700 if ($pod =~ /\G(.+)/xgcs) {
1701 warn "parse error (at $1)($nest[-1][0]) while expanding cfpod:\n$pod";
1702 last;
1703 } else {
1704 warn "parse error (unclosed interior sequence at end of cfpod) while expanding cfpod:\n$pod";
1705 return "<b>Sorry, the server encountered an internal error when formatting this message, please report this.</b>";
1706 }
1707 }
1708 }
1709 }
1710
1711 $xml
1712}
1713
1714sub hintmode {
1715 $_[0]{hintmode} = $_[1] if @_ > 1;
1716 $_[0]{hintmode}
1717}
1718 1671
1719=item $player->ext_reply ($msgid, @msg) 1672=item $player->ext_reply ($msgid, @msg)
1720 1673
1721Sends an ext reply to the player. 1674Sends an ext reply to the player.
1722 1675
2536 2489
2537=item $player_object->enter_link 2490=item $player_object->enter_link
2538 2491
2539Freezes the player and moves him/her to a special map (C<{link}>). 2492Freezes the player and moves him/her to a special map (C<{link}>).
2540 2493
2541The player should be reasonably safe there for short amounts of time. You 2494The player should be reasonably safe there for short amounts of time (e.g.
2542I<MUST> call C<leave_link> as soon as possible, though. 2495for loading a map). You I<MUST> call C<leave_link> as soon as possible,
2496though, as the palyer cannot control the character while it is on the link
2497map.
2543 2498
2544Will never block. 2499Will never block.
2545 2500
2546=item $player_object->leave_link ($map, $x, $y) 2501=item $player_object->leave_link ($map, $x, $y)
2547 2502
2605 2560
2606 $map->load; 2561 $map->load;
2607 $map->load_neighbours; 2562 $map->load_neighbours;
2608 2563
2609 return unless $self->contr->active; 2564 return unless $self->contr->active;
2565 $self->flag (cf::FLAG_DEBUG, 0);#d# temp
2610 $self->activate_recursive; 2566 $self->activate_recursive;
2611 2567
2612 local $self->{_prev_pos} = $link_pos; # ugly hack for rent.ext 2568 local $self->{_prev_pos} = $link_pos; # ugly hack for rent.ext
2613 $self->enter_map ($map, $x, $y); 2569 $self->enter_map ($map, $x, $y);
2614} 2570}
2777 $self->contr->savebed ($map, $x, $y) 2733 $self->contr->savebed ($map, $x, $y)
2778 if $exit->flag (cf::FLAG_DAMNED); 2734 if $exit->flag (cf::FLAG_DAMNED);
2779 2735
2780 1 2736 1
2781 }) { 2737 }) {
2782 $self->message ("Something went wrong deep within the crossfire server. " 2738 $self->message ("Something went wrong deep within the deliantra server. "
2783 . "I'll try to bring you back to the map you were before. " 2739 . "I'll try to bring you back to the map you were before. "
2784 . "Please report this to the dungeon master!", 2740 . "Please report this to the dungeon master!",
2785 cf::NDI_UNIQUE | cf::NDI_RED); 2741 cf::NDI_UNIQUE | cf::NDI_RED);
2786 2742
2787 warn "ERROR in enter_exit: $@"; 2743 warn "ERROR in enter_exit: $@";
2853 id => "infobox", 2809 id => "infobox",
2854 title => "Body Parts", 2810 title => "Body Parts",
2855 reply => undef, 2811 reply => undef,
2856 tooltip => "Shows which body parts you posess and are available", 2812 tooltip => "Shows which body parts you posess and are available",
2857 }, 2813 },
2814 "c/skills" => {
2815 id => "infobox",
2816 title => "Skills",
2817 reply => undef,
2818 tooltip => "Shows your experience per skill and item power",
2819 },
2858 "c/uptime" => { 2820 "c/uptime" => {
2859 id => "infobox", 2821 id => "infobox",
2860 title => "Uptime", 2822 title => "Uptime",
2861 reply => undef, 2823 reply => undef,
2862 tooltip => "How long the server has been running since last restart", 2824 tooltip => "How long the server has been running since last restart",
2876); 2838);
2877 2839
2878sub cf::client::send_msg { 2840sub cf::client::send_msg {
2879 my ($self, $channel, $msg, $color, @extra) = @_; 2841 my ($self, $channel, $msg, $color, @extra) = @_;
2880 2842
2881 $msg = $self->pl->expand_cfpod ($msg); 2843 $msg = $self->pl->expand_cfpod ($msg)
2844 unless $color & cf::NDI_VERBATIM;
2882 2845
2883 $color &= cf::NDI_CLIENT_MASK; # just in case... 2846 $color &= cf::NDI_CLIENT_MASK; # just in case...
2884 2847
2885 # check predefined channels, for the benefit of C 2848 # check predefined channels, for the benefit of C
2886 if ($CHANNEL{$channel}) { 2849 if ($CHANNEL{$channel}) {
3415 reload_treasures; 3378 reload_treasures;
3416 3379
3417 warn "finished reloading resource files\n"; 3380 warn "finished reloading resource files\n";
3418} 3381}
3419 3382
3420sub init {
3421 my $guard = freeze_mainloop;
3422
3423 evthread_start IO::AIO::poll_fileno;
3424
3425 reload_resources;
3426}
3427
3428sub reload_config { 3383sub reload_config {
3429 open my $fh, "<:utf8", "$CONFDIR/config" 3384 open my $fh, "<:utf8", "$CONFDIR/config"
3430 or return; 3385 or return;
3431 3386
3432 local $/; 3387 local $/;
3444 }; 3399 };
3445 warn $@ if $@; 3400 warn $@ if $@;
3446 } 3401 }
3447} 3402}
3448 3403
3404sub pidfile() {
3405 sysopen my $fh, $PIDFILE, O_RDWR | O_CREAT
3406 or die "$PIDFILE: $!";
3407 flock $fh, &Fcntl::LOCK_EX
3408 or die "$PIDFILE: flock: $!";
3409 $fh
3410}
3411
3412# make sure only one server instance is running at any one time
3413sub atomic {
3414 my $fh = pidfile;
3415
3416 my $pid = <$fh>;
3417 kill 9, $pid if $pid > 0;
3418
3419 seek $fh, 0, 0;
3420 print $fh $$;
3421}
3422
3449sub main { 3423sub main {
3424 cf::init_globals; # initialise logging
3425
3426 LOG llevInfo, "Welcome to Deliantra, v" . VERSION;
3427 LOG llevInfo, "Copyright (C) 2005-2008 Marc Alexander Lehmann / Robin Redeker / the Deliantra team.";
3428 LOG llevInfo, "Copyright (C) 1994 Mark Wedel.";
3429 LOG llevInfo, "Copyright (C) 1992 Frank Tore Johansen.";
3430
3431 cf::init_experience;
3432 cf::init_anim;
3433 cf::init_attackmess;
3434 cf::init_dynamic;
3435 cf::init_block;
3436
3437 $Coro::current->prio (Coro::PRIO_MAX); # give the main loop max. priority
3438
3450 # we must not ever block the main coroutine 3439 # we must not ever block the main coroutine
3451 local $Coro::idle = sub { 3440 local $Coro::idle = sub {
3452 Carp::cluck "FATAL: Coro::idle was called, major BUG, use cf::sync_job!\n";#d# 3441 Carp::cluck "FATAL: Coro::idle was called, major BUG, use cf::sync_job!\n";#d#
3453 (async { 3442 (async {
3454 $Coro::current->{desc} = "IDLE BUG HANDLER"; 3443 $Coro::current->{desc} = "IDLE BUG HANDLER";
3455 EV::loop EV::LOOP_ONESHOT; 3444 EV::loop EV::LOOP_ONESHOT;
3456 })->prio (Coro::PRIO_MAX); 3445 })->prio (Coro::PRIO_MAX);
3457 }; 3446 };
3458 3447
3459 { 3448 evthread_start IO::AIO::poll_fileno;
3460 my $guard = freeze_mainloop; 3449
3450 cf::sync_job {
3451 reload_resources;
3461 reload_config; 3452 reload_config;
3462 db_init; 3453 db_init;
3454
3455 cf::load_settings;
3456 cf::load_materials;
3457 cf::init_uuid;
3458 cf::init_signals;
3459 cf::init_commands;
3460 cf::init_skills;
3461
3462 cf::init_beforeplay;
3463
3464 atomic;
3465
3463 load_extensions; 3466 load_extensions;
3464 3467
3465 $Coro::current->prio (Coro::PRIO_MAX); # give the main loop max. priority 3468 utime time, time, $RUNTIMEFILE;
3469
3470 # no (long-running) fork's whatsoever before this point(!)
3471 POSIX::close delete $ENV{LOCKUTIL_LOCK_FD} if exists $ENV{LOCKUTIL_LOCK_FD};
3472
3473 (pop @POST_INIT)->(0) while @POST_INIT;
3466 } 3474 };
3467 3475
3468 EV::loop; 3476 EV::loop;
3469} 3477}
3470 3478
3471############################################################################# 3479#############################################################################
3480 }; 3488 };
3481 } 3489 }
3482} 3490}
3483 3491
3484sub write_runtime_sync { 3492sub write_runtime_sync {
3485 my $runtime = "$LOCALDIR/runtime";
3486
3487 # first touch the runtime file to show we are still running: 3493 # first touch the runtime file to show we are still running:
3488 # the fsync below can take a very very long time. 3494 # the fsync below can take a very very long time.
3489 3495
3490 IO::AIO::aio_utime $runtime, undef, undef; 3496 IO::AIO::aio_utime $RUNTIMEFILE, undef, undef;
3491 3497
3492 my $guard = cf::lock_acquire "write_runtime"; 3498 my $guard = cf::lock_acquire "write_runtime";
3493 3499
3494 my $fh = aio_open "$runtime~", O_WRONLY | O_CREAT, 0644 3500 my $fh = aio_open "$RUNTIMEFILE~", O_WRONLY | O_CREAT, 0644
3495 or return; 3501 or return;
3496 3502
3497 my $value = $cf::RUNTIME + 90 + 10; 3503 my $value = $cf::RUNTIME + 90 + 10;
3498 # 10 is the runtime save interval, for a monotonic clock 3504 # 10 is the runtime save interval, for a monotonic clock
3499 # 60 allows for the watchdog to kill the server. 3505 # 60 allows for the watchdog to kill the server.
3509 aio_utime $fh, undef, undef; 3515 aio_utime $fh, undef, undef;
3510 3516
3511 close $fh 3517 close $fh
3512 or return; 3518 or return;
3513 3519
3514 aio_rename "$runtime~", $runtime 3520 aio_rename "$RUNTIMEFILE~", $RUNTIMEFILE
3515 and return; 3521 and return;
3516 3522
3517 warn "runtime file written.\n"; 3523 warn "runtime file written.\n";
3518 3524
3519 1 3525 1
3531 my $uuid = "$LOCALDIR/uuid"; 3537 my $uuid = "$LOCALDIR/uuid";
3532 3538
3533 my $fh = aio_open "$uuid~", O_WRONLY | O_CREAT, 0644 3539 my $fh = aio_open "$uuid~", O_WRONLY | O_CREAT, 0644
3534 or return; 3540 or return;
3535 3541
3536 my $value = uuid_str $uuid_skip + uuid_seq uuid_cur; 3542 my $value = uuid_seq uuid_cur;
3543
3544 unless ($value) {
3545 warn "cowardly refusing to write zero uuid value!\n";
3546 return;
3547 }
3548
3549 my $value = uuid_str $value + $uuid_skip;
3537 $uuid_skip = 0; 3550 $uuid_skip = 0;
3538 3551
3539 (aio_write $fh, 0, (length $value), $value, 0) <= 0 3552 (aio_write $fh, 0, (length $value), $value, 0) <= 0
3540 and return; 3553 and return;
3541 3554
3563} 3576}
3564 3577
3565sub emergency_save() { 3578sub emergency_save() {
3566 my $freeze_guard = cf::freeze_mainloop; 3579 my $freeze_guard = cf::freeze_mainloop;
3567 3580
3568 warn "enter emergency perl save\n"; 3581 warn "emergency_perl_save: enter\n";
3569 3582
3570 cf::sync_job { 3583 cf::sync_job {
3584 # this is a trade-off: we want to be very quick here, so
3585 # save all maps without fsync, and later call a global sync
3586 # (which in turn might be very very slow)
3587 local $USE_FSYNC = 0;
3588
3571 # use a peculiar iteration method to avoid tripping on perl 3589 # use a peculiar iteration method to avoid tripping on perl
3572 # refcount bugs in for. also avoids problems with players 3590 # refcount bugs in for. also avoids problems with players
3573 # and maps saved/destroyed asynchronously. 3591 # and maps saved/destroyed asynchronously.
3574 warn "begin emergency player save\n"; 3592 warn "emergency_perl_save: begin player save\n";
3575 for my $login (keys %cf::PLAYER) { 3593 for my $login (keys %cf::PLAYER) {
3576 my $pl = $cf::PLAYER{$login} or next; 3594 my $pl = $cf::PLAYER{$login} or next;
3577 $pl->valid or next; 3595 $pl->valid or next;
3578 delete $pl->{unclean_save}; # not strictly necessary, but cannot hurt 3596 delete $pl->{unclean_save}; # not strictly necessary, but cannot hurt
3579 $pl->save; 3597 $pl->save;
3580 } 3598 }
3581 warn "end emergency player save\n"; 3599 warn "emergency_perl_save: end player save\n";
3582 3600
3583 warn "begin emergency map save\n"; 3601 warn "emergency_perl_save: begin map save\n";
3584 for my $path (keys %cf::MAP) { 3602 for my $path (keys %cf::MAP) {
3585 my $map = $cf::MAP{$path} or next; 3603 my $map = $cf::MAP{$path} or next;
3586 $map->valid or next; 3604 $map->valid or next;
3587 $map->save; 3605 $map->save;
3588 } 3606 }
3589 warn "end emergency map save\n"; 3607 warn "emergency_perl_save: end map save\n";
3590 3608
3591 warn "begin emergency database checkpoint\n"; 3609 warn "emergency_perl_save: begin database checkpoint\n";
3592 BDB::db_env_txn_checkpoint $DB_ENV; 3610 BDB::db_env_txn_checkpoint $DB_ENV;
3593 warn "end emergency database checkpoint\n"; 3611 warn "emergency_perl_save: end database checkpoint\n";
3594 3612
3595 warn "begin write uuid\n"; 3613 warn "emergency_perl_save: begin write uuid\n";
3596 write_uuid_sync 1; 3614 write_uuid_sync 1;
3597 warn "end write uuid\n"; 3615 warn "emergency_perl_save: end write uuid\n";
3598 }; 3616 };
3599 3617
3618 warn "emergency_perl_save: starting sync()\n";
3619 IO::AIO::aio_sync sub {
3620 warn "emergency_perl_save: finished sync()\n";
3621 };
3622
3600 warn "leave emergency perl save\n"; 3623 warn "emergency_perl_save: leave\n";
3601} 3624}
3602 3625
3603sub post_cleanup { 3626sub post_cleanup {
3604 my ($make_core) = @_; 3627 my ($make_core) = @_;
3605 3628
3606 warn Carp::longmess "post_cleanup backtrace" 3629 warn Carp::longmess "post_cleanup backtrace"
3607 if $make_core; 3630 if $make_core;
3631
3632 my $fh = pidfile;
3633 unlink $PIDFILE if <$fh> == $$;
3608} 3634}
3609 3635
3610# a safer delete_package, copied from Symbol 3636# a safer delete_package, copied from Symbol
3611sub clear_package($) { 3637sub clear_package($) {
3612 my $pkg = shift; 3638 my $pkg = shift;
3628 my $leaf_symtab = *{$stem_symtab->{$leaf}}{HASH}; 3654 my $leaf_symtab = *{$stem_symtab->{$leaf}}{HASH};
3629 for my $name (keys %$leaf_symtab) { 3655 for my $name (keys %$leaf_symtab) {
3630 _gv_clear *{"$pkg$name"}; 3656 _gv_clear *{"$pkg$name"};
3631# use PApp::Util; PApp::Util::sv_dump *{"$pkg$name"}; 3657# use PApp::Util; PApp::Util::sv_dump *{"$pkg$name"};
3632 } 3658 }
3633 warn "cleared package #$pkg\n";#d# 3659 warn "cleared package $pkg\n";#d#
3634} 3660}
3635
3636our $RELOAD; # how many times to reload
3637 3661
3638sub do_reload_perl() { 3662sub do_reload_perl() {
3639 # can/must only be called in main 3663 # can/must only be called in main
3640 if ($Coro::current != $Coro::main) { 3664 if ($Coro::current != $Coro::main) {
3641 warn "can only reload from main coroutine"; 3665 warn "can only reload from main coroutine";
3642 return; 3666 return;
3643 } 3667 }
3644 3668
3645 return if $RELOAD++; 3669 return if $RELOAD++;
3670
3671 my $t1 = EV::time;
3646 3672
3647 while ($RELOAD) { 3673 while ($RELOAD) {
3648 warn "reloading..."; 3674 warn "reloading...";
3649 3675
3650 warn "entering sync_job"; 3676 warn "entering sync_job";
3729 cf::reload_config; 3755 cf::reload_config;
3730 3756
3731 warn "loading extensions"; 3757 warn "loading extensions";
3732 cf::load_extensions; 3758 cf::load_extensions;
3733 3759
3760 if ($REATTACH_ON_RELOAD) {
3734 warn "reattaching attachments to objects/players"; 3761 warn "reattaching attachments to objects/players";
3735 _global_reattach; # objects, sockets 3762 _global_reattach; # objects, sockets
3736 warn "reattaching attachments to maps"; 3763 warn "reattaching attachments to maps";
3737 reattach $_ for values %MAP; 3764 reattach $_ for values %MAP;
3738 warn "reattaching attachments to players"; 3765 warn "reattaching attachments to players";
3739 reattach $_ for values %PLAYER; 3766 reattach $_ for values %PLAYER;
3767 }
3768
3769 warn "running post_init jobs";
3770 (pop @POST_INIT)->(1) while @POST_INIT;
3740 3771
3741 warn "leaving sync_job"; 3772 warn "leaving sync_job";
3742 3773
3743 1 3774 1
3744 } or do { 3775 } or do {
3747 }; 3778 };
3748 3779
3749 warn "reloaded"; 3780 warn "reloaded";
3750 --$RELOAD; 3781 --$RELOAD;
3751 } 3782 }
3783
3784 $t1 = EV::time - $t1;
3785 warn "reload completed in ${t1}s\n";
3752}; 3786};
3753 3787
3754our $RELOAD_WATCHER; # used only during reload 3788our $RELOAD_WATCHER; # used only during reload
3755 3789
3756sub reload_perl() { 3790sub reload_perl() {
3757 # doing reload synchronously and two reloads happen back-to-back, 3791 # doing reload synchronously and two reloads happen back-to-back,
3758 # coro crashes during coro_state_free->destroy here. 3792 # coro crashes during coro_state_free->destroy here.
3759 3793
3794 $RELOAD_WATCHER ||= cf::async {
3795 Coro::AIO::aio_wait cache_extensions;
3796
3760 $RELOAD_WATCHER ||= EV::timer 0, 0, sub { 3797 $RELOAD_WATCHER = EV::timer $TICK * 1.5, 0, sub {
3761 do_reload_perl; 3798 do_reload_perl;
3762 undef $RELOAD_WATCHER; 3799 undef $RELOAD_WATCHER;
3800 };
3763 }; 3801 };
3764} 3802}
3765 3803
3766register_command "reload" => sub { 3804register_command "reload" => sub {
3767 my ($who, $arg) = @_; 3805 my ($who, $arg) = @_;
3893 $msg =~ s/\n//; 3931 $msg =~ s/\n//;
3894 3932
3895 # limit the # of concurrent backtraces 3933 # limit the # of concurrent backtraces
3896 if ($_log_backtrace < 2) { 3934 if ($_log_backtrace < 2) {
3897 ++$_log_backtrace; 3935 ++$_log_backtrace;
3936 my $perl_bt = Carp::longmess $msg;
3898 async { 3937 async {
3899 $Coro::current->{desc} = "abt $msg"; 3938 $Coro::current->{desc} = "abt $msg";
3900 3939
3901 my @bt = fork_call { 3940 my @bt = fork_call {
3902 @addr = map { sprintf "%x", $_ } @addr; 3941 @addr = map { sprintf "%x", $_ } @addr;
3913 } 3952 }
3914 3953
3915 @funcs 3954 @funcs
3916 }; 3955 };
3917 3956
3918 LOG llevInfo, "[ABT] $msg\n"; 3957 LOG llevInfo, "[ABT] $perl_bt\n";
3958 LOG llevInfo, "[ABT] --- C backtrace follows ---\n";
3919 LOG llevInfo, "[ABT] $_\n" for @bt; 3959 LOG llevInfo, "[ABT] $_\n" for @bt;
3920 --$_log_backtrace; 3960 --$_log_backtrace;
3921 }; 3961 };
3922 } else { 3962 } else {
3923 LOG llevInfo, "[ABT] $msg\n"; 3963 LOG llevInfo, "[ABT] $msg\n";

Diff Legend

Removed lines
+ Added lines
< Changed lines
> Changed lines