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