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