2330bcda5639f5ae02986ce7119d206b5f1990b5
[spider.git] / perl / cluster.pl
1 #!/usr/bin/perl -w
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 # $Id$
11
12
13 require 5.004;
14
15 # make sure that modules are searched in the order local then perl
16 BEGIN {
17         umask 002;
18         
19         # root of directory tree for this system
20         $root = "/spider"; 
21         $root = $ENV{'DXSPIDER_ROOT'} if $ENV{'DXSPIDER_ROOT'};
22         
23         unshift @INC, "$root/perl";     # this IS the right way round!
24         unshift @INC, "$root/local";
25
26         # try to create and lock a lockfile (this isn't atomic but 
27         # should do for now
28         $lockfn = "$root/perl/cluster.lock";       # lock file name
29         if (-e $lockfn) {
30                 open(CLLOCK, "$lockfn") or die "Can't open Lockfile ($lockfn) $!";
31                 my $pid = <CLLOCK>;
32                 chomp $pid;
33                 die "Lockfile ($lockfn) and process $pid exist, another cluster running?" if kill 0, $pid;
34                 close CLLOCK;
35         }
36         open(CLLOCK, ">$lockfn") or die "Can't open Lockfile ($lockfn) $!";
37         print CLLOCK "$$\n";
38         close CLLOCK;
39 }
40
41 use Msg;
42 use DXVars;
43 use DXDebug;
44 use DXLog;
45 use DXLogPrint;
46 use DXUtil;
47 use DXChannel;
48 use DXUser;
49 use DXM;
50 use DXCommandmode;
51 use DXProt;
52 use DXMsg;
53 use DXCluster;
54 use DXCron;
55 use DXConnect;
56 use Prefix;
57 use Bands;
58 use Geomag;
59 use CmdAlias;
60 use Filter;
61 use Local;
62 use Fcntl ':flock'; 
63
64 use Carp;
65
66 package main;
67
68 @inqueue = ();                                  # the main input queue, an array of hashes
69 $systime = 0;                                   # the time now (in seconds)
70 $version = "1.24";                              # the version no of the software
71 $starttime = 0;                 # the starting time of the cluster   
72 $lockfn = "cluster.lock";       # lock file name
73       
74 # handle disconnections
75 sub disconnect
76 {
77         my $dxchan = shift;
78         return if !defined $dxchan;
79         $dxchan->disconnect();
80 }
81
82 # send a message to call on conn and disconnect
83 sub already_conn
84 {
85         my ($conn, $call, $mess) = @_;
86         
87         dbg('chan', "-> D $call $mess\n"); 
88         $conn->send_now("D$call|$mess");
89         sleep(1);
90         dbg('chan', "-> Z $call bye\n");
91         $conn->send_now("Z$call|bye"); # this will cause 'client' to disconnect
92 }
93
94 # handle incoming messages
95 sub rec
96 {
97         my ($conn, $msg, $err) = @_;
98         my $dxchan = DXChannel->get_by_cnum($conn); # get the dxconnnect object for this message
99         
100         if (defined $err && $err) {
101                 disconnect($dxchan) if defined $dxchan;
102                 return;
103         }
104         
105         # set up the basic channel info - this needs a bit more thought - there is duplication here
106         if (!defined $dxchan) {
107                 my ($sort, $call, $line) = $msg =~ /^(\w)(\S+)\|(.*)$/;
108                 
109                 # is there one already connected elsewhere in the cluster (and not a cluster)
110                 my $user = DXUser->get($call);
111                 if ($user) {
112                         if (($user->sort eq 'A' || $call eq $myalias) && !DXCluster->get_exact($call)) {
113                                 ;
114                         } else {
115                                 if (DXCluster->get($call) || DXChannel->get($call)) {
116                                         my $mess = DXM::msg($lang, $user->sort eq 'A' ? 'concluster' : 'conother', $call);
117                                         already_conn($conn, $call, $mess);
118                                         return;
119                                 }
120                         }
121                         $user->{lang} = $main::lang if !$user->{lang}; # to autoupdate old systems
122                 } else {
123                         if (DXCluster->get($call)) {
124                                 my $mess = DXM::msg($lang, 'conother', $call);
125                                 already_conn($conn, $call, $mess);
126                                 return;
127                         }
128                         $user = DXUser->new($call);
129                 }
130
131                 # is he locked out ?
132                 if ($user->lockout) {
133                         Log('DXCommand', "$call is locked out, disconnected");
134                         $conn->send_now("Z$call|bye"); # this will cause 'client' to disconnect
135                         return;
136                 }
137
138                 # create the channel
139                 $dxchan = DXCommandmode->new($call, $conn, $user) if ($user->sort eq 'U');
140                 $dxchan = DXProt->new($call, $conn, $user) if ($user->sort eq 'A');
141                 die "Invalid sort of user on $call = $sort" if !$dxchan;
142         }
143         
144         # queue the message and the channel object for later processing
145         if (defined $msg) {
146                 my $self = bless {}, "inqueue";
147                 $self->{dxchan} = $dxchan;
148                 $self->{data} = $msg;
149                 push @inqueue, $self;
150         }
151 }
152
153 sub login
154 {
155         return \&rec;
156 }
157
158 # cease running this program, close down all the connections nicely
159 sub cease
160 {
161         my $dxchan;
162         
163         eval {
164                 Local::finish();   # end local processing
165         };
166         dbg('local', "Local::finish error $@") if $@;
167         
168         foreach $dxchan (DXChannel->get_all()) {
169                 disconnect($dxchan) unless $dxchan == $DXProt::me;
170         }
171         Msg->event_loop(1, 0.05);
172         Msg->event_loop(1, 0.05);
173         Msg->event_loop(1, 0.05);
174         Msg->event_loop(1, 0.05);
175         Log('cluster', "DXSpider V$version stopped");
176         DXUser::finish();
177         unlink $lockfn;
178         exit(0);
179 }
180
181 # the reaper of children
182 sub reap
183 {
184         $SIG{'CHLD'} = \&reap;
185         my $cpid = wait;
186 }
187
188 # this is where the input queue is dealt with and things are dispatched off to other parts of
189 # the cluster
190 sub process_inqueue
191 {
192         my $self = shift @inqueue;
193         return if !$self;
194         
195         my $data = $self->{data};
196         my $dxchan = $self->{dxchan};
197         my ($sort, $call, $line) = $data =~ /^(\w)(\S+)\|(.*)$/;
198         
199         # do the really sexy console interface bit! (Who is going to do the TK interface then?)
200         dbg('chan', "<- $sort $call $line\n") unless $sort eq 'D';
201         
202         # handle A records
203         my $user = $dxchan->user;
204         if ($sort eq 'A' || $sort eq 'O') {
205                 $dxchan->start($line, $sort);  
206         } elsif ($sort eq 'I') {
207                 die "\$user not defined for $call" if !defined $user;
208                 
209                 # normal input
210                 $dxchan->normal($line);
211                 
212                 disconnect($dxchan) if ($dxchan->{state} eq 'bye');
213         } elsif ($sort eq 'Z') {
214                 disconnect($dxchan);
215         } elsif ($sort eq 'D') {
216                 ;                       # ignored (an echo)
217         } else {
218                 print STDERR atime, " Unknown command letter ($sort) received from $call\n";
219         }
220 }
221
222 sub uptime
223 {
224         my $t = $systime - $starttime;
225         my $days = int $t / 86400;
226         $t -= $days * 86400;
227         my $hours = int $t / 3600;
228         $t -= $hours * 3600;
229         my $mins = int $t / 60;
230         return sprintf "%d %02d:%02d", $days, $hours, $mins;
231 }
232 #############################################################
233 #
234 # The start of the main line of code 
235 #
236 #############################################################
237
238 $starttime = $systime = time;
239
240 # open the debug file, set various FHs to be unbuffered
241 foreach (@debug) {
242         dbgadd($_);
243 }
244 STDOUT->autoflush(1);
245
246 Log('cluster', "DXSpider V$version started");
247
248 # banner
249 print "DXSpider DX Cluster Version $version\nCopyright (c) 1998 Dirk Koopman G1TLH\n";
250
251 # load Prefixes
252 print "loading prefixes ...\n";
253 Prefix::load();
254
255 # load band data
256 print "loading band data ...\n";
257 Bands::load();
258
259 # initialise User file system
260 print "loading user file system ...\n"; 
261 DXUser->init($userfn, 1);
262
263 # start listening for incoming messages/connects
264 print "starting listener ...\n";
265 Msg->new_server("$clusteraddr", $clusterport, \&login);
266
267 # prime some signals
268 $SIG{'INT'} = \&cease;
269 $SIG{'TERM'} = \&cease;
270 $SIG{'HUP'} = 'IGNORE';
271 $SIG{'CHLD'} = \&reap;
272
273 # read in system messages
274 DXM->init();
275
276 # read in command aliases
277 CmdAlias->init();
278
279 # initialise the Geomagnetic data engine
280 Geomag->init();
281
282 # initial the Spot stuff
283 Spot->init();
284
285 # initialise the protocol engine
286 print "reading in duplicate spot and WWV info ...\n";
287 DXProt->init();
288
289
290 # put in a DXCluster node for us here so we can add users and take them away
291 DXNode->new(0, $mycall, 0, 1, $DXProt::myprot_version); 
292
293 # read in any existing message headers and clean out old crap
294 print "reading existing message headers ...\n";
295 DXMsg->init();
296 DXMsg::clean_old();
297
298 # read in any cron jobs
299 print "reading cron jobs ...\n";
300 DXCron->init();
301
302 # starting local stuff
303 print "doing local initialisation ...\n";
304 eval {
305         Local::init();
306 };
307 dbg('local', "Local::init error $@") if $@;
308
309 # print various flags
310 #print "useful info - \$^D: $^D \$^W: $^W \$^S: $^S \$^P: $^P\n";
311
312 # this, such as it is, is the main loop!
313 print "orft we jolly well go ...\n";
314 for (;;) {
315         my $timenow;
316         Msg->event_loop(1, 0.001);
317         $timenow = time;
318         process_inqueue();                      # read in lines from the input queue and despatch them
319         
320         # do timed stuff, ongoing processing happens one a second
321         if ($timenow != $systime) {
322                 $systime = $timenow;
323                 $cldate = &cldate();
324                 $ztime = &ztime();
325                 DXCron::process();      # do cron jobs
326                 DXCommandmode::process(); # process ongoing command mode stuff
327                 DXProt::process();              # process ongoing ak1a pcxx stuff
328                 DXConnect::process();
329                 eval { 
330                         Local::process();       # do any localised processing
331                 };
332                 dbg('local', "Local::process error $@") if $@;
333         }
334         if ($decease) {
335                 last if --$decease <= 0;
336         }
337 }
338
339