Annotation of loncom/loncnew, revision 1.16
1.1 foxr 1: #!/usr/bin/perl
1.2 albertel 2: # The LearningOnline Network with CAPA
3: # lonc maintains the connections to remote computers
4: #
1.16 ! foxr 5: # $Id: loncnew,v 1.15 2003/07/15 02:07:05 foxr Exp $
1.2 albertel 6: #
7: # Copyright Michigan State University Board of Trustees
8: #
9: # This file is part of the LearningOnline Network with CAPA (LON-CAPA).
10: #
11: # LON-CAPA is free software; you can redistribute it and/or modify
12: # it under the terms of the GNU General Public License as published by
13: # the Free Software Foundation; either version 2 of the License, or
14: # (at your option) any later version.
15: #
16: # LON-CAPA is distributed in the hope that it will be useful,
17: # but WITHOUT ANY WARRANTY; without even the implied warranty of
18: # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
19: # GNU General Public License for more details.
20: #
21: # You should have received a copy of the GNU General Public License
22: # along with LON-CAPA; if not, write to the Free Software
23: # Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
24: #
25: # /home/httpd/html/adm/gpl.txt
26: #
27: # http://www.lon-capa.org/
28: #
1.1 foxr 29: #
1.15 foxr 30: # new lonc handles n request out bver m connections to londs.
1.1 foxr 31: # This module is based on the Event class.
32: # Development iterations:
33: # - Setup basic event loop. (done)
34: # - Add timer dispatch. (done)
35: # - Add ability to accept lonc UNIX domain sockets. (done)
36: # - Add ability to create/negotiate lond connections (done).
1.7 foxr 37: # - Add general logic for dispatching requests and timeouts. (done).
38: # - Add support for the lonc/lond requests. (done).
1.1 foxr 39: # - Add logging/status monitoring.
40: # - Add Signal handling - HUP restarts. USR1 status report.
1.7 foxr 41: # - Add Configuration file I/O (done).
1.1 foxr 42: # - Add management/status request interface.
1.8 foxr 43: # - Add deferred request capability. (done)
1.9 foxr 44: # - Detect transmission timeouts.
1.7 foxr 45: #
46:
47: # Change log:
1.8 foxr 48: # $Log: loncnew,v $
1.16 ! foxr 49: # Revision 1.15 2003/07/15 02:07:05 foxr
! 50: # Added code for lonc/lond transaction timeouts. Who knows if it works right.
! 51: # The intent is for a timeout to fail any transaction in progress and kill
! 52: # off the sockt that timed out.
! 53: #
1.15 foxr 54: # Revision 1.14 2003/07/03 02:10:18 foxr
55: # Get all of the signals to work correctly.
56: #
1.14 foxr 57: # Revision 1.13 2003/07/02 01:31:55 foxr
58: # Added kill -HUP logic (restart).
59: #
1.12 foxr 60: # Revision 1.11 2003/06/25 01:54:44 foxr
61: # Fix more problems with transaction failure.
62: #
1.11 foxr 63: # Revision 1.10 2003/06/24 02:46:04 foxr
64: # Put a limit on the number of times we'll retry a connection.
65: # Start getting the signal stuff put in as well...note that need to get signals
66: # going or else 6the client will permanently give up on dead servers.
67: #
1.10 foxr 68: # Revision 1.9 2003/06/13 02:38:43 foxr
69: # Add logging in 'expected format'
70: #
1.9 foxr 71: # Revision 1.8 2003/06/11 02:04:35 foxr
72: # Support delayed transactions... this is done uniformly by encapsulating
73: # transactions in an object ... a LondTransaction that is implemented by
74: # LondTransaction.pm
75: #
1.8 foxr 76: # Revision 1.7 2003/06/03 01:59:39 foxr
77: # complete coding to support deferred transactions.
78: #
1.7 foxr 79: #
1.1 foxr 80:
81: use lib "/home/httpd/lib/perl/";
82: use lib "/home/foxr/newloncapa/types";
83: use Event qw(:DEFAULT );
84: use POSIX qw(:signal_h);
1.12 foxr 85: use POSIX;
1.1 foxr 86: use IO::Socket;
87: use IO::Socket::INET;
88: use IO::Socket::UNIX;
1.9 foxr 89: use IO::File;
1.6 foxr 90: use IO::Handle;
1.1 foxr 91: use Socket;
92: use Crypt::IDEA;
93: use LONCAPA::Queue;
94: use LONCAPA::Stack;
95: use LONCAPA::LondConnection;
1.7 foxr 96: use LONCAPA::LondTransaction;
1.1 foxr 97: use LONCAPA::Configuration;
98: use LONCAPA::HashIterator;
99:
100:
101: #
102: # Disable all signals we might receive from outside for now.
103: #
1.14 foxr 104: #$SIG{QUIT} = IGNORE;
105: #$SIG{HUP} = IGNORE;
106: #$SIG{USR1} = IGNORE;
107: #$SIG{INT} = IGNORE;
108: #$SIG{CHLD} = IGNORE;
109: #$SIG{__DIE__} = IGNORE;
1.1 foxr 110:
111:
112: # Read the httpd configuration file to get perl variables
113: # normally set in apache modules:
114:
115: my $perlvarref = LONCAPA::Configuration::read_conf('loncapa.conf');
116: my %perlvar = %{$perlvarref};
117:
118: #
119: # parent and shared variables.
120:
121: my %ChildHash; # by pid -> host.
122:
123:
1.9 foxr 124: my $MaxConnectionCount = 10; # Will get from config later.
1.1 foxr 125: my $ClientConnection = 0; # Uniquifier for client events.
126:
1.9 foxr 127: my $DebugLevel = 0;
1.16 ! foxr 128: my $NextDebugLevel= 10; # So Sigint can toggle this.
1.1 foxr 129: my $IdleTimeout= 3600; # Wait an hour before pruning connections.
130:
131: #
132: # The variables below are only used by the child processes.
133: #
134: my $RemoteHost; # Name of host child is talking to.
135: my $UnixSocketDir= "/home/httpd/sockets";
136: my $IdleConnections = Stack->new(); # Set of idle connections
137: my %ActiveConnections; # Connections to the remote lond.
1.7 foxr 138: my %ActiveTransactions; # LondTransactions in flight.
1.1 foxr 139: my %ActiveClients; # Serial numbers of active clients by socket.
140: my $WorkQueue = Queue->new(); # Queue of pending transactions.
141: my $ConnectionCount = 0;
1.4 foxr 142: my $IdleSeconds = 0; # Number of seconds idle.
1.9 foxr 143: my $Status = ""; # Current status string.
1.14 foxr 144: my $RecentLogEntry = "";
1.10 foxr 145: my $ConnectionRetries=5; # Number of connection retries allowed.
146: my $ConnectionRetriesLeft=5; # Number of connection retries remaining.
1.1 foxr 147:
148: #
1.9 foxr 149: # The hash below gives the HTML format for log messages
150: # given a severity.
151: #
152: my %LogFormats;
153:
154: $LogFormats{"CRITICAL"} = "<font color=red>CRITICAL: %s</font>";
155: $LogFormats{"SUCCESS"} = "<font color=green>SUCCESS: %s</font>";
156: $LogFormats{"INFO"} = "<font color=yellow>INFO: %s</font>";
157: $LogFormats{"WARNING"} = "<font color=blue>WARNING: %s</font>";
158: $LogFormats{"DEFAULT"} = " %s ";
159:
1.10 foxr 160:
161:
162: =pod
163:
164: =head2 LogPerm
165:
166: Makes an entry into the permanent log file.
167:
168: =cut
169: sub LogPerm {
170: my $message=shift;
171: my $execdir=$perlvar{'lonDaemons'};
172: my $now=time;
173: my $local=localtime($now);
174: my $fh=IO::File->new(">>$execdir/logs/lonnet.perm.log");
175: print $fh "$now:$message:$local\n";
176: }
1.9 foxr 177:
178: =pod
179:
180: =head2 Log
181:
182: Logs a message to the log file.
183: Parameters:
184:
185: =item severity
186:
187: One of CRITICAL, WARNING, INFO, SUCCESS used to select the
188: format string used to format the message. if the severity is
189: not a defined severity the Default format string is used.
190:
191: =item message
192:
193: The base message. In addtion to the format string, the message
194: will be appended to a string containing the name of our remote
195: host and the time will be formatted into the message.
196:
197: =cut
198:
199: sub Log {
200: my $severity = shift;
201: my $message = shift;
202:
203: if(!$LogFormats{$severity}) {
204: $severity = "DEFAULT";
205: }
206:
207: my $format = $LogFormats{$severity};
208:
209: # Put the window dressing in in front of the message format:
210:
211: my $now = time;
212: my $local = localtime($now);
213: my $finalformat = "$local ($$) [$RemoteHost] [$Status] ";
214: my $finalformat = $finalformat.$format."\n";
215:
216: # open the file and put the result.
217:
218: my $execdir = $perlvar{'lonDaemons'};
219: my $fh = IO::File->new(">>$execdir/logs/lonc.log");
220: my $msg = sprintf($finalformat, $message);
1.14 foxr 221: $RecentLogEntry = $msg;
1.9 foxr 222: print $fh $msg;
223:
1.10 foxr 224:
1.9 foxr 225: }
1.6 foxr 226:
1.3 albertel 227:
1.1 foxr 228: =pod
1.3 albertel 229:
230: =head2 GetPeerName
231:
232: Returns the name of the host that a socket object is connected to.
233:
1.1 foxr 234: =cut
235:
236: sub GetPeername {
237: my $connection = shift;
238: my $AdrFamily = shift;
239: my $peer = $connection->peername();
240: my $peerport;
241: my $peerip;
242: if($AdrFamily == AF_INET) {
243: ($peerport, $peerip) = sockaddr_in($peer);
244: my $peername = gethostbyaddr($iaddr, $AdrFamily);
245: return $peername;
246: } elsif ($AdrFamily == AF_UNIX) {
247: my $peerfile;
248: ($peerfile) = sockaddr_un($peer);
249: return $peerfile;
250: }
251: }
252: #----------------------------- Timer management ------------------------
253: =pod
1.3 albertel 254:
1.1 foxr 255: =head2 Debug
1.3 albertel 256:
257: Invoked to issue a debug message.
258:
1.1 foxr 259: =cut
1.3 albertel 260:
1.1 foxr 261: sub Debug {
262: my $level = shift;
263: my $message = shift;
264: if ($level <= $DebugLevel) {
1.16 ! foxr 265: Log("INFO", "-Debug- $message host = $RemotHost");
1.1 foxr 266: }
267: }
268:
269: sub SocketDump {
270: my $level = shift;
271: my $socket= shift;
272: if($level <= $DebugLevel) {
273: $socket->Dump();
274: }
275: }
1.3 albertel 276:
1.1 foxr 277: =pod
1.3 albertel 278:
1.5 foxr 279: =head2 ShowStatus
280:
281: Place some text as our pid status.
1.10 foxr 282: and as what we return in a SIGUSR1
1.5 foxr 283:
284: =cut
285: sub ShowStatus {
1.10 foxr 286: my $state = shift;
287: my $now = time;
288: my $local = localtime($now);
289: $Status = $local.": ".$state;
290: $0='lonc: '.$state.' '.$local;
1.5 foxr 291: }
292:
293: =pod
294:
1.15 foxr 295: =head 2 SocketTimeout
296:
297: Called when an action on the socket times out. The socket is
298: destroyed and any active transaction is failed.
299:
300:
301: =cut
302: sub SocketTimeout {
303: my $Socket = shift;
304:
305: KillSocket($Socket);
306: }
307:
308: =pod
309:
1.1 foxr 310: =head2 Tick
1.3 albertel 311:
312: Invoked each timer tick.
313:
1.1 foxr 314: =cut
315:
1.5 foxr 316:
1.1 foxr 317: sub Tick {
318: my $client;
1.5 foxr 319: ShowStatus(GetServerHost()." Connection count: ".$ConnectionCount);
1.12 foxr 320:
1.4 foxr 321: # Is it time to prune connection count:
322:
323:
324: if($IdleConnections->Count() &&
325: ($WorkQueue->Count() == 0)) { # Idle connections and nothing to do?
326: $IdleSeconds++;
327: if($IdleSeconds > $IdleTimeout) { # Prune a connection...
328: $Socket = $IdleConnections->pop();
1.6 foxr 329: KillSocket($Socket);
1.4 foxr 330: }
331: } else {
332: $IdleSeconds = 0; # Reset idle count if not idle.
333: }
1.15 foxr 334: #
335: # For each inflight transaction, tick down its timeout counter.
336: #
337: foreach $item (keys %ActiveTransactions) {
338: my $Socket = $ActiveTransactions{$item}->getServer();
339: $Socket->Tick();
340: }
1.5 foxr 341: # Do we have work in the queue, but no connections to service them?
342: # If so, try to make some new connections to get things going again.
343: #
344:
345: my $Requests = $WorkQueue->Count();
1.10 foxr 346: if (($ConnectionCount == 0) && ($Requests > 0)) {
347: if ($ConnectionRetriesLeft > 0) {
348: my $Connections = ($Requests <= $MaxConnectionCount) ?
349: $Requests : $MaxConnectionCount;
350: Debug(1,"Work but no connections, start ".$Connections." of them");
351: for ($i =0; $i < $Connections; $i++) {
352: MakeLondConnection();
353: }
354: } else {
355: Debug(1,"Work in queue, but gave up on connections..flushing\n");
356: EmptyQueue(); # Connections can't be established.
1.5 foxr 357: }
358:
359: }
1.1 foxr 360: }
361:
362: =pod
1.3 albertel 363:
1.1 foxr 364: =head2 SetupTimer
365:
1.3 albertel 366: Sets up a 1 per sec recurring timer event. The event handler is used to:
1.1 foxr 367:
1.3 albertel 368: =item
369:
370: Trigger timeouts on communications along active sockets.
371:
372: =item
373:
374: Trigger disconnections of idle sockets.
1.1 foxr 375:
376: =cut
377:
378: sub SetupTimer {
379: Debug(6, "SetupTimer");
380: Event->timer(interval => 1, debug => 1, cb => \&Tick );
381: }
1.3 albertel 382:
1.1 foxr 383: =pod
1.3 albertel 384:
1.1 foxr 385: =head2 ServerToIdle
1.3 albertel 386:
387: This function is called when a connection to the server is
388: ready for more work.
389:
390: If there is work in the Work queue the top element is dequeued
1.1 foxr 391: and the connection will start to work on it. If the work queue is
392: empty, the connection is pushed on the idle connection stack where
393: it will either get another work unit, or alternatively, if it sits there
394: long enough, it will be shut down and released.
395:
1.3 albertel 396: =cut
1.1 foxr 397:
398: sub ServerToIdle {
399: my $Socket = shift; # Get the socket.
1.7 foxr 400: delete($ActiveTransactions{$Socket}); # Server has no transaction
1.1 foxr 401:
402: &Debug(6, "Server to idle");
403:
404: # If there's work to do, start the transaction:
405:
1.7 foxr 406: $reqdata = $WorkQueue->dequeue(); # This is a LondTransaction
1.1 foxr 407: unless($reqdata eq undef) {
1.7 foxr 408: Debug(9, "Queue gave request data: ".$reqdata->getRequest());
409: &StartRequest($Socket, $reqdata);
1.8 foxr 410:
1.1 foxr 411: } else {
412:
413: # There's no work waiting, so push the server to idle list.
414: &Debug(8, "No new work requests, server connection going idle");
415: $IdleConnections->push($Socket);
416: }
417: }
1.3 albertel 418:
1.1 foxr 419: =pod
1.3 albertel 420:
1.1 foxr 421: =head2 ClientWritable
1.3 albertel 422:
423: Event callback for when a client socket is writable.
424:
425: This callback is established when a transaction reponse is
426: avaiable from lond. The response is forwarded to the unix socket
427: as it becomes writable in this sub.
428:
1.1 foxr 429: Parameters:
430:
1.3 albertel 431: =item Event
432:
433: The event that has been triggered. Event->w->data is
434: the data and Event->w->fd is the socket to write.
1.1 foxr 435:
436: =cut
1.3 albertel 437:
1.1 foxr 438: sub ClientWritable {
439: my $Event = shift;
440: my $Watcher = $Event->w;
441: my $Data = $Watcher->data;
442: my $Socket = $Watcher->fd;
443:
444: # Try to send the data:
445:
446: &Debug(6, "ClientWritable writing".$Data);
447: &Debug(9, "Socket is: ".$Socket);
448:
1.6 foxr 449: if($Socket->connected) {
450: my $result = $Socket->send($Data, 0);
451:
452: # $result undefined: the write failed.
453: # otherwise $result is the number of bytes written.
454: # Remove that preceding string from the data.
455: # If the resulting data is empty, destroy the watcher
456: # and set up a read event handler to accept the next
457: # request.
458:
459: &Debug(9,"Send result is ".$result." Defined: ".defined($result));
460: if(defined($result)) {
461: &Debug(9, "send result was defined");
462: if($result == length($Data)) { # Entire string sent.
463: &Debug(9, "ClientWritable data all written");
464: $Watcher->cancel();
465: #
466: # Set up to read next request from socket:
467:
468: my $descr = sprintf("Connection to lonc client %d",
469: $ActiveClients{$Socket});
470: Event->io(cb => \&ClientRequest,
471: poll => 'r',
472: desc => $descr,
473: data => "",
474: fd => $Socket);
475:
476: } else { # Partial string sent.
477: $Watcher->data(substr($Data, $result));
1.15 foxr 478: if($result == 0) { # client hung up on us!!
479: Log("INFO", "lonc pipe client hung up on us!");
480: $Watcher->cancel;
481: $Socket->shutdown(2);
482: $Socket->close();
483: }
1.6 foxr 484: }
485:
486: } else { # Error of some sort...
487:
488: # Some errnos are possible:
489: my $errno = $!;
490: if($errno == POSIX::EWOULDBLOCK ||
491: $errno == POSIX::EAGAIN ||
492: $errno == POSIX::EINTR) {
493: # No action taken?
494: } else { # Unanticipated errno.
495: &Debug(5,"ClientWritable error or peer shutdown".$RemoteHost);
496: $Watcher->cancel; # Stop the watcher.
497: $Socket->shutdown(2); # Kill connection
498: $Socket->close(); # Close the socket.
499: }
1.1 foxr 500:
501: }
1.6 foxr 502: } else {
503: $Watcher->cancel(); # A delayed request...just cancel.
1.1 foxr 504: }
505: }
506:
507: =pod
1.3 albertel 508:
1.1 foxr 509: =head2 CompleteTransaction
1.3 albertel 510:
511: Called when the reply data has been received for a lond
1.1 foxr 512: transaction. The reply data must now be sent to the
513: ultimate client on the other end of the Unix socket. This is
514: done by setting up a writable event for the socket with the
515: data the reply data.
1.3 albertel 516:
1.1 foxr 517: Parameters:
1.3 albertel 518:
519: =item Socket
520:
521: Socket on which the lond transaction occured. This is a
522: LondConnection. The data received is in the TransactionReply member.
523:
1.7 foxr 524: =item Transaction
1.3 albertel 525:
1.7 foxr 526: The transaction that is being completed.
1.1 foxr 527:
528: =cut
1.3 albertel 529:
1.1 foxr 530: sub CompleteTransaction {
531: &Debug(6,"Complete transaction");
532: my $Socket = shift;
1.7 foxr 533: my $Transaction = shift;
1.1 foxr 534:
1.7 foxr 535: if (!$Transaction->isDeferred()) { # Normal transaction
536: my $data = $Socket->GetReply(); # Data to send.
537: StartClientReply($Transaction, $data);
538: } else { # Delete deferred transaction file.
1.9 foxr 539: Log("SUCCESS", "A delayed transaction was completed");
1.10 foxr 540: LogPerm("S:$Client:".$Transaction->getRequest());
1.7 foxr 541: unlink $Transaction->getFile();
542: }
1.6 foxr 543: }
544: =pod
545: =head1 StartClientReply
546:
547: Initiates a reply to a client where the reply data is a parameter.
548:
1.7 foxr 549: =head2 parameters:
550:
551: =item Transaction
552:
553: The transaction for which we are responding to the client.
554:
555: =item data
556:
557: The data to send to apached client.
558:
1.6 foxr 559: =cut
560: sub StartClientReply {
1.7 foxr 561: my $Transaction = shift;
1.6 foxr 562: my $data = shift;
1.1 foxr 563:
1.12 foxr 564:
1.7 foxr 565: my $Client = $Transaction->getClient();
566:
1.1 foxr 567: &Debug(8," Reply was: ".$data);
568: my $Serial = $ActiveClients{$Client};
569: my $desc = sprintf("Connection to lonc client %d",
1.6 foxr 570:
1.1 foxr 571: $Serial);
572: Event->io(fd => $Client,
573: poll => "w",
574: desc => $desc,
575: cb => \&ClientWritable,
576: data => $data);
577: }
1.4 foxr 578: =pod
579: =head2 FailTransaction
580:
581: Finishes a transaction with failure because the associated lond socket
1.7 foxr 582: disconnected. There are two possibilities:
583: - The transaction is deferred: in which case we just quietly
584: delete the transaction since there is no client connection.
585: - The transaction is 'live' in which case we initiate the sending
586: of "con_lost" to the client.
587:
588: Deleting the transaction means killing it from the
589: %ActiveTransactions hash.
1.4 foxr 590:
591: Parameters:
592:
593: =item client
594:
1.7 foxr 595: The LondTransaction we are failing.
596:
1.4 foxr 597: =cut
598:
599: sub FailTransaction {
1.7 foxr 600: my $transaction = shift;
1.10 foxr 601: Debug(1, "Failing transaction: ".$transaction->getRequest());
602: if (!$transaction->isDeferred()) { # If the transaction is deferred we'll get to it.
1.11 foxr 603: my $client = $transaction->getClient();
1.10 foxr 604: Debug(1," Replying con_lost to ".$transaction->getRequest());
1.11 foxr 605: StartClientReply($transaction, "con_lost\n");
1.7 foxr 606: }
1.4 foxr 607:
608: }
609:
610: =pod
1.6 foxr 611: =head1 EmptyQueue
1.7 foxr 612:
1.6 foxr 613: Fails all items in the work queue with con_lost.
1.7 foxr 614: Note that each item in the work queue is a transaction.
615:
1.6 foxr 616: =cut
617: sub EmptyQueue {
618: while($WorkQueue->Count()) {
1.10 foxr 619: my $request = $WorkQueue->dequeue(); # This is a transaction
1.7 foxr 620: FailTransaction($request);
1.6 foxr 621: }
622: }
623:
624: =pod
1.4 foxr 625:
1.9 foxr 626: =head2 CloseAllLondConnections
627:
628: Close all connections open on lond prior to exit e.g.
629:
630: =cut
631: sub CloseAllLondConnections {
632: foreach $Socket (keys %ActiveConnections) {
633: KillSocket($Socket);
634: }
635: }
636: =cut
637:
638: =pod
639:
1.4 foxr 640: =head2 KillSocket
641:
642: Destroys a socket. This function can be called either when a socket
643: has died of 'natural' causes or because a socket needs to be pruned due to
644: idleness. If the socket has died naturally, if there are no longer any
645: live connections a new connection is created (in case there are transactions
646: in the queue). If the socket has been pruned, it is never re-created.
647:
648: Parameters:
1.1 foxr 649:
1.4 foxr 650: =item Socket
651:
652: The socket to kill off.
653:
654: =item Restart
655:
656: nonzero if we are allowed to create a new connection.
657:
658:
659: =cut
660: sub KillSocket {
661: my $Socket = shift;
662:
1.9 foxr 663: $Socket->Shutdown();
664:
1.7 foxr 665: # If the socket came from the active connection set,
666: # delete its transaction... note that FailTransaction should
667: # already have been called!!!
668: # otherwise it came from the idle set.
669: #
1.4 foxr 670:
671: if(exists($ActiveTransactions{$Socket})) {
672: delete ($ActiveTransactions{$Socket});
673: }
674: if(exists($ActiveConnections{$Socket})) {
675: delete($ActiveConnections{$Socket});
676: }
677: $ConnectionCount--;
1.6 foxr 678:
679: # If the connection count has gone to zero and there is work in the
680: # work queue, the work all gets failed with con_lost.
681: #
682: if($ConnectionCount == 0) {
683: EmptyQueue;
1.4 foxr 684: }
685: }
1.1 foxr 686:
687: =pod
1.3 albertel 688:
1.1 foxr 689: =head2 LondReadable
1.3 albertel 690:
1.1 foxr 691: This function is called whenever a lond connection
692: is readable. The action is state dependent:
693:
1.3 albertel 694: =head3 State=Initialized
695:
696: We''re waiting for the challenge, this is a no-op until the
1.1 foxr 697: state changes.
1.3 albertel 698:
1.1 foxr 699: =head3 State=Challenged
1.3 albertel 700:
701: The challenge has arrived we need to transition to Writable.
1.1 foxr 702: The connection must echo the challenge back.
1.3 albertel 703:
1.1 foxr 704: =head3 State=ChallengeReplied
1.3 albertel 705:
706: The challenge has been replied to. The we are receiveing the
1.1 foxr 707: 'ok' from the partner.
1.3 albertel 708:
1.1 foxr 709: =head3 State=RequestingKey
1.3 albertel 710:
711: The ok has been received and we need to send the request for
1.1 foxr 712: an encryption key. Transition to writable for that.
1.3 albertel 713:
1.1 foxr 714: =head3 State=ReceivingKey
1.3 albertel 715:
716: The the key has been requested, now we are reading the new key.
717:
1.1 foxr 718: =head3 State=Idle
1.3 albertel 719:
720: The encryption key has been negotiated or we have finished
1.1 foxr 721: reading data from the a transaction. If the callback data has
722: a client as well as the socket iformation, then we are
723: doing a transaction and the data received is relayed to the client
724: before the socket is put on the idle list.
1.3 albertel 725:
1.1 foxr 726: =head3 State=SendingRequest
1.3 albertel 727:
728: I do not think this state can be received here, but if it is,
1.1 foxr 729: the appropriate thing to do is to transition to writable, and send
730: the request.
1.3 albertel 731:
1.1 foxr 732: =head3 State=ReceivingReply
1.3 albertel 733:
734: We finished sending the request to the server and now transition
1.1 foxr 735: to readable to receive the reply.
736:
737: The parameter to this function are:
1.3 albertel 738:
1.1 foxr 739: The event. Implicit in this is the watcher and its data. The data
740: contains at least the lond connection object and, if a
741: transaction is in progress, the socket attached to the local client.
742:
1.3 albertel 743: =cut
1.1 foxr 744:
745: sub LondReadable {
1.8 foxr 746:
1.1 foxr 747: my $Event = shift;
748: my $Watcher = $Event->w;
749: my $Socket = $Watcher->data;
750: my $client = undef;
751:
1.8 foxr 752: &Debug(6,"LondReadable called state = ".$State);
753:
1.1 foxr 754:
755: my $State = $Socket->GetState(); # All action depends on the state.
756:
757: SocketDump(6, $Socket);
1.12 foxr 758: my $status = $Socket->Readable();
759: &Debug(2, "Socket->Readable returned: $status");
1.1 foxr 760:
1.12 foxr 761: if($status != 0) {
1.4 foxr 762: # bad return from socket read. Currently this means that
763: # The socket has become disconnected. We fail the transaction.
764:
765: if(exists($ActiveTransactions{$Socket})) {
766: Debug(3,"Lond connection lost failing transaction");
767: FailTransaction($ActiveTransactions{$Socket});
768: }
769: $Watcher->cancel();
1.6 foxr 770: KillSocket($Socket);
1.4 foxr 771: return;
1.1 foxr 772: }
773: SocketDump(6,$Socket);
774:
775: $State = $Socket->GetState(); # Update in case of transition.
776: &Debug(6, "After read, state is ".$State);
777:
778: if($State eq "Initialized") {
779:
780:
781: } elsif ($State eq "ChallengeReceived") {
782: # The challenge must be echoed back; The state machine
783: # in the connection takes care of setting that up. Just
784: # need to transition to writable:
785:
1.8 foxr 786: $Watcher->cb(\&LondWritable);
1.1 foxr 787: $Watcher->poll("w");
788:
789: } elsif ($State eq "ChallengeReplied") {
790:
791:
792: } elsif ($State eq "RequestingKey") {
793: # The ok was received. Now we need to request the key
794: # That requires us to be writable:
795:
1.8 foxr 796: $Watcher->cb(\&LondWritable);
1.1 foxr 797: $Watcher->poll("w");
798:
799: } elsif ($State eq "ReceivingKey") {
800:
801: } elsif ($State eq "Idle") {
802: # If necessary, complete a transaction and then go into the
803: # idle queue.
1.8 foxr 804: $Watcher->cancel();
1.1 foxr 805: if(exists($ActiveTransactions{$Socket})) {
806: Debug(8,"Completing transaction!!");
807: CompleteTransaction($Socket,
808: $ActiveTransactions{$Socket});
1.9 foxr 809: } else {
810: Log("SUCCESS", "Connection ".$ConnectionCount." to "
811: .$RemoteHost." now ready for action");
1.1 foxr 812: }
813: ServerToIdle($Socket); # Next work unit or idle.
1.6 foxr 814:
1.1 foxr 815: } elsif ($State eq "SendingRequest") {
816: # We need to be writable for this and probably don't belong
817: # here inthe first place.
818:
819: Deubg(6, "SendingRequest state encountered in readable");
820: $Watcher->poll("w");
821: $Watcher->cb(\&LondWritable);
822:
823: } elsif ($State eq "ReceivingReply") {
824:
825:
826: } else {
827: # Invalid state.
828: Debug(4, "Invalid state in LondReadable");
829: }
830: }
1.3 albertel 831:
1.1 foxr 832: =pod
1.3 albertel 833:
1.1 foxr 834: =head2 LondWritable
1.3 albertel 835:
1.1 foxr 836: This function is called whenever a lond connection
837: becomes writable while there is a writeable monitoring
838: event. The action taken is very state dependent:
1.3 albertel 839:
1.1 foxr 840: =head3 State = Connected
1.3 albertel 841:
842: The connection is in the process of sending the 'init' hailing to the
843: lond on the remote end. The connection object''s Writable member is
844: called. On error, ConnectionError is called to destroy the connection
845: and remove it from the ActiveConnections hash
846:
1.1 foxr 847: =head3 Initialized
1.3 albertel 848:
849: 'init' has been sent, writability monitoring is removed and
850: readability monitoring is started with LondReadable as the callback.
851:
1.1 foxr 852: =head3 ChallengeReceived
1.3 albertel 853:
854: The connection has received the who are you challenge from the remote
855: system, and is in the process of sending the challenge
856: response. Writable is called.
857:
1.1 foxr 858: =head3 ChallengeReplied
1.3 albertel 859:
860: The connection has replied to the initial challenge The we switch to
861: monitoring readability looking for the server to reply with 'ok'.
862:
1.1 foxr 863: =head3 RequestingKey
1.3 albertel 864:
865: The connection is in the process of requesting its encryption key.
866: Writable is called.
867:
1.1 foxr 868: =head3 ReceivingKey
1.3 albertel 869:
870: The connection has sent the request for a key. Switch to readability
871: monitoring to accept the key
872:
1.1 foxr 873: =head3 SendingRequest
1.3 albertel 874:
875: The connection is in the process of sending a request to the server.
876: This request is part of a client transaction. All the states until
877: now represent the client setup protocol. Writable is called.
878:
1.1 foxr 879: =head3 ReceivingReply
880:
1.3 albertel 881: The connection has sent a request. Now it must receive a reply.
882: Readability monitoring is requested.
883:
884: This function is an event handler and therefore receives as
1.1 foxr 885: a parameter the event that has fired. The data for the watcher
886: of this event is a reference to a list of one or two elements,
887: depending on state. The first (and possibly only) element is the
888: socket. The second (present only if a request is in progress)
889: is the socket on which to return a reply to the caller.
890:
891: =cut
1.3 albertel 892:
1.1 foxr 893: sub LondWritable {
894: my $Event = shift;
895: my $Watcher = $Event->w;
1.8 foxr 896: my $Socket = $Watcher->data;
897: my $State = $Socket->GetState();
1.1 foxr 898:
1.8 foxr 899: Debug(6,"LondWritable State = ".$State."\n");
1.1 foxr 900:
1.8 foxr 901:
1.1 foxr 902: # Figure out what to do depending on the state of the socket:
903:
904:
905:
906:
907: SocketDump(6,$Socket);
908:
909: if ($State eq "Connected") {
910:
911: if ($Socket->Writable() != 0) {
912: # The write resulted in an error.
1.4 foxr 913: # We'll treat this as if the socket got disconnected:
1.9 foxr 914: Log("WARNING", "Connection to ".$RemoteHost.
915: " has been disconnected");
1.4 foxr 916: $Watcher->cancel();
1.6 foxr 917: KillSocket($Socket);
1.4 foxr 918: return;
1.1 foxr 919: }
1.4 foxr 920: # "init" is being sent...
921:
1.1 foxr 922:
923: } elsif ($State eq "Initialized") {
924:
925: # Now that init was sent, we switch
926: # to watching for readability:
927:
1.8 foxr 928: $Watcher->cb(\&LondReadable);
1.1 foxr 929: $Watcher->poll("r");
930:
931: } elsif ($State eq "ChallengeReceived") {
932: # We received the challenge, now we
933: # are echoing it back. This is a no-op,
934: # we're waiting for the state to change
935:
936: if($Socket->Writable() != 0) {
1.5 foxr 937:
938: $Watcher->cancel();
1.6 foxr 939: KillSocket($Socket);
1.5 foxr 940: return;
1.1 foxr 941: }
942:
943: } elsif ($State eq "ChallengeReplied") {
944: # The echo was sent back, so we switch
945: # to watching readability.
946:
1.8 foxr 947: $Watcher->cb(\&LondReadable);
1.1 foxr 948: $Watcher->poll("r");
949:
950: } elsif ($State eq "RequestingKey") {
951: # At this time we're requesting the key.
952: # again, this is essentially a no-op.
953: # we'll write the next chunk until the
954: # state changes.
955:
956: if($Socket->Writable() != 0) {
957: # Write resulted in an error.
1.5 foxr 958:
959: $Watcher->cancel();
1.6 foxr 960: KillSocket($Socket);
1.5 foxr 961: return;
962:
1.1 foxr 963: }
964: } elsif ($State eq "ReceivingKey") {
965: # Now we need to wait for the key
966: # to come back from the peer:
967:
1.8 foxr 968: $Watcher->cb(\&LondReadable);
1.1 foxr 969: $Watcher->poll("r");
970:
971: } elsif ($State eq "SendingRequest") {
972: # At this time we are sending a request to the
973: # peer... write the next chunk:
974:
975: if($Socket->Writable() != 0) {
976:
1.5 foxr 977: if(exists($ActiveTransactions{$Socket})) {
978: Debug(3, "Lond connection lost, failing transactions");
979: FailTransaction($ActiveTransactions{$Socket});
980: }
981: $Watcher->cancel();
1.6 foxr 982: KillSocket($Socket);
1.5 foxr 983: return;
984:
1.1 foxr 985: }
986:
987: } elsif ($State eq "ReceivingReply") {
988: # The send has completed. Wait for the
989: # data to come in for a reply.
990: Debug(8,"Writable sent request/receiving reply");
1.8 foxr 991: $Watcher->cb(\&LondReadable);
1.1 foxr 992: $Watcher->poll("r");
993:
994: } else {
995: # Control only passes here on an error:
996: # the socket state does not match any
997: # of the known states... so an error
998: # must be logged.
999:
1000: &Debug(4, "Invalid socket state ".$State."\n");
1001: }
1002:
1003: }
1.6 foxr 1004: =pod
1005:
1006: =cut
1007: sub QueueDelayed {
1.8 foxr 1008: Debug(3,"QueueDelayed called");
1009:
1.6 foxr 1010: my $path = "$perlvar{'lonSockDir'}/delayed";
1.8 foxr 1011:
1012: Debug(4, "Delayed path: ".$path);
1.6 foxr 1013: opendir(DIRHANDLE, $path);
1.8 foxr 1014:
1.6 foxr 1015: @alldelayed = grep /\.$RemoteHost$/, readdir DIRHANDLE;
1.8 foxr 1016: Debug(4, "Got ".$alldelayed." delayed files");
1.6 foxr 1017: closedir(DIRHANDLE);
1018: my $dfname;
1.8 foxr 1019: my $reqfile;
1020: foreach $dfname (sort @alldelayed) {
1021: $reqfile = "$path/$dfname";
1022: Debug(4, "queueing ".$reqfile);
1.6 foxr 1023: my $Handle = IO::File->new($reqfile);
1024: my $cmd = <$Handle>;
1.8 foxr 1025: chomp $cmd; # There may or may not be a newline...
1.12 foxr 1026: $cmd = $cmd."\n"; # now for sure there's exactly one newline.
1.7 foxr 1027: my $Transaction = LondTransaction->new($cmd);
1028: $Transaction->SetDeferred($reqfile);
1029: QueueTransaction($Transaction);
1.6 foxr 1030: }
1031:
1032: }
1.1 foxr 1033:
1034: =pod
1.3 albertel 1035:
1.1 foxr 1036: =head2 MakeLondConnection
1.3 albertel 1037:
1038: Create a new lond connection object, and start it towards its initial
1039: idleness. Once idle, it becomes elligible to receive transactions
1040: from the work queue. If the work queue is not empty when the
1041: connection is completed and becomes idle, it will dequeue an entry and
1042: start off on it.
1043:
1.1 foxr 1044: =cut
1.3 albertel 1045:
1.1 foxr 1046: sub MakeLondConnection {
1047: Debug(4,"MakeLondConnection to ".GetServerHost()." on port "
1048: .GetServerPort());
1049:
1050: my $Connection = LondConnection->new(&GetServerHost(),
1051: &GetServerPort());
1052:
1053: if($Connection == undef) { # Needs to be more robust later.
1.9 foxr 1054: Log("CRITICAL","Failed to make a connection with lond.");
1.10 foxr 1055: $ConnectionRetriesLeft--;
1056: return 0; # Failure.
1.5 foxr 1057: } else {
1.10 foxr 1058: $ConnectionRetriesLeft = $ConnectionRetries; # success resets the count
1.5 foxr 1059: # The connection needs to have writability
1060: # monitored in order to send the init sequence
1061: # that starts the whole authentication/key
1062: # exchange underway.
1063: #
1064: my $Socket = $Connection->GetSocket();
1065: if($Socket == undef) {
1066: die "did not get a socket from the connection";
1067: } else {
1068: &Debug(9,"MakeLondConnection got socket: ".$Socket);
1069: }
1.1 foxr 1070:
1.5 foxr 1071:
1072: $event = Event->io(fd => $Socket,
1073: poll => 'w',
1074: cb => \&LondWritable,
1.8 foxr 1075: data => $Connection,
1.5 foxr 1076: desc => 'Connection to lond server');
1077: $ActiveConnections{$Connection} = $event;
1078:
1079: $ConnectionCount++;
1.8 foxr 1080: Debug(4, "Connection count = ".$ConnectionCount);
1.6 foxr 1081: if($ConnectionCount == 1) { # First Connection:
1082: QueueDelayed;
1083: }
1.9 foxr 1084: Log("SUCESS", "Created connection ".$ConnectionCount
1085: ." to host ".GetServerHost());
1.10 foxr 1086: return 1; # Return success.
1.1 foxr 1087: }
1088:
1089: }
1.3 albertel 1090:
1.1 foxr 1091: =pod
1.3 albertel 1092:
1.1 foxr 1093: =head2 StartRequest
1.3 albertel 1094:
1095: Starts a lond request going on a specified lond connection.
1096: parameters are:
1097:
1098: =item $Lond
1099:
1100: Connection to the lond that will send the transaction and receive the
1101: reply.
1102:
1103: =item $Client
1104:
1105: Connection to the client that is making this request We got the
1106: request from this socket, and when the request has been relayed to
1107: lond and we get a reply back from lond it will get sent to this
1108: socket.
1109:
1110: =item $Request
1111:
1112: The text of the request to send.
1113:
1.1 foxr 1114: =cut
1115:
1116: sub StartRequest {
1117: my $Lond = shift;
1.7 foxr 1118: my $Request = shift; # This is a LondTransaction.
1.1 foxr 1119:
1.7 foxr 1120: Debug(6, "StartRequest: ".$Request->getRequest());
1.1 foxr 1121:
1122: my $Socket = $Lond->GetSocket();
1123:
1.7 foxr 1124: $Request->Activate($Lond);
1125: $ActiveTransactions{$Lond} = $Request;
1.1 foxr 1126:
1.7 foxr 1127: $Lond->InitiateTransaction($Request->getRequest());
1.8 foxr 1128: $event = Event->io(fd => $Socket,
1.1 foxr 1129: poll => "w",
1130: cb => \&LondWritable,
1131: data => $Lond,
1132: desc => "lond transaction connection");
1133: $ActiveConnections{$Lond} = $event;
1134: Debug(8," Start Request made watcher data with ".$event->data."\n");
1135: }
1136:
1137: =pod
1.3 albertel 1138:
1.1 foxr 1139: =head2 QueueTransaction
1.3 albertel 1140:
1141: If there is an idle lond connection, it is put to work doing this
1142: transaction. Otherwise, the transaction is placed in the work queue.
1143: If placed in the work queue and the maximum number of connections has
1144: not yet been created, a new connection will be started. Our goal is
1145: to eventually have a sufficient number of connections that the work
1146: queue will typically be empty. parameters are:
1147:
1148: =item Socket
1149:
1150: open on the lonc client.
1151:
1152: =item Request
1153:
1154: data to send to the lond.
1.1 foxr 1155:
1156: =cut
1.3 albertel 1157:
1.1 foxr 1158: sub QueueTransaction {
1159:
1.7 foxr 1160: my $requestData = shift; # This is a LondTransaction.
1161: my $cmd = $requestData->getRequest();
1162:
1163: Debug(6,"QueueTransaction: ".$cmd);
1.1 foxr 1164:
1165: my $LondSocket = $IdleConnections->pop();
1166: if(!defined $LondSocket) { # Need to queue request.
1167: Debug(8,"Must queue...");
1168: $WorkQueue->enqueue($requestData);
1169: if($ConnectionCount < $MaxConnectionCount) {
1170: Debug(4,"Starting additional lond connection");
1171: MakeLondConnection();
1172: }
1173: } else { # Can start the request:
1174: Debug(8,"Can start...");
1.7 foxr 1175: StartRequest($LondSocket, $requestData);
1.1 foxr 1176: }
1177: }
1178:
1179: #-------------------------- Lonc UNIX socket handling ---------------------
1.3 albertel 1180:
1.1 foxr 1181: =pod
1.3 albertel 1182:
1.1 foxr 1183: =head2 ClientRequest
1.3 albertel 1184: Callback that is called when data can be read from the UNIX domain
1185: socket connecting us with an apache server process.
1.1 foxr 1186:
1187: =cut
1188:
1189: sub ClientRequest {
1190: Debug(6, "ClientRequest");
1191: my $event = shift;
1192: my $watcher = $event->w;
1193: my $socket = $watcher->fd;
1194: my $data = $watcher->data;
1195: my $thisread;
1196:
1197: Debug(9, " Watcher named: ".$watcher->desc);
1198:
1199: my $rv = $socket->recv($thisread, POSIX::BUFSIZ, 0);
1200: Debug(8, "rcv: data length = ".length($thisread)
1201: ." read =".$thisread);
1202: unless (defined $rv && length($thisread)) {
1203: # Likely eof on socket.
1204: Debug(5,"Client Socket closed on lonc for ".$RemoteHost);
1205: close($socket);
1206: $watcher->cancel();
1207: delete($ActiveClients{$socket});
1.10 foxr 1208: return;
1.1 foxr 1209: }
1210: Debug(8,"Data: ".$data." this read: ".$thisread);
1211: $data = $data.$thisread; # Append new data.
1212: $watcher->data($data);
1213: if($data =~ /(.*\n)/) { # Request entirely read.
1.10 foxr 1214: if($data eq "close_connection_exit\n") {
1.9 foxr 1215: Log("CRITICAL",
1216: "Request Close Connection ... exiting");
1217: CloseAllLondConnections();
1218: exit;
1219: }
1.1 foxr 1220: Debug(8, "Complete transaction received: ".$data);
1.8 foxr 1221: my $Transaction = LondTransaction->new($data);
1.7 foxr 1222: $Transaction->SetClient($socket);
1223: QueueTransaction($Transaction);
1.1 foxr 1224: $watcher->cancel(); # Done looking for input data.
1225: }
1226:
1227: }
1228:
1229:
1230: =pod
1.3 albertel 1231:
1.1 foxr 1232: =head2 NewClient
1.3 albertel 1233:
1234: Callback that is called when a connection is received on the unix
1235: socket for a new client of lonc. The callback is parameterized by the
1236: event.. which is a-priori assumed to be an io event, and therefore has
1237: an fd member that is the Listener socket. We Accept the connection
1238: and register a new event on the readability of that socket:
1239:
1.1 foxr 1240: =cut
1.3 albertel 1241:
1.1 foxr 1242: sub NewClient {
1243: Debug(6, "NewClient");
1244: my $event = shift; # Get the event parameters.
1245: my $watcher = $event->w;
1246: my $socket = $watcher->fd; # Get the event' socket.
1247: my $connection = $socket->accept(); # Accept the client connection.
1248: Debug(8,"Connection request accepted from "
1249: .GetPeername($connection, AF_UNIX));
1250:
1251:
1252: my $description = sprintf("Connection to lonc client %d",
1253: $ClientConnection);
1254: Debug(9, "Creating event named: ".$description);
1255: Event->io(cb => \&ClientRequest,
1256: poll => 'r',
1257: desc => $description,
1258: data => "",
1259: fd => $connection);
1260: $ActiveClients{$connection} = $ClientConnection;
1261: $ClientConnection++;
1262: }
1.3 albertel 1263:
1264: =pod
1265:
1266: =head2 GetLoncSocketPath
1267:
1268: Returns the name of the UNIX socket on which to listen for client
1269: connections.
1.1 foxr 1270:
1271: =cut
1.3 albertel 1272:
1.1 foxr 1273: sub GetLoncSocketPath {
1274: return $UnixSocketDir."/".GetServerHost();
1275: }
1276:
1.3 albertel 1277: =pod
1278:
1279: =head2 GetServerHost
1280:
1281: Returns the host whose lond we talk with.
1282:
1.1 foxr 1283: =cut
1.3 albertel 1284:
1.7 foxr 1285: sub GetServerHost {
1.1 foxr 1286: return $RemoteHost; # Setup by the fork.
1287: }
1.3 albertel 1288:
1289: =pod
1290:
1291: =head2 GetServerPort
1292:
1293: Returns the lond port number.
1294:
1.1 foxr 1295: =cut
1.3 albertel 1296:
1.7 foxr 1297: sub GetServerPort {
1.1 foxr 1298: return $perlvar{londPort};
1299: }
1.3 albertel 1300:
1301: =pod
1302:
1303: =head2 SetupLoncListener
1304:
1305: Setup a lonc listener event. The event is called when the socket
1306: becomes readable.. that corresponds to the receipt of a new
1307: connection. The event handler established will accept the connection
1308: (creating a communcations channel), that int turn will establish
1309: another event handler to subess requests.
1.1 foxr 1310:
1311: =cut
1.3 albertel 1312:
1.1 foxr 1313: sub SetupLoncListener {
1314:
1315: my $socket;
1316: my $SocketName = GetLoncSocketPath();
1317: unlink($SocketName);
1.7 foxr 1318: unless ($socket =IO::Socket::UNIX->new(Local => $SocketName,
1.1 foxr 1319: Listen => 10,
1320: Type => SOCK_STREAM)) {
1321: die "Failed to create a lonc listner socket";
1322: }
1323: Event->io(cb => \&NewClient,
1324: poll => 'r',
1325: desc => 'Lonc listener Unix Socket',
1326: fd => $socket);
1327: }
1328:
1.14 foxr 1329: =pod
1330:
1331: =head2 ChildStatus
1332:
1333: Child USR1 signal handler to report the most recent status
1334: into the status file.
1335:
1336: =cut
1337: sub ChildStatus {
1338: my $event = shift;
1339: my $watcher = $event->w;
1340:
1341: Debug(2, "Reporting child status because : ".$watcher->data);
1342: my $docdir = $perlvar{'lonDocRoot'};
1343: my $fh = IO::File->new(">>$docdir/lon-status/loncstatus.txt");
1344: print $fh $$."\t".$RemoteHost."\t".$Status."\t".
1345: $RecentLogEntry."\n";
1346: }
1347:
1.1 foxr 1348: =pod
1.3 albertel 1349:
1.10 foxr 1350: =head2 SignalledToDeath
1351:
1352: Called in response to a signal that causes a chid process to die.
1353:
1354: =cut
1355:
1356:
1357: sub SignalledToDeath {
1.14 foxr 1358: my $event = shift;
1359: my $watcher= $event->w;
1360:
1361: Debug(2,"Signalled to death! via ".$watcher->data);
1.10 foxr 1362: my ($signal) = @_;
1363: chomp($signal);
1364: Log("CRITICAL", "Abnormal exit. Child $$ for $RemoteHost "
1365: ."died through "."\"$signal\"");
1366: LogPerm("F:lonc: $$ on $RemoteHost signalled to death: "
1367: ."\"$signal\"");
1368: die("Signal abnormal end");
1.12 foxr 1369: exit 0;
1.10 foxr 1370:
1371: }
1.16 ! foxr 1372:
! 1373: =head2 ToggleDebug
! 1374:
! 1375: This sub toggles trace debugging on and off.
! 1376:
! 1377: =cut
! 1378:
! 1379: sub ToggleDebug {
! 1380: my $Current = $DebugLevel;
! 1381: $DebugLevel = $NextDebugLevel;
! 1382: $NextDebugLevel = $Current;
! 1383:
! 1384: Log("SUCCESS", "New debugging level for $RemoteHost now $DebugLevel");
! 1385:
! 1386: }
! 1387:
1.1 foxr 1388: =head2 ChildProcess
1389:
1390: This sub implements a child process for a single lonc daemon.
1391:
1392: =cut
1393:
1394: sub ChildProcess {
1395:
1396:
1.14 foxr 1397: #
1398: # Signals must be handled by the Event framework...
1399: #
1400:
1401: Event->signal(signal => "QUIT",
1402: cb => \&SignalledToDeath,
1403: data => "QUIT");
1404: Event->signal(signal => "HUP",
1405: cb => \&ChildStatus,
1406: data => "HUP");
1407: Event->signal(signal => "USR1",
1408: cb => \&ChildStatus,
1409: data => "USR1");
1.16 ! foxr 1410: Event->signal(signal => "INT",
! 1411: cb => \&ToggleDebug,
! 1412: data => "INT");
1.1 foxr 1413:
1414: SetupTimer();
1415:
1416: SetupLoncListener();
1417:
1418: $Event::Debuglevel = $DebugLevel;
1419:
1420: Debug(9, "Making initial lond connection for ".$RemoteHost);
1421:
1422: # Setup the initial server connection:
1423:
1.14 foxr 1424: # &MakeLondConnection(); // let first work requirest do it.
1.10 foxr 1425:
1.5 foxr 1426:
1.1 foxr 1427: Debug(9,"Entering event loop");
1428: my $ret = Event::loop(); # Start the main event loop.
1429:
1430:
1431: die "Main event loop exited!!!";
1432: }
1433:
1434: # Create a new child for host passed in:
1435:
1436: sub CreateChild {
1.12 foxr 1437: my $sigset = POSIX::SigSet->new(SIGINT);
1438: sigprocmask(SIG_BLOCK, $sigset);
1.1 foxr 1439: my $host = shift;
1440: $RemoteHost = $host;
1.9 foxr 1441: Log("CRITICAL", "Forking server for ".$host);
1.1 foxr 1442: $pid = fork;
1443: if($pid) { # Parent
1444: $ChildHash{$pid} = $RemoteHost;
1.12 foxr 1445: sigprocmask(SIG_UNBLOCK, $sigset);
1446:
1.1 foxr 1447: } else { # child.
1.5 foxr 1448: ShowStatus("Connected to ".$RemoteHost);
1.12 foxr 1449: $SIG{INT} = DEFAULT;
1450: sigprocmask(SIG_UNBLOCK, $sigset);
1451: ChildProcess; # Does not return.
1.1 foxr 1452: }
1453:
1454: }
1455: #
1456: # Parent process logic pass 1:
1457: # For each entry in the hosts table, we will
1458: # fork off an instance of ChildProcess to service the transactions
1459: # to that host. Each pid will be entered in a global hash
1460: # with the value of the key, the host.
1461: # The parent will then enter a loop to wait for process exits.
1462: # Each exit gets logged and the child gets restarted.
1463: #
1464:
1.5 foxr 1465: #
1466: # Fork and start in new session so hang-up isn't going to
1467: # happen without intent.
1468: #
1469:
1470:
1.6 foxr 1471:
1472:
1.8 foxr 1473:
1.6 foxr 1474:
1475: ShowStatus("Forming new session");
1476: my $childpid = fork;
1477: if ($childpid != 0) {
1478: sleep 4; # Give child a chacne to break to
1479: exit 0; # a new sesion.
1480: }
1.8 foxr 1481: #
1482: # Write my pid into the pid file so I can be located
1483: #
1484:
1485: ShowStatus("Parent writing pid file:");
1486: $execdir = $perlvar{'lonDaemons'};
1487: open (PIDSAVE, ">$execdir/logs/lonc.pid");
1488: print PIDSAVE "$$\n";
1489: close(PIDSAVE);
1.6 foxr 1490:
1491: if (POSIX::setsid() < 0) {
1492: print "Could not create new session\n";
1493: exit -1;
1494: }
1.5 foxr 1495:
1496: ShowStatus("Forking node servers");
1497:
1.9 foxr 1498: Log("CRITICAL", "--------------- Starting children ---------------");
1499:
1.1 foxr 1500: my $HostIterator = LondConnection::GetHostIterator;
1501: while (! $HostIterator->end()) {
1502:
1503: $hostentryref = $HostIterator->get();
1504: CreateChild($hostentryref->[0]);
1505: $HostIterator->next();
1506: }
1.12 foxr 1507: $RemoteHost = "Parent Server";
1.1 foxr 1508:
1509: # Maintain the population:
1.5 foxr 1510:
1511: ShowStatus("Parent keeping the flock");
1.1 foxr 1512:
1.10 foxr 1513: #
1514: # Set up parent signals:
1515: #
1.12 foxr 1516:
1.14 foxr 1517: $SIG{INT} = \&Terminate;
1518: $SIG{TERM} = \&Terminate;
1.13 foxr 1519: $SIG{HUP} = \&Restart;
1.14 foxr 1520: $SIG{USR1} = \&CheckKids;
1.10 foxr 1521:
1.1 foxr 1522: while(1) {
1523: $deadchild = wait();
1524: if(exists $ChildHash{$deadchild}) { # need to restart.
1525: $deadhost = $ChildHash{$deadchild};
1526: delete($ChildHash{$deadchild});
1.9 foxr 1527: Log("WARNING","Lost child pid= ".$deadchild.
1.1 foxr 1528: "Connected to host ".$deadhost);
1.9 foxr 1529: Log("INFO", "Restarting child procesing ".$deadhost);
1.1 foxr 1530: CreateChild($deadhost);
1531: }
1.13 foxr 1532: }
1533:
1.14 foxr 1534:
1535:
1536: =pod
1537:
1538: =head1 CheckKids
1539:
1540: Since kids do not die as easily in this implementation
1541: as the previous one, there is no need to restart the
1542: dead ones (all dead kids get restarted when they die!!)
1543: The only thing this function does is to pass USR1 to the
1544: kids so that they report their status.
1545:
1546: =cut
1547:
1548: sub CheckKids {
1549: Debug(2, "Checking status of children");
1550: my $docdir = $perlvar{'lonDocRoot'};
1551: my $fh = IO::File->new(">$docdir/lon-status/loncstatus.txt");
1552: my $now=time;
1553: my $local=localtime($now);
1554: print $fh "LONC status $local - parent $$ \n\n";
1555: foreach $pid (keys %ChildHash) {
1556: Debug(2, "Sending USR1 -> $pid");
1557: kill 'USR1' => $pid; # Tell Child to report status.
1558: sleep 1; # Wait so file doesn't intermix.
1559: }
1560: }
1561:
1.13 foxr 1562: =pod
1563:
1564: =head1 Restart
1565:
1566: Signal handler for HUP... all children are killed and
1567: we self restart. This is an el-cheapo way to re read
1568: the config file.
1569:
1570: =cut
1571:
1572: sub Restart {
1573: KillThemAll; # First kill all the children.
1574: Log("CRITICAL", "Restarting");
1575: my $execdir = $perlvar{'lonDaemons'};
1576: unlink("$execdir/logs/lonc.pid");
1577: exec("$execdir/lonc");
1.10 foxr 1578: }
1.12 foxr 1579:
1580: =pod
1581:
1582: =head1 KillThemAll
1583:
1584: Signal handler that kills all children by sending them a
1585: SIGINT. Responds to sigint and sigterm.
1586:
1587: =cut
1588:
1.10 foxr 1589: sub KillThemAll {
1.12 foxr 1590: Debug(2, "Kill them all!!");
1591: local($SIG{CHLD}) = 'IGNORE'; # Our children >will< die.
1592: foreach $pid (keys %ChildHash) {
1593: my $serving = $ChildHash{$pid};
1594: Debug(2, "Killing lonc for $serving pid = $pid");
1595: ShowStatus("Killing lonc for $serving pid = $pid");
1596: Log("CRITICAL", "Killing lonc for $serving pid = $pid");
1597: kill('INT', $pid);
1.14 foxr 1598: delete($ChildeHash{$pid});
1.12 foxr 1599: }
1.14 foxr 1600: my $execdir = $perlvar{'lonDaemons'};
1601: unlink("$execdir/logs/lonc.pid");
1602: ShowStatus("Killing the master process");
1.12 foxr 1603: Log("CRITICAL", "Killing the master process.");
1.1 foxr 1604: }
1.12 foxr 1605:
1.14 foxr 1606: =pod
1607:
1608: =head1 Terminate
1609:
1610: Terminate the system.
1611:
1612: =cut
1613:
1614: sub Terminate {
1615: KillThemAll;
1616: exit;
1617:
1618: }
1.12 foxr 1619: =pod
1.1 foxr 1620:
1621: =head1 Theory
1.3 albertel 1622:
1623: The event class is used to build this as a single process with an
1624: event driven model. The following events are handled:
1.1 foxr 1625:
1626: =item UNIX Socket connection Received
1627:
1628: =item Request data arrives on UNIX data transfer socket.
1629:
1630: =item lond connection becomes writable.
1631:
1632: =item timer fires at 1 second intervals.
1633:
1634: All sockets are run in non-blocking mode. Timeouts managed by the timer
1635: handler prevents hung connections.
1636:
1637: Key data structures:
1638:
1.3 albertel 1639: =item RequestQueue
1640:
1641: A queue of requests received from UNIX sockets that are
1642: waiting for a chance to be forwarded on a lond connection socket.
1643:
1644: =item ActiveConnections
1645:
1646: A hash of lond connections that have transactions in process that are
1647: available to be timed out.
1648:
1649: =item ActiveTransactions
1650:
1651: A hash indexed by lond connections that contain the client reply
1652: socket for each connection that has an active transaction on it.
1653:
1654: =item IdleConnections
1655:
1656: A hash of lond connections that have no work to do. These connections
1657: can be closed if they are idle for a long enough time.
1.1 foxr 1658:
1659: =cut
FreeBSD-CVSweb <freebsd-cvsweb@FreeBSD.org>