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.101 by root, Mon Dec 25 14:43:23 2006 UTC vs.
Revision 1.105 by root, Sun Dec 31 17:17:23 2006 UTC

8use Storable; 8use Storable;
9use Opcode; 9use Opcode;
10use Safe; 10use Safe;
11use Safe::Hole; 11use Safe::Hole;
12 12
13use Coro; 13use Coro 3.3;
14use Coro::Event; 14use Coro::Event;
15use Coro::Timer; 15use Coro::Timer;
16use Coro::Signal; 16use Coro::Signal;
17use Coro::Semaphore; 17use Coro::Semaphore;
18use Coro::AIO;
18 19
20use Fcntl;
19use IO::AIO 2.3; 21use IO::AIO 2.31 ();
20use YAML::Syck (); 22use YAML::Syck ();
21use Time::HiRes; 23use Time::HiRes;
22 24
23use Event; $Event::Eval = 1; # no idea why this is required, but it is 25use Event; $Event::Eval = 1; # no idea why this is required, but it is
24 26
25# work around bug in YAML::Syck - bad news for perl6, will it be as broken wrt. unicode? 27# work around bug in YAML::Syck - bad news for perl6, will it be as broken wrt. unicode?
26$YAML::Syck::ImplicitUnicode = 1; 28$YAML::Syck::ImplicitUnicode = 1;
27 29
28$Coro::main->prio (Coro::PRIO_MIN); 30$Coro::main->prio (2); # run main coroutine ("the server") with very high priority
29 31
30sub WF_AUTOCANCEL () { 1 } # automatically cancel this watcher on reload 32sub WF_AUTOCANCEL () { 1 } # automatically cancel this watcher on reload
31 33
32our %COMMAND = (); 34our %COMMAND = ();
33our %COMMAND_TIME = (); 35our %COMMAND_TIME = ();
37our $LIBDIR = datadir . "/ext"; 39our $LIBDIR = datadir . "/ext";
38 40
39our $TICK = MAX_TIME * 1e-6; 41our $TICK = MAX_TIME * 1e-6;
40our $TICK_WATCHER; 42our $TICK_WATCHER;
41our $NEXT_TICK; 43our $NEXT_TICK;
44our $NOW;
42 45
43our %CFG; 46our %CFG;
44 47
45our $UPTIME; $UPTIME ||= time; 48our $UPTIME; $UPTIME ||= time;
49our $RUNTIME;
50
51our %MAP; # all maps
52our $LINK_MAP; # the special {link} map
53our $FREEZE;
54
55binmode STDOUT;
56binmode STDERR;
57
58# read virtual server time, if available
59unless ($RUNTIME || !-e cf::localdir . "/runtime") {
60 open my $fh, "<", cf::localdir . "/runtime"
61 or die "unable to read runtime file: $!";
62 $RUNTIME = <$fh> + 0.;
63}
64
65mkdir cf::localdir;
66mkdir cf::localdir . "/" . cf::playerdir;
67mkdir cf::localdir . "/" . cf::tmpdir;
68mkdir cf::localdir . "/" . cf::uniquedir;
69
70our %EXT_CORO;
46 71
47############################################################################# 72#############################################################################
48 73
49=head2 GLOBAL VARIABLES 74=head2 GLOBAL VARIABLES
50 75
51=over 4 76=over 4
52 77
53=item $cf::UPTIME 78=item $cf::UPTIME
54 79
55The timestamp of the server start (so not actually an uptime). 80The timestamp of the server start (so not actually an uptime).
81
82=item $cf::RUNTIME
83
84The time this server has run, starts at 0 and is increased by $cf::TICK on
85every server tick.
56 86
57=item $cf::LIBDIR 87=item $cf::LIBDIR
58 88
59The perl library directory, where extensions and cf-specific modules can 89The perl library directory, where extensions and cf-specific modules can
60be found. It will be added to C<@INC> automatically. 90be found. It will be added to C<@INC> automatically.
91
92=item $cf::NOW
93
94The time of the last (current) server tick.
61 95
62=item $cf::TICK 96=item $cf::TICK
63 97
64The interval between server ticks, in seconds. 98The interval between server ticks, in seconds.
65 99
73=cut 107=cut
74 108
75BEGIN { 109BEGIN {
76 *CORE::GLOBAL::warn = sub { 110 *CORE::GLOBAL::warn = sub {
77 my $msg = join "", @_; 111 my $msg = join "", @_;
112 utf8::encode $msg;
113
78 $msg .= "\n" 114 $msg .= "\n"
79 unless $msg =~ /\n$/; 115 unless $msg =~ /\n$/;
80 116
81 print STDERR "cfperl: $msg";
82 LOG llevError, "cfperl: $msg"; 117 LOG llevError, "cfperl: $msg";
83 }; 118 };
84} 119}
85 120
86@safe::cf::global::ISA = @cf::global::ISA = 'cf::attachable'; 121@safe::cf::global::ISA = @cf::global::ISA = 'cf::attachable';
139sub to_json($) { 174sub to_json($) {
140 $JSON::Syck::ImplicitUnicode = 0; # work around JSON::Syck bugs 175 $JSON::Syck::ImplicitUnicode = 0; # work around JSON::Syck bugs
141 JSON::Syck::Dump $_[0] 176 JSON::Syck::Dump $_[0]
142} 177}
143 178
179# main coro must never ever "block" except in Event
180# sync_job ensures this by running the job in a coroutine
181# and waiting in Event while the server is otherwise frozen
182sub sync_job(&) {
183 my ($job) = @_;
184
185 my $busy = 1;
186 my @res;
187
188 local $FREEZE = 1;
189
190 my $coro = Coro::async {
191 @res = eval { $job->() };
192 warn $@ if $@;
193 undef $busy;
194 };
195
196 if ($Coro::current == $Coro::main) {
197 $coro->prio (Coro::PRIO_MAX);
198 while ($busy) {
199 Coro::cede_notself;
200 Event::one_event unless Coro::nready;
201 }
202 } else {
203 $coro->join;
204 }
205
206 wantarray ? @res : $res[0]
207}
208
209=item $coro = cf::coro { BLOCK }
210
211Creates and returns a new coro. This coro is automcatially being canceled
212when the extension calling this is being unloaded.
213
214=cut
215
216sub coro(&) {
217 my $cb = shift;
218
219 my $coro; $coro = async {
220 eval {
221 $cb->();
222 };
223 warn $@ if $@;
224 };
225
226 $coro->on_destroy (sub {
227 delete $EXT_CORO{$coro+0};
228 });
229 $EXT_CORO{$coro+0} = $coro;
230
231 $coro
232}
233
144=back 234=back
145 235
146=cut 236=cut
147 237
148############################################################################# 238#############################################################################
454=cut 544=cut
455 545
456############################################################################# 546#############################################################################
457# object support 547# object support
458 548
549sub reattach {
550 # basically do the same as instantiate, without calling instantiate
551 my ($obj) = @_;
552
553 my $registry = $obj->registry;
554
555 @$registry = ();
556
557 delete $obj->{_attachment} unless scalar keys %{ $obj->{_attachment} || {} };
558
559 for my $name (keys %{ $obj->{_attachment} || {} }) {
560 if (my $attach = $attachment{$name}) {
561 for (@$attach) {
562 my ($klass, @attach) = @$_;
563 _attach $registry, $klass, @attach;
564 }
565 } else {
566 warn "object uses attachment '$name' that is not available, postponing.\n";
567 }
568 }
569}
570
459cf::attachable->attach ( 571cf::attachable->attach (
460 prio => -1000000, 572 prio => -1000000,
461 on_instantiate => sub { 573 on_instantiate => sub {
462 my ($obj, $data) = @_; 574 my ($obj, $data) = @_;
463 575
467 my ($name, $args) = @$_; 579 my ($name, $args) = @$_;
468 580
469 $obj->attach ($name, %{$args || {} }); 581 $obj->attach ($name, %{$args || {} });
470 } 582 }
471 }, 583 },
472 on_reattach => sub { 584 on_reattach => \&reattach,
473 # basically do the same as instantiate, without calling instantiate
474 my ($obj) = @_;
475 my $registry = $obj->registry;
476
477 @$registry = ();
478
479 delete $obj->{_attachment} unless scalar keys %{ $obj->{_attachment} || {} };
480
481 for my $name (keys %{ $obj->{_attachment} || {} }) {
482 if (my $attach = $attachment{$name}) {
483 for (@$attach) {
484 my ($klass, @attach) = @$_;
485 _attach $registry, $klass, @attach;
486 }
487 } else {
488 warn "object uses attachment '$name' that is not available, postponing.\n";
489 }
490 }
491 },
492 on_clone => sub { 585 on_clone => sub {
493 my ($src, $dst) = @_; 586 my ($src, $dst) = @_;
494 587
495 @{$dst->registry} = @{$src->registry}; 588 @{$dst->registry} = @{$src->registry};
496 589
502); 595);
503 596
504sub object_freezer_save { 597sub object_freezer_save {
505 my ($filename, $rdata, $objs) = @_; 598 my ($filename, $rdata, $objs) = @_;
506 599
600 sync_job {
507 if (length $$rdata) { 601 if (length $$rdata) {
508 warn sprintf "saving %s (%d,%d)\n", 602 warn sprintf "saving %s (%d,%d)\n",
509 $filename, length $$rdata, scalar @$objs; 603 $filename, length $$rdata, scalar @$objs;
510 604
511 if (open my $fh, ">:raw", "$filename~") { 605 if (my $fh = aio_open "$filename~", O_WRONLY | O_CREAT, 0600) {
512 chmod SAVE_MODE, $fh;
513 syswrite $fh, $$rdata;
514 close $fh;
515
516 if (@$objs && open my $fh, ">:raw", "$filename.pst~") {
517 chmod SAVE_MODE, $fh; 606 chmod SAVE_MODE, $fh;
518 syswrite $fh, Storable::nfreeze { version => 1, objs => $objs }; 607 aio_write $fh, 0, (length $$rdata), $$rdata, 0;
608 aio_fsync $fh;
519 close $fh; 609 close $fh;
610
611 if (@$objs) {
612 if (my $fh = aio_open "$filename.pst~", O_WRONLY | O_CREAT, 0600) {
613 chmod SAVE_MODE, $fh;
614 my $data = Storable::nfreeze { version => 1, objs => $objs };
615 aio_write $fh, 0, (length $data), $data, 0;
616 aio_fsync $fh;
617 close $fh;
520 rename "$filename.pst~", "$filename.pst"; 618 aio_rename "$filename.pst~", "$filename.pst";
619 }
620 } else {
621 aio_unlink "$filename.pst";
622 }
623
624 aio_rename "$filename~", $filename;
521 } else { 625 } else {
522 unlink "$filename.pst"; 626 warn "FATAL: $filename~: $!\n";
523 } 627 }
524
525 rename "$filename~", $filename;
526 } else { 628 } else {
527 warn "FATAL: $filename~: $!\n";
528 }
529 } else {
530 unlink $filename; 629 aio_unlink $filename;
531 unlink "$filename.pst"; 630 aio_unlink "$filename.pst";
631 }
532 } 632 }
533} 633}
534 634
535sub object_freezer_as_string { 635sub object_freezer_as_string {
536 my ($rdata, $objs) = @_; 636 my ($rdata, $objs) = @_;
541} 641}
542 642
543sub object_thawer_load { 643sub object_thawer_load {
544 my ($filename) = @_; 644 my ($filename) = @_;
545 645
546 local $/; 646 my ($data, $av);
547 647
548 my $av; 648 (aio_load $filename, $data) >= 0
649 or return;
549 650
550 #TODO: use sysread etc. 651 unless (aio_stat "$filename.pst") {
551 if (open my $data, "<:raw:perlio", $filename) { 652 (aio_load "$filename.pst", $av) >= 0
552 $data = <$data>; 653 or return;
553 if (open my $pst, "<:raw:perlio", "$filename.pst") {
554 $av = eval { (Storable::thaw <$pst>)->{objs} }; 654 $av = eval { (Storable::thaw <$av>)->{objs} };
555 } 655 }
656
556 return ($data, $av); 657 return ($data, $av);
557 }
558
559 ()
560} 658}
561 659
562############################################################################# 660#############################################################################
563# command handling &c 661# command handling &c
564 662
913 my $coro; $coro = async { 1011 my $coro; $coro = async {
914 eval { 1012 eval {
915 $cb->(); 1013 $cb->();
916 }; 1014 };
917 warn $@ if $@; 1015 warn $@ if $@;
1016 };
1017
1018 $coro->on_destroy (sub {
918 delete $self->{_coro}{$coro+0}; 1019 delete $self->{_coro}{$coro+0};
919 }; 1020 });
920 1021
921 $self->{_coro}{$coro+0} = $coro; 1022 $self->{_coro}{$coro+0} = $coro;
1023
1024 $coro
922} 1025}
923 1026
924cf::client->attach ( 1027cf::client->attach (
925 on_destroy => sub { 1028 on_destroy => sub {
926 my ($ns) = @_; 1029 my ($ns) = @_;
1167} 1270}
1168 1271
1169############################################################################# 1272#############################################################################
1170# initialisation 1273# initialisation
1171 1274
1172sub _perl_reload(&) { 1275sub _perl_reload() {
1173 my ($msg) = @_; 1276 warn "reloading...";
1174
1175 $msg->("reloading...");
1176 1277
1177 eval { 1278 eval {
1279 local $FREEZE = 1;
1280
1281 cf::emergency_save;
1282
1178 # cancel all watchers 1283 # cancel all watchers
1179 for (Event::all_watchers) { 1284 for (Event::all_watchers) {
1180 $_->cancel if $_->data & WF_AUTOCANCEL; 1285 $_->cancel if $_->data & WF_AUTOCANCEL;
1181 } 1286 }
1182 1287
1288 # cancel all extension coros
1289 $_->cancel for values %EXT_CORO;
1290 %EXT_CORO = ();
1291
1183 # unload all extensions 1292 # unload all extensions
1184 for (@exts) { 1293 for (@exts) {
1185 $msg->("unloading <$_>"); 1294 warn "unloading <$_>";
1186 unload_extension $_; 1295 unload_extension $_;
1187 } 1296 }
1188 1297
1189 # unload all modules loaded from $LIBDIR 1298 # unload all modules loaded from $LIBDIR
1190 while (my ($k, $v) = each %INC) { 1299 while (my ($k, $v) = each %INC) {
1191 next unless $v =~ /^\Q$LIBDIR\E\/.*\.pm$/; 1300 next unless $v =~ /^\Q$LIBDIR\E\/.*\.pm$/;
1192 1301
1193 $msg->("removing <$k>"); 1302 warn "removing <$k>";
1194 delete $INC{$k}; 1303 delete $INC{$k};
1195 1304
1196 $k =~ s/\.pm$//; 1305 $k =~ s/\.pm$//;
1197 $k =~ s/\//::/g; 1306 $k =~ s/\//::/g;
1198 1307
1203 Symbol::delete_package $k; 1312 Symbol::delete_package $k;
1204 } 1313 }
1205 1314
1206 # sync database to disk 1315 # sync database to disk
1207 cf::db_sync; 1316 cf::db_sync;
1317 IO::AIO::flush;
1208 1318
1209 # get rid of safe::, as good as possible 1319 # get rid of safe::, as good as possible
1210 Symbol::delete_package "safe::$_" 1320 Symbol::delete_package "safe::$_"
1211 for qw(cf::object cf::object::player cf::player cf::map cf::party cf::region); 1321 for qw(cf::attachable cf::object cf::object::player cf::client cf::player cf::map cf::party cf::region);
1212 1322
1213 # remove register_script_function callbacks 1323 # remove register_script_function callbacks
1214 # TODO 1324 # TODO
1215 1325
1216 # unload cf.pm "a bit" 1326 # unload cf.pm "a bit"
1219 # don't, removes xs symbols, too, 1329 # don't, removes xs symbols, too,
1220 # and global variables created in xs 1330 # and global variables created in xs
1221 #Symbol::delete_package __PACKAGE__; 1331 #Symbol::delete_package __PACKAGE__;
1222 1332
1223 # reload cf.pm 1333 # reload cf.pm
1224 $msg->("reloading cf.pm"); 1334 warn "reloading cf.pm";
1225 require cf; 1335 require cf;
1226 cf::_connect_to_perl; # nominally unnecessary, but cannot hurt 1336 cf::_connect_to_perl; # nominally unnecessary, but cannot hurt
1227 1337
1228 # load config and database again 1338 # load config and database again
1229 cf::cfg_load; 1339 cf::cfg_load;
1230 cf::db_load; 1340 cf::db_load;
1231 1341
1232 # load extensions 1342 # load extensions
1233 $msg->("load extensions"); 1343 warn "load extensions";
1234 cf::load_extensions; 1344 cf::load_extensions;
1235 1345
1236 # reattach attachments to objects 1346 # reattach attachments to objects
1237 $msg->("reattach"); 1347 warn "reattach";
1238 _global_reattach; 1348 _global_reattach;
1239 }; 1349 };
1240 $msg->($@) if $@; 1350 warn $@ if $@;
1241 1351
1242 $msg->("reloaded"); 1352 warn "reloaded";
1243}; 1353};
1244 1354
1245sub perl_reload() { 1355sub perl_reload() {
1246 _perl_reload { 1356 _perl_reload;
1247 warn $_[0];
1248 print "$_[0]\n";
1249 };
1250} 1357}
1251 1358
1252register "<global>", __PACKAGE__; 1359register "<global>", __PACKAGE__;
1253 1360
1254register_command "perl-reload" => sub { 1361register_command "perl-reload" => sub {
1255 my ($who, $arg) = @_; 1362 my ($who, $arg) = @_;
1256 1363
1257 if ($who->flag (FLAG_WIZ)) { 1364 if ($who->flag (FLAG_WIZ)) {
1365 $who->message ("reloading...");
1258 _perl_reload { 1366 _perl_reload;
1259 warn $_[0];
1260 $who->message ($_[0]);
1261 };
1262 } 1367 }
1263}; 1368};
1264 1369
1265unshift @INC, $LIBDIR; 1370unshift @INC, $LIBDIR;
1266 1371
1267$TICK_WATCHER = Event->timer ( 1372$TICK_WATCHER = Event->timer (
1373 reentrant => 0,
1268 prio => 0, 1374 prio => 0,
1269 at => $NEXT_TICK || 1, 1375 at => $NEXT_TICK || $TICK,
1270 data => WF_AUTOCANCEL, 1376 data => WF_AUTOCANCEL,
1271 cb => sub { 1377 cb => sub {
1378 unless ($FREEZE) {
1272 cf::server_tick; # one server iteration 1379 cf::server_tick; # one server iteration
1380 $RUNTIME += $TICK;
1381 }
1273 1382
1274 my $NOW = Event::time;
1275 $NEXT_TICK += $TICK; 1383 $NEXT_TICK += $TICK;
1276 1384
1277 # if we are delayed by four ticks or more, skip them all 1385 # if we are delayed by four ticks or more, skip them all
1278 $NEXT_TICK = $NOW if $NOW >= $NEXT_TICK + $TICK * 4; 1386 $NEXT_TICK = Event::time if Event::time >= $NEXT_TICK + $TICK * 4;
1279 1387
1280 $TICK_WATCHER->at ($NEXT_TICK); 1388 $TICK_WATCHER->at ($NEXT_TICK);
1281 $TICK_WATCHER->start; 1389 $TICK_WATCHER->start;
1282 }, 1390 },
1283); 1391);
1288 poll => 'r', 1396 poll => 'r',
1289 prio => 5, 1397 prio => 5,
1290 data => WF_AUTOCANCEL, 1398 data => WF_AUTOCANCEL,
1291 cb => \&IO::AIO::poll_cb); 1399 cb => \&IO::AIO::poll_cb);
1292 1400
1401# we must not ever block the main coroutine
1402$Coro::idle = sub {
1403 #Carp::cluck "FATAL: Coro::idle was called, major BUG\n";#d#
1404 warn "FATAL: Coro::idle was called, major BUG\n";
1405 (Coro::unblock_sub {
1406 Event::one_event;
1407 })->();
1408};
1409
12931 14101
1294 1411

Diff Legend

Removed lines
+ Added lines
< Changed lines
> Changed lines