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