Fix all the DXUser API changes to use JSON
[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
384         if (defined &Local::finish) {
385                 eval {
386                         Local::finish();   # end local processing
387                 };
388                 dbg("Local::finish error $@") if $@;
389         }
390
391
392         # disconnect AGW
393         AGWMsg::finish();
394         BPQMsg::finish();
395
396         # disconnect UDP customers
397         UDPMsg::finish();
398
399         # end everything else
400         DXUser::finish();
401         DXDupe::finish();
402
403         # close all databases
404         DXDb::closeall;
405
406         # close all listeners
407         foreach my $l (@listeners) {
408                 $l->close_server;
409         }
410
411         LogDbg('cluster', "DXSpider V$version, build $build (git: $gitversion) ended");
412         dbg("bye bye everyone - bye bye");
413         dbgclose();
414         Logclose();
415
416         $dbh->finish if $dbh;
417
418         unlink $lockfn;
419 }
420
421 # the reaper of children
422 sub reap
423 {
424         my $cpid;
425         while (($cpid = waitpid(-1, WNOHANG)) > 0) {
426                 dbg("cpid: $cpid") if isdbg('reap');
427 #               Msg->pid_gone($cpid);
428                 $zombies-- if $zombies > 0;
429         }
430         dbg("cpid: $cpid") if isdbg('reap');
431 }
432
433 # this is where the input queue is dealt with and things are dispatched off to other parts of
434 # the cluster
435
436 sub uptime
437 {
438         my $t = $systime - $starttime;
439         my $days = int $t / 86400;
440         $t -= $days * 86400;
441         my $hours = int $t / 3600;
442         $t -= $hours * 3600;
443         my $mins = int $t / 60;
444         return sprintf "%d %02d:%02d", $days, $hours, $mins;
445 }
446
447 sub AGWrestart
448 {
449         AGWMsg::init(\&new_channel);
450 }
451
452
453 sub setup_start
454 {
455
456         #############################################################
457         #
458         # The start of the main line of code
459         #
460         #############################################################
461
462         $starttime = $systime = time;
463         $systime_days = int ($systime / 86400);
464         $systime_daystart = $systime_days * 86400;
465         $lang = 'en' unless $lang;
466
467         unless ($DB::VERSION) {
468                 $SIG{INT} = $SIG{TERM} = \&cease;
469         }
470
471         # open the debug file, set various FHs to be unbuffered
472         dbginit($broadcast_debug ? \&DXCommandmode::broadcast_debug : undef);
473         foreach (@debug) {
474                 dbgadd($_);
475         }
476         STDOUT->autoflush(1);
477
478         
479         # try to load the database
480         if (DXSql::init($dsn)) {
481                 $dbh = DXSql->new($dsn);
482                 $dbh = $dbh->connect($dsn, $dbuser, $dbpass) if $dbh;
483         }
484
485         # try to load Encode and Git
486         {
487                 local $^W = 0;
488                 my $w = $SIG{__DIE__};
489                 $SIG{__DIE__} = 'IGNORE';
490                 eval { require Encode; };
491                 unless ($@) {
492                         import Encode;
493                         $can_encode = 1;
494                 }
495                 eval { require Git; };
496                 unless ($@) {
497                         import Git;
498                 
499                         # determine the real version number
500                         my $repo = Git->repository(Directory => "$root/.git");
501                         if ($repo) {
502                                 my $desc = $repo->command_oneline(['describe', '--long'], STDERR => 0);
503                                 if ($desc) {
504                                         my ($v, $s, $b, $g) = $desc =~ /^([\d.]+)(?:\.(\d+))?-(\d+)-g([0-9a-f]+)/;
505                                         $s ||= '';
506                                         dbg("Git: $desc");
507                                         dbg("Git: V=$v S=$s B=$b g=$g");
508                                         $version = $v;
509                                         $build = $b || 0;
510                                         $gitversion = "$g\[r]";
511                                 }
512                         }
513                 }
514                 $SIG{__DIE__} = $w;
515         }
516
517         # try to load XML::Simple
518         DXXml::init();
519
520         # banner
521         my ($year) = (gmtime)[5];
522         $year += 1900;
523         LogDbg('cluster', "DXSpider V$version, build $build (git: $gitversion) started");
524         dbg("Copyright (c) 1998-$year Dirk Koopman G1TLH");
525
526         # load Prefixes
527         dbg("loading prefixes ...");
528         dbg(USDB::init());
529         my $r = Prefix::init();
530         confess $r if $r;
531
532         # load band data
533         dbg("loading band data ...");
534         Bands::load();
535
536         # initialise User file system
537         dbg("loading user file system ...");
538         DXUser::init(4);                        # version 4 == json format
539
540         # look for the sysop and the alias user and complain if they aren't there
541         {
542                 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;
543                 my $ref = DXUser::get($mycall);
544                 die "$mycall missing, run the create_sysop.pl script and please RTFM" unless $ref && $ref->priv == 9;
545                 my $oldsort = $ref->sort;
546                 if ($oldsort ne 'S') {
547                         $ref->sort('S');
548                         dbg "Resetting node type from $oldsort -> DXSpider ('S')";
549                 }
550                 $ref = DXUser::get($myalias);
551                 die "$myalias missing, run the create_sysop.pl script and please RTFM" unless $ref && $ref->priv == 9;
552                 $oldsort = $ref->sort;
553                 if ($oldsort ne 'U') {
554                         $ref->sort('U');
555                         dbg "Resetting sysop user type from $oldsort -> User ('U')";
556                 }
557         }
558
559         # start listening for incoming messages/connects
560         dbg("starting listeners ...");
561         my $conn = IntMsg->new_server($clusteraddr, $clusterport, \&login);
562         $conn->conns("Server $clusteraddr/$clusterport using IntMsg");
563         push @listeners, $conn;
564         dbg("Internal port: $clusteraddr $clusterport using IntMsg");
565         foreach my $l (@main::listen) {
566                 no strict 'refs';
567                 my $pkg = $l->[2] || 'ExtMsg';
568                 my $login = $l->[3] || 'login';
569
570                 $conn = $pkg->new_server($l->[0], $l->[1], \&{"${pkg}::${login}"});
571                 $conn->conns("Server $l->[0]/$l->[1] using ${pkg}::${login}");
572                 push @listeners, $conn;
573                 dbg("External Port: $l->[0] $l->[1] using ${pkg}::${login}");
574         }
575
576         dbg("AGW Listener") if $AGWMsg::enable;
577         AGWrestart();
578
579         dbg("BPQ Listener") if $BPQMsg::enable;
580         BPQMsg::init(\&new_channel);
581
582         dbg("UDP Listener") if $UDPMsg::enable;
583         UDPMsg::init(\&new_channel);
584
585         # load bad words
586         dbg("load badwords: " . (BadWords::load or "Ok"));
587
588         # prime some signals
589         unless ($DB::VERSION) {
590                 $SIG{INT} = $SIG{TERM} = sub { $ending = 10; };
591         }
592
593         unless ($is_win) {
594                 $SIG{HUP} = 'IGNORE';
595                 $SIG{CHLD} = sub { $zombies++ };
596
597                 $SIG{PIPE} = sub {      dbg("Broken PIPE signal received"); };
598                 $SIG{IO} = sub {        dbg("SIGIO received"); };
599                 $SIG{WINCH} = $SIG{STOP} = $SIG{CONT} = 'IGNORE';
600                 $SIG{KILL} = 'DEFAULT'; # as if it matters....
601
602                 # catch the rest with a hopeful message
603                 for (keys %SIG) {
604                         if (!$SIG{$_}) {
605                                 #               dbg("Catching SIG $_") if isdbg('chan');
606                                 $SIG{$_} = sub { my $sig = shift;       DXDebug::confess("Caught signal $sig");  };
607                         }
608                 }
609         }
610
611         # start dupe system
612         dbg("Starting Dupe system");
613         DXDupe::init();
614
615         # read in system messages
616         dbg("Read in Messages");
617         DXM->init();
618
619         # read in command aliases
620         dbg("Read in Aliases");
621         CmdAlias->init();
622
623         # initialise the Geomagnetic data engine
624         dbg("Start WWV");
625         Geomag->init();
626         dbg("Start WCY");
627         WCY->init();
628
629         # initial the Spot stuff
630         dbg("Starting DX Spot system");
631         Spot->init();
632
633         # initialise the protocol engine
634         dbg("Start Protocol Engines ...");
635         DXProt->init();
636
637         # put in a DXCluster node for us here so we can add users and take them away
638         $routeroot = Route::Node->new($mycall, $version*100+5300, Route::here($main::me->here)|Route::conf($main::me->conf));
639         $routeroot->do_pc9x(1);
640         $routeroot->via_pc92(1);
641
642         # make sure that there is a routing OUTPUT node default file
643         #unless (Filter::read_in('route', 'node_default', 0)) {
644         #       my $dxcc = $main::me->dxcc;
645         #       $Route::filterdef->cmd($main::me, 'route', 'accept', "node_default call $mycall" );
646         #}
647
648         # read in any existing message headers and clean out old crap
649         dbg("reading existing message headers ...");
650         DXMsg->init();
651         DXMsg::clean_old();
652
653         # read in any cron jobs
654         dbg("reading cron jobs ...");
655         DXCron->init();
656
657         # read in database desriptors
658         dbg("reading database descriptors ...");
659         DXDb::load();
660
661         # starting local stuff
662         dbg("doing local initialisation ...");
663         QSL::init(1);
664         if (defined &Local::init) {
665                 eval {
666                         Local::init();
667                 };
668                 dbg("Local::init error $@") if $@;
669         }
670
671
672         # this, such as it is, is the main loop!
673         dbg("orft we jolly well go ...");
674         my $script = new Script "startup";
675         $script->run($main::me) if $script;
676
677         #open(DB::OUT, "|tee /tmp/aa");
678 }
679
680 our $io_disconnected;
681
682 sub idle_loop
683 {
684         BPQMsg::process();
685 #       DXCommandmode::process(); # process ongoing command mode stuff
686 #       DXProt::process();              # process ongoing ak1a pcxx stuff
687
688         if (defined &Local::process) {
689                 eval {
690                         Local::process();       # do any localised processing
691                 };
692                 dbg("Local::process error $@") if $@;
693         }
694
695         while ($ending) {
696                 my $dxchan;
697
698                 dbg("DXSpider Ending $ending");
699
700                 unless ($io_disconnected++) {
701
702                         # disconnect users
703                         foreach $dxchan (DXChannel::get_all_users) {
704                                 $dxchan->disconnect;
705                         }
706
707                         # disconnect nodes
708                         foreach $dxchan (DXChannel::get_all_nodes) {
709                                 next if $dxchan == $main::me;
710                                 $dxchan->disconnect(2);
711                         }
712                         $main::me->disconnect;
713                 }
714
715                 Mojo::IOLoop->stop if --$ending <= 0;
716         }
717 }
718
719 sub per_sec
720 {
721         my $timenow = time;
722
723         reap() if $zombies;
724         $systime = $timenow;
725         my $days = int ($systime / 86400);
726         if ($systime_days != $days) {
727                 $systime_days = $days;
728                 $systime_daystart = $days * 86400;
729         }
730         IsoTime::update($systime);
731         DXCommandmode::process(); # process ongoing command mode stuff
732         DXProt::process();              # process ongoing ak1a pcxx stuff
733         DXCron::process();      # do cron jobs
734         DXXml::process();
735         DXConnect::process();
736         DXMsg::process();
737         DXDb::process();
738         DXUser::process();
739         DXDupe::process();
740         DXCron::process();                      # do cron jobs
741         IsoTime::update($systime);
742         DXConnect::process();
743         DXUser::process();
744         AGWMsg::process();
745         
746         Timer::handler();
747         DXLog::flushall();
748 }
749
750 sub per_10_sec
751 {
752
753 }
754
755
756 sub per_minute
757 {
758
759 }
760
761 sub per_10_minute
762 {
763
764 }
765
766 sub per_hour
767 {
768
769 }
770
771 sub per_day
772 {
773
774 }
775
776 sub start_node
777 {
778         dbg("Before Web::start_node");
779
780         Mojo::IOLoop->start unless Mojo::IOLoop->is_running;
781
782         dbg("After Web::start_node");
783 }
784
785 setup_start();
786
787 my $main_loop = Mojo::IOLoop->recurring($idle_interval => \&idle_loop);
788 my $log_flush_loop = Mojo::IOLoop->recurring($log_flush_interval => \&DXLog::flushall);
789 my $cpusecs_loop = Mojo::IOLoop->recurring(5 => sub {my @t = times; $clssecs = $t[0]+$t[1]; $cldsecs = $t[2]+$t[3]});
790 my $persec =  Mojo::IOLoop->recurring(1 => \&per_sec);
791 my $per10sec =  Mojo::IOLoop->recurring(10 => \&per_10_sec);
792 my $permin =  Mojo::IOLoop->recurring(60 => \&per_minute);
793 my $per10min =  Mojo::IOLoop->recurring(600 => \&per_10_minute);
794 my $perhour =  Mojo::IOLoop->recurring(3600 => \&per_hour);
795 my $perday =  Mojo::IOLoop->recurring(86400 => \&per_day);
796
797 start_node();
798
799 cease(0);
800
801 exit(0);
802