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