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.440 by root, Mon Aug 11 23:23:41 2008 UTC vs.
Revision 1.457 by root, Wed Oct 1 05:50:19 2008 UTC

19# The authors can be reached via e-mail to <support@deliantra.net> 19# The authors can be reached via e-mail to <support@deliantra.net>
20# 20#
21 21
22package cf; 22package cf;
23 23
24use 5.10.0;
24use utf8; 25use utf8;
25use strict; 26use strict "vars", "subs";
26 27
27use Symbol; 28use Symbol;
28use List::Util; 29use List::Util;
29use Socket; 30use Socket;
30use EV; 31use EV;
34use Storable (); 35use Storable ();
35 36
36use Coro (); 37use Coro ();
37use Coro::State; 38use Coro::State;
38use Coro::Handle; 39use Coro::Handle;
40use Coro::EV;
39use Coro::AnyEvent; 41use Coro::AnyEvent;
40use Coro::Timer; 42use Coro::Timer;
41use Coro::Signal; 43use Coro::Signal;
42use Coro::Semaphore; 44use Coro::Semaphore;
43use Coro::AnyEvent; 45use Coro::AnyEvent;
61 63
62# configure various modules to our taste 64# configure various modules to our taste
63# 65#
64$Storable::canonical = 1; # reduce rsync transfers 66$Storable::canonical = 1; # reduce rsync transfers
65Coro::State::cctx_stacksize 256000; # 1-2MB stack, for deep recursions in maze generator 67Coro::State::cctx_stacksize 256000; # 1-2MB stack, for deep recursions in maze generator
68
69$Coro::main->prio (Coro::PRIO_MAX); # run main coroutine ("the server") with very high priority
70
71# make sure c-lzf reinitialises itself
72Compress::LZF::set_serializer "Storable", "Storable::net_mstore", "Storable::mretrieve";
66Compress::LZF::sfreeze_cr { }; # prime Compress::LZF so it does not use require later 73Compress::LZF::sfreeze_cr { }; # prime Compress::LZF so it does not use require later
67
68$Coro::main->prio (Coro::PRIO_MAX); # run main coroutine ("the server") with very high priority
69 74
70sub WF_AUTOCANCEL () { 1 } # automatically cancel this watcher on reload 75sub WF_AUTOCANCEL () { 1 } # automatically cancel this watcher on reload
71 76
72our %COMMAND = (); 77our %COMMAND = ();
73our %COMMAND_TIME = (); 78our %COMMAND_TIME = ();
76our %EXTCMD = (); 81our %EXTCMD = ();
77our %EXTICMD = (); 82our %EXTICMD = ();
78our %EXT_CORO = (); # coroutines bound to extensions 83our %EXT_CORO = (); # coroutines bound to extensions
79our %EXT_MAP = (); # pluggable maps 84our %EXT_MAP = (); # pluggable maps
80 85
81our $RELOAD; # number of reloads so far 86our $RELOAD; # number of reloads so far, non-zero while in reload
82our @EVENT; 87our @EVENT;
83 88
84our $CONFDIR = confdir; 89our $CONFDIR = confdir;
85our $DATADIR = datadir; 90our $DATADIR = datadir;
86our $LIBDIR = "$DATADIR/ext"; 91our $LIBDIR = "$DATADIR/ext";
87our $PODDIR = "$DATADIR/pod"; 92our $PODDIR = "$DATADIR/pod";
88our $MAPDIR = "$DATADIR/" . mapdir; 93our $MAPDIR = "$DATADIR/" . mapdir;
89our $LOCALDIR = localdir; 94our $LOCALDIR = localdir;
90our $TMPDIR = "$LOCALDIR/" . tmpdir; 95our $TMPDIR = "$LOCALDIR/" . tmpdir;
91our $UNIQUEDIR = "$LOCALDIR/" . uniquedir; 96our $UNIQUEDIR = "$LOCALDIR/" . uniquedir;
92our $PLAYERDIR = "$LOCALDIR/" . playerdir; 97our $PLAYERDIR = "$LOCALDIR/" . playerdir;
93our $RANDOMDIR = "$LOCALDIR/random"; 98our $RANDOMDIR = "$LOCALDIR/random";
94our $BDBDIR = "$LOCALDIR/db"; 99our $BDBDIR = "$LOCALDIR/db";
100our $PIDFILE = "$LOCALDIR/pid";
101our $RUNTIMEFILE = "$LOCALDIR/runtime";
102
95our %RESOURCE; 103our %RESOURCE;
96 104
97our $TICK = MAX_TIME * 1e-6; # this is a CONSTANT(!) 105our $TICK = MAX_TIME * 1e-6; # this is a CONSTANT(!)
98our $NEXT_RUNTIME_WRITE; # when should the runtime file be written 106our $NEXT_RUNTIME_WRITE; # when should the runtime file be written
99our $NEXT_TICK; 107our $NEXT_TICK;
120our $LOAD; # a number between 0 (idle) and 1 (too many objects) 128our $LOAD; # a number between 0 (idle) and 1 (too many objects)
121our $LOADAVG; # same thing, but with alpha-smoothing 129our $LOADAVG; # same thing, but with alpha-smoothing
122our $JITTER; # average jitter 130our $JITTER; # average jitter
123our $TICK_START; # for load detecting purposes 131our $TICK_START; # for load detecting purposes
124 132
133our @POST_INIT;
134
135our $REATTACH_ON_RELOAD; # ste to true to force object reattach on reload (slow)
136
125binmode STDOUT; 137binmode STDOUT;
126binmode STDERR; 138binmode STDERR;
127 139
128# read virtual server time, if available 140# read virtual server time, if available
129unless ($RUNTIME || !-e "$LOCALDIR/runtime") { 141unless ($RUNTIME || !-e $RUNTIMEFILE) {
130 open my $fh, "<", "$LOCALDIR/runtime" 142 open my $fh, "<", $RUNTIMEFILE
131 or die "unable to read runtime file: $!"; 143 or die "unable to read $RUNTIMEFILE file: $!";
132 $RUNTIME = <$fh> + 0.; 144 $RUNTIME = <$fh> + 0.;
133} 145}
134 146
135mkdir $_ 147mkdir $_
136 for $LOCALDIR, $TMPDIR, $UNIQUEDIR, $PLAYERDIR, $RANDOMDIR, $BDBDIR; 148 for $LOCALDIR, $TMPDIR, $UNIQUEDIR, $PLAYERDIR, $RANDOMDIR, $BDBDIR;
246 cf::client cf::player 258 cf::client cf::player
247 cf::arch cf::living 259 cf::arch cf::living
248 cf::map cf::mapspace 260 cf::map cf::mapspace
249 cf::party cf::region 261 cf::party cf::region
250)) { 262)) {
251 no strict 'refs';
252 @{"safe::$pkg\::wrap::ISA"} = @{"$pkg\::wrap::ISA"} = $pkg; 263 @{"safe::$pkg\::wrap::ISA"} = @{"$pkg\::wrap::ISA"} = $pkg;
253} 264}
254 265
255$EV::DIED = sub { 266$EV::DIED = sub {
256 warn "error in event callback: @_"; 267 warn "error in event callback: @_";
298our $json_coder = JSON::XS->new->utf8->max_size (1e6); # accept ~1mb max 309our $json_coder = JSON::XS->new->utf8->max_size (1e6); # accept ~1mb max
299 310
300sub encode_json($) { $json_coder->encode ($_[0]) } 311sub encode_json($) { $json_coder->encode ($_[0]) }
301sub decode_json($) { $json_coder->decode ($_[0]) } 312sub decode_json($) { $json_coder->decode ($_[0]) }
302 313
314=item cf::post_init { BLOCK }
315
316Execute the given codeblock, I<after> all extensions have been (re-)loaded,
317but I<before> the server starts ticking again.
318
319The cdoeblock will have a single boolean argument to indicate whether this
320is a reload or not.
321
322=cut
323
324sub post_init(&) {
325 push @POST_INIT, shift;
326}
327
303=item cf::lock_wait $string 328=item cf::lock_wait $string
304 329
305Wait until the given lock is available. See cf::lock_acquire. 330Wait until the given lock is available. See cf::lock_acquire.
306 331
307=item my $lock = cf::lock_acquire $string 332=item my $lock = cf::lock_acquire $string
334 return;#d# 359 return;#d#
335 }#d# 360 }#d#
336 361
337 # wait for lock, if any 362 # wait for lock, if any
338 while ($LOCK{$key}) { 363 while ($LOCK{$key}) {
364 #local $Coro::current->{desc} = "$Coro::current->{desc} <waiting for lock $key>";
339 push @{ $LOCK{$key} }, $Coro::current; 365 push @{ $LOCK{$key} }, $Coro::current;
340 Coro::schedule; 366 Coro::schedule;
341 } 367 }
342} 368}
343 369
726 752
727############################################################################# 753#############################################################################
728 754
729=head2 ATTACHABLE OBJECTS 755=head2 ATTACHABLE OBJECTS
730 756
731Many objects in crossfire are so-called attachable objects. That means you can 757Many objects in deliantra are so-called attachable objects. That means you can
732attach callbacks/event handlers (a collection of which is called an "attachment") 758attach callbacks/event handlers (a collection of which is called an "attachment")
733to it. All such attachable objects support the following methods. 759to it. All such attachable objects support the following methods.
734 760
735In the following description, CLASS can be any of C<global>, C<object> 761In the following description, CLASS can be any of C<global>, C<object>
736C<player>, C<client> or C<map> (i.e. the attachable objects in 762C<player>, C<client> or C<map> (i.e. the attachable objects in
786=item cf::CLASS::attachment $name, ... 812=item cf::CLASS::attachment $name, ...
787 813
788Register an attachment by C<$name> through which attachable objects of the 814Register an attachment by C<$name> through which attachable objects of the
789given CLASS can refer to this attachment. 815given CLASS can refer to this attachment.
790 816
791Some classes such as crossfire maps and objects can specify attachments 817Some classes such as deliantra maps and objects can specify attachments
792that are attached at load/instantiate time, thus the need for a name. 818that are attached at load/instantiate time, thus the need for a name.
793 819
794These calls expect any number of the following handler/hook descriptions: 820These calls expect any number of the following handler/hook descriptions:
795 821
796=over 4 822=over 4
1087 1113
1088sub reattach { 1114sub reattach {
1089 # basically do the same as instantiate, without calling instantiate 1115 # basically do the same as instantiate, without calling instantiate
1090 my ($obj) = @_; 1116 my ($obj) = @_;
1091 1117
1118 # no longer needed after getting rid of delete_package?
1092 bless $obj, ref $obj; # re-bless in case extensions have been reloaded 1119 #bless $obj, ref $obj; # re-bless in case extensions have been reloaded
1093 1120
1094 my $registry = $obj->registry; 1121 my $registry = $obj->registry;
1095 1122
1096 @$registry = (); 1123 @$registry = ();
1097 1124
1162 } else { 1189 } else {
1163 aio_unlink "$filename.pst"; 1190 aio_unlink "$filename.pst";
1164 } 1191 }
1165 1192
1166 aio_rename "$filename~", $filename; 1193 aio_rename "$filename~", $filename;
1194
1195 $filename =~ s%/[^/]+$%%;
1196 aio_pathsync $filename if $cf::USE_FSYNC;
1167 } else { 1197 } else {
1168 warn "FATAL: $filename~: $!\n"; 1198 warn "FATAL: $filename~: $!\n";
1169 } 1199 }
1170 } else { 1200 } else {
1171 aio_unlink $filename; 1201 aio_unlink $filename;
1264 my ($name, $cb) = @_; 1294 my ($name, $cb) = @_;
1265 1295
1266 $EXTICMD{$name} = $cb; 1296 $EXTICMD{$name} = $cb;
1267} 1297}
1268 1298
1299use File::Glob ();
1300
1269cf::player->attach ( 1301cf::player->attach (
1270 on_command => sub { 1302 on_command => sub {
1271 my ($pl, $name, $params) = @_; 1303 my ($pl, $name, $params) = @_;
1272 1304
1273 my $cb = $COMMAND{$name} 1305 my $cb = $COMMAND{$name}
1305 1337
1306 cf::override; 1338 cf::override;
1307 }, 1339 },
1308); 1340);
1309 1341
1342# "readahead" all extensions
1343sub cache_extensions {
1344 my $grp = IO::AIO::aio_group;
1345
1346 add $grp IO::AIO::aio_readdir $LIBDIR, sub {
1347 for (grep /\.ext$/, @{$_[0]}) {
1348 add $grp IO::AIO::aio_load "$LIBDIR/$_", my $data;
1349 }
1350 };
1351
1352 $grp
1353}
1354
1310sub load_extensions { 1355sub load_extensions {
1311 cf::sync_job { 1356 cf::sync_job {
1312 my %todo; 1357 my %todo;
1313 1358
1314 for my $path (<$LIBDIR/*.ext>) { 1359 for my $path (<$LIBDIR/*.ext>) {
1333 1378
1334 $ext{meta} = { map { (split /=/, $_, 2)[0, 1] } split /\s+/, $1 } 1379 $ext{meta} = { map { (split /=/, $_, 2)[0, 1] } split /\s+/, $1 }
1335 if $source =~ /\A#!.*?perl.*?#\s*(.*)$/m; 1380 if $source =~ /\A#!.*?perl.*?#\s*(.*)$/m;
1336 1381
1337 $ext{source} = 1382 $ext{source} =
1338 "package $pkg; use strict; use utf8;\n" 1383 "package $pkg; use 5.10.0; use strict 'vars', 'subs'; use utf8;\n"
1339 . "#line 1 \"$path\"\n{\n" 1384 . "#line 1 \"$path\"\n{\n"
1340 . $source 1385 . $source
1341 . "\n};\n1"; 1386 . "\n};\n1";
1342 1387
1343 $todo{$base} = \%ext; 1388 $todo{$base} = \%ext;
1383 1428
1384=back 1429=back
1385 1430
1386=head2 CORE EXTENSIONS 1431=head2 CORE EXTENSIONS
1387 1432
1388Functions and methods that extend core crossfire objects. 1433Functions and methods that extend core deliantra objects.
1389 1434
1390=cut 1435=cut
1391 1436
1392package cf::player; 1437package cf::player;
1393 1438
1436 1481
1437sub exists($) { 1482sub exists($) {
1438 my ($login) = @_; 1483 my ($login) = @_;
1439 1484
1440 $cf::PLAYER{$login} 1485 $cf::PLAYER{$login}
1441 or cf::sync_job { !aio_stat path $login } 1486 or !aio_stat path $login
1442} 1487}
1443 1488
1444sub find($) { 1489sub find($) {
1445 return $cf::PLAYER{$_[0]} || do { 1490 return $cf::PLAYER{$_[0]} || do {
1446 my $login = $_[0]; 1491 my $login = $_[0];
1521 my ($pl) = @_; 1566 my ($pl) = @_;
1522 1567
1523 my $name = $pl->ob->name; 1568 my $name = $pl->ob->name;
1524 1569
1525 $pl->{deny_save} = 1; 1570 $pl->{deny_save} = 1;
1526 $pl->password ("*"); # this should lock out the player until we nuked the dir 1571 $pl->password ("*"); # this should lock out the player until we have nuked the dir
1527 1572
1528 $pl->invoke (cf::EVENT_PLAYER_LOGOUT, 1) if $pl->active; 1573 $pl->invoke (cf::EVENT_PLAYER_LOGOUT, 1) if $pl->active;
1529 $pl->deactivate; 1574 $pl->deactivate;
1530 my $killer = cf::arch::get "killer_quit"; $pl->killer ($killer); $killer->destroy; 1575 my $killer = cf::arch::get "killer_quit"; $pl->killer ($killer); $killer->destroy;
1531 $pl->ob->check_score; 1576 $pl->ob->check_score;
1617 } 1662 }
1618 1663
1619 \@paths 1664 \@paths
1620} 1665}
1621 1666
1622=item $protocol_xml = $player->expand_cfpod ($crossfire_pod) 1667=item $protocol_xml = $player->expand_cfpod ($cfpod)
1623 1668
1624Expand crossfire pod fragments into protocol xml. 1669Expand deliantra pod fragments into protocol xml.
1625
1626=cut
1627
1628use re 'eval';
1629
1630my $group;
1631my $interior; $interior = qr{
1632 # match a pod interior sequence sans C<< >>
1633 (?:
1634 \ (.*?)\ (?{ $group = $^N })
1635 | < (??{$interior}) >
1636 )
1637}x;
1638
1639sub expand_cfpod {
1640 my ($self, $pod) = @_;
1641
1642 my $xml;
1643
1644 while () {
1645 if ($pod =~ /\G( (?: [^BCGHITU]+ | .(?!<) )+ )/xgcs) {
1646 $group = $1;
1647
1648 $group =~ s/&/&amp;/g;
1649 $group =~ s/</&lt;/g;
1650
1651 $xml .= $group;
1652 } elsif ($pod =~ m%\G
1653 ([BCGHITU])
1654 <
1655 (?:
1656 ([^<>]*) (?{ $group = $^N })
1657 | < $interior >
1658 )
1659 >
1660 %gcsx
1661 ) {
1662 my ($code, $data) = ($1, $group);
1663
1664 if ($code eq "B") {
1665 $xml .= "<b>" . expand_cfpod ($self, $data) . "</b>";
1666 } elsif ($code eq "I") {
1667 $xml .= "<i>" . expand_cfpod ($self, $data) . "</i>";
1668 } elsif ($code eq "U") {
1669 $xml .= "<u>" . expand_cfpod ($self, $data) . "</u>";
1670 } elsif ($code eq "C") {
1671 $xml .= "<tt>" . expand_cfpod ($self, $data) . "</tt>";
1672 } elsif ($code eq "T") {
1673 $xml .= "<big><b>" . expand_cfpod ($self, $data) . "</b></big>";
1674 } elsif ($code eq "G") {
1675 my ($male, $female) = split /\|/, $data;
1676 $data = $self->gender ? $female : $male;
1677 $xml .= expand_cfpod ($self, $data);
1678 } elsif ($code eq "H") {
1679 $xml .= ("<fg name=\"lightblue\">[" . expand_cfpod ($self, $data) . " (Use hintmode to suppress hints)]</fg>",
1680 "<fg name=\"lightblue\">[Hint suppressed, see hintmode]</fg>",
1681 "")
1682 [$self->{hintmode}];
1683 } else {
1684 $xml .= "error processing '$code($data)' directive";
1685 }
1686 } else {
1687 if ($pod =~ /\G(.+)/) {
1688 warn "parse error while expanding $pod (at $1)";
1689 }
1690 last;
1691 }
1692 }
1693
1694 for ($xml) {
1695 # create single paragraphs (very hackish)
1696 s/(?<=\S)\n(?=\w)/ /g;
1697
1698 # compress some whitespace
1699 s/\s+\n/\n/g; # ws line-ends
1700 s/\n\n+/\n/g; # double lines
1701 s/^\n+//; # beginning lines
1702 s/\n+$//; # ending lines
1703 }
1704
1705 $xml
1706}
1707
1708no re 'eval';
1709
1710sub hintmode {
1711 $_[0]{hintmode} = $_[1] if @_ > 1;
1712 $_[0]{hintmode}
1713}
1714 1670
1715=item $player->ext_reply ($msgid, @msg) 1671=item $player->ext_reply ($msgid, @msg)
1716 1672
1717Sends an ext reply to the player. 1673Sends an ext reply to the player.
1718 1674
2532 2488
2533=item $player_object->enter_link 2489=item $player_object->enter_link
2534 2490
2535Freezes the player and moves him/her to a special map (C<{link}>). 2491Freezes the player and moves him/her to a special map (C<{link}>).
2536 2492
2537The player should be reasonably safe there for short amounts of time. You 2493The player should be reasonably safe there for short amounts of time (e.g.
2538I<MUST> call C<leave_link> as soon as possible, though. 2494for loading a map). You I<MUST> call C<leave_link> as soon as possible,
2495though, as the palyer cannot control the character while it is on the link
2496map.
2539 2497
2540Will never block. 2498Will never block.
2541 2499
2542=item $player_object->leave_link ($map, $x, $y) 2500=item $player_object->leave_link ($map, $x, $y)
2543 2501
2601 2559
2602 $map->load; 2560 $map->load;
2603 $map->load_neighbours; 2561 $map->load_neighbours;
2604 2562
2605 return unless $self->contr->active; 2563 return unless $self->contr->active;
2564 $self->flag (cf::FLAG_DEBUG, 0);#d# temp
2606 $self->activate_recursive; 2565 $self->activate_recursive;
2607 2566
2608 local $self->{_prev_pos} = $link_pos; # ugly hack for rent.ext 2567 local $self->{_prev_pos} = $link_pos; # ugly hack for rent.ext
2609 $self->enter_map ($map, $x, $y); 2568 $self->enter_map ($map, $x, $y);
2610} 2569}
2773 $self->contr->savebed ($map, $x, $y) 2732 $self->contr->savebed ($map, $x, $y)
2774 if $exit->flag (cf::FLAG_DAMNED); 2733 if $exit->flag (cf::FLAG_DAMNED);
2775 2734
2776 1 2735 1
2777 }) { 2736 }) {
2778 $self->message ("Something went wrong deep within the crossfire server. " 2737 $self->message ("Something went wrong deep within the deliantra server. "
2779 . "I'll try to bring you back to the map you were before. " 2738 . "I'll try to bring you back to the map you were before. "
2780 . "Please report this to the dungeon master!", 2739 . "Please report this to the dungeon master!",
2781 cf::NDI_UNIQUE | cf::NDI_RED); 2740 cf::NDI_UNIQUE | cf::NDI_RED);
2782 2741
2783 warn "ERROR in enter_exit: $@"; 2742 warn "ERROR in enter_exit: $@";
2849 id => "infobox", 2808 id => "infobox",
2850 title => "Body Parts", 2809 title => "Body Parts",
2851 reply => undef, 2810 reply => undef,
2852 tooltip => "Shows which body parts you posess and are available", 2811 tooltip => "Shows which body parts you posess and are available",
2853 }, 2812 },
2813 "c/skills" => {
2814 id => "infobox",
2815 title => "Skills",
2816 reply => undef,
2817 tooltip => "Shows your experience per skill and item power",
2818 },
2854 "c/uptime" => { 2819 "c/uptime" => {
2855 id => "infobox", 2820 id => "infobox",
2856 title => "Uptime", 2821 title => "Uptime",
2857 reply => undef, 2822 reply => undef,
2858 tooltip => "How long the server has been running since last restart", 2823 tooltip => "How long the server has been running since last restart",
2872); 2837);
2873 2838
2874sub cf::client::send_msg { 2839sub cf::client::send_msg {
2875 my ($self, $channel, $msg, $color, @extra) = @_; 2840 my ($self, $channel, $msg, $color, @extra) = @_;
2876 2841
2877 $msg = $self->pl->expand_cfpod ($msg); 2842 $msg = $self->pl->expand_cfpod ($msg)
2843 unless $color & cf::NDI_VERBATIM;
2878 2844
2879 $color &= cf::NDI_CLIENT_MASK; # just in case... 2845 $color &= cf::NDI_CLIENT_MASK; # just in case...
2880 2846
2881 # check predefined channels, for the benefit of C 2847 # check predefined channels, for the benefit of C
2882 if ($CHANNEL{$channel}) { 2848 if ($CHANNEL{$channel}) {
2903 if ($self->can_msg) { 2869 if ($self->can_msg) {
2904 # default colour, mask it out 2870 # default colour, mask it out
2905 $color &= ~(cf::NDI_COLOR_MASK | cf::NDI_DEF) 2871 $color &= ~(cf::NDI_COLOR_MASK | cf::NDI_DEF)
2906 if $color & cf::NDI_DEF; 2872 if $color & cf::NDI_DEF;
2907 2873
2908 $self->send_packet ("msg " . $self->{json_coder}->encode ( 2874 my $pkt = "msg "
2875 . $self->{json_coder}->encode (
2909 [$color & cf::NDI_CLIENT_MASK, $channel, $msg, @extra])); 2876 [$color & cf::NDI_CLIENT_MASK, $channel, $msg, @extra]
2877 );
2878
2879 # try lzf for large packets
2880 $pkt = "lzf " . Compress::LZF::compress $pkt
2881 if 1024 <= length $pkt and $self->{can_lzf};
2882
2883 # split very large packets
2884 if (8192 < length $pkt and $self->{can_lzf}) {
2885 $self->send_packet ("frag $_") for unpack "(a8192)*", $pkt;
2886 $pkt = "frag";
2887 }
2888
2889 $self->send_packet ($pkt);
2910 } else { 2890 } else {
2911 if ($color >= 0) { 2891 if ($color >= 0) {
2912 # replace some tags by gcfclient-compatible ones 2892 # replace some tags by gcfclient-compatible ones
2913 for ($msg) { 2893 for ($msg) {
2914 1 while 2894 1 while
3397 reload_treasures; 3377 reload_treasures;
3398 3378
3399 warn "finished reloading resource files\n"; 3379 warn "finished reloading resource files\n";
3400} 3380}
3401 3381
3402sub init {
3403 my $guard = freeze_mainloop;
3404
3405 evthread_start IO::AIO::poll_fileno;
3406
3407 reload_resources;
3408}
3409
3410sub reload_config { 3382sub reload_config {
3411 open my $fh, "<:utf8", "$CONFDIR/config" 3383 open my $fh, "<:utf8", "$CONFDIR/config"
3412 or return; 3384 or return;
3413 3385
3414 local $/; 3386 local $/;
3426 }; 3398 };
3427 warn $@ if $@; 3399 warn $@ if $@;
3428 } 3400 }
3429} 3401}
3430 3402
3403sub pidfile() {
3404 sysopen my $fh, $PIDFILE, O_RDWR | O_CREAT
3405 or die "$PIDFILE: $!";
3406 flock $fh, &Fcntl::LOCK_EX
3407 or die "$PIDFILE: flock: $!";
3408 $fh
3409}
3410
3411# make sure only one server instance is running at any one time
3412sub atomic {
3413 my $fh = pidfile;
3414
3415 my $pid = <$fh>;
3416 kill 9, $pid if $pid > 0;
3417
3418 seek $fh, 0, 0;
3419 print $fh $$;
3420}
3421
3431sub main { 3422sub main {
3423 cf::init_globals; # initialise logging
3424
3425 LOG llevInfo, "Welcome to Deliantra, v" . VERSION;
3426 LOG llevInfo, "Copyright (C) 2005-2008 Marc Alexander Lehmann / Robin Redeker / the Deliantra team.";
3427 LOG llevInfo, "Copyright (C) 1994 Mark Wedel.";
3428 LOG llevInfo, "Copyright (C) 1992 Frank Tore Johansen.";
3429
3430 cf::init_experience;
3431 cf::init_anim;
3432 cf::init_attackmess;
3433 cf::init_dynamic;
3434 cf::init_block;
3435
3436 $Coro::current->prio (Coro::PRIO_MAX); # give the main loop max. priority
3437
3432 # we must not ever block the main coroutine 3438 # we must not ever block the main coroutine
3433 local $Coro::idle = sub { 3439 local $Coro::idle = sub {
3434 Carp::cluck "FATAL: Coro::idle was called, major BUG, use cf::sync_job!\n";#d# 3440 Carp::cluck "FATAL: Coro::idle was called, major BUG, use cf::sync_job!\n";#d#
3435 (async { 3441 (async {
3436 $Coro::current->{desc} = "IDLE BUG HANDLER"; 3442 $Coro::current->{desc} = "IDLE BUG HANDLER";
3437 EV::loop EV::LOOP_ONESHOT; 3443 EV::loop EV::LOOP_ONESHOT;
3438 })->prio (Coro::PRIO_MAX); 3444 })->prio (Coro::PRIO_MAX);
3439 }; 3445 };
3440 3446
3441 { 3447 evthread_start IO::AIO::poll_fileno;
3442 my $guard = freeze_mainloop; 3448
3449 cf::sync_job {
3450 reload_resources;
3443 reload_config; 3451 reload_config;
3444 db_init; 3452 db_init;
3453
3454 cf::load_settings;
3455 cf::load_materials;
3456 cf::init_uuid;
3457 cf::init_signals;
3458 cf::init_commands;
3459 cf::init_skills;
3460
3461 cf::init_beforeplay;
3462
3463 atomic;
3464
3445 load_extensions; 3465 load_extensions;
3446 3466
3447 $Coro::current->prio (Coro::PRIO_MAX); # give the main loop max. priority 3467 utime time, time, $RUNTIMEFILE;
3468
3469 # no (long-running) fork's whatsoever before this point(!)
3470 POSIX::close delete $ENV{LOCKUTIL_LOCK_FD} if exists $ENV{LOCKUTIL_LOCK_FD};
3471
3472 (pop @POST_INIT)->(0) while @POST_INIT;
3448 } 3473 };
3449 3474
3450 EV::loop; 3475 EV::loop;
3451} 3476}
3452 3477
3453############################################################################# 3478#############################################################################
3462 }; 3487 };
3463 } 3488 }
3464} 3489}
3465 3490
3466sub write_runtime_sync { 3491sub write_runtime_sync {
3467 my $runtime = "$LOCALDIR/runtime";
3468
3469 # first touch the runtime file to show we are still running: 3492 # first touch the runtime file to show we are still running:
3470 # the fsync below can take a very very long time. 3493 # the fsync below can take a very very long time.
3471 3494
3472 IO::AIO::aio_utime $runtime, undef, undef; 3495 IO::AIO::aio_utime $RUNTIMEFILE, undef, undef;
3473 3496
3474 my $guard = cf::lock_acquire "write_runtime"; 3497 my $guard = cf::lock_acquire "write_runtime";
3475 3498
3476 my $fh = aio_open "$runtime~", O_WRONLY | O_CREAT, 0644 3499 my $fh = aio_open "$RUNTIMEFILE~", O_WRONLY | O_CREAT, 0644
3477 or return; 3500 or return;
3478 3501
3479 my $value = $cf::RUNTIME + 90 + 10; 3502 my $value = $cf::RUNTIME + 90 + 10;
3480 # 10 is the runtime save interval, for a monotonic clock 3503 # 10 is the runtime save interval, for a monotonic clock
3481 # 60 allows for the watchdog to kill the server. 3504 # 60 allows for the watchdog to kill the server.
3491 aio_utime $fh, undef, undef; 3514 aio_utime $fh, undef, undef;
3492 3515
3493 close $fh 3516 close $fh
3494 or return; 3517 or return;
3495 3518
3496 aio_rename "$runtime~", $runtime 3519 aio_rename "$RUNTIMEFILE~", $RUNTIMEFILE
3497 and return; 3520 and return;
3498 3521
3499 warn "runtime file written.\n"; 3522 warn "runtime file written.\n";
3500 3523
3501 1 3524 1
3513 my $uuid = "$LOCALDIR/uuid"; 3536 my $uuid = "$LOCALDIR/uuid";
3514 3537
3515 my $fh = aio_open "$uuid~", O_WRONLY | O_CREAT, 0644 3538 my $fh = aio_open "$uuid~", O_WRONLY | O_CREAT, 0644
3516 or return; 3539 or return;
3517 3540
3518 my $value = uuid_str $uuid_skip + uuid_seq uuid_cur; 3541 my $value = uuid_seq uuid_cur;
3542
3543 unless ($value) {
3544 warn "cowardly refusing to write zero uuid value!\n";
3545 return;
3546 }
3547
3548 my $value = uuid_str $value + $uuid_skip;
3519 $uuid_skip = 0; 3549 $uuid_skip = 0;
3520 3550
3521 (aio_write $fh, 0, (length $value), $value, 0) <= 0 3551 (aio_write $fh, 0, (length $value), $value, 0) <= 0
3522 and return; 3552 and return;
3523 3553
3545} 3575}
3546 3576
3547sub emergency_save() { 3577sub emergency_save() {
3548 my $freeze_guard = cf::freeze_mainloop; 3578 my $freeze_guard = cf::freeze_mainloop;
3549 3579
3550 warn "enter emergency perl save\n"; 3580 warn "emergency_perl_save: enter\n";
3551 3581
3552 cf::sync_job { 3582 cf::sync_job {
3583 # this is a trade-off: we want to be very quick here, so
3584 # save all maps without fsync, and later call a global sync
3585 # (which in turn might be very very slow)
3586 local $USE_FSYNC = 0;
3587
3553 # use a peculiar iteration method to avoid tripping on perl 3588 # use a peculiar iteration method to avoid tripping on perl
3554 # refcount bugs in for. also avoids problems with players 3589 # refcount bugs in for. also avoids problems with players
3555 # and maps saved/destroyed asynchronously. 3590 # and maps saved/destroyed asynchronously.
3556 warn "begin emergency player save\n"; 3591 warn "emergency_perl_save: begin player save\n";
3557 for my $login (keys %cf::PLAYER) { 3592 for my $login (keys %cf::PLAYER) {
3558 my $pl = $cf::PLAYER{$login} or next; 3593 my $pl = $cf::PLAYER{$login} or next;
3559 $pl->valid or next; 3594 $pl->valid or next;
3560 delete $pl->{unclean_save}; # not strictly necessary, but cannot hurt 3595 delete $pl->{unclean_save}; # not strictly necessary, but cannot hurt
3561 $pl->save; 3596 $pl->save;
3562 } 3597 }
3563 warn "end emergency player save\n"; 3598 warn "emergency_perl_save: end player save\n";
3564 3599
3565 warn "begin emergency map save\n"; 3600 warn "emergency_perl_save: begin map save\n";
3566 for my $path (keys %cf::MAP) { 3601 for my $path (keys %cf::MAP) {
3567 my $map = $cf::MAP{$path} or next; 3602 my $map = $cf::MAP{$path} or next;
3568 $map->valid or next; 3603 $map->valid or next;
3569 $map->save; 3604 $map->save;
3570 } 3605 }
3571 warn "end emergency map save\n"; 3606 warn "emergency_perl_save: end map save\n";
3572 3607
3573 warn "begin emergency database checkpoint\n"; 3608 warn "emergency_perl_save: begin database checkpoint\n";
3574 BDB::db_env_txn_checkpoint $DB_ENV; 3609 BDB::db_env_txn_checkpoint $DB_ENV;
3575 warn "end emergency database checkpoint\n"; 3610 warn "emergency_perl_save: end database checkpoint\n";
3576 3611
3577 warn "begin write uuid\n"; 3612 warn "emergency_perl_save: begin write uuid\n";
3578 write_uuid_sync 1; 3613 write_uuid_sync 1;
3579 warn "end write uuid\n"; 3614 warn "emergency_perl_save: end write uuid\n";
3580 }; 3615 };
3581 3616
3617 warn "emergency_perl_save: starting sync()\n";
3618 IO::AIO::aio_sync sub {
3619 warn "emergency_perl_save: finished sync()\n";
3620 };
3621
3582 warn "leave emergency perl save\n"; 3622 warn "emergency_perl_save: leave\n";
3583} 3623}
3584 3624
3585sub post_cleanup { 3625sub post_cleanup {
3586 my ($make_core) = @_; 3626 my ($make_core) = @_;
3587 3627
3588 warn Carp::longmess "post_cleanup backtrace" 3628 warn Carp::longmess "post_cleanup backtrace"
3589 if $make_core; 3629 if $make_core;
3630
3631 my $fh = pidfile;
3632 unlink $PIDFILE if <$fh> == $$;
3633}
3634
3635# a safer delete_package, copied from Symbol
3636sub clear_package($) {
3637 my $pkg = shift;
3638
3639 # expand to full symbol table name if needed
3640 unless ($pkg =~ /^main::.*::$/) {
3641 $pkg = "main$pkg" if $pkg =~ /^::/;
3642 $pkg = "main::$pkg" unless $pkg =~ /^main::/;
3643 $pkg .= '::' unless $pkg =~ /::$/;
3644 }
3645
3646 my($stem, $leaf) = $pkg =~ m/(.*::)(\w+::)$/;
3647 my $stem_symtab = *{$stem}{HASH};
3648
3649 defined $stem_symtab and exists $stem_symtab->{$leaf}
3650 or return;
3651
3652 # clear all symbols
3653 my $leaf_symtab = *{$stem_symtab->{$leaf}}{HASH};
3654 for my $name (keys %$leaf_symtab) {
3655 _gv_clear *{"$pkg$name"};
3656# use PApp::Util; PApp::Util::sv_dump *{"$pkg$name"};
3657 }
3658 warn "cleared package $pkg\n";#d#
3590} 3659}
3591 3660
3592sub do_reload_perl() { 3661sub do_reload_perl() {
3593 # can/must only be called in main 3662 # can/must only be called in main
3594 if ($Coro::current != $Coro::main) { 3663 if ($Coro::current != $Coro::main) {
3595 warn "can only reload from main coroutine"; 3664 warn "can only reload from main coroutine";
3596 return; 3665 return;
3597 } 3666 }
3598 3667
3668 return if $RELOAD++;
3669
3670 my $t1 = EV::time;
3671
3672 while ($RELOAD) {
3599 warn "reloading..."; 3673 warn "reloading...";
3600 3674
3601 warn "entering sync_job"; 3675 warn "entering sync_job";
3602 3676
3603 cf::sync_job { 3677 cf::sync_job {
3604 cf::write_runtime_sync; # external watchdog should not bark 3678 cf::write_runtime_sync; # external watchdog should not bark
3605 cf::emergency_save; 3679 cf::emergency_save;
3606 cf::write_runtime_sync; # external watchdog should not bark 3680 cf::write_runtime_sync; # external watchdog should not bark
3607 3681
3608 warn "syncing database to disk"; 3682 warn "syncing database to disk";
3609 BDB::db_env_txn_checkpoint $DB_ENV; 3683 BDB::db_env_txn_checkpoint $DB_ENV;
3610 3684
3611 # if anything goes wrong in here, we should simply crash as we already saved 3685 # if anything goes wrong in here, we should simply crash as we already saved
3612 3686
3613 warn "flushing outstanding aio requests"; 3687 warn "flushing outstanding aio requests";
3614 for (;;) {
3615 BDB::flush;
3616 IO::AIO::flush;
3617 Coro::cede_notself;
3618 last unless IO::AIO::nreqs || BDB::nreqs; 3688 while (IO::AIO::nreqs || BDB::nreqs) {
3619 warn "iterate..."; 3689 Coro::EV::timer_once 0.01; # let the sync_job do it's thing
3620 }
3621
3622 ++$RELOAD;
3623
3624 warn "cancelling all extension coros";
3625 $_->cancel for values %EXT_CORO;
3626 %EXT_CORO = ();
3627
3628 warn "removing commands";
3629 %COMMAND = ();
3630
3631 warn "removing ext/exti commands";
3632 %EXTCMD = ();
3633 %EXTICMD = ();
3634
3635 warn "unloading/nuking all extensions";
3636 for my $pkg (@EXTS) {
3637 warn "... unloading $pkg";
3638
3639 if (my $cb = $pkg->can ("unload")) {
3640 eval {
3641 $cb->($pkg);
3642 1
3643 } or warn "$pkg unloaded, but with errors: $@";
3644 } 3690 }
3645 3691
3646 warn "... nuking $pkg"; 3692 warn "cancelling all extension coros";
3647 Symbol::delete_package $pkg; 3693 $_->cancel for values %EXT_CORO;
3648 } 3694 %EXT_CORO = ();
3649 3695
3650 warn "unloading all perl modules loaded from $LIBDIR"; 3696 warn "removing commands";
3651 while (my ($k, $v) = each %INC) { 3697 %COMMAND = ();
3652 next unless $v =~ /^\Q$LIBDIR\E\/.*\.pm$/;
3653 3698
3699 warn "removing ext/exti commands";
3700 %EXTCMD = ();
3701 %EXTICMD = ();
3702
3703 warn "unloading/nuking all extensions";
3704 for my $pkg (@EXTS) {
3654 warn "... unloading $k"; 3705 warn "... unloading $pkg";
3655 delete $INC{$k};
3656 3706
3657 $k =~ s/\.pm$//;
3658 $k =~ s/\//::/g;
3659
3660 if (my $cb = $k->can ("unload_module")) { 3707 if (my $cb = $pkg->can ("unload")) {
3708 eval {
3661 $cb->(); 3709 $cb->($pkg);
3710 1
3711 } or warn "$pkg unloaded, but with errors: $@";
3712 }
3713
3714 warn "... clearing $pkg";
3715 clear_package $pkg;
3662 } 3716 }
3663 3717
3664 Symbol::delete_package $k; 3718 warn "unloading all perl modules loaded from $LIBDIR";
3719 while (my ($k, $v) = each %INC) {
3720 next unless $v =~ /^\Q$LIBDIR\E\/.*\.pm$/;
3721
3722 warn "... unloading $k";
3723 delete $INC{$k};
3724
3725 $k =~ s/\.pm$//;
3726 $k =~ s/\//::/g;
3727
3728 if (my $cb = $k->can ("unload_module")) {
3729 $cb->();
3730 }
3731
3732 clear_package $k;
3665 } 3733 }
3666 3734
3667 warn "getting rid of safe::, as good as possible"; 3735 warn "getting rid of safe::, as good as possible";
3668 Symbol::delete_package "safe::$_" 3736 clear_package "safe::$_"
3669 for qw(cf::attachable cf::object cf::object::player cf::client cf::player cf::map cf::party cf::region); 3737 for qw(cf::attachable cf::object cf::object::player cf::client cf::player cf::map cf::party cf::region);
3670 3738
3671 warn "unloading cf.pm \"a bit\""; 3739 warn "unloading cf.pm \"a bit\"";
3672 delete $INC{"cf.pm"}; 3740 delete $INC{"cf.pm"};
3673 delete $INC{"cf/pod.pm"}; 3741 delete $INC{"cf/pod.pm"};
3674 3742
3675 # don't, removes xs symbols, too, 3743 # don't, removes xs symbols, too,
3676 # and global variables created in xs 3744 # and global variables created in xs
3677 #Symbol::delete_package __PACKAGE__; 3745 #clear_package __PACKAGE__;
3678 3746
3679 warn "unload completed, starting to reload now"; 3747 warn "unload completed, starting to reload now";
3680 3748
3681 warn "reloading cf.pm"; 3749 warn "reloading cf.pm";
3682 require cf; 3750 require cf;
3683 cf::_connect_to_perl; # nominally unnecessary, but cannot hurt 3751 cf::_connect_to_perl; # nominally unnecessary, but cannot hurt
3684 3752
3685 warn "loading config and database again"; 3753 warn "loading config and database again";
3686 cf::reload_config; 3754 cf::reload_config;
3687 3755
3688 warn "loading extensions"; 3756 warn "loading extensions";
3689 cf::load_extensions; 3757 cf::load_extensions;
3690 3758
3759 if ($REATTACH_ON_RELOAD) {
3691 warn "reattaching attachments to objects/players"; 3760 warn "reattaching attachments to objects/players";
3692 _global_reattach; # objects, sockets 3761 _global_reattach; # objects, sockets
3693 warn "reattaching attachments to maps"; 3762 warn "reattaching attachments to maps";
3694 reattach $_ for values %MAP; 3763 reattach $_ for values %MAP;
3695 warn "reattaching attachments to players"; 3764 warn "reattaching attachments to players";
3696 reattach $_ for values %PLAYER; 3765 reattach $_ for values %PLAYER;
3766 }
3697 3767
3768 warn "running post_init jobs";
3769 (pop @POST_INIT)->(1) while @POST_INIT;
3770
3698 warn "leaving sync_job"; 3771 warn "leaving sync_job";
3699 3772
3700 1 3773 1
3701 } or do { 3774 } or do {
3702 warn $@; 3775 warn $@;
3703 cf::cleanup "error while reloading, exiting."; 3776 cf::cleanup "error while reloading, exiting.";
3704 }; 3777 };
3705 3778
3706 warn "reloaded"; 3779 warn "reloaded";
3780 --$RELOAD;
3781 }
3782
3783 $t1 = EV::time - $t1;
3784 warn "reload completed in ${t1}s\n";
3707}; 3785};
3708 3786
3709our $RELOAD_WATCHER; # used only during reload 3787our $RELOAD_WATCHER; # used only during reload
3710 3788
3711sub reload_perl() { 3789sub reload_perl() {
3712 # doing reload synchronously and two reloads happen back-to-back, 3790 # doing reload synchronously and two reloads happen back-to-back,
3713 # coro crashes during coro_state_free->destroy here. 3791 # coro crashes during coro_state_free->destroy here.
3714 3792
3793 $RELOAD_WATCHER ||= cf::async {
3794 Coro::AIO::aio_wait cache_extensions;
3795
3715 $RELOAD_WATCHER ||= EV::timer 0, 0, sub { 3796 $RELOAD_WATCHER = EV::timer $TICK * 1.5, 0, sub {
3716 do_reload_perl; 3797 do_reload_perl;
3717 undef $RELOAD_WATCHER; 3798 undef $RELOAD_WATCHER;
3799 };
3718 }; 3800 };
3719} 3801}
3720 3802
3721register_command "reload" => sub { 3803register_command "reload" => sub {
3722 my ($who, $arg) = @_; 3804 my ($who, $arg) = @_;
3848 $msg =~ s/\n//; 3930 $msg =~ s/\n//;
3849 3931
3850 # limit the # of concurrent backtraces 3932 # limit the # of concurrent backtraces
3851 if ($_log_backtrace < 2) { 3933 if ($_log_backtrace < 2) {
3852 ++$_log_backtrace; 3934 ++$_log_backtrace;
3935 my $perl_bt = Carp::longmess $msg;
3853 async { 3936 async {
3854 $Coro::current->{desc} = "abt $msg"; 3937 $Coro::current->{desc} = "abt $msg";
3855 3938
3856 my @bt = fork_call { 3939 my @bt = fork_call {
3857 @addr = map { sprintf "%x", $_ } @addr; 3940 @addr = map { sprintf "%x", $_ } @addr;
3868 } 3951 }
3869 3952
3870 @funcs 3953 @funcs
3871 }; 3954 };
3872 3955
3873 LOG llevInfo, "[ABT] $msg\n"; 3956 LOG llevInfo, "[ABT] $perl_bt\n";
3957 LOG llevInfo, "[ABT] --- C backtrace follows ---\n";
3874 LOG llevInfo, "[ABT] $_\n" for @bt; 3958 LOG llevInfo, "[ABT] $_\n" for @bt;
3875 --$_log_backtrace; 3959 --$_log_backtrace;
3876 }; 3960 };
3877 } else { 3961 } else {
3878 LOG llevInfo, "[ABT] $msg\n"; 3962 LOG llevInfo, "[ABT] $msg\n";

Diff Legend

Removed lines
+ Added lines
< Changed lines
> Changed lines