Annotation of loncom/loncnew, revision 1.62
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.62 ! foxr 5: # $Id: loncnew,v 1.61 2004/09/29 10:37:35 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.38 foxr 38: # - Add logging/status monitoring. (done)
39: # - Add Signal handling - HUP restarts. USR1 status report. (done)
1.7 foxr 40: # - Add Configuration file I/O (done).
1.38 foxr 41: # - Add management/status request interface. (done)
1.8 foxr 42: # - Add deferred request capability. (done)
1.38 foxr 43: # - Detect transmission timeouts. (done)
1.7 foxr 44: #
45:
1.23 foxr 46: use strict;
1.1 foxr 47: use lib "/home/httpd/lib/perl/";
48: use Event qw(:DEFAULT );
49: use POSIX qw(:signal_h);
1.12 foxr 50: use POSIX;
1.1 foxr 51: use IO::Socket;
52: use IO::Socket::INET;
53: use IO::Socket::UNIX;
1.9 foxr 54: use IO::File;
1.6 foxr 55: use IO::Handle;
1.1 foxr 56: use Socket;
57: use Crypt::IDEA;
58: use LONCAPA::Queue;
59: use LONCAPA::Stack;
60: use LONCAPA::LondConnection;
1.7 foxr 61: use LONCAPA::LondTransaction;
1.1 foxr 62: use LONCAPA::Configuration;
63: use LONCAPA::HashIterator;
64:
65:
66: # Read the httpd configuration file to get perl variables
67: # normally set in apache modules:
68:
69: my $perlvarref = LONCAPA::Configuration::read_conf('loncapa.conf');
70: my %perlvar = %{$perlvarref};
71:
72: #
73: # parent and shared variables.
74:
75: my %ChildHash; # by pid -> host.
1.26 foxr 76: my %HostToPid; # By host -> pid.
77: my %HostHash; # by loncapaname -> IP.
1.62 ! foxr 78: my %listening_to; # Socket->host table for who the parent
! 79: # is listening to.
! 80: my %parent_dispatchers; # host-> listener watcher events.
1.1 foxr 81:
1.9 foxr 82: my $MaxConnectionCount = 10; # Will get from config later.
1.1 foxr 83: my $ClientConnection = 0; # Uniquifier for client events.
84:
1.9 foxr 85: my $DebugLevel = 0;
1.29 foxr 86: my $NextDebugLevel= 2; # So Sigint can toggle this.
1.50 albertel 87: my $IdleTimeout= 600; # Wait 10 minutes before pruning connections.
1.1 foxr 88:
1.39 foxr 89: my $LogTransactions = 0; # When True, all transactions/replies get logged.
90:
1.1 foxr 91: #
92: # The variables below are only used by the child processes.
93: #
94: my $RemoteHost; # Name of host child is talking to.
1.20 albertel 95: my $UnixSocketDir= $perlvar{'lonSockDir'};
1.1 foxr 96: my $IdleConnections = Stack->new(); # Set of idle connections
97: my %ActiveConnections; # Connections to the remote lond.
1.7 foxr 98: my %ActiveTransactions; # LondTransactions in flight.
1.1 foxr 99: my %ActiveClients; # Serial numbers of active clients by socket.
100: my $WorkQueue = Queue->new(); # Queue of pending transactions.
101: my $ConnectionCount = 0;
1.4 foxr 102: my $IdleSeconds = 0; # Number of seconds idle.
1.9 foxr 103: my $Status = ""; # Current status string.
1.14 foxr 104: my $RecentLogEntry = "";
1.30 foxr 105: my $ConnectionRetries=2; # Number of connection retries allowed.
106: my $ConnectionRetriesLeft=2; # Number of connection retries remaining.
1.40 foxr 107: my $LondVersion = "unknown"; # Version of lond we talk with.
1.49 foxr 108: my $KeyMode = ""; # e.g. ssl, local, insecure from last connect.
1.54 foxr 109: my $LondConnecting = 0; # True when a connection is being built.
1.1 foxr 110:
1.60 foxr 111:
112: # DO NOT SET THE NEXT VARIABLE TO NON ZERO!!!!!!!!!!!!!!!
113:
1.57 foxr 114: my $DieWhenIdle = 0; # When true children die when trimmed -> 0.
1.62 ! foxr 115: my $I_am_child = 0; # True if this is the child process.
1.57 foxr 116:
1.1 foxr 117: #
1.9 foxr 118: # The hash below gives the HTML format for log messages
119: # given a severity.
120: #
121: my %LogFormats;
122:
1.45 albertel 123: $LogFormats{"CRITICAL"} = "<font color='red'>CRITICAL: %s</font>";
124: $LogFormats{"SUCCESS"} = "<font color='green'>SUCCESS: %s</font>";
125: $LogFormats{"INFO"} = "<font color='yellow'>INFO: %s</font>";
126: $LogFormats{"WARNING"} = "<font color='blue'>WARNING: %s</font>";
1.9 foxr 127: $LogFormats{"DEFAULT"} = " %s ";
128:
1.10 foxr 129:
1.57 foxr 130: # UpdateStatus;
131: # Update the idle status display to show how many connections
132: # are left, retries and other stuff.
133: #
134: sub UpdateStatus {
135: if ($ConnectionRetriesLeft > 0) {
136: ShowStatus(GetServerHost()." Connection count: ".$ConnectionCount
137: ." Retries remaining: ".$ConnectionRetriesLeft
138: ." ($KeyMode)");
139: } else {
140: ShowStatus(GetServerHost()." >> DEAD <<");
141: }
142: }
143:
1.10 foxr 144:
145: =pod
146:
147: =head2 LogPerm
148:
149: Makes an entry into the permanent log file.
150:
151: =cut
152: sub LogPerm {
153: my $message=shift;
154: my $execdir=$perlvar{'lonDaemons'};
155: my $now=time;
156: my $local=localtime($now);
157: my $fh=IO::File->new(">>$execdir/logs/lonnet.perm.log");
158: print $fh "$now:$message:$local\n";
159: }
1.9 foxr 160:
161: =pod
162:
163: =head2 Log
164:
165: Logs a message to the log file.
166: Parameters:
167:
168: =item severity
169:
170: One of CRITICAL, WARNING, INFO, SUCCESS used to select the
171: format string used to format the message. if the severity is
172: not a defined severity the Default format string is used.
173:
174: =item message
175:
176: The base message. In addtion to the format string, the message
177: will be appended to a string containing the name of our remote
178: host and the time will be formatted into the message.
179:
180: =cut
181:
182: sub Log {
1.47 foxr 183:
184: my ($severity, $message) = @_;
185:
1.9 foxr 186: if(!$LogFormats{$severity}) {
187: $severity = "DEFAULT";
188: }
189:
190: my $format = $LogFormats{$severity};
191:
192: # Put the window dressing in in front of the message format:
193:
194: my $now = time;
195: my $local = localtime($now);
196: my $finalformat = "$local ($$) [$RemoteHost] [$Status] ";
197: my $finalformat = $finalformat.$format."\n";
198:
199: # open the file and put the result.
200:
201: my $execdir = $perlvar{'lonDaemons'};
202: my $fh = IO::File->new(">>$execdir/logs/lonc.log");
203: my $msg = sprintf($finalformat, $message);
1.14 foxr 204: $RecentLogEntry = $msg;
1.9 foxr 205: print $fh $msg;
206:
1.10 foxr 207:
1.9 foxr 208: }
1.6 foxr 209:
1.3 albertel 210:
1.1 foxr 211: =pod
1.3 albertel 212:
213: =head2 GetPeerName
214:
215: Returns the name of the host that a socket object is connected to.
216:
1.1 foxr 217: =cut
218:
219: sub GetPeername {
1.47 foxr 220:
221:
222: my ($connection, $AdrFamily) = @_;
223:
1.1 foxr 224: my $peer = $connection->peername();
225: my $peerport;
226: my $peerip;
227: if($AdrFamily == AF_INET) {
228: ($peerport, $peerip) = sockaddr_in($peer);
1.23 foxr 229: my $peername = gethostbyaddr($peerip, $AdrFamily);
1.1 foxr 230: return $peername;
231: } elsif ($AdrFamily == AF_UNIX) {
232: my $peerfile;
233: ($peerfile) = sockaddr_un($peer);
234: return $peerfile;
235: }
236: }
237: =pod
1.3 albertel 238:
1.1 foxr 239: =head2 Debug
1.3 albertel 240:
241: Invoked to issue a debug message.
242:
1.1 foxr 243: =cut
1.3 albertel 244:
1.1 foxr 245: sub Debug {
1.47 foxr 246:
247: my ($level, $message) = @_;
248:
1.1 foxr 249: if ($level <= $DebugLevel) {
1.23 foxr 250: Log("INFO", "-Debug- $message host = $RemoteHost");
1.1 foxr 251: }
252: }
253:
254: sub SocketDump {
1.47 foxr 255:
256: my ($level, $socket) = @_;
257:
1.1 foxr 258: if($level <= $DebugLevel) {
1.48 foxr 259: $socket->Dump(-1); # Ensure it will get dumped.
1.1 foxr 260: }
261: }
1.3 albertel 262:
1.1 foxr 263: =pod
1.3 albertel 264:
1.5 foxr 265: =head2 ShowStatus
266:
267: Place some text as our pid status.
1.10 foxr 268: and as what we return in a SIGUSR1
1.5 foxr 269:
270: =cut
271: sub ShowStatus {
1.10 foxr 272: my $state = shift;
273: my $now = time;
274: my $local = localtime($now);
275: $Status = $local.": ".$state;
276: $0='lonc: '.$state.' '.$local;
1.5 foxr 277: }
278:
279: =pod
280:
1.15 foxr 281: =head 2 SocketTimeout
282:
283: Called when an action on the socket times out. The socket is
284: destroyed and any active transaction is failed.
285:
286:
287: =cut
288: sub SocketTimeout {
289: my $Socket = shift;
1.38 foxr 290: Log("WARNING", "A socket timeout was detected");
1.52 foxr 291: Debug(5, " SocketTimeout called: ");
1.48 foxr 292: $Socket->Dump(0);
1.42 foxr 293: if(exists($ActiveTransactions{$Socket})) {
1.43 albertel 294: FailTransaction($ActiveTransactions{$Socket});
1.42 foxr 295: }
1.22 foxr 296: KillSocket($Socket); # A transaction timeout also counts as
297: # a connection failure:
298: $ConnectionRetriesLeft--;
1.42 foxr 299: if($ConnectionRetriesLeft <= 0) {
1.52 foxr 300: Log("CRITICAL", "Host marked DEAD: ".GetServerHost());
1.56 foxr 301: $LondConnecting = 0;
1.42 foxr 302: }
303:
1.15 foxr 304: }
1.35 foxr 305: #----------------------------- Timer management ------------------------
1.15 foxr 306:
307: =pod
308:
1.1 foxr 309: =head2 Tick
1.3 albertel 310:
311: Invoked each timer tick.
312:
1.1 foxr 313: =cut
314:
1.5 foxr 315:
1.1 foxr 316: sub Tick {
1.52 foxr 317: my ($Event) = @_;
318: my $clock_watcher = $Event->w;
319:
1.1 foxr 320: my $client;
1.57 foxr 321: UpdateStatus();
322:
1.4 foxr 323: # Is it time to prune connection count:
324:
325:
326: if($IdleConnections->Count() &&
327: ($WorkQueue->Count() == 0)) { # Idle connections and nothing to do?
1.52 foxr 328: $IdleSeconds++;
1.4 foxr 329: if($IdleSeconds > $IdleTimeout) { # Prune a connection...
1.23 foxr 330: my $Socket = $IdleConnections->pop();
1.6 foxr 331: KillSocket($Socket);
1.54 foxr 332: $IdleSeconds = 0; # Otherwise all connections get trimmed to fast.
1.57 foxr 333: UpdateStatus();
334: if(($ConnectionCount == 0) && $DieWhenIdle) {
335: #
336: # Create a lock file since there will be a time window
337: # between our exit and the parent's picking up the listen
338: # during which no listens will be done on the
339: # lonnet client socket.
340: #
341: my $lock_file = GetLoncSocketPath().".lock";
342: open(LOCK,">$lock_file");
343: print LOCK "Contents not important";
344: close(LOCK);
345:
346: exit(0);
347: }
1.4 foxr 348: }
349: } else {
350: $IdleSeconds = 0; # Reset idle count if not idle.
351: }
1.15 foxr 352: #
353: # For each inflight transaction, tick down its timeout counter.
354: #
1.35 foxr 355:
1.34 albertel 356: foreach my $item (keys %ActiveConnections) {
357: my $State = $ActiveConnections{$item}->data->GetState();
1.35 foxr 358: if ($State ne 'Idle') {
1.34 albertel 359: Debug(5,"Ticking Socket $State $item");
360: $ActiveConnections{$item}->data->Tick();
361: }
1.15 foxr 362: }
1.5 foxr 363: # Do we have work in the queue, but no connections to service them?
364: # If so, try to make some new connections to get things going again.
365: #
1.57 foxr 366: # Note this code is dead now...
367: #
1.5 foxr 368: my $Requests = $WorkQueue->Count();
1.56 foxr 369: if (($ConnectionCount == 0) && ($Requests > 0) && (!$LondConnecting)) {
1.10 foxr 370: if ($ConnectionRetriesLeft > 0) {
1.56 foxr 371: Debug(5,"Work but no connections, Make a new one");
372: my $success;
373: $success = &MakeLondConnection;
374: if($success == 0) { # All connections failed:
1.29 foxr 375: Debug(5,"Work in queue failed to make any connectiouns\n");
1.22 foxr 376: EmptyQueue(); # Fail pending transactions with con_lost.
1.42 foxr 377: CloseAllLondConnections(); # Should all be closed but....
1.10 foxr 378: }
379: } else {
1.56 foxr 380: $LondConnecting = 0;
1.22 foxr 381: ShowStatus(GetServerHost()." >>> DEAD!!! <<<");
1.29 foxr 382: Debug(5,"Work in queue, but gave up on connections..flushing\n");
1.10 foxr 383: EmptyQueue(); # Connections can't be established.
1.42 foxr 384: CloseAllLondConnections(); # Should all already be closed but...
1.5 foxr 385: }
386:
387: }
1.49 foxr 388: if ($ConnectionCount == 0) {
389: $KeyMode = "";
1.52 foxr 390: $clock_watcher->cancel();
1.49 foxr 391: }
1.1 foxr 392: }
393:
394: =pod
1.3 albertel 395:
1.1 foxr 396: =head2 SetupTimer
397:
1.3 albertel 398: Sets up a 1 per sec recurring timer event. The event handler is used to:
1.1 foxr 399:
1.3 albertel 400: =item
401:
402: Trigger timeouts on communications along active sockets.
403:
404: =item
405:
406: Trigger disconnections of idle sockets.
1.1 foxr 407:
408: =cut
409:
410: sub SetupTimer {
1.52 foxr 411: Debug(6, "SetupTimer");
412: Event->timer(interval => 1, cb => \&Tick );
1.1 foxr 413: }
1.3 albertel 414:
1.1 foxr 415: =pod
1.3 albertel 416:
1.1 foxr 417: =head2 ServerToIdle
1.3 albertel 418:
419: This function is called when a connection to the server is
420: ready for more work.
421:
422: If there is work in the Work queue the top element is dequeued
1.1 foxr 423: and the connection will start to work on it. If the work queue is
424: empty, the connection is pushed on the idle connection stack where
425: it will either get another work unit, or alternatively, if it sits there
426: long enough, it will be shut down and released.
427:
1.3 albertel 428: =cut
1.1 foxr 429:
430: sub ServerToIdle {
431: my $Socket = shift; # Get the socket.
1.49 foxr 432: $KeyMode = $Socket->{AuthenticationMode};
1.7 foxr 433: delete($ActiveTransactions{$Socket}); # Server has no transaction
1.1 foxr 434:
1.29 foxr 435: &Debug(5, "Server to idle");
1.1 foxr 436:
437: # If there's work to do, start the transaction:
438:
1.23 foxr 439: my $reqdata = $WorkQueue->dequeue(); # This is a LondTransaction
1.29 foxr 440: if ($reqdata ne undef) {
441: Debug(5, "Queue gave request data: ".$reqdata->getRequest());
1.7 foxr 442: &StartRequest($Socket, $reqdata);
1.8 foxr 443:
1.1 foxr 444: } else {
445:
446: # There's no work waiting, so push the server to idle list.
1.29 foxr 447: &Debug(5, "No new work requests, server connection going idle");
1.1 foxr 448: $IdleConnections->push($Socket);
449: }
450: }
1.3 albertel 451:
1.1 foxr 452: =pod
1.3 albertel 453:
1.1 foxr 454: =head2 ClientWritable
1.3 albertel 455:
456: Event callback for when a client socket is writable.
457:
458: This callback is established when a transaction reponse is
459: avaiable from lond. The response is forwarded to the unix socket
460: as it becomes writable in this sub.
461:
1.1 foxr 462: Parameters:
463:
1.3 albertel 464: =item Event
465:
466: The event that has been triggered. Event->w->data is
467: the data and Event->w->fd is the socket to write.
1.1 foxr 468:
469: =cut
1.3 albertel 470:
1.1 foxr 471: sub ClientWritable {
472: my $Event = shift;
473: my $Watcher = $Event->w;
474: my $Data = $Watcher->data;
475: my $Socket = $Watcher->fd;
476:
477: # Try to send the data:
478:
479: &Debug(6, "ClientWritable writing".$Data);
480: &Debug(9, "Socket is: ".$Socket);
481:
1.6 foxr 482: if($Socket->connected) {
483: my $result = $Socket->send($Data, 0);
484:
485: # $result undefined: the write failed.
486: # otherwise $result is the number of bytes written.
487: # Remove that preceding string from the data.
488: # If the resulting data is empty, destroy the watcher
489: # and set up a read event handler to accept the next
490: # request.
491:
492: &Debug(9,"Send result is ".$result." Defined: ".defined($result));
1.29 foxr 493: if($result ne undef) {
1.6 foxr 494: &Debug(9, "send result was defined");
495: if($result == length($Data)) { # Entire string sent.
496: &Debug(9, "ClientWritable data all written");
497: $Watcher->cancel();
498: #
499: # Set up to read next request from socket:
500:
501: my $descr = sprintf("Connection to lonc client %d",
502: $ActiveClients{$Socket});
503: Event->io(cb => \&ClientRequest,
504: poll => 'r',
505: desc => $descr,
506: data => "",
507: fd => $Socket);
508:
509: } else { # Partial string sent.
510: $Watcher->data(substr($Data, $result));
1.15 foxr 511: if($result == 0) { # client hung up on us!!
1.52 foxr 512: # Log("INFO", "lonc pipe client hung up on us!");
1.15 foxr 513: $Watcher->cancel;
514: $Socket->shutdown(2);
515: $Socket->close();
516: }
1.6 foxr 517: }
518:
519: } else { # Error of some sort...
520:
521: # Some errnos are possible:
522: my $errno = $!;
523: if($errno == POSIX::EWOULDBLOCK ||
524: $errno == POSIX::EAGAIN ||
525: $errno == POSIX::EINTR) {
526: # No action taken?
527: } else { # Unanticipated errno.
528: &Debug(5,"ClientWritable error or peer shutdown".$RemoteHost);
529: $Watcher->cancel; # Stop the watcher.
530: $Socket->shutdown(2); # Kill connection
531: $Socket->close(); # Close the socket.
532: }
1.1 foxr 533:
534: }
1.6 foxr 535: } else {
536: $Watcher->cancel(); # A delayed request...just cancel.
1.1 foxr 537: }
538: }
539:
540: =pod
1.3 albertel 541:
1.1 foxr 542: =head2 CompleteTransaction
1.3 albertel 543:
544: Called when the reply data has been received for a lond
1.1 foxr 545: transaction. The reply data must now be sent to the
546: ultimate client on the other end of the Unix socket. This is
547: done by setting up a writable event for the socket with the
548: data the reply data.
1.3 albertel 549:
1.1 foxr 550: Parameters:
1.3 albertel 551:
552: =item Socket
553:
554: Socket on which the lond transaction occured. This is a
555: LondConnection. The data received is in the TransactionReply member.
556:
1.7 foxr 557: =item Transaction
1.3 albertel 558:
1.7 foxr 559: The transaction that is being completed.
1.1 foxr 560:
561: =cut
1.3 albertel 562:
1.1 foxr 563: sub CompleteTransaction {
1.29 foxr 564: &Debug(5,"Complete transaction");
1.47 foxr 565:
566: my ($Socket, $Transaction) = @_;
1.1 foxr 567:
1.7 foxr 568: if (!$Transaction->isDeferred()) { # Normal transaction
569: my $data = $Socket->GetReply(); # Data to send.
1.39 foxr 570: if($LogTransactions) {
571: Log("SUCCESS", "Reply from lond: '$data'");
572: }
1.7 foxr 573: StartClientReply($Transaction, $data);
574: } else { # Delete deferred transaction file.
1.9 foxr 575: Log("SUCCESS", "A delayed transaction was completed");
1.23 foxr 576: LogPerm("S:$Transaction->getClient() :".$Transaction->getRequest());
1.7 foxr 577: unlink $Transaction->getFile();
578: }
1.6 foxr 579: }
1.42 foxr 580:
1.6 foxr 581: =pod
1.42 foxr 582:
1.6 foxr 583: =head1 StartClientReply
584:
585: Initiates a reply to a client where the reply data is a parameter.
586:
1.7 foxr 587: =head2 parameters:
588:
589: =item Transaction
590:
591: The transaction for which we are responding to the client.
592:
593: =item data
594:
595: The data to send to apached client.
596:
1.6 foxr 597: =cut
1.42 foxr 598:
1.6 foxr 599: sub StartClientReply {
1.1 foxr 600:
1.47 foxr 601: my ($Transaction, $data) = @_;
1.12 foxr 602:
1.7 foxr 603: my $Client = $Transaction->getClient();
604:
1.1 foxr 605: &Debug(8," Reply was: ".$data);
606: my $Serial = $ActiveClients{$Client};
607: my $desc = sprintf("Connection to lonc client %d",
608: $Serial);
609: Event->io(fd => $Client,
610: poll => "w",
611: desc => $desc,
612: cb => \&ClientWritable,
613: data => $data);
614: }
1.42 foxr 615:
1.4 foxr 616: =pod
1.42 foxr 617:
1.4 foxr 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:
1.42 foxr 627: Deleting the transaction means killing it from the %ActiveTransactions hash.
1.4 foxr 628:
629: Parameters:
630:
631: =item client
632:
1.7 foxr 633: The LondTransaction we are failing.
634:
1.42 foxr 635:
1.4 foxr 636: =cut
637:
638: sub FailTransaction {
1.7 foxr 639: my $transaction = shift;
1.52 foxr 640:
641: # If the socket is dead, that's already logged.
642:
643: if ($ConnectionRetriesLeft > 0) {
644: Log("WARNING", "Failing transaction "
645: .$transaction->getRequest());
646: }
1.30 foxr 647: Debug(1, "Failing transaction: ".$transaction->getRequest());
1.10 foxr 648: if (!$transaction->isDeferred()) { # If the transaction is deferred we'll get to it.
1.11 foxr 649: my $client = $transaction->getClient();
1.30 foxr 650: Debug(1," Replying con_lost to ".$transaction->getRequest());
1.11 foxr 651: StartClientReply($transaction, "con_lost\n");
1.7 foxr 652: }
1.4 foxr 653:
654: }
655:
656: =pod
1.6 foxr 657: =head1 EmptyQueue
1.7 foxr 658:
1.6 foxr 659: Fails all items in the work queue with con_lost.
1.7 foxr 660: Note that each item in the work queue is a transaction.
661:
1.6 foxr 662: =cut
663: sub EmptyQueue {
1.22 foxr 664: $ConnectionRetriesLeft--; # Counts as connection failure too.
1.6 foxr 665: while($WorkQueue->Count()) {
1.10 foxr 666: my $request = $WorkQueue->dequeue(); # This is a transaction
1.7 foxr 667: FailTransaction($request);
1.6 foxr 668: }
669: }
670:
671: =pod
1.4 foxr 672:
1.9 foxr 673: =head2 CloseAllLondConnections
674:
675: Close all connections open on lond prior to exit e.g.
676:
677: =cut
678: sub CloseAllLondConnections {
1.23 foxr 679: foreach my $Socket (keys %ActiveConnections) {
1.42 foxr 680: if(exists($ActiveTransactions{$Socket})) {
681: FailTransaction($ActiveTransactions{$Socket});
682: }
683: KillSocket($Socket);
1.9 foxr 684: }
685: }
686: =cut
687:
688: =pod
689:
1.4 foxr 690: =head2 KillSocket
691:
692: Destroys a socket. This function can be called either when a socket
693: has died of 'natural' causes or because a socket needs to be pruned due to
694: idleness. If the socket has died naturally, if there are no longer any
695: live connections a new connection is created (in case there are transactions
696: in the queue). If the socket has been pruned, it is never re-created.
697:
698: Parameters:
1.1 foxr 699:
1.4 foxr 700: =item Socket
701:
702: The socket to kill off.
703:
704: =item Restart
705:
706: nonzero if we are allowed to create a new connection.
707:
708:
709: =cut
710: sub KillSocket {
711: my $Socket = shift;
712:
1.17 foxr 713: Log("WARNING", "Shutting down a socket");
1.9 foxr 714: $Socket->Shutdown();
715:
1.7 foxr 716: # If the socket came from the active connection set,
717: # delete its transaction... note that FailTransaction should
718: # already have been called!!!
719: # otherwise it came from the idle set.
720: #
1.4 foxr 721:
722: if(exists($ActiveTransactions{$Socket})) {
723: delete ($ActiveTransactions{$Socket});
724: }
725: if(exists($ActiveConnections{$Socket})) {
726: delete($ActiveConnections{$Socket});
1.37 albertel 727: $ConnectionCount--;
728: if ($ConnectionCount < 0) { $ConnectionCount = 0; }
1.4 foxr 729: }
1.6 foxr 730: # If the connection count has gone to zero and there is work in the
731: # work queue, the work all gets failed with con_lost.
732: #
733: if($ConnectionCount == 0) {
1.22 foxr 734: EmptyQueue();
1.42 foxr 735: CloseAllLondConnections; # Should all already be closed but...
1.4 foxr 736: }
737: }
1.1 foxr 738:
739: =pod
1.3 albertel 740:
1.1 foxr 741: =head2 LondReadable
1.3 albertel 742:
1.1 foxr 743: This function is called whenever a lond connection
744: is readable. The action is state dependent:
745:
1.3 albertel 746: =head3 State=Initialized
747:
748: We''re waiting for the challenge, this is a no-op until the
1.1 foxr 749: state changes.
1.3 albertel 750:
1.1 foxr 751: =head3 State=Challenged
1.3 albertel 752:
753: The challenge has arrived we need to transition to Writable.
1.1 foxr 754: The connection must echo the challenge back.
1.3 albertel 755:
1.1 foxr 756: =head3 State=ChallengeReplied
1.3 albertel 757:
758: The challenge has been replied to. The we are receiveing the
1.1 foxr 759: 'ok' from the partner.
1.3 albertel 760:
1.40 foxr 761: =head3 State=ReadingVersionString
762:
763: We have requested the lond version and are reading the
764: version back. Upon completion, we'll store the version away
765: for future use(?).
766:
767: =head3 State=HostSet
768:
769: We have selected the domain name of our peer (multhomed hosts)
770: and are getting the reply (presumably ok) back.
771:
1.1 foxr 772: =head3 State=RequestingKey
1.3 albertel 773:
774: The ok has been received and we need to send the request for
1.1 foxr 775: an encryption key. Transition to writable for that.
1.3 albertel 776:
1.1 foxr 777: =head3 State=ReceivingKey
1.3 albertel 778:
779: The the key has been requested, now we are reading the new key.
780:
1.1 foxr 781: =head3 State=Idle
1.3 albertel 782:
783: The encryption key has been negotiated or we have finished
1.1 foxr 784: reading data from the a transaction. If the callback data has
785: a client as well as the socket iformation, then we are
786: doing a transaction and the data received is relayed to the client
787: before the socket is put on the idle list.
1.3 albertel 788:
1.1 foxr 789: =head3 State=SendingRequest
1.3 albertel 790:
791: I do not think this state can be received here, but if it is,
1.1 foxr 792: the appropriate thing to do is to transition to writable, and send
793: the request.
1.3 albertel 794:
1.1 foxr 795: =head3 State=ReceivingReply
1.3 albertel 796:
797: We finished sending the request to the server and now transition
1.1 foxr 798: to readable to receive the reply.
799:
800: The parameter to this function are:
1.3 albertel 801:
1.1 foxr 802: The event. Implicit in this is the watcher and its data. The data
803: contains at least the lond connection object and, if a
804: transaction is in progress, the socket attached to the local client.
805:
1.3 albertel 806: =cut
1.1 foxr 807:
808: sub LondReadable {
1.8 foxr 809:
1.41 albertel 810: my $Event = shift;
811: my $Watcher = $Event->w;
812: my $Socket = $Watcher->data;
813: my $client = undef;
1.40 foxr 814:
1.41 albertel 815: &Debug(6,"LondReadable called state = ".$Socket->GetState());
1.40 foxr 816:
817:
1.41 albertel 818: my $State = $Socket->GetState(); # All action depends on the state.
1.40 foxr 819:
1.41 albertel 820: SocketDump(6, $Socket);
821: my $status = $Socket->Readable();
1.40 foxr 822:
1.41 albertel 823: &Debug(2, "Socket->Readable returned: $status");
1.40 foxr 824:
1.41 albertel 825: if($status != 0) {
826: # bad return from socket read. Currently this means that
827: # The socket has become disconnected. We fail the transaction.
1.40 foxr 828:
1.41 albertel 829: Log("WARNING",
830: "Lond connection lost.");
831: if(exists($ActiveTransactions{$Socket})) {
832: FailTransaction($ActiveTransactions{$Socket});
1.56 foxr 833: } else {
834: # Socket is connecting and failed... need to mark
835: # no longer connecting.
836:
837: $LondConnecting = 0;
1.41 albertel 838: }
839: $Watcher->cancel();
840: KillSocket($Socket);
841: $ConnectionRetriesLeft--; # Counts as connection failure
842: return;
843: }
844: SocketDump(6,$Socket);
1.17 foxr 845:
1.41 albertel 846: $State = $Socket->GetState(); # Update in case of transition.
847: &Debug(6, "After read, state is ".$State);
1.1 foxr 848:
1.41 albertel 849: if($State eq "Initialized") {
1.1 foxr 850:
851:
1.41 albertel 852: } elsif ($State eq "ChallengeReceived") {
1.1 foxr 853: # The challenge must be echoed back; The state machine
854: # in the connection takes care of setting that up. Just
855: # need to transition to writable:
1.41 albertel 856:
857: $Watcher->cb(\&LondWritable);
858: $Watcher->poll("w");
1.1 foxr 859:
1.41 albertel 860: } elsif ($State eq "ChallengeReplied") {
1.1 foxr 861:
1.41 albertel 862: } elsif ($State eq "RequestingVersion") {
863: # Need to ask for the version... that is writiability:
1.1 foxr 864:
1.41 albertel 865: $Watcher->cb(\&LondWritable);
866: $Watcher->poll("w");
867:
868: } elsif ($State eq "ReadingVersionString") {
869: # Read the rest of the version string...
870: } elsif ($State eq "SetHost") {
871: # Need to request the actual domain get set...
872:
873: $Watcher->cb(\&LondWritable);
874: $Watcher->poll("w");
875: } elsif ($State eq "HostSet") {
876: # Reading the 'ok' from the peer.
877:
878: } elsif ($State eq "RequestingKey") {
1.1 foxr 879: # The ok was received. Now we need to request the key
880: # That requires us to be writable:
881:
1.41 albertel 882: $Watcher->cb(\&LondWritable);
883: $Watcher->poll("w");
1.1 foxr 884:
1.41 albertel 885: } elsif ($State eq "ReceivingKey") {
1.1 foxr 886:
1.41 albertel 887: } elsif ($State eq "Idle") {
1.40 foxr 888:
1.41 albertel 889: # This is as good a spot as any to get the peer version
890: # string:
1.40 foxr 891:
1.41 albertel 892: if($LondVersion eq "unknown") {
893: $LondVersion = $Socket->PeerVersion();
894: Log("INFO", "Connected to lond version: $LondVersion");
895: }
1.1 foxr 896: # If necessary, complete a transaction and then go into the
897: # idle queue.
1.22 foxr 898: # Note that a trasition to idle indicates a live lond
899: # on the other end so reset the connection retries.
900: #
1.41 albertel 901: $ConnectionRetriesLeft = $ConnectionRetries; # success resets the count
902: $Watcher->cancel();
903: if(exists($ActiveTransactions{$Socket})) {
904: Debug(5,"Completing transaction!!");
905: CompleteTransaction($Socket,
906: $ActiveTransactions{$Socket});
907: } else {
908: Log("SUCCESS", "Connection ".$ConnectionCount." to "
909: .$RemoteHost." now ready for action");
910: }
911: ServerToIdle($Socket); # Next work unit or idle.
1.54 foxr 912:
913: #
914: $LondConnecting = 0; # Best spot I can think of for this.
915: #
1.6 foxr 916:
1.41 albertel 917: } elsif ($State eq "SendingRequest") {
1.1 foxr 918: # We need to be writable for this and probably don't belong
919: # here inthe first place.
920:
1.41 albertel 921: Deubg(6, "SendingRequest state encountered in readable");
922: $Watcher->poll("w");
923: $Watcher->cb(\&LondWritable);
1.1 foxr 924:
1.41 albertel 925: } elsif ($State eq "ReceivingReply") {
1.1 foxr 926:
927:
1.41 albertel 928: } else {
929: # Invalid state.
930: Debug(4, "Invalid state in LondReadable");
931: }
1.1 foxr 932: }
1.3 albertel 933:
1.1 foxr 934: =pod
1.3 albertel 935:
1.1 foxr 936: =head2 LondWritable
1.3 albertel 937:
1.1 foxr 938: This function is called whenever a lond connection
939: becomes writable while there is a writeable monitoring
940: event. The action taken is very state dependent:
1.3 albertel 941:
1.1 foxr 942: =head3 State = Connected
1.3 albertel 943:
944: The connection is in the process of sending the 'init' hailing to the
945: lond on the remote end. The connection object''s Writable member is
946: called. On error, ConnectionError is called to destroy the connection
947: and remove it from the ActiveConnections hash
948:
1.1 foxr 949: =head3 Initialized
1.3 albertel 950:
951: 'init' has been sent, writability monitoring is removed and
952: readability monitoring is started with LondReadable as the callback.
953:
1.1 foxr 954: =head3 ChallengeReceived
1.3 albertel 955:
956: The connection has received the who are you challenge from the remote
957: system, and is in the process of sending the challenge
958: response. Writable is called.
959:
1.1 foxr 960: =head3 ChallengeReplied
1.3 albertel 961:
962: The connection has replied to the initial challenge The we switch to
963: monitoring readability looking for the server to reply with 'ok'.
964:
1.1 foxr 965: =head3 RequestingKey
1.3 albertel 966:
967: The connection is in the process of requesting its encryption key.
968: Writable is called.
969:
1.1 foxr 970: =head3 ReceivingKey
1.3 albertel 971:
972: The connection has sent the request for a key. Switch to readability
973: monitoring to accept the key
974:
1.1 foxr 975: =head3 SendingRequest
1.3 albertel 976:
977: The connection is in the process of sending a request to the server.
978: This request is part of a client transaction. All the states until
979: now represent the client setup protocol. Writable is called.
980:
1.1 foxr 981: =head3 ReceivingReply
982:
1.3 albertel 983: The connection has sent a request. Now it must receive a reply.
984: Readability monitoring is requested.
985:
986: This function is an event handler and therefore receives as
1.1 foxr 987: a parameter the event that has fired. The data for the watcher
988: of this event is a reference to a list of one or two elements,
989: depending on state. The first (and possibly only) element is the
990: socket. The second (present only if a request is in progress)
991: is the socket on which to return a reply to the caller.
992:
993: =cut
1.3 albertel 994:
1.1 foxr 995: sub LondWritable {
996: my $Event = shift;
997: my $Watcher = $Event->w;
1.8 foxr 998: my $Socket = $Watcher->data;
999: my $State = $Socket->GetState();
1.1 foxr 1000:
1.8 foxr 1001: Debug(6,"LondWritable State = ".$State."\n");
1.1 foxr 1002:
1.8 foxr 1003:
1.1 foxr 1004: # Figure out what to do depending on the state of the socket:
1005:
1006:
1007:
1008:
1009: SocketDump(6,$Socket);
1010:
1.42 foxr 1011: # If the socket is writable, we must always write.
1012: # Only by writing will we undergo state transitions.
1013: # Old logic wrote in state specific code below, however
1014: # That forces us at least through another invocation of
1015: # this function after writability is possible again.
1016: # This logic also factors out common code for handling
1017: # write failures... in all cases, write failures
1018: # Kill the socket.
1019: # This logic makes the branches of the >big< if below
1020: # so that the writing states are actually NO-OPs.
1021:
1022: if ($Socket->Writable() != 0) {
1.43 albertel 1023: # The write resulted in an error.
1024: # We'll treat this as if the socket got disconnected:
1025: Log("WARNING", "Connection to ".$RemoteHost.
1026: " has been disconnected");
1027: if(exists($ActiveTransactions{$Socket})) {
1028: FailTransaction($ActiveTransactions{$Socket});
1.56 foxr 1029: } else {
1030: # In the process of conneting, so need to turn that off.
1031:
1032: $LondConnecting = 0;
1.43 albertel 1033: }
1034: $Watcher->cancel();
1035: KillSocket($Socket);
1036: return;
1.42 foxr 1037: }
1038:
1039:
1040:
1.41 albertel 1041: if ($State eq "Connected") {
1.1 foxr 1042:
1.41 albertel 1043: # "init" is being sent...
1.42 foxr 1044:
1.41 albertel 1045: } elsif ($State eq "Initialized") {
1.4 foxr 1046:
1.41 albertel 1047: # Now that init was sent, we switch
1048: # to watching for readability:
1.1 foxr 1049:
1.41 albertel 1050: $Watcher->cb(\&LondReadable);
1051: $Watcher->poll("r");
1052:
1053: } elsif ($State eq "ChallengeReceived") {
1054: # We received the challenge, now we
1055: # are echoing it back. This is a no-op,
1056: # we're waiting for the state to change
1.1 foxr 1057:
1.41 albertel 1058: } elsif ($State eq "ChallengeReplied") {
1059: # The echo was sent back, so we switch
1060: # to watching readability.
1061:
1062: $Watcher->cb(\&LondReadable);
1063: $Watcher->poll("r");
1064: } elsif ($State eq "RequestingVersion") {
1065: # Sending the peer a version request...
1.42 foxr 1066:
1.41 albertel 1067: } elsif ($State eq "ReadingVersionString") {
1068: # Transition to read since we have sent the
1069: # version command and now just need to read the
1070: # version string from the peer:
1.40 foxr 1071:
1.41 albertel 1072: $Watcher->cb(\&LondReadable);
1073: $Watcher->poll("r");
1.40 foxr 1074:
1.41 albertel 1075: } elsif ($State eq "SetHost") {
1076: # Setting the remote domain...
1.42 foxr 1077:
1.41 albertel 1078: } elsif ($State eq "HostSet") {
1079: # Back to readable to get the ok.
1.40 foxr 1080:
1.41 albertel 1081: $Watcher->cb(\&LondReadable);
1082: $Watcher->poll("r");
1.40 foxr 1083:
1084:
1.41 albertel 1085: } elsif ($State eq "RequestingKey") {
1086: # At this time we're requesting the key.
1087: # again, this is essentially a no-op.
1088:
1089: } elsif ($State eq "ReceivingKey") {
1090: # Now we need to wait for the key
1091: # to come back from the peer:
1092:
1093: $Watcher->cb(\&LondReadable);
1094: $Watcher->poll("r");
1095:
1096: } elsif ($State eq "SendingRequest") {
1.40 foxr 1097:
1.41 albertel 1098: # At this time we are sending a request to the
1.1 foxr 1099: # peer... write the next chunk:
1100:
1.41 albertel 1101:
1102: } elsif ($State eq "ReceivingReply") {
1103: # The send has completed. Wait for the
1104: # data to come in for a reply.
1105: Debug(8,"Writable sent request/receiving reply");
1106: $Watcher->cb(\&LondReadable);
1107: $Watcher->poll("r");
1.1 foxr 1108:
1.41 albertel 1109: } else {
1110: # Control only passes here on an error:
1111: # the socket state does not match any
1112: # of the known states... so an error
1113: # must be logged.
1.1 foxr 1114:
1.41 albertel 1115: &Debug(4, "Invalid socket state ".$State."\n");
1116: }
1.1 foxr 1117:
1118: }
1.6 foxr 1119: =pod
1120:
1121: =cut
1122: sub QueueDelayed {
1.8 foxr 1123: Debug(3,"QueueDelayed called");
1124:
1.6 foxr 1125: my $path = "$perlvar{'lonSockDir'}/delayed";
1.8 foxr 1126:
1127: Debug(4, "Delayed path: ".$path);
1.6 foxr 1128: opendir(DIRHANDLE, $path);
1.8 foxr 1129:
1.23 foxr 1130: my @alldelayed = grep /\.$RemoteHost$/, readdir DIRHANDLE;
1.6 foxr 1131: closedir(DIRHANDLE);
1132: my $dfname;
1.8 foxr 1133: my $reqfile;
1134: foreach $dfname (sort @alldelayed) {
1135: $reqfile = "$path/$dfname";
1136: Debug(4, "queueing ".$reqfile);
1.6 foxr 1137: my $Handle = IO::File->new($reqfile);
1138: my $cmd = <$Handle>;
1.8 foxr 1139: chomp $cmd; # There may or may not be a newline...
1.12 foxr 1140: $cmd = $cmd."\n"; # now for sure there's exactly one newline.
1.7 foxr 1141: my $Transaction = LondTransaction->new($cmd);
1142: $Transaction->SetDeferred($reqfile);
1143: QueueTransaction($Transaction);
1.6 foxr 1144: }
1145:
1146: }
1.1 foxr 1147:
1148: =pod
1.3 albertel 1149:
1.1 foxr 1150: =head2 MakeLondConnection
1.3 albertel 1151:
1152: Create a new lond connection object, and start it towards its initial
1153: idleness. Once idle, it becomes elligible to receive transactions
1154: from the work queue. If the work queue is not empty when the
1155: connection is completed and becomes idle, it will dequeue an entry and
1156: start off on it.
1157:
1.1 foxr 1158: =cut
1.3 albertel 1159:
1.1 foxr 1160: sub MakeLondConnection {
1161: Debug(4,"MakeLondConnection to ".GetServerHost()." on port "
1162: .GetServerPort());
1163:
1164: my $Connection = LondConnection->new(&GetServerHost(),
1165: &GetServerPort());
1166:
1.30 foxr 1167: if($Connection eq undef) { # Needs to be more robust later.
1.9 foxr 1168: Log("CRITICAL","Failed to make a connection with lond.");
1.10 foxr 1169: $ConnectionRetriesLeft--;
1170: return 0; # Failure.
1.5 foxr 1171: } else {
1.22 foxr 1172:
1.5 foxr 1173: # The connection needs to have writability
1174: # monitored in order to send the init sequence
1175: # that starts the whole authentication/key
1176: # exchange underway.
1177: #
1178: my $Socket = $Connection->GetSocket();
1.30 foxr 1179: if($Socket eq undef) {
1.5 foxr 1180: die "did not get a socket from the connection";
1181: } else {
1182: &Debug(9,"MakeLondConnection got socket: ".$Socket);
1183: }
1.1 foxr 1184:
1.21 foxr 1185: $Connection->SetTimeoutCallback(\&SocketTimeout);
1186:
1.23 foxr 1187: my $event = Event->io(fd => $Socket,
1.5 foxr 1188: poll => 'w',
1189: cb => \&LondWritable,
1.8 foxr 1190: data => $Connection,
1.5 foxr 1191: desc => 'Connection to lond server');
1192: $ActiveConnections{$Connection} = $event;
1.52 foxr 1193: if ($ConnectionCount == 0) {
1194: &SetupTimer; # Need to handle timeouts with connections...
1195: }
1.5 foxr 1196: $ConnectionCount++;
1.8 foxr 1197: Debug(4, "Connection count = ".$ConnectionCount);
1.6 foxr 1198: if($ConnectionCount == 1) { # First Connection:
1199: QueueDelayed;
1200: }
1.9 foxr 1201: Log("SUCESS", "Created connection ".$ConnectionCount
1202: ." to host ".GetServerHost());
1.54 foxr 1203: $LondConnecting = 1; # Connection in progress.
1.10 foxr 1204: return 1; # Return success.
1.1 foxr 1205: }
1206:
1207: }
1.3 albertel 1208:
1.1 foxr 1209: =pod
1.3 albertel 1210:
1.1 foxr 1211: =head2 StartRequest
1.3 albertel 1212:
1213: Starts a lond request going on a specified lond connection.
1214: parameters are:
1215:
1216: =item $Lond
1217:
1218: Connection to the lond that will send the transaction and receive the
1219: reply.
1220:
1221: =item $Client
1222:
1223: Connection to the client that is making this request We got the
1224: request from this socket, and when the request has been relayed to
1225: lond and we get a reply back from lond it will get sent to this
1226: socket.
1227:
1228: =item $Request
1229:
1230: The text of the request to send.
1231:
1.1 foxr 1232: =cut
1233:
1234: sub StartRequest {
1.47 foxr 1235:
1236: my ($Lond, $Request) = @_;
1.1 foxr 1237:
1.7 foxr 1238: Debug(6, "StartRequest: ".$Request->getRequest());
1.1 foxr 1239:
1240: my $Socket = $Lond->GetSocket();
1241:
1.7 foxr 1242: $Request->Activate($Lond);
1243: $ActiveTransactions{$Lond} = $Request;
1.1 foxr 1244:
1.7 foxr 1245: $Lond->InitiateTransaction($Request->getRequest());
1.23 foxr 1246: my $event = Event->io(fd => $Socket,
1.1 foxr 1247: poll => "w",
1248: cb => \&LondWritable,
1249: data => $Lond,
1250: desc => "lond transaction connection");
1251: $ActiveConnections{$Lond} = $event;
1252: Debug(8," Start Request made watcher data with ".$event->data."\n");
1253: }
1254:
1255: =pod
1.3 albertel 1256:
1.1 foxr 1257: =head2 QueueTransaction
1.3 albertel 1258:
1259: If there is an idle lond connection, it is put to work doing this
1260: transaction. Otherwise, the transaction is placed in the work queue.
1261: If placed in the work queue and the maximum number of connections has
1262: not yet been created, a new connection will be started. Our goal is
1263: to eventually have a sufficient number of connections that the work
1264: queue will typically be empty. parameters are:
1265:
1266: =item Socket
1267:
1268: open on the lonc client.
1269:
1270: =item Request
1271:
1272: data to send to the lond.
1.1 foxr 1273:
1274: =cut
1.3 albertel 1275:
1.1 foxr 1276: sub QueueTransaction {
1277:
1.7 foxr 1278: my $requestData = shift; # This is a LondTransaction.
1279: my $cmd = $requestData->getRequest();
1280:
1281: Debug(6,"QueueTransaction: ".$cmd);
1.1 foxr 1282:
1283: my $LondSocket = $IdleConnections->pop();
1284: if(!defined $LondSocket) { # Need to queue request.
1.29 foxr 1285: Debug(5,"Must queue...");
1.1 foxr 1286: $WorkQueue->enqueue($requestData);
1.56 foxr 1287: Debug(5, "Queue Transaction startnew $ConnectionCount $LondConnecting");
1288: if(($ConnectionCount < $MaxConnectionCount) && (! $LondConnecting)) {
1289:
1.22 foxr 1290: if($ConnectionRetriesLeft > 0) {
1.29 foxr 1291: Debug(5,"Starting additional lond connection");
1.56 foxr 1292: if(&MakeLondConnection() == 0) {
1.22 foxr 1293: EmptyQueue(); # Fail transactions, can't make connection.
1.42 foxr 1294: CloseAllLondConnections; # Should all be closed but...
1.22 foxr 1295: }
1296: } else {
1297: ShowStatus(GetServerHost()." >>> DEAD !!!! <<<");
1.56 foxr 1298: $LondConnecting = 0;
1.22 foxr 1299: EmptyQueue(); # It's worse than that ... he's dead Jim.
1.42 foxr 1300: CloseAllLondConnections; # Should all be closed but..
1.17 foxr 1301: }
1.1 foxr 1302: }
1303: } else { # Can start the request:
1304: Debug(8,"Can start...");
1.7 foxr 1305: StartRequest($LondSocket, $requestData);
1.1 foxr 1306: }
1307: }
1308:
1309: #-------------------------- Lonc UNIX socket handling ---------------------
1.3 albertel 1310:
1.1 foxr 1311: =pod
1.3 albertel 1312:
1.1 foxr 1313: =head2 ClientRequest
1.3 albertel 1314: Callback that is called when data can be read from the UNIX domain
1315: socket connecting us with an apache server process.
1.1 foxr 1316:
1317: =cut
1318:
1319: sub ClientRequest {
1320: Debug(6, "ClientRequest");
1321: my $event = shift;
1322: my $watcher = $event->w;
1323: my $socket = $watcher->fd;
1324: my $data = $watcher->data;
1325: my $thisread;
1326:
1327: Debug(9, " Watcher named: ".$watcher->desc);
1328:
1329: my $rv = $socket->recv($thisread, POSIX::BUFSIZ, 0);
1330: Debug(8, "rcv: data length = ".length($thisread)
1331: ." read =".$thisread);
1.29 foxr 1332: unless (defined $rv && length($thisread)) {
1.1 foxr 1333: # Likely eof on socket.
1334: Debug(5,"Client Socket closed on lonc for ".$RemoteHost);
1335: close($socket);
1336: $watcher->cancel();
1337: delete($ActiveClients{$socket});
1.10 foxr 1338: return;
1.1 foxr 1339: }
1340: Debug(8,"Data: ".$data." this read: ".$thisread);
1341: $data = $data.$thisread; # Append new data.
1342: $watcher->data($data);
1.44 albertel 1343: if($data =~ /\n$/) { # Request entirely read.
1.10 foxr 1344: if($data eq "close_connection_exit\n") {
1.9 foxr 1345: Log("CRITICAL",
1346: "Request Close Connection ... exiting");
1347: CloseAllLondConnections();
1348: exit;
1349: }
1.1 foxr 1350: Debug(8, "Complete transaction received: ".$data);
1.39 foxr 1351: if($LogTransactions) {
1352: Log("SUCCESS", "Transaction: '$data'"); # Transaction has \n.
1353: }
1.8 foxr 1354: my $Transaction = LondTransaction->new($data);
1.7 foxr 1355: $Transaction->SetClient($socket);
1356: QueueTransaction($Transaction);
1.1 foxr 1357: $watcher->cancel(); # Done looking for input data.
1358: }
1359:
1360: }
1361:
1.62 ! foxr 1362: #
! 1363: # Accept a connection request for a client (lonc child) and
! 1364: # start up an event watcher to keep an eye on input from that
! 1365: # Event. This can be called both from NewClient and from
! 1366: # ChildProcess if we are started in DieWhenIdle mode.
! 1367: # Parameters:
! 1368: # $socket - The listener socket.
! 1369: # Returns:
! 1370: # NONE
! 1371: # Side Effects:
! 1372: # An event is made to watch the accepted connection.
! 1373: # Active clients hash is updated to reflect the new connection.
! 1374: # The client connection count is incremented.
! 1375: #
! 1376: sub accept_client {
! 1377: my ($socket) = @_;
! 1378:
! 1379: Debug(8, "Entering accept for lonc UNIX socket\n");
! 1380: my $connection = $socket->accept(); # Accept the client connection.
! 1381: Debug(8,"Connection request accepted from "
! 1382: .GetPeername($connection, AF_UNIX));
! 1383:
! 1384:
! 1385: my $description = sprintf("Connection to lonc client %d",
! 1386: $ClientConnection);
! 1387: Debug(9, "Creating event named: ".$description);
! 1388: Event->io(cb => \&ClientRequest,
! 1389: poll => 'r',
! 1390: desc => $description,
! 1391: data => "",
! 1392: fd => $connection);
! 1393: $ActiveClients{$connection} = $ClientConnection;
! 1394: $ClientConnection++;
! 1395: }
1.1 foxr 1396:
1397: =pod
1.3 albertel 1398:
1.1 foxr 1399: =head2 NewClient
1.3 albertel 1400:
1401: Callback that is called when a connection is received on the unix
1402: socket for a new client of lonc. The callback is parameterized by the
1403: event.. which is a-priori assumed to be an io event, and therefore has
1404: an fd member that is the Listener socket. We Accept the connection
1405: and register a new event on the readability of that socket:
1406:
1.1 foxr 1407: =cut
1.3 albertel 1408:
1.1 foxr 1409: sub NewClient {
1410: Debug(6, "NewClient");
1411: my $event = shift; # Get the event parameters.
1412: my $watcher = $event->w;
1413: my $socket = $watcher->fd; # Get the event' socket.
1414:
1.62 ! foxr 1415: &accept_client($socket);
1.1 foxr 1416: }
1.3 albertel 1417:
1418: =pod
1419:
1420: =head2 GetLoncSocketPath
1421:
1422: Returns the name of the UNIX socket on which to listen for client
1423: connections.
1.1 foxr 1424:
1.58 foxr 1425: =head2 Parameters:
1426:
1427: host (optional) - Name of the host socket to return.. defaults to
1428: the return from GetServerHost().
1429:
1.1 foxr 1430: =cut
1.3 albertel 1431:
1.1 foxr 1432: sub GetLoncSocketPath {
1.58 foxr 1433:
1434: my $host = GetServerHost(); # Default host.
1435: if (@_) {
1436: ($host) = @_; # Override if supplied.
1437: }
1438: return $UnixSocketDir."/".$host;
1.1 foxr 1439: }
1440:
1.3 albertel 1441: =pod
1442:
1443: =head2 GetServerHost
1444:
1445: Returns the host whose lond we talk with.
1446:
1.1 foxr 1447: =cut
1.3 albertel 1448:
1.7 foxr 1449: sub GetServerHost {
1.1 foxr 1450: return $RemoteHost; # Setup by the fork.
1451: }
1.3 albertel 1452:
1453: =pod
1454:
1455: =head2 GetServerPort
1456:
1457: Returns the lond port number.
1458:
1.1 foxr 1459: =cut
1.3 albertel 1460:
1.7 foxr 1461: sub GetServerPort {
1.1 foxr 1462: return $perlvar{londPort};
1463: }
1.3 albertel 1464:
1465: =pod
1466:
1467: =head2 SetupLoncListener
1468:
1469: Setup a lonc listener event. The event is called when the socket
1470: becomes readable.. that corresponds to the receipt of a new
1471: connection. The event handler established will accept the connection
1472: (creating a communcations channel), that int turn will establish
1473: another event handler to subess requests.
1.1 foxr 1474:
1.58 foxr 1475: =head2 Parameters:
1476:
1477: host (optional) Name of the host to set up a unix socket to.
1478:
1.1 foxr 1479: =cut
1.3 albertel 1480:
1.1 foxr 1481: sub SetupLoncListener {
1482:
1.58 foxr 1483: my $host = GetServerHost(); # Default host.
1484: if (@_) {
1485: ($host) = @_ # Override host with parameter.
1486: }
1487:
1.1 foxr 1488: my $socket;
1.58 foxr 1489: my $SocketName = GetLoncSocketPath($host);
1.1 foxr 1490: unlink($SocketName);
1.7 foxr 1491: unless ($socket =IO::Socket::UNIX->new(Local => $SocketName,
1.55 albertel 1492: Listen => 250,
1.1 foxr 1493: Type => SOCK_STREAM)) {
1494: die "Failed to create a lonc listner socket";
1495: }
1.59 foxr 1496: return $socket;
1.1 foxr 1497: }
1498:
1.39 foxr 1499: #
1500: # Toggle transaction logging.
1501: # Implicit inputs:
1502: # LogTransactions
1503: # Implicit Outputs:
1504: # LogTransactions
1505: sub ToggleTransactionLogging {
1506: print STDERR "Toggle transaction logging...\n";
1507: if(!$LogTransactions) {
1508: $LogTransactions = 1;
1509: } else {
1510: $LogTransactions = 0;
1511: }
1512:
1513:
1514: Log("SUCCESS", "Toggled transaction logging: $LogTransactions \n");
1515: }
1516:
1.14 foxr 1517: =pod
1518:
1519: =head2 ChildStatus
1520:
1521: Child USR1 signal handler to report the most recent status
1522: into the status file.
1523:
1.22 foxr 1524: We also use this to reset the retries count in order to allow the
1525: client to retry connections with a previously dead server.
1.14 foxr 1526: =cut
1.46 albertel 1527:
1.14 foxr 1528: sub ChildStatus {
1529: my $event = shift;
1530: my $watcher = $event->w;
1531:
1532: Debug(2, "Reporting child status because : ".$watcher->data);
1533: my $docdir = $perlvar{'lonDocRoot'};
1534: my $fh = IO::File->new(">>$docdir/lon-status/loncstatus.txt");
1535: print $fh $$."\t".$RemoteHost."\t".$Status."\t".
1536: $RecentLogEntry."\n";
1.38 foxr 1537: #
1538: # Write out information about each of the connections:
1539: #
1.46 albertel 1540: if ($DebugLevel > 2) {
1541: print $fh "Active connection statuses: \n";
1542: my $i = 1;
1543: print STDERR "================================= Socket Status Dump:\n";
1544: foreach my $item (keys %ActiveConnections) {
1545: my $Socket = $ActiveConnections{$item}->data;
1546: my $state = $Socket->GetState();
1547: print $fh "Connection $i State: $state\n";
1548: print STDERR "---------------------- Connection $i \n";
1.48 foxr 1549: $Socket->Dump(-1); # Ensure it gets dumped..
1.46 albertel 1550: $i++;
1551: }
1.38 foxr 1552: }
1.22 foxr 1553: $ConnectionRetriesLeft = $ConnectionRetries;
1.14 foxr 1554: }
1555:
1.1 foxr 1556: =pod
1.3 albertel 1557:
1.10 foxr 1558: =head2 SignalledToDeath
1559:
1560: Called in response to a signal that causes a chid process to die.
1561:
1562: =cut
1563:
1564:
1565: sub SignalledToDeath {
1.14 foxr 1566: my $event = shift;
1567: my $watcher= $event->w;
1568:
1569: Debug(2,"Signalled to death! via ".$watcher->data);
1.17 foxr 1570: my ($signal) = $watcher->data;
1.10 foxr 1571: chomp($signal);
1572: Log("CRITICAL", "Abnormal exit. Child $$ for $RemoteHost "
1573: ."died through "."\"$signal\"");
1574: LogPerm("F:lonc: $$ on $RemoteHost signalled to death: "
1575: ."\"$signal\"");
1.12 foxr 1576: exit 0;
1.10 foxr 1577:
1578: }
1.16 foxr 1579:
1580: =head2 ToggleDebug
1581:
1582: This sub toggles trace debugging on and off.
1583:
1584: =cut
1585:
1586: sub ToggleDebug {
1587: my $Current = $DebugLevel;
1588: $DebugLevel = $NextDebugLevel;
1589: $NextDebugLevel = $Current;
1590:
1591: Log("SUCCESS", "New debugging level for $RemoteHost now $DebugLevel");
1592:
1593: }
1594:
1.1 foxr 1595: =head2 ChildProcess
1596:
1597: This sub implements a child process for a single lonc daemon.
1.61 foxr 1598: Optional parameter:
1599: $socket - if provided, this is a socket already open for listen
1600: on the client socket. Otherwise, a new listen is set up.
1.1 foxr 1601:
1602: =cut
1603:
1604: sub ChildProcess {
1.62 ! foxr 1605: # If we are in DieWhenIdle mode, we've inherited all the
! 1606: # events of our parent and those have to be cancelled or else
! 1607: # all holy bloody chaos will result.. trust me, I already made
! 1608: # >that< mistake.
! 1609:
! 1610: my $host = GetServerHost();
! 1611: foreach my $listener (keys %parent_dispatchers) {
! 1612: my $watcher = $parent_dispatchers{$listener};
! 1613: my $s = $watcher->fd;
! 1614: if ($listener ne $host) { # Close everyone but me.
! 1615: Debug(5, "Closing listen socket for $listener");
! 1616: $s->close();
! 1617: }
! 1618: Debug(5, "Killing watcher for $listener");
! 1619:
! 1620: $watcher->cancel();
! 1621: undef $parent_dispatchers{$listener};
! 1622:
! 1623: }
! 1624: $I_am_child = 1; # Seems like in spite of it all I'm still getting
! 1625: # parent event dispatches.
1.1 foxr 1626:
1627:
1.14 foxr 1628: #
1629: # Signals must be handled by the Event framework...
1.61 foxr 1630: #
1.14 foxr 1631:
1632: Event->signal(signal => "QUIT",
1633: cb => \&SignalledToDeath,
1634: data => "QUIT");
1635: Event->signal(signal => "HUP",
1636: cb => \&ChildStatus,
1637: data => "HUP");
1638: Event->signal(signal => "USR1",
1639: cb => \&ChildStatus,
1640: data => "USR1");
1.39 foxr 1641: Event->signal(signal => "USR2",
1642: cb => \&ToggleTransactionLogging);
1.16 foxr 1643: Event->signal(signal => "INT",
1644: cb => \&ToggleDebug,
1645: data => "INT");
1.1 foxr 1646:
1.62 ! foxr 1647: # Figure out if we got passed a socket or need to open one to listen for
! 1648: # client requests.
! 1649:
1.61 foxr 1650: my ($socket) = @_;
1651: if (!$socket) {
1652:
1653: $socket = SetupLoncListener();
1654: }
1.62 ! foxr 1655: # Establish an event to listen for client connection requests.
! 1656:
! 1657:
1.59 foxr 1658: Event->io(cb => \&NewClient,
1659: poll => 'r',
1660: desc => 'Lonc Listener Unix Socket',
1661: fd => $socket);
1.1 foxr 1662:
1663: $Event::Debuglevel = $DebugLevel;
1664:
1665: Debug(9, "Making initial lond connection for ".$RemoteHost);
1666:
1667: # Setup the initial server connection:
1668:
1.62 ! foxr 1669: # &MakeLondConnection(); // let first work request do it.
1.10 foxr 1670:
1.62 ! foxr 1671: # If We are in diwhenidle, need to accept the connection since the
! 1672: # event may not fire.
! 1673:
! 1674: if ($DieWhenIdle) {
! 1675: &accept_client($socket);
! 1676: }
1.5 foxr 1677:
1.1 foxr 1678: Debug(9,"Entering event loop");
1679: my $ret = Event::loop(); # Start the main event loop.
1680:
1681:
1682: die "Main event loop exited!!!";
1683: }
1684:
1685: # Create a new child for host passed in:
1686:
1687: sub CreateChild {
1.62 ! foxr 1688: my ($host, $socket) = @_;
1.52 foxr 1689:
1.12 foxr 1690: my $sigset = POSIX::SigSet->new(SIGINT);
1691: sigprocmask(SIG_BLOCK, $sigset);
1.1 foxr 1692: $RemoteHost = $host;
1.9 foxr 1693: Log("CRITICAL", "Forking server for ".$host);
1.23 foxr 1694: my $pid = fork;
1.1 foxr 1695: if($pid) { # Parent
1.17 foxr 1696: $RemoteHost = "Parent";
1.27 foxr 1697: $ChildHash{$pid} = $host;
1.26 foxr 1698: $HostToPid{$host}= $pid;
1.12 foxr 1699: sigprocmask(SIG_UNBLOCK, $sigset);
1700:
1.1 foxr 1701: } else { # child.
1.5 foxr 1702: ShowStatus("Connected to ".$RemoteHost);
1.23 foxr 1703: $SIG{INT} = 'DEFAULT';
1.12 foxr 1704: sigprocmask(SIG_UNBLOCK, $sigset);
1.62 ! foxr 1705: if(defined $socket) {
! 1706: &ChildProcess($socket);
! 1707: } else {
! 1708: ChildProcess; # Does not return.
! 1709: }
1.1 foxr 1710: }
1.61 foxr 1711: }
1.1 foxr 1712:
1.61 foxr 1713: # parent_client_connection:
1714: # Event handler that processes client connections for the parent process.
1715: # This sub is called when the parent is listening on a socket and
1716: # a connection request arrives. We must:
1717: # Start a child process to accept the connection request.
1718: # Kill our listen on the socket.
1719: # Setup an event to handle the child process exit. (SIGCHLD).
1720: # Parameter:
1721: # event - The event object that was created to monitor this socket.
1722: # event->w->fd is the socket.
1723: # Returns:
1724: # NONE
1725: #
1726: sub parent_client_connection {
1.62 ! foxr 1727: if ($I_am_child) {
! 1728: # Should not get here, but seem to anyway:
! 1729: &Debug(5," Child caught parent client connection event!!");
! 1730: my ($event) = @_;
! 1731: my $watcher = $event->w;
! 1732: $watcher->cancel(); # Try to kill it off again!!
! 1733: } else {
! 1734: &Debug(9, "parent_client_connection");
! 1735: my ($event) = @_;
! 1736: my $watcher = $event->w;
! 1737: my $socket = $watcher->fd;
! 1738:
! 1739: # Lookup the host associated with this socket:
! 1740:
! 1741: my $host = $listening_to{$socket};
! 1742:
! 1743: # Start the child:
! 1744:
! 1745:
! 1746:
! 1747: &Debug(9,"Creating child for $host (parent_client_connection)");
! 1748: &CreateChild($host, $socket);
! 1749:
! 1750: # Clean up the listen since now the child takes over until it exits.
! 1751:
! 1752: $watcher->cancel(); # Nolonger listening to this event
! 1753: delete($listening_to{$socket});
! 1754: delete($parent_dispatchers{$host});
! 1755: $socket->close();
! 1756: }
1.61 foxr 1757: }
1758:
1759: # parent_listen:
1760: # Opens a socket and starts a listen for the parent process on a client UNIX
1761: # domain socket.
1762: #
1763: # This involves:
1764: # Creating a socket for listen.
1765: # Removing any socket lock file
1766: # Adding an event handler for this socket becoming readable
1767: # To the parent's event dispatcher.
1768: # Parameters:
1769: # loncapa_host - LonCAPA cluster name of the host represented by the client
1770: # socket.
1771: # Returns:
1772: # NONE
1773: #
1774: sub parent_listen {
1775: my ($loncapa_host) = @_;
1776: Debug(5, "parent_listen: $loncapa_host");
1777:
1778: my $socket = &SetupLoncListener($loncapa_host);
1.62 ! foxr 1779: $listening_to{$socket} = $loncapa_host;
1.61 foxr 1780: if (!$socket) {
1781: die "Unable to create a listen socket for $loncapa_host";
1782: }
1783:
1.62 ! foxr 1784: my $lock_file = &GetLoncSocketPath($loncapa_host).".lock";
1.61 foxr 1785: unlink($lock_file); # No problem if it doesn't exist yet [startup e.g.]
1786:
1.62 ! foxr 1787: my $watcher = Event->io(cb => \&parent_client_connection,
1.61 foxr 1788: poll => 'r',
1.62 ! foxr 1789: desc => "Parent listener unix socket ($loncapa_host)",
1.61 foxr 1790: fd => $socket);
1.62 ! foxr 1791: $parent_dispatchers{$loncapa_host} = $watcher;
1.61 foxr 1792:
1793: }
1794:
1795:
1796: # listen_on_all_unix_sockets:
1797: # This sub initiates a listen on all unix domain lonc client sockets.
1798: # This will be called in the case where we are trimming idle processes.
1799: # When idle processes are trimmed, loncnew starts up with no children,
1800: # and only spawns off children when a connection request occurs on the
1801: # client unix socket. The spawned child continues to run until it has
1802: # been idle a while at which point it eventually exits and once more
1803: # the parent picks up the listen.
1804: #
1805: # Parameters:
1806: # NONE
1807: # Implicit Inputs:
1808: # The configuration file that has been read in by LondConnection.
1809: # Returns:
1810: # NONE
1811: #
1812: sub listen_on_all_unix_sockets {
1813: Debug(5, "listen_on_all_unix_sockets");
1814: my $host_iterator = &LondConnection::GetHostIterator();
1815: while (!$host_iterator->end()) {
1816: my $host_entry_ref = $host_iterator->get();
1817: my $host_name = $host_entry_ref->[0];
1818: Debug(9, "Listen for $host_name");
1819: &parent_listen($host_name);
1820: $host_iterator->next();
1821: }
1.1 foxr 1822: }
1.61 foxr 1823:
1.1 foxr 1824: #
1825: # Parent process logic pass 1:
1826: # For each entry in the hosts table, we will
1827: # fork off an instance of ChildProcess to service the transactions
1828: # to that host. Each pid will be entered in a global hash
1829: # with the value of the key, the host.
1830: # The parent will then enter a loop to wait for process exits.
1831: # Each exit gets logged and the child gets restarted.
1832: #
1833:
1.5 foxr 1834: #
1835: # Fork and start in new session so hang-up isn't going to
1836: # happen without intent.
1837: #
1838:
1839:
1.6 foxr 1840:
1841:
1.8 foxr 1842:
1.6 foxr 1843:
1844: ShowStatus("Forming new session");
1845: my $childpid = fork;
1846: if ($childpid != 0) {
1847: sleep 4; # Give child a chacne to break to
1848: exit 0; # a new sesion.
1849: }
1.8 foxr 1850: #
1851: # Write my pid into the pid file so I can be located
1852: #
1853:
1854: ShowStatus("Parent writing pid file:");
1.23 foxr 1855: my $execdir = $perlvar{'lonDaemons'};
1.8 foxr 1856: open (PIDSAVE, ">$execdir/logs/lonc.pid");
1857: print PIDSAVE "$$\n";
1858: close(PIDSAVE);
1.6 foxr 1859:
1.17 foxr 1860:
1861:
1.6 foxr 1862: if (POSIX::setsid() < 0) {
1863: print "Could not create new session\n";
1864: exit -1;
1865: }
1.5 foxr 1866:
1867: ShowStatus("Forking node servers");
1868:
1.9 foxr 1869: Log("CRITICAL", "--------------- Starting children ---------------");
1870:
1.31 foxr 1871: LondConnection::ReadConfig; # Read standard config files.
1.1 foxr 1872: my $HostIterator = LondConnection::GetHostIterator;
1873:
1.60 foxr 1874: if ($DieWhenIdle) {
1.61 foxr 1875: $RemoteHost = "[parent]";
1876: &listen_on_all_unix_sockets();
1.60 foxr 1877: } else {
1878:
1879: while (! $HostIterator->end()) {
1880:
1881: my $hostentryref = $HostIterator->get();
1882: CreateChild($hostentryref->[0]);
1883: $HostHash{$hostentryref->[0]} = $hostentryref->[4];
1884: $HostIterator->next();
1885: }
1.1 foxr 1886: }
1.60 foxr 1887:
1.12 foxr 1888: $RemoteHost = "Parent Server";
1.1 foxr 1889:
1890: # Maintain the population:
1.5 foxr 1891:
1892: ShowStatus("Parent keeping the flock");
1.1 foxr 1893:
1.12 foxr 1894:
1.60 foxr 1895: if ($DieWhenIdle) {
1.61 foxr 1896: $Event::DebugLevel = $DebugLevel;
1897: Debug(9, "Parent entering event loop");
1898: my $ret = Event::loop();
1899: die "Main Event loop exited: $ret";
1900:
1901:
1.60 foxr 1902: } else {
1.61 foxr 1903: #
1904: # Set up parent signals:
1905: #
1.60 foxr 1906:
1907: $SIG{INT} = \&Terminate;
1908: $SIG{TERM} = \&Terminate;
1909: $SIG{HUP} = \&Restart;
1910: $SIG{USR1} = \&CheckKids;
1911: $SIG{USR2} = \&UpdateKids; # LonManage update request.
1912:
1913: while(1) {
1914: my $deadchild = wait();
1915: if(exists $ChildHash{$deadchild}) { # need to restart.
1916: my $deadhost = $ChildHash{$deadchild};
1917: delete($HostToPid{$deadhost});
1918: delete($ChildHash{$deadchild});
1919: Log("WARNING","Lost child pid= ".$deadchild.
1920: "Connected to host ".$deadhost);
1921: Log("INFO", "Restarting child procesing ".$deadhost);
1922: CreateChild($deadhost);
1923: }
1.1 foxr 1924: }
1.13 foxr 1925: }
1926:
1.14 foxr 1927:
1928: =pod
1929:
1930: =head1 CheckKids
1931:
1932: Since kids do not die as easily in this implementation
1933: as the previous one, there is no need to restart the
1934: dead ones (all dead kids get restarted when they die!!)
1935: The only thing this function does is to pass USR1 to the
1936: kids so that they report their status.
1937:
1938: =cut
1939:
1940: sub CheckKids {
1941: Debug(2, "Checking status of children");
1942: my $docdir = $perlvar{'lonDocRoot'};
1943: my $fh = IO::File->new(">$docdir/lon-status/loncstatus.txt");
1944: my $now=time;
1945: my $local=localtime($now);
1946: print $fh "LONC status $local - parent $$ \n\n";
1.23 foxr 1947: foreach my $pid (keys %ChildHash) {
1.14 foxr 1948: Debug(2, "Sending USR1 -> $pid");
1949: kill 'USR1' => $pid; # Tell Child to report status.
1950: sleep 1; # Wait so file doesn't intermix.
1951: }
1952: }
1.24 foxr 1953:
1954: =pod
1955:
1956: =head1 UpdateKids
1957:
1.25 foxr 1958: parent's SIGUSR2 handler. This handler:
1.24 foxr 1959:
1960: =item
1961:
1962: Rereads the hosts file.
1963:
1964: =item
1965:
1966: Kills off (via sigint) children for hosts that have disappeared.
1967:
1968: =item
1969:
1.27 foxr 1970: QUITs children for hosts that already exist (this just forces a status display
1.24 foxr 1971: and resets the connection retry count for that host.
1972:
1973: =item
1974:
1975: Starts new children for hosts that have been added to the hosts.tab file since
1976: the start of the master program and maintains them.
1977:
1978: =cut
1979:
1980: sub UpdateKids {
1.27 foxr 1981:
1.25 foxr 1982: Log("INFO", "Updating connections via SIGUSR2");
1.27 foxr 1983:
1984: # Just in case we need to kill our own lonc, we wait a few seconds to
1985: # give it a chance to receive and relay lond's response to the
1986: # re-init command.
1987: #
1988:
1989: sleep(2); # Wait a couple of seconds.
1990:
1991: my %hosts; # Indexed by loncapa hostname, value=ip.
1992:
1993: # Need to re-read the host table:
1994:
1995:
1996: LondConnection::ReadConfig();
1997: my $I = LondConnection::GetHostIterator;
1998: while (! $I->end()) {
1999: my $item = $I->get();
2000: $hosts{$item->[0]} = $item->[4];
2001: $I->next();
2002: }
2003:
2004: # The logic below is written for clarity not for efficiency.
2005: # Since I anticipate that this function is only rarely called, that's
2006: # appropriate. There are certainly ways to combine the loops below,
2007: # and anyone wishing to obscure the logic is welcome to go for it.
2008: # Note that we don't re-direct sigchild. Instead we do what's needed
2009: # to the data structures that keep track of children to ensure that
2010: # when sigchild is honored, no new child is born.
2011: #
2012:
2013: # For each existing child; if it's host doesn't exist, kill the child.
2014:
2015: foreach my $child (keys %ChildHash) {
2016: my $oldhost = $ChildHash{$child};
2017: if (!(exists $hosts{$oldhost})) {
2018: Log("CRITICAL", "Killing child for $oldhost host no longer exists");
2019: delete $ChildHash{$child};
2020: delete $HostToPid{$oldhost};
2021: kill 'QUIT' => $child;
2022: }
2023: }
2024: # For each remaining existing child; if it's host's ip has changed,
2025: # Restart the child on the new IP.
2026:
2027: foreach my $child (keys %ChildHash) {
2028: my $oldhost = $ChildHash{$child};
2029: my $oldip = $HostHash{$oldhost};
2030: if ($hosts{$oldhost} ne $oldip) {
2031:
2032: # kill the old child.
2033:
2034: Log("CRITICAL", "Killing child for $oldhost host ip has changed...");
2035: delete $ChildHash{$child};
2036: delete $HostToPid{$oldhost};
2037: kill 'QUIT' => $child;
2038:
2039: # Do the book-keeping needed to start a new child on the
2040: # new ip.
2041:
2042: $HostHash{$oldhost} = $hosts{$oldhost};
2043: CreateChild($oldhost);
2044: }
2045: }
2046: # Finally, for each new host, not in the host hash, create a
2047: # enter the host and create a new child.
2048: # Force a status display of any existing process.
2049:
2050: foreach my $host (keys %hosts) {
2051: if(!(exists $HostHash{$host})) {
2052: Log("INFO", "New host $host discovered in hosts.tab...");
2053: $HostHash{$host} = $hosts{$host};
2054: CreateChild($host);
2055: } else {
2056: kill 'HUP' => $HostToPid{$host}; # status display.
2057: }
2058: }
1.24 foxr 2059: }
2060:
1.14 foxr 2061:
1.13 foxr 2062: =pod
2063:
2064: =head1 Restart
2065:
2066: Signal handler for HUP... all children are killed and
2067: we self restart. This is an el-cheapo way to re read
2068: the config file.
2069:
2070: =cut
2071:
2072: sub Restart {
1.23 foxr 2073: &KillThemAll; # First kill all the children.
1.13 foxr 2074: Log("CRITICAL", "Restarting");
2075: my $execdir = $perlvar{'lonDaemons'};
2076: unlink("$execdir/logs/lonc.pid");
1.28 albertel 2077: exec("$execdir/loncnew");
1.10 foxr 2078: }
1.12 foxr 2079:
2080: =pod
2081:
2082: =head1 KillThemAll
2083:
2084: Signal handler that kills all children by sending them a
1.17 foxr 2085: SIGHUP. Responds to sigint and sigterm.
1.12 foxr 2086:
2087: =cut
2088:
1.10 foxr 2089: sub KillThemAll {
1.12 foxr 2090: Debug(2, "Kill them all!!");
2091: local($SIG{CHLD}) = 'IGNORE'; # Our children >will< die.
1.23 foxr 2092: foreach my $pid (keys %ChildHash) {
1.12 foxr 2093: my $serving = $ChildHash{$pid};
1.52 foxr 2094: ShowStatus("Nicely Killing lonc for $serving pid = $pid");
2095: Log("CRITICAL", "Nicely Killing lonc for $serving pid = $pid");
1.17 foxr 2096: kill 'QUIT' => $pid;
1.12 foxr 2097: }
1.52 foxr 2098:
1.17 foxr 2099:
1.1 foxr 2100: }
1.12 foxr 2101:
1.52 foxr 2102:
2103: #
2104: # Kill all children via KILL. Just in case the
2105: # first shot didn't get them.
2106:
2107: sub really_kill_them_all_dammit
2108: {
2109: Debug(2, "Kill them all Dammit");
2110: local($SIG{CHLD} = 'IGNORE'); # In case some purist reenabled them.
2111: foreach my $pid (keys %ChildHash) {
2112: my $serving = $ChildHash{$pid};
2113: &ShowStatus("Nastily killing lonc for $serving pid = $pid");
2114: Log("CRITICAL", "Nastily killing lonc for $serving pid = $pid");
2115: kill 'KILL' => $pid;
2116: delete($ChildHash{$pid});
2117: my $execdir = $perlvar{'lonDaemons'};
2118: unlink("$execdir/logs/lonc.pid");
2119: }
2120: }
1.14 foxr 2121: =pod
2122:
2123: =head1 Terminate
2124:
2125: Terminate the system.
2126:
2127: =cut
2128:
2129: sub Terminate {
1.52 foxr 2130: &Log("CRITICAL", "Asked to kill children.. first be nice...");
2131: &KillThemAll;
2132: #
2133: # By now they really should all be dead.. but just in case
2134: # send them all SIGKILL's after a bit of waiting:
2135:
2136: sleep(4);
2137: &Log("CRITICAL", "Now kill children nasty");
2138: &really_kill_them_all_dammit;
1.17 foxr 2139: Log("CRITICAL","Master process exiting");
2140: exit 0;
1.14 foxr 2141:
2142: }
1.12 foxr 2143: =pod
1.1 foxr 2144:
2145: =head1 Theory
1.3 albertel 2146:
2147: The event class is used to build this as a single process with an
2148: event driven model. The following events are handled:
1.1 foxr 2149:
2150: =item UNIX Socket connection Received
2151:
2152: =item Request data arrives on UNIX data transfer socket.
2153:
2154: =item lond connection becomes writable.
2155:
2156: =item timer fires at 1 second intervals.
2157:
2158: All sockets are run in non-blocking mode. Timeouts managed by the timer
2159: handler prevents hung connections.
2160:
2161: Key data structures:
2162:
1.3 albertel 2163: =item RequestQueue
2164:
2165: A queue of requests received from UNIX sockets that are
2166: waiting for a chance to be forwarded on a lond connection socket.
2167:
2168: =item ActiveConnections
2169:
2170: A hash of lond connections that have transactions in process that are
2171: available to be timed out.
2172:
2173: =item ActiveTransactions
2174:
2175: A hash indexed by lond connections that contain the client reply
2176: socket for each connection that has an active transaction on it.
2177:
2178: =item IdleConnections
2179:
2180: A hash of lond connections that have no work to do. These connections
2181: can be closed if they are idle for a long enough time.
1.1 foxr 2182:
2183: =cut
FreeBSD-CVSweb <freebsd-cvsweb@FreeBSD.org>