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