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