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.396 by root, Wed Nov 14 08:09:46 2007 UTC vs.
Revision 1.419 by root, Sun Apr 13 01:34:09 2008 UTC

1#
2# This file is part of Deliantra, the Roguelike Realtime MMORPG.
3#
4# Copyright (©) 2006,2007,2008 Marc Alexander Lehmann / Robin Redeker / the Deliantra team
5#
6# Deliantra is free software: you can redistribute it and/or modify
7# it under the terms of the GNU General Public License as published by
8# the Free Software Foundation, either version 3 of the License, or
9# (at your option) any later version.
10#
11# This program is distributed in the hope that it will be useful,
12# but WITHOUT ANY WARRANTY; without even the implied warranty of
13# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
14# GNU General Public License for more details.
15#
16# You should have received a copy of the GNU General Public License
17# along with this program. If not, see <http://www.gnu.org/licenses/>.
18#
19# The authors can be reached via e-mail to <support@deliantra.net>
20#
21
1package cf; 22package cf;
2 23
3use utf8; 24use utf8;
4use strict; 25use strict;
5 26
6use Symbol; 27use Symbol;
7use List::Util; 28use List::Util;
8use Socket; 29use Socket;
9use EV; 30use EV 3.2;
10use Opcode; 31use Opcode;
11use Safe; 32use Safe;
12use Safe::Hole; 33use Safe::Hole;
13use Storable (); 34use Storable ();
14 35
15use Coro 4.1 (); 36use Coro 4.50 ();
16use Coro::State; 37use Coro::State;
17use Coro::Handle; 38use Coro::Handle;
18use Coro::EV; 39use Coro::EV;
19use Coro::Timer; 40use Coro::Timer;
20use Coro::Signal; 41use Coro::Signal;
21use Coro::Semaphore; 42use Coro::Semaphore;
22use Coro::AIO; 43use Coro::AIO;
44use Coro::BDB;
23use Coro::Storable; 45use Coro::Storable;
24use Coro::Util (); 46use Coro::Util ();
25 47
26use JSON::XS (); 48use JSON::XS 2.01 ();
27use BDB (); 49use BDB ();
28use Data::Dumper; 50use Data::Dumper;
29use Digest::MD5; 51use Digest::MD5;
30use Fcntl; 52use Fcntl;
31use YAML::Syck (); 53use YAML ();
32use IO::AIO 2.51 (); 54use IO::AIO 2.51 ();
33use Time::HiRes; 55use Time::HiRes;
34use Compress::LZF; 56use Compress::LZF;
35use Digest::MD5 (); 57use Digest::MD5 ();
36 58
37# configure various modules to our taste 59# configure various modules to our taste
38# 60#
39$Storable::canonical = 1; # reduce rsync transfers 61$Storable::canonical = 1; # reduce rsync transfers
40Coro::State::cctx_stacksize 256000; # 1-2MB stack, for deep recursions in maze generator 62Coro::State::cctx_stacksize 256000; # 1-2MB stack, for deep recursions in maze generator
41Compress::LZF::sfreeze_cr { }; # prime Compress::LZF so it does not use require later 63Compress::LZF::sfreeze_cr { }; # prime Compress::LZF so it does not use require later
42
43# work around bug in YAML::Syck - bad news for perl6, will it be as broken wrt. unicode?
44$YAML::Syck::ImplicitUnicode = 1;
45 64
46$Coro::main->prio (Coro::PRIO_MAX); # run main coroutine ("the server") with very high priority 65$Coro::main->prio (Coro::PRIO_MAX); # run main coroutine ("the server") with very high priority
47 66
48sub WF_AUTOCANCEL () { 1 } # automatically cancel this watcher on reload 67sub WF_AUTOCANCEL () { 1 } # automatically cancel this watcher on reload
49 68
68our $TMPDIR = "$LOCALDIR/" . tmpdir; 87our $TMPDIR = "$LOCALDIR/" . tmpdir;
69our $UNIQUEDIR = "$LOCALDIR/" . uniquedir; 88our $UNIQUEDIR = "$LOCALDIR/" . uniquedir;
70our $PLAYERDIR = "$LOCALDIR/" . playerdir; 89our $PLAYERDIR = "$LOCALDIR/" . playerdir;
71our $RANDOMDIR = "$LOCALDIR/random"; 90our $RANDOMDIR = "$LOCALDIR/random";
72our $BDBDIR = "$LOCALDIR/db"; 91our $BDBDIR = "$LOCALDIR/db";
92our %RESOURCE;
73 93
74our $TICK = MAX_TIME * 1e-6; # this is a CONSTANT(!) 94our $TICK = MAX_TIME * 1e-6; # this is a CONSTANT(!)
75our $TICK_WATCHER;
76our $AIO_POLL_WATCHER; 95our $AIO_POLL_WATCHER;
77our $NEXT_RUNTIME_WRITE; # when should the runtime file be written 96our $NEXT_RUNTIME_WRITE; # when should the runtime file be written
78our $NEXT_TICK; 97our $NEXT_TICK;
79our $NOW;
80our $USE_FSYNC = 1; # use fsync to write maps - default off 98our $USE_FSYNC = 1; # use fsync to write maps - default off
81 99
82our $BDB_POLL_WATCHER; 100our $BDB_POLL_WATCHER;
83our $BDB_DEADLOCK_WATCHER; 101our $BDB_DEADLOCK_WATCHER;
84our $BDB_CHECKPOINT_WATCHER; 102our $BDB_CHECKPOINT_WATCHER;
87 105
88our %CFG; 106our %CFG;
89 107
90our $UPTIME; $UPTIME ||= time; 108our $UPTIME; $UPTIME ||= time;
91our $RUNTIME; 109our $RUNTIME;
110our $NOW;
92 111
93our (%PLAYER, %PLAYER_LOADING); # all users 112our (%PLAYER, %PLAYER_LOADING); # all users
94our (%MAP, %MAP_LOADING ); # all maps 113our (%MAP, %MAP_LOADING ); # all maps
95our $LINK_MAP; # the special {link} map, which is always available 114our $LINK_MAP; # the special {link} map, which is always available
96 115
97# used to convert map paths into valid unix filenames by replacing / by ∕ 116# used to convert map paths into valid unix filenames by replacing / by ∕
98our $PATH_SEP = "∕"; # U+2215, chosen purely for visual reasons 117our $PATH_SEP = "∕"; # U+2215, chosen purely for visual reasons
99 118
100our $LOAD; # a number between 0 (idle) and 1 (too many objects) 119our $LOAD; # a number between 0 (idle) and 1 (too many objects)
101our $LOADAVG; # same thing, but with alpha-smoothing 120our $LOADAVG; # same thing, but with alpha-smoothing
121our $JITTER; # average jitter
102our $tick_start; # for load detecting purposes 122our $TICK_START; # for load detecting purposes
103 123
104binmode STDOUT; 124binmode STDOUT;
105binmode STDERR; 125binmode STDERR;
106 126
107# read virtual server time, if available 127# read virtual server time, if available
191 $msg =~ s/([\x00-\x08\x0b-\x1f])/sprintf "\\x%02x", ord $1/ge; 211 $msg =~ s/([\x00-\x08\x0b-\x1f])/sprintf "\\x%02x", ord $1/ge;
192 212
193 LOG llevError, $msg; 213 LOG llevError, $msg;
194 }; 214 };
195} 215}
216
217$Coro::State::DIEHOOK = sub {
218 return unless $^S eq 0; # "eq", not "=="
219
220 if ($Coro::current == $Coro::main) {#d#
221 warn "DIEHOOK called in main context, Coro bug?\n";#d#
222 return;#d#
223 }#d#
224
225 # kill coroutine otherwise
226 warn Carp::longmess $_[0];
227 Coro::terminate
228};
229
230$SIG{__DIE__} = sub { }; #d#?
196 231
197@safe::cf::global::ISA = @cf::global::ISA = 'cf::attachable'; 232@safe::cf::global::ISA = @cf::global::ISA = 'cf::attachable';
198@safe::cf::object::ISA = @cf::object::ISA = 'cf::attachable'; 233@safe::cf::object::ISA = @cf::object::ISA = 'cf::attachable';
199@safe::cf::player::ISA = @cf::player::ISA = 'cf::attachable'; 234@safe::cf::player::ISA = @cf::player::ISA = 'cf::attachable';
200@safe::cf::client::ISA = @cf::client::ISA = 'cf::attachable'; 235@safe::cf::client::ISA = @cf::client::ISA = 'cf::attachable';
246 $d =~ s/([\x00-\x07\x09\x0b\x0c\x0e-\x1f])/sprintf "\\x%02x", ord($1)/ge; 281 $d =~ s/([\x00-\x07\x09\x0b\x0c\x0e-\x1f])/sprintf "\\x%02x", ord($1)/ge;
247 $d 282 $d
248 } || "[unable to dump $_[0]: '$@']"; 283 } || "[unable to dump $_[0]: '$@']";
249} 284}
250 285
251=item $ref = cf::from_json $json 286=item $ref = cf::decode_json $json
252 287
253Converts a JSON string into the corresponding perl data structure. 288Converts a JSON string into the corresponding perl data structure.
254 289
255=item $json = cf::to_json $ref 290=item $json = cf::encode_json $ref
256 291
257Converts a perl data structure into its JSON representation. 292Converts a perl data structure into its JSON representation.
258 293
259=cut 294=cut
260 295
261our $json_coder = JSON::XS->new->utf8->max_size (1e6); # accept ~1mb max 296our $json_coder = JSON::XS->new->utf8->max_size (1e6); # accept ~1mb max
262 297
263sub to_json ($) { $json_coder->encode ($_[0]) } 298sub encode_json($) { $json_coder->encode ($_[0]) }
264sub from_json ($) { $json_coder->decode ($_[0]) } 299sub decode_json($) { $json_coder->decode ($_[0]) }
265 300
266=item cf::lock_wait $string 301=item cf::lock_wait $string
267 302
268Wait until the given lock is available. See cf::lock_acquire. 303Wait until the given lock is available. See cf::lock_acquire.
269 304
325 360
326 ! ! $LOCK{$key} 361 ! ! $LOCK{$key}
327} 362}
328 363
329sub freeze_mainloop { 364sub freeze_mainloop {
330 return unless $TICK_WATCHER->is_active; 365 tick_inhibit_inc;
331 366
332 my $guard = Coro::guard { 367 Coro::guard \&tick_inhibit_dec;
333 $TICK_WATCHER->start;
334 };
335 $TICK_WATCHER->stop;
336 $guard
337} 368}
338 369
339=item cf::periodic $interval, $cb 370=item cf::periodic $interval, $cb
340 371
341Like EV::periodic, but randomly selects a starting point so that the actions 372Like EV::periodic, but randomly selects a starting point so that the actions
442 # this is the main coro, too bad, we have to block 473 # this is the main coro, too bad, we have to block
443 # till the operation succeeds, freezing the server :/ 474 # till the operation succeeds, freezing the server :/
444 475
445 LOG llevError, Carp::longmess "sync job";#d# 476 LOG llevError, Carp::longmess "sync job";#d#
446 477
447 # TODO: use suspend/resume instead
448 # (but this is cancel-safe)
449 my $freeze_guard = freeze_mainloop; 478 my $freeze_guard = freeze_mainloop;
450 479
451 my $busy = 1; 480 my $busy = 1;
452 my @res; 481 my @res;
453 482
464 } else { 493 } else {
465 EV::loop EV::LOOP_ONESHOT; 494 EV::loop EV::LOOP_ONESHOT;
466 } 495 }
467 } 496 }
468 497
469 $time = EV::time - $time; 498 my $time = EV::time - $time;
470 499
471 LOG llevError | logBacktrace, Carp::longmess "long sync job"
472 if $time > $TICK * 0.5 && $TICK_WATCHER->is_active;
473
474 $tick_start += $time; # do not account sync jobs to server load 500 $TICK_START += $time; # do not account sync jobs to server load
475 501
476 wantarray ? @res : $res[0] 502 wantarray ? @res : $res[0]
477 } else { 503 } else {
478 # we are in another coroutine, how wonderful, everything just works 504 # we are in another coroutine, how wonderful, everything just works
479 505
521 reset_signals; 547 reset_signals;
522 &$cb 548 &$cb
523 }, @args; 549 }, @args;
524 550
525 wantarray ? @res : $res[-1] 551 wantarray ? @res : $res[-1]
552}
553
554=item $coin = coin_from_name $name
555
556=cut
557
558our %coin_alias = (
559 "silver" => "silvercoin",
560 "silvercoin" => "silvercoin",
561 "silvercoins" => "silvercoin",
562 "gold" => "goldcoin",
563 "goldcoin" => "goldcoin",
564 "goldcoins" => "goldcoin",
565 "platinum" => "platinacoin",
566 "platinumcoin" => "platinacoin",
567 "platinumcoins" => "platinacoin",
568 "platina" => "platinacoin",
569 "platinacoin" => "platinacoin",
570 "platinacoins" => "platinacoin",
571 "royalty" => "royalty",
572 "royalties" => "royalty",
573);
574
575sub coin_from_name($) {
576 $coin_alias{$_[0]}
577 ? cf::arch::find $coin_alias{$_[0]}
578 : undef
526} 579}
527 580
528=item $value = cf::db_get $family => $key 581=item $value = cf::db_get $family => $key
529 582
530Returns a single value from the environment database. 583Returns a single value from the environment database.
967 } 1020 }
968 1021
969 0 1022 0
970} 1023}
971 1024
972=item $bool = cf::global::invoke (EVENT_CLASS_XXX, ...) 1025=item $bool = cf::global->invoke (EVENT_CLASS_XXX, ...)
973 1026
974=item $bool = $attachable->invoke (EVENT_CLASS_XXX, ...) 1027=item $bool = $attachable->invoke (EVENT_CLASS_XXX, ...)
975 1028
976Generate an object-specific event with the given arguments. 1029Generate an object-specific event with the given arguments.
977 1030
1055cf::attachable->attach ( 1108cf::attachable->attach (
1056 prio => -1000000, 1109 prio => -1000000,
1057 on_instantiate => sub { 1110 on_instantiate => sub {
1058 my ($obj, $data) = @_; 1111 my ($obj, $data) = @_;
1059 1112
1060 $data = from_json $data; 1113 $data = decode_json $data;
1061 1114
1062 for (@$data) { 1115 for (@$data) {
1063 my ($name, $args) = @$_; 1116 my ($name, $args) = @$_;
1064 1117
1065 $obj->attach ($name, %{$args || {} }); 1118 $obj->attach ($name, %{$args || {} });
1302 my $msg = $@ ? "$v->{path}: $@\n" 1355 my $msg = $@ ? "$v->{path}: $@\n"
1303 : "$v->{base}: extension inactive.\n"; 1356 : "$v->{base}: extension inactive.\n";
1304 1357
1305 if (exists $v->{meta}{mandatory}) { 1358 if (exists $v->{meta}{mandatory}) {
1306 warn $msg; 1359 warn $msg;
1307 warn "mandatory extension failed to load, exiting.\n"; 1360 cf::cleanup "mandatory extension failed to load, exiting.";
1308 exit 1;
1309 } 1361 }
1310 1362
1311 warn $msg; 1363 warn $msg;
1312 } 1364 }
1313 1365
1723our $MAX_RESET = 3600; 1775our $MAX_RESET = 3600;
1724our $DEFAULT_RESET = 3000; 1776our $DEFAULT_RESET = 3000;
1725 1777
1726sub generate_random_map { 1778sub generate_random_map {
1727 my ($self, $rmp) = @_; 1779 my ($self, $rmp) = @_;
1780
1781 my $lock = cf::lock_acquire "generate_random_map"; # the random map generator is NOT reentrant ATM
1782
1728 # mit "rum" bekleckern, nicht 1783 # mit "rum" bekleckern, nicht
1729 $self->_create_random_map ( 1784 $self->_create_random_map (
1730 $rmp->{wallstyle}, $rmp->{wall_name}, $rmp->{floorstyle}, $rmp->{monsterstyle}, 1785 $rmp->{wallstyle}, $rmp->{wall_name}, $rmp->{floorstyle}, $rmp->{monsterstyle},
1731 $rmp->{treasurestyle}, $rmp->{layoutstyle}, $rmp->{doorstyle}, $rmp->{decorstyle}, 1786 $rmp->{treasurestyle}, $rmp->{layoutstyle}, $rmp->{doorstyle}, $rmp->{decorstyle},
1732 $rmp->{origin_map}, $rmp->{final_map}, $rmp->{exitstyle}, $rmp->{this_map}, 1787 $rmp->{origin_map}, $rmp->{final_map}, $rmp->{exitstyle}, $rmp->{this_map},
1854 1909
1855# the temporary/swap location 1910# the temporary/swap location
1856sub save_path { 1911sub save_path {
1857 my ($self) = @_; 1912 my ($self) = @_;
1858 1913
1859 (my $path = $_[0]{path}) =~ s/\//$PATH_SEP/g; 1914 (my $path = $_[0]{path}) =~ s/\//$PATH_SEP/go;
1860 "$TMPDIR/$path.map" 1915 "$TMPDIR/$path.map"
1861} 1916}
1862 1917
1863# the unique path, undef == no special unique path 1918# the unique path, undef == no special unique path
1864sub uniq_path { 1919sub uniq_path {
1865 my ($self) = @_; 1920 my ($self) = @_;
1866 1921
1867 (my $path = $_[0]{path}) =~ s/\//$PATH_SEP/g; 1922 (my $path = $_[0]{path}) =~ s/\//$PATH_SEP/go;
1868 "$UNIQUEDIR/$path" 1923 "$UNIQUEDIR/$path"
1869} 1924}
1870 1925
1871# and all this just because we cannot iterate over 1926# and all this just because we cannot iterate over
1872# all maps in C++... 1927# all maps in C++...
2318 2373
2319sub unique_maps() { 2374sub unique_maps() {
2320 [ 2375 [
2321 map { 2376 map {
2322 utf8::decode $_; 2377 utf8::decode $_;
2323 /\.map$/ 2378 s/\.map$//; # TODO future compatibility hack
2379 /\.pst$/ || !/^$PATH_SEP/o # TODO unique maps apparebntly lack the .map suffix :/
2380 ? ()
2324 ? normalise $_ 2381 : normalise $_
2325 : ()
2326 } @{ aio_readdir $UNIQUEDIR or [] } 2382 } @{ aio_readdir $UNIQUEDIR or [] }
2327 ] 2383 ]
2328} 2384}
2329 2385
2330package cf;
2331
2332=back 2386=back
2333 2387
2334=head3 cf::object 2388=head3 cf::object
2335 2389
2336=cut 2390=cut
2339 2393
2340=over 4 2394=over 4
2341 2395
2342=item $ob->inv_recursive 2396=item $ob->inv_recursive
2343 2397
2344Returns the inventory of the object _and_ their inventories, recursively. 2398Returns the inventory of the object I<and> their inventories, recursively,
2399but I<not> the object itself.
2345 2400
2346=cut 2401=cut
2347 2402
2348sub inv_recursive_; 2403sub inv_recursive_;
2349sub inv_recursive_ { 2404sub inv_recursive_ {
2354 inv_recursive_ inv $_[0] 2409 inv_recursive_ inv $_[0]
2355} 2410}
2356 2411
2357=item $ref = $ob->ref 2412=item $ref = $ob->ref
2358 2413
2359creates and returns a persistent reference to an objetc that can be stored as a string. 2414Creates and returns a persistent reference to an object that can be stored as a string.
2360 2415
2361=item $ob = cf::object::deref ($refstring) 2416=item $ob = cf::object::deref ($refstring)
2362 2417
2363returns the objetc referenced by refstring. may return undef when it cnanot find the object, 2418returns the objetc referenced by refstring. may return undef when it cnanot find the object,
2364even if the object actually exists. May block. 2419even if the object actually exists. May block.
2638 $rmp->{origin_y} = $exit->y; 2693 $rmp->{origin_y} = $exit->y;
2639 } 2694 }
2640 2695
2641 $rmp->{random_seed} ||= $exit->random_seed; 2696 $rmp->{random_seed} ||= $exit->random_seed;
2642 2697
2643 my $data = cf::to_json $rmp; 2698 my $data = cf::encode_json $rmp;
2644 my $md5 = Digest::MD5::md5_hex $data; 2699 my $md5 = Digest::MD5::md5_hex $data;
2645 my $meta = "$RANDOMDIR/$md5.meta"; 2700 my $meta = "$RANDOMDIR/$md5.meta";
2646 2701
2647 if (my $fh = aio_open "$meta~", O_WRONLY | O_CREAT, 0666) { 2702 if (my $fh = aio_open "$meta~", O_WRONLY | O_CREAT, 0666) {
2648 aio_write $fh, 0, (length $data), $data, 0; 2703 aio_write $fh, 0, (length $data), $data, 0;
3148 { 3203 {
3149 my $faces = $facedata->{faceinfo}; 3204 my $faces = $facedata->{faceinfo};
3150 3205
3151 while (my ($face, $info) = each %$faces) { 3206 while (my ($face, $info) = each %$faces) {
3152 my $idx = (cf::face::find $face) || cf::face::alloc $face; 3207 my $idx = (cf::face::find $face) || cf::face::alloc $face;
3208
3153 cf::face::set_visibility $idx, $info->{visibility}; 3209 cf::face::set_visibility $idx, $info->{visibility};
3154 cf::face::set_magicmap $idx, $info->{magicmap}; 3210 cf::face::set_magicmap $idx, $info->{magicmap};
3155 cf::face::set_data $idx, 0, $info->{data32}, Digest::MD5::md5 $info->{data32}; 3211 cf::face::set_data $idx, 0, $info->{data32}, Digest::MD5::md5 $info->{data32};
3156 cf::face::set_data $idx, 1, $info->{data64}, Digest::MD5::md5 $info->{data64}; 3212 cf::face::set_data $idx, 1, $info->{data64}, Digest::MD5::md5 $info->{data64};
3157 3213
3158 cf::cede_to_tick; 3214 cf::cede_to_tick;
3159 } 3215 }
3160 3216
3161 while (my ($face, $info) = each %$faces) { 3217 while (my ($face, $info) = each %$faces) {
3162 next unless $info->{smooth}; 3218 next unless $info->{smooth};
3219
3163 my $idx = cf::face::find $face 3220 my $idx = cf::face::find $face
3164 or next; 3221 or next;
3222
3165 if (my $smooth = cf::face::find $info->{smooth}) { 3223 if (my $smooth = cf::face::find $info->{smooth}) {
3166 cf::face::set_smooth $idx, $smooth; 3224 cf::face::set_smooth $idx, $smooth;
3167 cf::face::set_smoothlevel $idx, $info->{smoothlevel}; 3225 cf::face::set_smoothlevel $idx, $info->{smoothlevel};
3168 } else { 3226 } else {
3169 warn "smooth face '$info->{smooth}' not found for face '$face'"; 3227 warn "smooth face '$info->{smooth}' not found for face '$face'";
3187 { 3245 {
3188 # TODO: for gcfclient pleasure, we should give resources 3246 # TODO: for gcfclient pleasure, we should give resources
3189 # that gcfclient doesn't grok a >10000 face index. 3247 # that gcfclient doesn't grok a >10000 face index.
3190 my $res = $facedata->{resource}; 3248 my $res = $facedata->{resource};
3191 3249
3192 my $soundconf = delete $res->{"res/sound.conf"};
3193
3194 while (my ($name, $info) = each %$res) { 3250 while (my ($name, $info) = each %$res) {
3251 if (defined $info->{type}) {
3195 my $idx = (cf::face::find $name) || cf::face::alloc $name; 3252 my $idx = (cf::face::find $name) || cf::face::alloc $name;
3196 my $data; 3253 my $data;
3197 3254
3198 if ($info->{type} & 1) { 3255 if ($info->{type} & 1) {
3199 # prepend meta info 3256 # prepend meta info
3200 3257
3201 my $meta = $enc->encode ({ 3258 my $meta = $enc->encode ({
3202 name => $name, 3259 name => $name,
3203 %{ $info->{meta} || {} }, 3260 %{ $info->{meta} || {} },
3204 }); 3261 });
3205 3262
3206 $data = pack "(w/a*)*", $meta, $info->{data}; 3263 $data = pack "(w/a*)*", $meta, $info->{data};
3264 } else {
3265 $data = $info->{data};
3266 }
3267
3268 cf::face::set_data $idx, 0, $data, Digest::MD5::md5 $data;
3269 cf::face::set_type $idx, $info->{type};
3207 } else { 3270 } else {
3208 $data = $info->{data}; 3271 $RESOURCE{$name} = $info;
3209 } 3272 }
3210 3273
3211 cf::face::set_data $idx, 0, $data, Digest::MD5::md5 $data;
3212 cf::face::set_type $idx, $info->{type};
3213
3214 cf::cede_to_tick; 3274 cf::cede_to_tick;
3215 } 3275 }
3216
3217 if ($soundconf) {
3218 $soundconf = $enc->decode (delete $soundconf->{data});
3219
3220 for (0 .. SOUND_CAST_SPELL_0 - 1) {
3221 my $sound = $soundconf->{compat}[$_]
3222 or next;
3223
3224 my $face = cf::face::find "sound/$sound->[1]";
3225 cf::sound::set $sound->[0] => $face;
3226 cf::sound::old_sound_index $_, $face; # gcfclient-compat
3227 }
3228
3229 while (my ($k, $v) = each %{$soundconf->{event}}) {
3230 my $face = cf::face::find "sound/$v";
3231 cf::sound::set $k => $face;
3232 }
3233 }
3234 } 3276 }
3277
3278 cf::global->invoke (EVENT_GLOBAL_RESOURCE_UPDATE);
3235 3279
3236 1 3280 1
3237} 3281}
3282
3283cf::global->attach (on_resource_update => sub {
3284 if (my $soundconf = $RESOURCE{"res/sound.conf"}) {
3285 $soundconf = JSON::XS->new->utf8->relaxed->decode ($soundconf->{data});
3286
3287 for (0 .. SOUND_CAST_SPELL_0 - 1) {
3288 my $sound = $soundconf->{compat}[$_]
3289 or next;
3290
3291 my $face = cf::face::find "sound/$sound->[1]";
3292 cf::sound::set $sound->[0] => $face;
3293 cf::sound::old_sound_index $_, $face; # gcfclient-compat
3294 }
3295
3296 while (my ($k, $v) = each %{$soundconf->{event}}) {
3297 my $face = cf::face::find "sound/$v";
3298 cf::sound::set $k => $face;
3299 }
3300 }
3301});
3238 3302
3239register_exticmd fx_want => sub { 3303register_exticmd fx_want => sub {
3240 my ($ns, $want) = @_; 3304 my ($ns, $want) = @_;
3241 3305
3242 while (my ($k, $v) = each %$want) { 3306 while (my ($k, $v) = each %$want) {
3297sub reload_config { 3361sub reload_config {
3298 open my $fh, "<:utf8", "$CONFDIR/config" 3362 open my $fh, "<:utf8", "$CONFDIR/config"
3299 or return; 3363 or return;
3300 3364
3301 local $/; 3365 local $/;
3302 *CFG = YAML::Syck::Load <$fh>; 3366 *CFG = YAML::Load <$fh>;
3303 3367
3304 $EMERGENCY_POSITION = $CFG{emergency_position} || ["/world/world_105_115", 5, 37]; 3368 $EMERGENCY_POSITION = $CFG{emergency_position} || ["/world/world_105_115", 5, 37];
3305 3369
3306 $cf::map::MAX_RESET = $CFG{map_max_reset} if exists $CFG{map_max_reset}; 3370 $cf::map::MAX_RESET = $CFG{map_max_reset} if exists $CFG{map_max_reset};
3307 $cf::map::DEFAULT_RESET = $CFG{map_default_reset} if exists $CFG{map_default_reset}; 3371 $cf::map::DEFAULT_RESET = $CFG{map_default_reset} if exists $CFG{map_default_reset};
3327 3391
3328 reload_config; 3392 reload_config;
3329 db_init; 3393 db_init;
3330 load_extensions; 3394 load_extensions;
3331 3395
3332 $TICK_WATCHER->start; 3396 $Coro::current->prio (Coro::PRIO_MAX); # give the main loop max. priority
3397 evthread_start IO::AIO::poll_fileno;
3333 EV::loop; 3398 EV::loop;
3334} 3399}
3335 3400
3336############################################################################# 3401#############################################################################
3337# initialisation and cleanup 3402# initialisation and cleanup
3344 cf::cleanup "SIG$signal"; 3409 cf::cleanup "SIG$signal";
3345 }; 3410 };
3346 } 3411 }
3347} 3412}
3348 3413
3349sub write_runtime { 3414sub write_runtime_sync {
3350 my $runtime = "$LOCALDIR/runtime"; 3415 my $runtime = "$LOCALDIR/runtime";
3351 3416
3352 # first touch the runtime file to show we are still running: 3417 # first touch the runtime file to show we are still running:
3353 # the fsync below can take a very very long time. 3418 # the fsync below can take a very very long time.
3354 3419
3380 and return; 3445 and return;
3381 3446
3382 warn "runtime file written.\n"; 3447 warn "runtime file written.\n";
3383 3448
3384 1 3449 1
3450}
3451
3452our $uuid_lock;
3453our $uuid_skip;
3454
3455sub write_uuid_sync($) {
3456 $uuid_skip ||= $_[0];
3457
3458 return if $uuid_lock;
3459 local $uuid_lock = 1;
3460
3461 my $uuid = "$LOCALDIR/uuid";
3462
3463 my $fh = aio_open "$uuid~", O_WRONLY | O_CREAT, 0644
3464 or return;
3465
3466 my $value = uuid_str $uuid_skip + uuid_seq uuid_cur;
3467 $uuid_skip = 0;
3468
3469 (aio_write $fh, 0, (length $value), $value, 0) <= 0
3470 and return;
3471
3472 # always fsync - this file is important
3473 aio_fsync $fh
3474 and return;
3475
3476 close $fh
3477 or return;
3478
3479 aio_rename "$uuid~", $uuid
3480 and return;
3481
3482 warn "uuid file written ($value).\n";
3483
3484 1
3485
3486}
3487
3488sub write_uuid($$) {
3489 my ($skip, $sync) = @_;
3490
3491 $sync ? write_uuid_sync $skip
3492 : async { write_uuid_sync $skip };
3385} 3493}
3386 3494
3387sub emergency_save() { 3495sub emergency_save() {
3388 my $freeze_guard = cf::freeze_mainloop; 3496 my $freeze_guard = cf::freeze_mainloop;
3389 3497
3411 warn "end emergency map save\n"; 3519 warn "end emergency map save\n";
3412 3520
3413 warn "begin emergency database checkpoint\n"; 3521 warn "begin emergency database checkpoint\n";
3414 BDB::db_env_txn_checkpoint $DB_ENV; 3522 BDB::db_env_txn_checkpoint $DB_ENV;
3415 warn "end emergency database checkpoint\n"; 3523 warn "end emergency database checkpoint\n";
3524
3525 warn "begin write uuid\n";
3526 write_uuid_sync 1;
3527 warn "end write uuid\n";
3416 }; 3528 };
3417 3529
3418 warn "leave emergency perl save\n"; 3530 warn "leave emergency perl save\n";
3419} 3531}
3420 3532
3435 warn "reloading..."; 3547 warn "reloading...";
3436 3548
3437 warn "entering sync_job"; 3549 warn "entering sync_job";
3438 3550
3439 cf::sync_job { 3551 cf::sync_job {
3440 cf::write_runtime; # external watchdog should not bark 3552 cf::write_runtime_sync; # external watchdog should not bark
3441 cf::emergency_save; 3553 cf::emergency_save;
3442 cf::write_runtime; # external watchdog should not bark 3554 cf::write_runtime_sync; # external watchdog should not bark
3443 3555
3444 warn "syncing database to disk"; 3556 warn "syncing database to disk";
3445 BDB::db_env_txn_checkpoint $DB_ENV; 3557 BDB::db_env_txn_checkpoint $DB_ENV;
3446 3558
3447 # if anything goes wrong in here, we should simply crash as we already saved 3559 # if anything goes wrong in here, we should simply crash as we already saved
3534 warn "leaving sync_job"; 3646 warn "leaving sync_job";
3535 3647
3536 1 3648 1
3537 } or do { 3649 } or do {
3538 warn $@; 3650 warn $@;
3539 warn "error while reloading, exiting."; 3651 cf::cleanup "error while reloading, exiting.";
3540 exit 1;
3541 }; 3652 };
3542 3653
3543 warn "reloaded"; 3654 warn "reloaded";
3544}; 3655};
3545 3656
3548sub reload_perl() { 3659sub reload_perl() {
3549 # doing reload synchronously and two reloads happen back-to-back, 3660 # doing reload synchronously and two reloads happen back-to-back,
3550 # coro crashes during coro_state_free->destroy here. 3661 # coro crashes during coro_state_free->destroy here.
3551 3662
3552 $RELOAD_WATCHER ||= EV::timer 0, 0, sub { 3663 $RELOAD_WATCHER ||= EV::timer 0, 0, sub {
3664 do_reload_perl;
3553 undef $RELOAD_WATCHER; 3665 undef $RELOAD_WATCHER;
3554 do_reload_perl;
3555 }; 3666 };
3556} 3667}
3557 3668
3558register_command "reload" => sub { 3669register_command "reload" => sub {
3559 my ($who, $arg) = @_; 3670 my ($who, $arg) = @_;
3573 3684
3574our @WAIT_FOR_TICK; 3685our @WAIT_FOR_TICK;
3575our @WAIT_FOR_TICK_BEGIN; 3686our @WAIT_FOR_TICK_BEGIN;
3576 3687
3577sub wait_for_tick { 3688sub wait_for_tick {
3578 return unless $TICK_WATCHER->is_active; 3689 return if tick_inhibit;
3579 return if $Coro::current == $Coro::main; 3690 return if $Coro::current == $Coro::main;
3580 3691
3581 my $signal = new Coro::Signal; 3692 my $signal = new Coro::Signal;
3582 push @WAIT_FOR_TICK, $signal; 3693 push @WAIT_FOR_TICK, $signal;
3583 $signal->wait; 3694 $signal->wait;
3584} 3695}
3585 3696
3586sub wait_for_tick_begin { 3697sub wait_for_tick_begin {
3587 return unless $TICK_WATCHER->is_active; 3698 return if tick_inhibit;
3588 return if $Coro::current == $Coro::main; 3699 return if $Coro::current == $Coro::main;
3589 3700
3590 my $signal = new Coro::Signal; 3701 my $signal = new Coro::Signal;
3591 push @WAIT_FOR_TICK_BEGIN, $signal; 3702 push @WAIT_FOR_TICK_BEGIN, $signal;
3592 $signal->wait; 3703 $signal->wait;
3593} 3704}
3594 3705
3595$TICK_WATCHER = EV::periodic_ns 0, $TICK, 0, sub { 3706sub tick {
3596 if ($Coro::current != $Coro::main) { 3707 if ($Coro::current != $Coro::main) {
3597 Carp::cluck "major BUG: server tick called outside of main coro, skipping it" 3708 Carp::cluck "major BUG: server tick called outside of main coro, skipping it"
3598 unless ++$bug_warning > 10; 3709 unless ++$bug_warning > 10;
3599 return; 3710 return;
3600 } 3711 }
3601 3712
3602 $NOW = $tick_start = EV::now;
3603
3604 cf::server_tick; # one server iteration 3713 cf::server_tick; # one server iteration
3605 3714
3606 $RUNTIME += $TICK;
3607 $NEXT_TICK += $TICK;
3608
3609 if ($NOW >= $NEXT_RUNTIME_WRITE) { 3715 if ($NOW >= $NEXT_RUNTIME_WRITE) {
3610 $NEXT_RUNTIME_WRITE = $NOW + 10; 3716 $NEXT_RUNTIME_WRITE = List::Util::max $NEXT_RUNTIME_WRITE + 10, $NOW + 5.;
3611 Coro::async_pool { 3717 Coro::async_pool {
3612 $Coro::current->{desc} = "runtime saver"; 3718 $Coro::current->{desc} = "runtime saver";
3613 write_runtime 3719 write_runtime_sync
3614 or warn "ERROR: unable to write runtime file: $!"; 3720 or warn "ERROR: unable to write runtime file: $!";
3615 }; 3721 };
3616 } 3722 }
3617 3723
3618 if (my $sig = shift @WAIT_FOR_TICK_BEGIN) { 3724 if (my $sig = shift @WAIT_FOR_TICK_BEGIN) {
3620 } 3726 }
3621 while (my $sig = shift @WAIT_FOR_TICK) { 3727 while (my $sig = shift @WAIT_FOR_TICK) {
3622 $sig->send; 3728 $sig->send;
3623 } 3729 }
3624 3730
3625 $LOAD = ($NOW - $tick_start) / $TICK; 3731 $LOAD = ($NOW - $TICK_START) / $TICK;
3626 $LOADAVG = $LOADAVG * 0.75 + $LOAD * 0.25; 3732 $LOADAVG = $LOADAVG * 0.75 + $LOAD * 0.25;
3627 3733
3628 _post_tick; 3734 if (0) {
3629}; 3735 if ($NEXT_TICK) {
3630$TICK_WATCHER->priority (EV::MAXPRI); 3736 my $jitter = $TICK_START - $NEXT_TICK;
3737 $JITTER = $JITTER * 0.75 + $jitter * 0.25;
3738 warn "jitter $JITTER\n";#d#
3739 }
3740 }
3741}
3631 3742
3632{ 3743{
3744 # configure BDB
3745
3633 BDB::min_parallel 8; 3746 BDB::min_parallel 8;
3634 BDB::max_poll_time $TICK * 0.1; 3747 BDB::max_poll_reqs $TICK * 0.1;
3635 $BDB_POLL_WATCHER = EV::io BDB::poll_fileno, EV::READ, \&BDB::poll_cb; 3748 $Coro::BDB::WATCHER->priority (1);
3636
3637 BDB::set_sync_prepare {
3638 my $status;
3639 my $current = $Coro::current;
3640 (
3641 sub {
3642 $status = $!;
3643 $current->ready; undef $current;
3644 },
3645 sub {
3646 Coro::schedule while defined $current;
3647 $! = $status;
3648 },
3649 )
3650 };
3651 3749
3652 unless ($DB_ENV) { 3750 unless ($DB_ENV) {
3653 $DB_ENV = BDB::db_env_create; 3751 $DB_ENV = BDB::db_env_create;
3654 $DB_ENV->set_flags (BDB::AUTO_COMMIT | BDB::REGION_INIT | BDB::TXN_NOSYNC 3752 $DB_ENV->set_flags (BDB::AUTO_COMMIT | BDB::REGION_INIT | BDB::TXN_NOSYNC
3655 | BDB::LOG_AUTOREMOVE, 1); 3753 | BDB::LOG_AUTOREMOVE, 1);
3682 BDB::db_env_memp_trickle $DB_ENV, 20, 0, sub { }; 3780 BDB::db_env_memp_trickle $DB_ENV, 20, 0, sub { };
3683 }; 3781 };
3684} 3782}
3685 3783
3686{ 3784{
3785 # configure IO::AIO
3786
3687 IO::AIO::min_parallel 8; 3787 IO::AIO::min_parallel 8;
3688
3689 undef $Coro::AIO::WATCHER;
3690 IO::AIO::max_poll_time $TICK * 0.1; 3788 IO::AIO::max_poll_time $TICK * 0.1;
3691 $AIO_POLL_WATCHER = EV::io IO::AIO::poll_fileno, EV::READ, \&IO::AIO::poll_cb; 3789 $Coro::AIO::WATCHER->priority (1);
3692} 3790}
3693 3791
3694my $_log_backtrace; 3792my $_log_backtrace;
3695 3793
3696sub _log_backtrace { 3794sub _log_backtrace {

Diff Legend

Removed lines
+ Added lines
< Changed lines
> Changed lines