1fc293f209ace278768b9aadf5d88c86c89fa951
[spider.git] / perl / cluster.pl
1 #!/usr/bin/env perl
2 #
3 # This is the DX cluster 'daemon'. It sits in the middle of its little
4 # web of client routines sucking and blowing data where it may.
5 #
6 # Hence the name of 'spider' (although it may become 'dxspider')
7 #
8 # Copyright (c) 1998 Dirk Koopman G1TLH
9 #
10 #
11 #
12
13 package main;
14
15 require 5.10.1;
16 use warnings;
17
18 use vars qw($root $is_win $systime $lockfn @inqueue $starttime $lockfn @outstanding_connects
19                         $zombies @listeners $lang $myalias @debug $userfn $clusteraddr
20                         $clusterport $mycall $decease $routeroot $me $reqreg $bumpexisting
21                         $allowdxby $dbh $dsn $dbuser $dbpass $do_xml $systime_days $systime_daystart
22                         $can_encode $maxconnect_user $maxconnect_node $idle_interval $log_flush_interval
23                         $broadcast_debug 
24                    );
25
26 $lang = 'en';                                   # default language
27 $clusteraddr = '127.0.0.1';             # cluster tcp host address - used for things like console.pl
28 $clusterport = 27754;                   # cluster tcp port
29 $yes = 'Yes';                                   # visual representation of yes
30 $no = 'No';                                             # ditto for no
31 $user_interval = 11*60;                 # the interval between unsolicited prompts if no traffic
32
33 # make sure that modules are searched in the order local then perl
34 BEGIN {
35         umask 002;
36
37         # take into account any local::lib that might be present
38         eval {
39                 require local::lib;
40         };
41         import local::lib unless ($@);
42
43         # root of directory tree for this system
44         $root = "/spider";
45         $root = $ENV{'DXSPIDER_ROOT'} if $ENV{'DXSPIDER_ROOT'};
46
47         unshift @INC, "$root/perl";     # this IS the right way round!
48         unshift @INC, "$root/local";
49
50         # do some validation of the input
51         die "The directory $root doesn't exist, please RTFM" unless -d $root;
52         die "$root/local doesn't exist, please RTFM" unless -d "$root/local";
53         die "$root/local/DXVars.pm doesn't exist, please RTFM" unless -e "$root/local/DXVars.pm";
54
55         # create some directories
56         mkdir "$root/local_cmd", 02774 unless -d "$root/local_cmd";
57
58         # locally stored data lives here
59         my $local_data = "$root/local_data";
60         mkdir $local_data, 02774 unless -d $local_data;
61
62         # try to create and lock a lockfile (this isn't atomic but
63         # should do for now
64         $lockfn = "$root/local_data/cluster.lck";       # lock file name
65         if (-w $lockfn) {
66                 open(CLLOCK, "$lockfn") or die "Can't open Lockfile ($lockfn) $!";
67                 my $pid = <CLLOCK>;
68                 if ($pid) {
69                         chomp $pid;
70                         if (kill 0, $pid) {
71                                 warn "Lockfile ($lockfn) and process $pid exist, another cluster running?\n";
72                                 exit 1;
73                         }
74                 }
75                 unlink $lockfn;
76                 close CLLOCK;
77         }
78         open(CLLOCK, ">$lockfn") or die "Can't open Lockfile ($lockfn) $!";
79         print CLLOCK "$$\n";
80         close CLLOCK;
81
82         $is_win = ($^O =~ /^MS/ || $^O =~ /^OS-2/) ? 1 : 0; # is it Windows?
83         $systime = time;
84         
85 }
86
87 use DXVars;
88 use SysVar;
89
90 use strict;
91
92 # order here is important - DXDebug snarfs Carp et al so that Mojo errors go into the debug log
93 use DXDebug;
94
95 use Mojolicious 7.26;
96 use Mojo::IOLoop;
97
98 use Msg;
99 use IntMsg;
100 use Internet;
101 use Listeners;
102 use ExtMsg;
103 use AGWConnect;
104 use AGWMsg;
105 use DXLog;
106 use DXLogPrint;
107 use DXUtil;
108 use DXChannel;
109 use DXUser;
110 use DXM;
111 use DXCommandmode;
112 use DXProtVars;
113 use DXProtout;
114 use DXProt;
115 use DXMsg;
116 use DXCron;
117 use DXConnect;
118 use DXBearing;
119 use DXDb;
120 use DXHash;
121 use DXDupe;
122 use Script;
123 use Prefix;
124 use Spot;
125 use Bands;
126 use Keps;
127 use Minimuf;
128 use Sun;
129 use Geomag;
130 use CmdAlias;
131 use Filter;
132 use AnnTalk;
133 use BBS;
134 use WCY;
135 use BadWords;
136 use Timer;
137 use Route;
138 use Route::Node;
139 use Route::User;
140 use Editable;
141 use Mrtg;
142 use USDB;
143 use UDPMsg;
144 use QSL;
145 use DXXml;
146 use DXSql;
147 use IsoTime;
148 use BPQMsg;
149 use RBN;
150
151
152 use Data::Dumper;
153 use IO::File;
154 use Fcntl ':flock';
155 use POSIX ":sys_wait_h";
156 use Web;
157
158 use vars qw($version $build $gitversion $gitbranch);
159
160 use Local;
161
162
163 @inqueue = ();                                  # the main input queue, an array of hashes
164 $systime = 0;                                   # the time now (in seconds)
165 $starttime = 0;                 # the starting time of the cluster
166 @outstanding_connects = ();     # list of outstanding connects
167 @listeners = ();                                # list of listeners
168 $reqreg = 0;                                    # 1 = registration required, 2 = deregister people
169 $bumpexisting = 1;                              # 1 = allow new connection to disconnect old, 0 - don't allow it
170 our $allowmultiple = 0;                         # This is used in conjunction with $bumpexisting, in a rather weird way.
171 our $min_reconnection_rate = 5*60;              # minimum value of seconds between connections per user to allow co-existing users
172 our $max_ssid = 15;                                     # highest ssid to be searched for a spare one on multiple connections
173
174 # If $allowmultiple > 0 and the $reconnection_rate is some value of seconds
175 # based on the average connection time calculated from the $user->conntimel entries / frequency is
176 # less than $reconnection_rate then we assume that there is more than one device (probably HRD) trying
177 # to connect "at once". In which case we probe for a spare SSID for a user callsign to allow up to 
178 # $allowmultiple connections per callsign. 
179
180 $allowdxby = 0;                                 # 1 = allow "dx by <othercall>", 0 - don't allow it
181 $maxconnect_user = 3;                   # the maximum no of concurrent connections a user can have at a time
182 $maxconnect_node = 0;                   # Ditto but for nodes. In either case if a new incoming connection
183                                                                 # takes the no of references in the routing table above these numbers
184                                                                 # then the connection is refused. This only affects INCOMING connections.
185 $idle_interval = 0.500;         # the wait between invocations of the main idle loop processing.
186 $log_flush_interval = 2;                # interval to wait between log flushes
187
188 our $ending;                                    # signal that we are ending;
189 our $broadcast_debug;                   # allow broadcasting of debug info down "enhanced" user connections
190 our $clssecs;                                   # the amount of cpu time the DXSpider process have consumed
191 our $cldsecs;                                   # the amount of cpu time any child processes have consumed
192
193
194 # send a message to call on conn and disconnect
195 sub already_conn
196 {
197         my ($conn, $call, $mess) = @_;
198
199         $conn->disable_read(1);
200         dbg("-> D $call $mess\n") if isdbg('chan');
201         $conn->send_now("D$call|$mess");
202         sleep(2);
203         $conn->disconnect;
204 }
205
206 # handle incoming messages
207 sub new_channel
208 {
209         my ($conn, $msg) = @_;
210         my ($sort, $call, $line) = DXChannel::decode_input(0, $msg);
211         return unless defined $sort;
212
213         my ($dxchan, $user);
214         
215         if (is_webcall($call) && $conn->isa('IntMsg')) {
216                 my $newcall = find_next_webcall();
217                 unless ($newcall) {
218                         already_conn($conn, $call, "Maximum no of web connected connects ($Web::maxssid) exceeded");
219                         return;
220                 }
221                 $call = $newcall;
222                 $user = DXUser::get_current($call);
223                 unless ($user) {
224                         $user = DXUser->new($call);
225                         $user->sort('W');
226                         $user->wantbeep(0);
227                         $user->name('web');
228                         $user->qth('on the web');
229                         $user->homenode($main::mycall);
230                         $user->lat($main::mylatitude);
231                         $user->long($main::mylongitude);
232                         $user->qra($main::mylocator);
233                 }
234                 $user->startt($main::systime);
235                 $conn->conns($call);
236                 $dxchan = Web->new($call, $conn, $user);
237                 $dxchan->enhanced(1);
238                 $dxchan->ve7cc(1);
239                 $msg =~ s/^A#WEB|/A$call|/;
240                 $conn->send_now("C$call");
241         } else {
242                 # "Normal" connections
243                 unless (is_callsign($call)) {
244                         already_conn($conn, $call, DXM::msg($lang, "illcall", $call));
245                         return;
246                 }
247
248                 # is he locked out ?
249                 $user = DXUser::get_current($call);
250                 my $basecall = $call;
251                 $basecall =~ s/-\d+$//; # remember this for later multiple user processing
252                 my $lock;
253                 if ($user) {
254                         # make sure we act on any locked status that the actual incoming call has.
255                         $lock = $user->lockout;
256                 } elsif ($allowmultiple && $call ne $basecall) {
257                     # if we are allowing multiple connections and there is a basecall minus incoming ssid, use the basecall's lock status
258                         $user = DXUser::get_current($basecall);
259                         $lock = $user->lockout if $user;
260                 }
261
262                 # now deal with the lock
263                 if ($lock) {
264                         my $host = $conn->peerhost;
265                         LogDbg('', "$call on $host is locked out, disconnected");
266                         $conn->disconnect;
267                         return;
268                 }
269
270                 # set up the basic channel info for "Normal" Users
271                 # is there one already connected to me - locally?
272
273                 $dxchan = DXChannel::get($call);
274                 my $newcall = $call;
275                 if ($dxchan) {
276                         if ($user && $user->is_node) {
277                                 already_conn($conn, $call, DXM::msg($lang, 'conother', $call, $main::mycall));
278                                 return;
279                         }
280                         if ($allowmultiple && $user->is_user) {
281                                 # determine whether we are a candidate, have we flip-flopped frequently enough?
282                                 my @lastconns = @{$user->connlist} if $user->connlist;
283                                 my $allow = 0;
284                                 if (@lastconns >= $DXUser::maxconnlist) {
285                                         $allow = $lastconns[-1]->[0] - $lastconns[0]->[0] < $min_reconnection_rate;
286                                 } 
287                                 # search for a spare ssid
288                         L1:     for (my $count = $call =~ /-\d+$/?0:1; $allow && $count < $allowmultiple; ) { # remember we have one call already
289                                         my $lastid = 1;
290                                         for (; $lastid < $max_ssid && $count < $allowmultiple; ++$lastid) {
291                                                 my $chan = DXChannel::get("$basecall-$lastid");
292                                                 if ($chan) {
293                                                         ++$count;
294                                                         next;
295                                                 }
296                                                 # we have a free call-ssid, save it
297                                                 $newcall = "$basecall-$lastid";
298                                                 last L1;
299                                         }
300                                 }
301                         }
302
303                         # handle "normal" (non-multiple) connections in the existing way
304                         if ($call eq $newcall) {
305                                 if ($bumpexisting) {
306                                         my $ip = $dxchan->hostname;
307                                         $dxchan->send_now('D', DXM::msg($lang, 'conbump', $call, $ip));
308                                         LogDbg('', "$call bumped off by $ip, disconnected");
309                                         $dxchan->disconnect;
310                                 } else {
311                                         already_conn($conn, $call, DXM::msg($lang, 'conother', $call, $main::mycall));
312                                         return;
313                                 }
314                         }
315
316                         # make sure that the conn has the (possibly) new callsign
317                         $conn->conns($newcall);
318                         $msg =~ s/$call/$newcall/;
319                 }
320
321
322                 # (fairly) politely disconnect people that are connected to too many other places at once
323                 my $r = Route::get($call);
324                 if ($conn->{sort} && $conn->{sort} =~ /^I/ && $r && $user) {
325                         my @n = $r->parents;
326                         my $m = $r->isa('Route::Node') ? $maxconnect_node : $maxconnect_user;
327                         my $c = $user->maxconnect;
328                         my $v;
329                         $v = defined $c ? $c : $m;
330                         if ($v && @n >= $v+$allowmultiple) {
331                                 my $nodes = join ',', @n;
332                                 LogDbg('', "$call has too many connections ($v) at $nodes - disconnected");
333                                 already_conn($conn, $call, DXM::msg($lang, 'contomany', $call, $v, $nodes));
334                                 return;
335                         }
336                 }
337                 
338                 if ($user) {
339                         $user->{lang} = $main::lang if !$user->{lang}; # to autoupdate old systems
340                 } else {
341                         $user = DXUser->new($call);
342                 }
343
344                 # create the channel
345                 # NOTE we are SHARING the same $user if $allowmultiple is > 1
346                 
347                 $user->startt($systime); # mark the start time of this connection
348                 if ($user->is_node) {
349                         $dxchan = DXProt->new($call, $conn, $user);     
350                 } elsif ($user->is_rbn) {
351                         $dxchan = RBN->new($newcall, $conn, $user);
352                 } elsif ($user->is_user) {
353                         $dxchan = DXCommandmode->new($newcall, $conn, $user);
354                 } else {
355                         die "Invalid sort of user on $call = $sort";
356                 }
357         }
358         
359
360         # set callbacks
361         $conn->set_error(sub {my $err = shift; LogDbg('', "Comms error '$err' received for call $dxchan->{call}"); $dxchan->disconnect(1);});
362         $conn->set_on_eof(sub {$dxchan->disconnect});
363         $conn->set_rproc(sub {my ($conn,$msg) = @_; $dxchan->rec($msg);});
364         if ($sort eq 'W') {
365                 $dxchan->enhanced(1);
366                 $dxchan->sort('W');
367         }
368         $dxchan->rec($msg);
369 }
370
371
372 sub login
373 {
374         return \&new_channel;
375 }
376
377 our $ceasing;
378
379 # cease running this program, close down all the connections nicely
380 sub cease
381 {
382         my $dxchan;
383
384         cluck("ceasing") if $ceasing; 
385         
386         return if $ceasing++;
387         
388         unless ($is_win) {
389                 $SIG{'TERM'} = 'IGNORE';
390                 $SIG{'INT'} = 'IGNORE';
391         }
392
393
394         if (defined &Local::finish) {
395                 eval {
396                         Local::finish();   # end local processing
397                 };
398                 dbg("Local::finish error $@") if $@;
399         }
400
401
402         # disconnect AGW
403         AGWMsg::finish();
404         BPQMsg::finish();
405
406         # disconnect UDP customers
407         UDPMsg::finish();
408
409         # end everything else
410         DXUser::finish();
411         DXDupe::finish();
412
413         # close all databases
414         DXDb::closeall;
415
416         # close all listeners
417         foreach my $l (@listeners) {
418                 $l->close_server;
419         }
420
421         LogDbg('cluster', "DXSpider V$version, build $build (git: $gitbranch/$gitversion) ended");
422         dbg("bye bye everyone - bye bye");
423         dbgclose();
424         Logclose();
425
426         $dbh->finish if $dbh;
427
428         unlink $lockfn;
429 }
430
431 # the reaper of children
432 sub reap
433 {
434         my $cpid;
435         while (($cpid = waitpid(-1, WNOHANG)) > 0) {
436                 dbg("cpid: $cpid") if isdbg('reap');
437 #               Msg->pid_gone($cpid);
438                 $zombies-- if $zombies > 0;
439         }
440         dbg("cpid: $cpid") if isdbg('reap');
441 }
442
443 # this is where the input queue is dealt with and things are dispatched off to other parts of
444 # the cluster
445
446 sub uptime
447 {
448         my $t = $systime - $starttime;
449         my $days = int $t / 86400;
450         $t -= $days * 86400;
451         my $hours = int $t / 3600;
452         $t -= $hours * 3600;
453         my $mins = int $t / 60;
454         return sprintf "%d %02d:%02d", $days, $hours, $mins;
455 }
456
457 sub AGWrestart
458 {
459         AGWMsg::init(\&new_channel);
460 }
461
462
463 sub setup_start
464 {
465
466         #############################################################
467         #
468         # The start of the main line of code
469         #
470         #############################################################
471
472         $starttime = $systime = time;
473         $systime_days = int ($systime / 86400);
474         $systime_daystart = $systime_days * 86400;
475         $lang = 'en' unless $lang;
476
477         unless ($DB::VERSION) {
478                 $SIG{INT} = $SIG{TERM} = \&cease;
479         }
480
481         # open the debug file, set various FHs to be unbuffered
482         dbginit($broadcast_debug ? \&DXCommandmode::broadcast_debug : undef);
483         foreach (@debug) {
484                 dbgadd($_);
485         }
486         STDOUT->autoflush(1);
487
488
489         # try to load the database
490         if (DXSql::init($dsn)) {
491                 $dbh = DXSql->new($dsn);
492                 $dbh = $dbh->connect($dsn, $dbuser, $dbpass) if $dbh;
493         }
494
495         # try to load Encode and Git
496         {
497                 local $^W = 0;
498                 my $w = $SIG{__DIE__};
499                 $SIG{__DIE__} = 'IGNORE';
500                 eval { require Encode; };
501                 unless ($@) {
502                         import Encode;
503                         $can_encode = 1;
504                 }
505                 $gitbranch = 'none';
506                 $gitversion = 'none';
507                 eval { require Git; };
508                 unless ($@) {
509                         import Git;
510                 
511                         # determine the real version number
512                         my $repo = Git->repository(Directory => "$root/.git");
513                         if ($repo) {
514                                 my $desc = $repo->command_oneline(['describe', '--long'], STDERR => 0);
515                                 if ($desc) {
516                                         my ($v, $s, $b, $g) = $desc =~ /^([\d.]+)(?:\.(\d+))?-(\d+)-g([0-9a-f]+)/;
517                                         $s ||= '';
518                                         dbg("Git: $desc") if isdbg('git');
519                                         dbg("Git: V=$v S=$s B=$b g=$g") if isdbg('git');
520                                         $version = $v;
521                                         $build = $b || 0;
522                                         $gitversion = "$g\[r]";
523                                 }
524                                 my @branch = $repo->command([qw{branch}], STDERR=>0);
525                                 for (@branch) {
526                                         my ($star, $b) = split /\s+/;
527                                         if ($star eq '*') {
528                                                 $gitbranch = $b;
529                                                 last;
530                                         }
531                                 }
532                         }
533                 }
534                 $SIG{__DIE__} = $w;
535         }
536
537         # try to load XML::Simple
538         DXXml::init();
539
540         # banner
541         my ($year) = (gmtime)[5];
542         $year += 1900;
543         LogDbg('cluster', "DXSpider V$version, build $build (git: $gitbranch/$gitversion) started");
544         dbg("Copyright (c) 1998-$year Dirk Koopman G1TLH");
545
546         # load Prefixes
547         dbg("loading prefixes ...");
548         dbg(USDB::init());
549         my $r = Prefix::init();
550         confess $r if $r;
551
552         # load band data
553         dbg("loading band data ...");
554         Bands::load();
555
556         # initialise User file system
557         dbg("loading user file system ...");
558         DXUser::init(4);                        # version 4 == json format
559
560         # look for the sysop and the alias user and complain if they aren't there
561         {
562                 die "\$myalias \& \$mycall are the same ($mycall)!, they must be different (hint: make \$mycall = '${mycall}-2';). Oh and don't forget to rerun create_sysop.pl!" if $mycall eq $myalias;
563                 my $ref = DXUser::get($mycall);
564                 die "$mycall missing, run the create_sysop.pl script and please RTFM" unless $ref && $ref->priv == 9;
565                 my $oldsort = $ref->sort;
566                 if ($oldsort ne 'S') {
567                         $ref->sort('S');
568                         dbg "Resetting node type from $oldsort -> DXSpider ('S')";
569                 }
570                 $ref = DXUser::get($myalias);
571                 die "$myalias missing, run the create_sysop.pl script and please RTFM" unless $ref && $ref->priv == 9;
572                 $oldsort = $ref->sort;
573                 if ($oldsort ne 'U') {
574                         $ref->sort('U');
575                         dbg "Resetting sysop user type from $oldsort -> User ('U')";
576                 }
577         }
578
579         # start listening for incoming messages/connects
580         dbg("starting listeners ...");
581         my $conn = IntMsg->new_server($clusteraddr, $clusterport, \&login);
582         $conn->conns("Server $clusteraddr/$clusterport using IntMsg");
583         push @listeners, $conn;
584         dbg("Internal port: $clusteraddr $clusterport using IntMsg");
585         foreach my $l (@main::listen) {
586                 no strict 'refs';
587                 my $pkg = $l->[2] || 'ExtMsg';
588                 my $login = $l->[3] || 'login';
589
590                 $conn = $pkg->new_server($l->[0], $l->[1], \&{"${pkg}::${login}"});
591                 $conn->conns("Server $l->[0]/$l->[1] using ${pkg}::${login}");
592                 push @listeners, $conn;
593                 dbg("External Port: $l->[0] $l->[1] using ${pkg}::${login}");
594         }
595
596         dbg("AGW Listener") if $AGWMsg::enable;
597         AGWrestart();
598
599         dbg("BPQ Listener") if $BPQMsg::enable;
600         BPQMsg::init(\&new_channel);
601
602         dbg("UDP Listener") if $UDPMsg::enable;
603         UDPMsg::init(\&new_channel);
604
605         # load bad words
606         dbg("load badwords: " . (BadWords::load or "Ok"));
607
608         # prime some signals
609         unless ($DB::VERSION) {
610                 $SIG{INT} = $SIG{TERM} = sub { $ending = 10; };
611         }
612
613         unless ($is_win) {
614                 $SIG{HUP} = 'IGNORE';
615                 $SIG{CHLD} = sub { $zombies++ };
616
617                 $SIG{PIPE} = sub {      dbg("Broken PIPE signal received"); };
618                 $SIG{IO} = sub {        dbg("SIGIO received"); };
619                 $SIG{WINCH} = $SIG{STOP} = $SIG{CONT} = 'IGNORE';
620                 $SIG{KILL} = 'DEFAULT'; # as if it matters....
621
622                 # catch the rest with a hopeful message
623                 for (keys %SIG) {
624                         if (!$SIG{$_}) {
625                                 #               dbg("Catching SIG $_") if isdbg('chan');
626                                 $SIG{$_} = sub { my $sig = shift;       DXDebug::confess("Caught signal $sig");  };
627                         }
628                 }
629         }
630
631         # start dupe system
632         dbg("Starting Dupe system");
633         DXDupe::init();
634
635         # read in system messages
636         dbg("Read in Messages");
637         DXM->init();
638
639         # read in command aliases
640         dbg("Read in Aliases");
641         CmdAlias->init();
642
643         # initialise the Geomagnetic data engine
644         dbg("Start WWV");
645         Geomag->init();
646         dbg("Start WCY");
647         WCY->init();
648
649         # initial the Spot stuff
650         dbg("Starting DX Spot system");
651         Spot->init();
652
653         # initialise the protocol engine
654         dbg("Start Protocol Engines ...");
655         DXProt->init();
656
657         # put in a DXCluster node for us here so we can add users and take them away
658         $routeroot = Route::Node->new($mycall, $version*100+5300, Route::here($main::me->here)|Route::conf($main::me->conf));
659         $routeroot->do_pc9x(1);
660         $routeroot->via_pc92(1);
661
662         # make sure that there is a routing OUTPUT node default file
663         #unless (Filter::read_in('route', 'node_default', 0)) {
664         #       my $dxcc = $main::me->dxcc;
665         #       $Route::filterdef->cmd($main::me, 'route', 'accept', "node_default call $mycall" );
666         #}
667
668         # read in any existing message headers and clean out old crap
669         dbg("reading existing message headers ...");
670         DXMsg->init();
671         DXMsg::clean_old();
672
673         # read in any cron jobs
674         dbg("reading cron jobs ...");
675         DXCron->init();
676
677         # read in database desriptors
678         dbg("reading database descriptors ...");
679         DXDb::load();
680
681         # starting local stuff
682         dbg("doing local initialisation ...");
683         QSL::init(1);
684         if (defined &Local::init) {
685                 eval {
686                         Local::init();
687                 };
688                 dbg("Local::init error $@") if $@;
689         }
690
691
692         # this, such as it is, is the main loop!
693         dbg("orft we jolly well go ...");
694         my $script = new Script "startup";
695         $script->run($main::me) if $script;
696
697         #open(DB::OUT, "|tee /tmp/aa");
698 }
699
700 our $io_disconnected;
701
702 sub idle_loop
703 {
704         BPQMsg::process();
705 #       DXCommandmode::process(); # process ongoing command mode stuff
706 #       DXProt::process();              # process ongoing ak1a pcxx stuff
707
708         if (defined &Local::process) {
709                 eval {
710                         Local::process();       # do any localised processing
711                 };
712                 dbg("Local::process error $@") if $@;
713         }
714
715         while ($ending) {
716                 my $dxchan;
717
718                 dbg("DXSpider Ending $ending");
719
720                 unless ($io_disconnected++) {
721
722                         # disconnect users
723                         foreach $dxchan (DXChannel::get_all_users) {
724                                 $dxchan->disconnect;
725                         }
726
727                         # disconnect nodes
728                         foreach $dxchan (DXChannel::get_all_nodes) {
729                                 next if $dxchan == $main::me;
730                                 $dxchan->disconnect(2);
731                         }
732                         $main::me->disconnect;
733                 }
734
735                 Mojo::IOLoop->stop if --$ending <= 0;
736         }
737 }
738
739 sub per_sec
740 {
741         my $timenow = time;
742
743         reap() if $zombies;
744         $systime = $timenow;
745         my $days = int ($systime / 86400);
746         if ($systime_days != $days) {
747                 $systime_days = $days;
748                 $systime_daystart = $days * 86400;
749         }
750         IsoTime::update($systime);
751         DXCommandmode::process(); # process ongoing command mode stuff
752         DXProt::process();              # process ongoing ak1a pcxx stuff
753         DXCron::process();      # do cron jobs
754         DXXml::process();
755         DXConnect::process();
756         DXMsg::process();
757         DXDb::process();
758         DXUser::process();
759         DXDupe::process();
760         DXCron::process();                      # do cron jobs
761         IsoTime::update($systime);
762         DXConnect::process();
763         DXUser::process();
764         AGWMsg::process();
765         
766         Timer::handler();
767         DXLog::flushall();
768 }
769
770 sub per_10_sec
771 {
772
773 }
774
775
776 sub per_minute
777 {
778
779 }
780
781 sub per_10_minute
782 {
783
784 }
785
786 sub per_hour
787 {
788
789 }
790
791 sub per_day
792 {
793
794 }
795
796 sub start_node
797 {
798         dbg("Before Web::start_node");
799
800         Mojo::IOLoop->start unless Mojo::IOLoop->is_running;
801
802         dbg("After Web::start_node");
803 }
804
805 setup_start();
806
807 my $main_loop = Mojo::IOLoop->recurring($idle_interval => \&idle_loop);
808 my $log_flush_loop = Mojo::IOLoop->recurring($log_flush_interval => \&DXLog::flushall);
809 my $cpusecs_loop = Mojo::IOLoop->recurring(5 => sub {my @t = times; $clssecs = $t[0]+$t[1]; $cldsecs = $t[2]+$t[3]});
810 my $persec =  Mojo::IOLoop->recurring(1 => \&per_sec);
811 my $per10sec =  Mojo::IOLoop->recurring(10 => \&per_10_sec);
812 my $permin =  Mojo::IOLoop->recurring(60 => \&per_minute);
813 my $per10min =  Mojo::IOLoop->recurring(600 => \&per_10_minute);
814 my $perhour =  Mojo::IOLoop->recurring(3600 => \&per_hour);
815 my $perday =  Mojo::IOLoop->recurring(86400 => \&per_day);
816
817 start_node();
818
819 cease(0);
820
821 exit(0);
822