Annotation of loncom/loncnew, revision 1.81
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.81 ! albertel 5: # $Id: loncnew,v 1.80 2007/03/28 00:23:46 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;
1.67 albertel 63: use Fcntl qw(:flock);
1.1 foxr 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.62 foxr 76: my %listening_to; # Socket->host table for who the parent
77: # is listening to.
78: my %parent_dispatchers; # host-> listener watcher events.
1.1 foxr 79:
1.65 foxr 80: my %parent_handlers; # Parent signal handlers...
81:
1.9 foxr 82: my $MaxConnectionCount = 10; # Will get from config later.
1.1 foxr 83: my $ClientConnection = 0; # Uniquifier for client events.
84:
1.9 foxr 85: my $DebugLevel = 0;
1.29 foxr 86: my $NextDebugLevel= 2; # So Sigint can toggle this.
1.50 albertel 87: my $IdleTimeout= 600; # Wait 10 minutes before pruning connections.
1.1 foxr 88:
1.39 foxr 89: my $LogTransactions = 0; # When True, all transactions/replies get logged.
1.65 foxr 90: my $executable = $0; # Get the full path to me.
1.39 foxr 91:
1.1 foxr 92: #
93: # The variables below are only used by the child processes.
94: #
95: my $RemoteHost; # Name of host child is talking to.
1.81 ! albertel 96: my $RemoteHostId; # default lonid 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.62 foxr 115: my $I_am_child = 0; # True if this is the child process.
1.57 foxr 116:
1.1 foxr 117: #
1.9 foxr 118: # The hash below gives the HTML format for log messages
119: # given a severity.
120: #
121: my %LogFormats;
122:
1.45 albertel 123: $LogFormats{"CRITICAL"} = "<font color='red'>CRITICAL: %s</font>";
124: $LogFormats{"SUCCESS"} = "<font color='green'>SUCCESS: %s</font>";
125: $LogFormats{"INFO"} = "<font color='yellow'>INFO: %s</font>";
126: $LogFormats{"WARNING"} = "<font color='blue'>WARNING: %s</font>";
1.9 foxr 127: $LogFormats{"DEFAULT"} = " %s ";
128:
1.10 foxr 129:
1.57 foxr 130: # UpdateStatus;
131: # Update the idle status display to show how many connections
132: # are left, retries and other stuff.
133: #
134: sub UpdateStatus {
135: if ($ConnectionRetriesLeft > 0) {
136: ShowStatus(GetServerHost()." Connection count: ".$ConnectionCount
137: ." Retries remaining: ".$ConnectionRetriesLeft
138: ." ($KeyMode)");
139: } else {
140: ShowStatus(GetServerHost()." >> DEAD <<");
141: }
142: }
143:
1.10 foxr 144:
145: =pod
146:
147: =head2 LogPerm
148:
149: Makes an entry into the permanent log file.
150:
151: =cut
1.69 matthew 152:
1.10 foxr 153: sub LogPerm {
154: my $message=shift;
155: my $execdir=$perlvar{'lonDaemons'};
156: my $now=time;
157: my $local=localtime($now);
158: my $fh=IO::File->new(">>$execdir/logs/lonnet.perm.log");
159: print $fh "$now:$message:$local\n";
160: }
1.9 foxr 161:
162: =pod
163:
164: =head2 Log
165:
166: Logs a message to the log file.
167: Parameters:
168:
169: =item severity
170:
171: One of CRITICAL, WARNING, INFO, SUCCESS used to select the
172: format string used to format the message. if the severity is
173: not a defined severity the Default format string is used.
174:
175: =item message
176:
177: The base message. In addtion to the format string, the message
178: will be appended to a string containing the name of our remote
179: host and the time will be formatted into the message.
180:
181: =cut
182:
183: sub Log {
1.47 foxr 184:
185: my ($severity, $message) = @_;
186:
1.9 foxr 187: if(!$LogFormats{$severity}) {
188: $severity = "DEFAULT";
189: }
190:
191: my $format = $LogFormats{$severity};
192:
193: # Put the window dressing in in front of the message format:
194:
195: my $now = time;
196: my $local = localtime($now);
197: my $finalformat = "$local ($$) [$RemoteHost] [$Status] ";
1.76 albertel 198: $finalformat = $finalformat.$format."\n";
1.9 foxr 199:
200: # open the file and put the result.
201:
202: my $execdir = $perlvar{'lonDaemons'};
203: my $fh = IO::File->new(">>$execdir/logs/lonc.log");
204: my $msg = sprintf($finalformat, $message);
1.14 foxr 205: $RecentLogEntry = $msg;
1.9 foxr 206: print $fh $msg;
207:
1.10 foxr 208:
1.9 foxr 209: }
1.6 foxr 210:
1.3 albertel 211:
1.1 foxr 212: =pod
1.3 albertel 213:
214: =head2 GetPeerName
215:
216: Returns the name of the host that a socket object is connected to.
217:
1.1 foxr 218: =cut
219:
220: sub GetPeername {
1.47 foxr 221:
222:
223: my ($connection, $AdrFamily) = @_;
224:
1.1 foxr 225: my $peer = $connection->peername();
226: my $peerport;
227: my $peerip;
228: if($AdrFamily == AF_INET) {
229: ($peerport, $peerip) = sockaddr_in($peer);
1.23 foxr 230: my $peername = gethostbyaddr($peerip, $AdrFamily);
1.1 foxr 231: return $peername;
232: } elsif ($AdrFamily == AF_UNIX) {
233: my $peerfile;
234: ($peerfile) = sockaddr_un($peer);
235: return $peerfile;
236: }
237: }
238: =pod
1.3 albertel 239:
1.1 foxr 240: =head2 Debug
1.3 albertel 241:
242: Invoked to issue a debug message.
243:
1.1 foxr 244: =cut
1.3 albertel 245:
1.1 foxr 246: sub Debug {
1.47 foxr 247:
248: my ($level, $message) = @_;
249:
1.1 foxr 250: if ($level <= $DebugLevel) {
1.23 foxr 251: Log("INFO", "-Debug- $message host = $RemoteHost");
1.1 foxr 252: }
253: }
254:
255: sub SocketDump {
1.47 foxr 256:
257: my ($level, $socket) = @_;
258:
1.1 foxr 259: if($level <= $DebugLevel) {
1.48 foxr 260: $socket->Dump(-1); # Ensure it will get dumped.
1.1 foxr 261: }
262: }
1.3 albertel 263:
1.1 foxr 264: =pod
1.3 albertel 265:
1.5 foxr 266: =head2 ShowStatus
267:
268: Place some text as our pid status.
1.10 foxr 269: and as what we return in a SIGUSR1
1.5 foxr 270:
271: =cut
1.69 matthew 272:
1.5 foxr 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.69 matthew 283: =head2 SocketTimeout
1.15 foxr 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
1.69 matthew 290:
1.15 foxr 291: sub SocketTimeout {
292: my $Socket = shift;
1.38 foxr 293: Log("WARNING", "A socket timeout was detected");
1.52 foxr 294: Debug(5, " SocketTimeout called: ");
1.48 foxr 295: $Socket->Dump(0);
1.42 foxr 296: if(exists($ActiveTransactions{$Socket})) {
1.43 albertel 297: FailTransaction($ActiveTransactions{$Socket});
1.42 foxr 298: }
1.22 foxr 299: KillSocket($Socket); # A transaction timeout also counts as
300: # a connection failure:
301: $ConnectionRetriesLeft--;
1.42 foxr 302: if($ConnectionRetriesLeft <= 0) {
1.52 foxr 303: Log("CRITICAL", "Host marked DEAD: ".GetServerHost());
1.56 foxr 304: $LondConnecting = 0;
1.42 foxr 305: }
306:
1.15 foxr 307: }
1.80 albertel 308:
1.64 foxr 309: #
310: # This function should be called by the child in all cases where it must
1.80 albertel 311: # exit. The child process must create a lock file for the AF_UNIX socket
312: # in order to prevent connection requests from lonnet in the time between
313: # process exit and the parent picking up the listen again.
314: #
1.64 foxr 315: # Parameters:
316: # exit_code - Exit status value, however see the next parameter.
317: # message - If this optional parameter is supplied, the exit
318: # is via a die with this message.
319: #
320: sub child_exit {
321: my ($exit_code, $message) = @_;
322:
323: # Regardless of how we exit, we may need to do the lock thing:
324:
1.80 albertel 325: #
326: # Create a lock file since there will be a time window
327: # between our exit and the parent's picking up the listen
328: # during which no listens will be done on the
329: # lonnet client socket.
330: #
331: my $lock_file = &GetLoncSocketPath().".lock";
332: open(LOCK,">$lock_file");
333: print LOCK "Contents not important";
334: close(LOCK);
1.81 ! albertel 335: unlink(&GetLoncSocketPath());
1.64 foxr 336:
1.80 albertel 337: if ($message) {
338: die($message);
1.64 foxr 339: } else {
340: exit($exit_code);
341: }
342: }
1.35 foxr 343: #----------------------------- Timer management ------------------------
1.15 foxr 344:
345: =pod
346:
1.1 foxr 347: =head2 Tick
1.3 albertel 348:
349: Invoked each timer tick.
350:
1.1 foxr 351: =cut
352:
1.5 foxr 353:
1.1 foxr 354: sub Tick {
1.52 foxr 355: my ($Event) = @_;
356: my $clock_watcher = $Event->w;
357:
1.1 foxr 358: my $client;
1.57 foxr 359: UpdateStatus();
360:
1.4 foxr 361: # Is it time to prune connection count:
362:
363:
364: if($IdleConnections->Count() &&
365: ($WorkQueue->Count() == 0)) { # Idle connections and nothing to do?
1.52 foxr 366: $IdleSeconds++;
1.4 foxr 367: if($IdleSeconds > $IdleTimeout) { # Prune a connection...
1.23 foxr 368: my $Socket = $IdleConnections->pop();
1.6 foxr 369: KillSocket($Socket);
1.54 foxr 370: $IdleSeconds = 0; # Otherwise all connections get trimmed to fast.
1.57 foxr 371: UpdateStatus();
1.80 albertel 372: if(($ConnectionCount == 0)) {
1.64 foxr 373: &child_exit(0);
374:
1.57 foxr 375: }
1.4 foxr 376: }
377: } else {
378: $IdleSeconds = 0; # Reset idle count if not idle.
379: }
1.15 foxr 380: #
381: # For each inflight transaction, tick down its timeout counter.
382: #
1.35 foxr 383:
1.34 albertel 384: foreach my $item (keys %ActiveConnections) {
385: my $State = $ActiveConnections{$item}->data->GetState();
1.35 foxr 386: if ($State ne 'Idle') {
1.34 albertel 387: Debug(5,"Ticking Socket $State $item");
388: $ActiveConnections{$item}->data->Tick();
389: }
1.15 foxr 390: }
1.5 foxr 391: # Do we have work in the queue, but no connections to service them?
392: # If so, try to make some new connections to get things going again.
393: #
1.57 foxr 394: # Note this code is dead now...
395: #
1.5 foxr 396: my $Requests = $WorkQueue->Count();
1.56 foxr 397: if (($ConnectionCount == 0) && ($Requests > 0) && (!$LondConnecting)) {
1.10 foxr 398: if ($ConnectionRetriesLeft > 0) {
1.56 foxr 399: Debug(5,"Work but no connections, Make a new one");
400: my $success;
401: $success = &MakeLondConnection;
402: if($success == 0) { # All connections failed:
1.29 foxr 403: Debug(5,"Work in queue failed to make any connectiouns\n");
1.22 foxr 404: EmptyQueue(); # Fail pending transactions with con_lost.
1.42 foxr 405: CloseAllLondConnections(); # Should all be closed but....
1.10 foxr 406: }
407: } else {
1.56 foxr 408: $LondConnecting = 0;
1.22 foxr 409: ShowStatus(GetServerHost()." >>> DEAD!!! <<<");
1.29 foxr 410: Debug(5,"Work in queue, but gave up on connections..flushing\n");
1.10 foxr 411: EmptyQueue(); # Connections can't be established.
1.42 foxr 412: CloseAllLondConnections(); # Should all already be closed but...
1.5 foxr 413: }
414:
415: }
1.49 foxr 416: if ($ConnectionCount == 0) {
417: $KeyMode = "";
1.52 foxr 418: $clock_watcher->cancel();
1.49 foxr 419: }
1.66 albertel 420: &UpdateStatus();
1.1 foxr 421: }
422:
423: =pod
1.3 albertel 424:
1.1 foxr 425: =head2 SetupTimer
426:
1.3 albertel 427: Sets up a 1 per sec recurring timer event. The event handler is used to:
1.1 foxr 428:
1.3 albertel 429: =item
430:
431: Trigger timeouts on communications along active sockets.
432:
433: =item
434:
435: Trigger disconnections of idle sockets.
1.1 foxr 436:
437: =cut
438:
439: sub SetupTimer {
1.52 foxr 440: Debug(6, "SetupTimer");
441: Event->timer(interval => 1, cb => \&Tick );
1.1 foxr 442: }
1.3 albertel 443:
1.1 foxr 444: =pod
1.3 albertel 445:
1.1 foxr 446: =head2 ServerToIdle
1.3 albertel 447:
448: This function is called when a connection to the server is
449: ready for more work.
450:
451: If there is work in the Work queue the top element is dequeued
1.1 foxr 452: and the connection will start to work on it. If the work queue is
453: empty, the connection is pushed on the idle connection stack where
454: it will either get another work unit, or alternatively, if it sits there
455: long enough, it will be shut down and released.
456:
1.3 albertel 457: =cut
1.1 foxr 458:
459: sub ServerToIdle {
460: my $Socket = shift; # Get the socket.
1.49 foxr 461: $KeyMode = $Socket->{AuthenticationMode};
1.7 foxr 462: delete($ActiveTransactions{$Socket}); # Server has no transaction
1.1 foxr 463:
1.29 foxr 464: &Debug(5, "Server to idle");
1.1 foxr 465:
466: # If there's work to do, start the transaction:
467:
1.23 foxr 468: my $reqdata = $WorkQueue->dequeue(); # This is a LondTransaction
1.29 foxr 469: if ($reqdata ne undef) {
470: Debug(5, "Queue gave request data: ".$reqdata->getRequest());
1.7 foxr 471: &StartRequest($Socket, $reqdata);
1.8 foxr 472:
1.1 foxr 473: } else {
474:
475: # There's no work waiting, so push the server to idle list.
1.29 foxr 476: &Debug(5, "No new work requests, server connection going idle");
1.1 foxr 477: $IdleConnections->push($Socket);
478: }
479: }
1.3 albertel 480:
1.1 foxr 481: =pod
1.3 albertel 482:
1.1 foxr 483: =head2 ClientWritable
1.3 albertel 484:
485: Event callback for when a client socket is writable.
486:
487: This callback is established when a transaction reponse is
488: avaiable from lond. The response is forwarded to the unix socket
489: as it becomes writable in this sub.
490:
1.1 foxr 491: Parameters:
492:
1.3 albertel 493: =item Event
494:
495: The event that has been triggered. Event->w->data is
496: the data and Event->w->fd is the socket to write.
1.1 foxr 497:
498: =cut
1.3 albertel 499:
1.1 foxr 500: sub ClientWritable {
501: my $Event = shift;
502: my $Watcher = $Event->w;
503: my $Data = $Watcher->data;
504: my $Socket = $Watcher->fd;
505:
506: # Try to send the data:
507:
508: &Debug(6, "ClientWritable writing".$Data);
509: &Debug(9, "Socket is: ".$Socket);
510:
1.6 foxr 511: if($Socket->connected) {
512: my $result = $Socket->send($Data, 0);
513:
514: # $result undefined: the write failed.
515: # otherwise $result is the number of bytes written.
516: # Remove that preceding string from the data.
517: # If the resulting data is empty, destroy the watcher
518: # and set up a read event handler to accept the next
519: # request.
520:
521: &Debug(9,"Send result is ".$result." Defined: ".defined($result));
1.29 foxr 522: if($result ne undef) {
1.6 foxr 523: &Debug(9, "send result was defined");
524: if($result == length($Data)) { # Entire string sent.
525: &Debug(9, "ClientWritable data all written");
526: $Watcher->cancel();
527: #
528: # Set up to read next request from socket:
529:
530: my $descr = sprintf("Connection to lonc client %d",
531: $ActiveClients{$Socket});
532: Event->io(cb => \&ClientRequest,
533: poll => 'r',
534: desc => $descr,
535: data => "",
536: fd => $Socket);
537:
538: } else { # Partial string sent.
539: $Watcher->data(substr($Data, $result));
1.15 foxr 540: if($result == 0) { # client hung up on us!!
1.52 foxr 541: # Log("INFO", "lonc pipe client hung up on us!");
1.15 foxr 542: $Watcher->cancel;
543: $Socket->shutdown(2);
544: $Socket->close();
545: }
1.6 foxr 546: }
547:
548: } else { # Error of some sort...
549:
550: # Some errnos are possible:
551: my $errno = $!;
552: if($errno == POSIX::EWOULDBLOCK ||
553: $errno == POSIX::EAGAIN ||
554: $errno == POSIX::EINTR) {
555: # No action taken?
556: } else { # Unanticipated errno.
557: &Debug(5,"ClientWritable error or peer shutdown".$RemoteHost);
558: $Watcher->cancel; # Stop the watcher.
559: $Socket->shutdown(2); # Kill connection
560: $Socket->close(); # Close the socket.
561: }
1.1 foxr 562:
563: }
1.6 foxr 564: } else {
565: $Watcher->cancel(); # A delayed request...just cancel.
1.1 foxr 566: }
567: }
568:
569: =pod
1.3 albertel 570:
1.1 foxr 571: =head2 CompleteTransaction
1.3 albertel 572:
573: Called when the reply data has been received for a lond
1.1 foxr 574: transaction. The reply data must now be sent to the
575: ultimate client on the other end of the Unix socket. This is
576: done by setting up a writable event for the socket with the
577: data the reply data.
1.3 albertel 578:
1.1 foxr 579: Parameters:
1.3 albertel 580:
581: =item Socket
582:
583: Socket on which the lond transaction occured. This is a
584: LondConnection. The data received is in the TransactionReply member.
585:
1.7 foxr 586: =item Transaction
1.3 albertel 587:
1.7 foxr 588: The transaction that is being completed.
1.1 foxr 589:
590: =cut
1.3 albertel 591:
1.1 foxr 592: sub CompleteTransaction {
1.29 foxr 593: &Debug(5,"Complete transaction");
1.47 foxr 594:
595: my ($Socket, $Transaction) = @_;
1.1 foxr 596:
1.7 foxr 597: if (!$Transaction->isDeferred()) { # Normal transaction
598: my $data = $Socket->GetReply(); # Data to send.
1.39 foxr 599: if($LogTransactions) {
600: Log("SUCCESS", "Reply from lond: '$data'");
601: }
1.7 foxr 602: StartClientReply($Transaction, $data);
603: } else { # Delete deferred transaction file.
1.9 foxr 604: Log("SUCCESS", "A delayed transaction was completed");
1.23 foxr 605: LogPerm("S:$Transaction->getClient() :".$Transaction->getRequest());
1.7 foxr 606: unlink $Transaction->getFile();
607: }
1.6 foxr 608: }
1.42 foxr 609:
1.6 foxr 610: =pod
1.42 foxr 611:
1.6 foxr 612: =head1 StartClientReply
613:
614: Initiates a reply to a client where the reply data is a parameter.
615:
1.7 foxr 616: =head2 parameters:
617:
618: =item Transaction
619:
620: The transaction for which we are responding to the client.
621:
622: =item data
623:
624: The data to send to apached client.
625:
1.6 foxr 626: =cut
1.42 foxr 627:
1.6 foxr 628: sub StartClientReply {
1.1 foxr 629:
1.47 foxr 630: my ($Transaction, $data) = @_;
1.12 foxr 631:
1.7 foxr 632: my $Client = $Transaction->getClient();
633:
1.1 foxr 634: &Debug(8," Reply was: ".$data);
635: my $Serial = $ActiveClients{$Client};
636: my $desc = sprintf("Connection to lonc client %d",
637: $Serial);
638: Event->io(fd => $Client,
639: poll => "w",
640: desc => $desc,
641: cb => \&ClientWritable,
642: data => $data);
643: }
1.42 foxr 644:
1.4 foxr 645: =pod
1.42 foxr 646:
1.4 foxr 647: =head2 FailTransaction
648:
649: Finishes a transaction with failure because the associated lond socket
1.7 foxr 650: disconnected. There are two possibilities:
651: - The transaction is deferred: in which case we just quietly
652: delete the transaction since there is no client connection.
653: - The transaction is 'live' in which case we initiate the sending
654: of "con_lost" to the client.
655:
1.42 foxr 656: Deleting the transaction means killing it from the %ActiveTransactions hash.
1.4 foxr 657:
658: Parameters:
659:
660: =item client
661:
1.7 foxr 662: The LondTransaction we are failing.
663:
1.42 foxr 664:
1.4 foxr 665: =cut
666:
667: sub FailTransaction {
1.7 foxr 668: my $transaction = shift;
1.52 foxr 669:
670: # If the socket is dead, that's already logged.
671:
672: if ($ConnectionRetriesLeft > 0) {
673: Log("WARNING", "Failing transaction "
1.71 albertel 674: .$transaction->getLoggableRequest());
1.52 foxr 675: }
1.71 albertel 676: Debug(1, "Failing transaction: ".$transaction->getLoggableRequest());
1.10 foxr 677: if (!$transaction->isDeferred()) { # If the transaction is deferred we'll get to it.
1.11 foxr 678: my $client = $transaction->getClient();
1.30 foxr 679: Debug(1," Replying con_lost to ".$transaction->getRequest());
1.11 foxr 680: StartClientReply($transaction, "con_lost\n");
1.7 foxr 681: }
1.4 foxr 682:
683: }
684:
685: =pod
1.69 matthew 686:
1.6 foxr 687: =head1 EmptyQueue
1.7 foxr 688:
1.6 foxr 689: Fails all items in the work queue with con_lost.
1.7 foxr 690: Note that each item in the work queue is a transaction.
691:
1.6 foxr 692: =cut
1.69 matthew 693:
1.6 foxr 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
1.69 matthew 709:
1.9 foxr 710: sub CloseAllLondConnections {
1.23 foxr 711: foreach my $Socket (keys %ActiveConnections) {
1.42 foxr 712: if(exists($ActiveTransactions{$Socket})) {
713: FailTransaction($ActiveTransactions{$Socket});
714: }
715: KillSocket($Socket);
1.9 foxr 716: }
717: }
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:
1.69 matthew 739: =cut
1.4 foxr 740:
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.73 albertel 952: Debug(6, "SendingRequest state encountered in readable");
1.41 albertel 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.81 ! albertel 1150:
1.6 foxr 1151: =pod
1152:
1153: =cut
1.69 matthew 1154:
1.81 ! albertel 1155:
1.6 foxr 1156: sub QueueDelayed {
1.8 foxr 1157: Debug(3,"QueueDelayed called");
1158:
1.6 foxr 1159: my $path = "$perlvar{'lonSockDir'}/delayed";
1.8 foxr 1160:
1161: Debug(4, "Delayed path: ".$path);
1.6 foxr 1162: opendir(DIRHANDLE, $path);
1.75 albertel 1163:
1.81 ! albertel 1164: use Apache::lonnet;
! 1165: my @all_host_ids = &Apache::lonnet::machine_ids($RemoteHost);
! 1166:
1.75 albertel 1167: my $host_id_re = '(?:'.join('|',@all_host_ids).')';
1168: my @alldelayed = grep(/\.$host_id_re$/, readdir(DIRHANDLE));
1.6 foxr 1169: closedir(DIRHANDLE);
1.75 albertel 1170: foreach my $dfname (sort(@alldelayed)) {
1171: my $reqfile = "$path/$dfname";
1172: my ($host_id) = ($dfname =~ /\.([^.]*)$/);
1173: Debug(4, "queueing ".$reqfile." for $host_id");
1.6 foxr 1174: my $Handle = IO::File->new($reqfile);
1175: my $cmd = <$Handle>;
1.8 foxr 1176: chomp $cmd; # There may or may not be a newline...
1.12 foxr 1177: $cmd = $cmd."\n"; # now for sure there's exactly one newline.
1.75 albertel 1178: my $Transaction = LondTransaction->new("sethost:$host_id:$cmd");
1.7 foxr 1179: $Transaction->SetDeferred($reqfile);
1180: QueueTransaction($Transaction);
1.6 foxr 1181: }
1182:
1183: }
1.1 foxr 1184:
1185: =pod
1.3 albertel 1186:
1.1 foxr 1187: =head2 MakeLondConnection
1.3 albertel 1188:
1189: Create a new lond connection object, and start it towards its initial
1190: idleness. Once idle, it becomes elligible to receive transactions
1191: from the work queue. If the work queue is not empty when the
1192: connection is completed and becomes idle, it will dequeue an entry and
1193: start off on it.
1194:
1.1 foxr 1195: =cut
1.3 albertel 1196:
1.1 foxr 1197: sub MakeLondConnection {
1198: Debug(4,"MakeLondConnection to ".GetServerHost()." on port "
1199: .GetServerPort());
1200:
1201: my $Connection = LondConnection->new(&GetServerHost(),
1.81 ! albertel 1202: &GetServerPort(),
! 1203: &GetHostId());
1.1 foxr 1204:
1.30 foxr 1205: if($Connection eq undef) { # Needs to be more robust later.
1.9 foxr 1206: Log("CRITICAL","Failed to make a connection with lond.");
1.10 foxr 1207: $ConnectionRetriesLeft--;
1208: return 0; # Failure.
1.5 foxr 1209: } else {
1.22 foxr 1210:
1.5 foxr 1211: # The connection needs to have writability
1212: # monitored in order to send the init sequence
1213: # that starts the whole authentication/key
1214: # exchange underway.
1215: #
1216: my $Socket = $Connection->GetSocket();
1.30 foxr 1217: if($Socket eq undef) {
1.64 foxr 1218: &child_exit(-1, "did not get a socket from the connection");
1.5 foxr 1219: } else {
1220: &Debug(9,"MakeLondConnection got socket: ".$Socket);
1221: }
1.1 foxr 1222:
1.21 foxr 1223: $Connection->SetTimeoutCallback(\&SocketTimeout);
1224:
1.23 foxr 1225: my $event = Event->io(fd => $Socket,
1.5 foxr 1226: poll => 'w',
1227: cb => \&LondWritable,
1.8 foxr 1228: data => $Connection,
1.5 foxr 1229: desc => 'Connection to lond server');
1230: $ActiveConnections{$Connection} = $event;
1.52 foxr 1231: if ($ConnectionCount == 0) {
1232: &SetupTimer; # Need to handle timeouts with connections...
1233: }
1.5 foxr 1234: $ConnectionCount++;
1.8 foxr 1235: Debug(4, "Connection count = ".$ConnectionCount);
1.6 foxr 1236: if($ConnectionCount == 1) { # First Connection:
1237: QueueDelayed;
1238: }
1.9 foxr 1239: Log("SUCESS", "Created connection ".$ConnectionCount
1240: ." to host ".GetServerHost());
1.54 foxr 1241: $LondConnecting = 1; # Connection in progress.
1.10 foxr 1242: return 1; # Return success.
1.1 foxr 1243: }
1244:
1245: }
1.3 albertel 1246:
1.1 foxr 1247: =pod
1.3 albertel 1248:
1.1 foxr 1249: =head2 StartRequest
1.3 albertel 1250:
1251: Starts a lond request going on a specified lond connection.
1252: parameters are:
1253:
1254: =item $Lond
1255:
1256: Connection to the lond that will send the transaction and receive the
1257: reply.
1258:
1259: =item $Client
1260:
1261: Connection to the client that is making this request We got the
1262: request from this socket, and when the request has been relayed to
1263: lond and we get a reply back from lond it will get sent to this
1264: socket.
1265:
1266: =item $Request
1267:
1268: The text of the request to send.
1269:
1.1 foxr 1270: =cut
1271:
1272: sub StartRequest {
1.47 foxr 1273:
1274: my ($Lond, $Request) = @_;
1.1 foxr 1275:
1.7 foxr 1276: Debug(6, "StartRequest: ".$Request->getRequest());
1.1 foxr 1277:
1278: my $Socket = $Lond->GetSocket();
1279:
1.7 foxr 1280: $Request->Activate($Lond);
1281: $ActiveTransactions{$Lond} = $Request;
1.1 foxr 1282:
1.7 foxr 1283: $Lond->InitiateTransaction($Request->getRequest());
1.23 foxr 1284: my $event = Event->io(fd => $Socket,
1.1 foxr 1285: poll => "w",
1286: cb => \&LondWritable,
1287: data => $Lond,
1288: desc => "lond transaction connection");
1289: $ActiveConnections{$Lond} = $event;
1290: Debug(8," Start Request made watcher data with ".$event->data."\n");
1291: }
1292:
1293: =pod
1.3 albertel 1294:
1.1 foxr 1295: =head2 QueueTransaction
1.3 albertel 1296:
1297: If there is an idle lond connection, it is put to work doing this
1298: transaction. Otherwise, the transaction is placed in the work queue.
1299: If placed in the work queue and the maximum number of connections has
1300: not yet been created, a new connection will be started. Our goal is
1301: to eventually have a sufficient number of connections that the work
1302: queue will typically be empty. parameters are:
1303:
1304: =item Socket
1305:
1306: open on the lonc client.
1307:
1308: =item Request
1309:
1310: data to send to the lond.
1.1 foxr 1311:
1312: =cut
1.3 albertel 1313:
1.1 foxr 1314: sub QueueTransaction {
1315:
1.7 foxr 1316: my $requestData = shift; # This is a LondTransaction.
1317: my $cmd = $requestData->getRequest();
1318:
1319: Debug(6,"QueueTransaction: ".$cmd);
1.1 foxr 1320:
1321: my $LondSocket = $IdleConnections->pop();
1322: if(!defined $LondSocket) { # Need to queue request.
1.29 foxr 1323: Debug(5,"Must queue...");
1.1 foxr 1324: $WorkQueue->enqueue($requestData);
1.56 foxr 1325: Debug(5, "Queue Transaction startnew $ConnectionCount $LondConnecting");
1326: if(($ConnectionCount < $MaxConnectionCount) && (! $LondConnecting)) {
1327:
1.22 foxr 1328: if($ConnectionRetriesLeft > 0) {
1.29 foxr 1329: Debug(5,"Starting additional lond connection");
1.56 foxr 1330: if(&MakeLondConnection() == 0) {
1.22 foxr 1331: EmptyQueue(); # Fail transactions, can't make connection.
1.42 foxr 1332: CloseAllLondConnections; # Should all be closed but...
1.22 foxr 1333: }
1334: } else {
1335: ShowStatus(GetServerHost()." >>> DEAD !!!! <<<");
1.56 foxr 1336: $LondConnecting = 0;
1.22 foxr 1337: EmptyQueue(); # It's worse than that ... he's dead Jim.
1.42 foxr 1338: CloseAllLondConnections; # Should all be closed but..
1.17 foxr 1339: }
1.1 foxr 1340: }
1341: } else { # Can start the request:
1342: Debug(8,"Can start...");
1.7 foxr 1343: StartRequest($LondSocket, $requestData);
1.1 foxr 1344: }
1345: }
1346:
1347: #-------------------------- Lonc UNIX socket handling ---------------------
1.3 albertel 1348:
1.1 foxr 1349: =pod
1.3 albertel 1350:
1.1 foxr 1351: =head2 ClientRequest
1.3 albertel 1352: Callback that is called when data can be read from the UNIX domain
1353: socket connecting us with an apache server process.
1.1 foxr 1354:
1355: =cut
1356:
1357: sub ClientRequest {
1358: Debug(6, "ClientRequest");
1359: my $event = shift;
1360: my $watcher = $event->w;
1361: my $socket = $watcher->fd;
1362: my $data = $watcher->data;
1363: my $thisread;
1364:
1365: Debug(9, " Watcher named: ".$watcher->desc);
1366:
1367: my $rv = $socket->recv($thisread, POSIX::BUFSIZ, 0);
1368: Debug(8, "rcv: data length = ".length($thisread)
1369: ." read =".$thisread);
1.29 foxr 1370: unless (defined $rv && length($thisread)) {
1.1 foxr 1371: # Likely eof on socket.
1372: Debug(5,"Client Socket closed on lonc for ".$RemoteHost);
1373: close($socket);
1374: $watcher->cancel();
1375: delete($ActiveClients{$socket});
1.10 foxr 1376: return;
1.1 foxr 1377: }
1378: Debug(8,"Data: ".$data." this read: ".$thisread);
1379: $data = $data.$thisread; # Append new data.
1380: $watcher->data($data);
1.44 albertel 1381: if($data =~ /\n$/) { # Request entirely read.
1.10 foxr 1382: if($data eq "close_connection_exit\n") {
1.9 foxr 1383: Log("CRITICAL",
1384: "Request Close Connection ... exiting");
1385: CloseAllLondConnections();
1386: exit;
1387: }
1.1 foxr 1388: Debug(8, "Complete transaction received: ".$data);
1.39 foxr 1389: if($LogTransactions) {
1390: Log("SUCCESS", "Transaction: '$data'"); # Transaction has \n.
1391: }
1.8 foxr 1392: my $Transaction = LondTransaction->new($data);
1.7 foxr 1393: $Transaction->SetClient($socket);
1394: QueueTransaction($Transaction);
1.1 foxr 1395: $watcher->cancel(); # Done looking for input data.
1396: }
1397:
1398: }
1399:
1.62 foxr 1400: #
1401: # Accept a connection request for a client (lonc child) and
1402: # start up an event watcher to keep an eye on input from that
1403: # Event. This can be called both from NewClient and from
1.80 albertel 1404: # ChildProcess.
1.62 foxr 1405: # Parameters:
1406: # $socket - The listener socket.
1407: # Returns:
1408: # NONE
1409: # Side Effects:
1410: # An event is made to watch the accepted connection.
1411: # Active clients hash is updated to reflect the new connection.
1412: # The client connection count is incremented.
1413: #
1414: sub accept_client {
1415: my ($socket) = @_;
1416:
1417: Debug(8, "Entering accept for lonc UNIX socket\n");
1418: my $connection = $socket->accept(); # Accept the client connection.
1419: Debug(8,"Connection request accepted from "
1420: .GetPeername($connection, AF_UNIX));
1421:
1422:
1423: my $description = sprintf("Connection to lonc client %d",
1424: $ClientConnection);
1425: Debug(9, "Creating event named: ".$description);
1426: Event->io(cb => \&ClientRequest,
1427: poll => 'r',
1428: desc => $description,
1429: data => "",
1430: fd => $connection);
1431: $ActiveClients{$connection} = $ClientConnection;
1432: $ClientConnection++;
1433: }
1.1 foxr 1434:
1435: =pod
1.3 albertel 1436:
1.1 foxr 1437: =head2 NewClient
1.3 albertel 1438:
1439: Callback that is called when a connection is received on the unix
1440: socket for a new client of lonc. The callback is parameterized by the
1441: event.. which is a-priori assumed to be an io event, and therefore has
1442: an fd member that is the Listener socket. We Accept the connection
1443: and register a new event on the readability of that socket:
1444:
1.1 foxr 1445: =cut
1.3 albertel 1446:
1.1 foxr 1447: sub NewClient {
1448: Debug(6, "NewClient");
1449: my $event = shift; # Get the event parameters.
1450: my $watcher = $event->w;
1451: my $socket = $watcher->fd; # Get the event' socket.
1452:
1.62 foxr 1453: &accept_client($socket);
1.1 foxr 1454: }
1.3 albertel 1455:
1456: =pod
1457:
1458: =head2 GetLoncSocketPath
1459:
1460: Returns the name of the UNIX socket on which to listen for client
1461: connections.
1.1 foxr 1462:
1.58 foxr 1463: =head2 Parameters:
1464:
1465: host (optional) - Name of the host socket to return.. defaults to
1466: the return from GetServerHost().
1467:
1.1 foxr 1468: =cut
1.3 albertel 1469:
1.1 foxr 1470: sub GetLoncSocketPath {
1.58 foxr 1471:
1472: my $host = GetServerHost(); # Default host.
1473: if (@_) {
1474: ($host) = @_; # Override if supplied.
1475: }
1476: return $UnixSocketDir."/".$host;
1.1 foxr 1477: }
1478:
1.3 albertel 1479: =pod
1480:
1481: =head2 GetServerHost
1482:
1483: Returns the host whose lond we talk with.
1484:
1.1 foxr 1485: =cut
1.3 albertel 1486:
1.7 foxr 1487: sub GetServerHost {
1.1 foxr 1488: return $RemoteHost; # Setup by the fork.
1489: }
1.3 albertel 1490:
1491: =pod
1492:
1.81 ! albertel 1493: =head2 GetServerId
! 1494:
! 1495: Returns the hostid whose lond we talk with.
! 1496:
! 1497: =cut
! 1498:
! 1499: sub GetHostId {
! 1500: return $RemoteHostId; # Setup by the fork.
! 1501: }
! 1502:
! 1503: =pod
! 1504:
1.3 albertel 1505: =head2 GetServerPort
1506:
1507: Returns the lond port number.
1508:
1.1 foxr 1509: =cut
1.3 albertel 1510:
1.7 foxr 1511: sub GetServerPort {
1.1 foxr 1512: return $perlvar{londPort};
1513: }
1.3 albertel 1514:
1515: =pod
1516:
1517: =head2 SetupLoncListener
1518:
1519: Setup a lonc listener event. The event is called when the socket
1520: becomes readable.. that corresponds to the receipt of a new
1521: connection. The event handler established will accept the connection
1522: (creating a communcations channel), that int turn will establish
1523: another event handler to subess requests.
1.1 foxr 1524:
1.58 foxr 1525: =head2 Parameters:
1526:
1527: host (optional) Name of the host to set up a unix socket to.
1528:
1.1 foxr 1529: =cut
1.3 albertel 1530:
1.1 foxr 1531: sub SetupLoncListener {
1.78 albertel 1532: my ($host,$SocketName) = @_;
1533: if (!$host) { $host = &GetServerHost(); }
1534: if (!$SocketName) { $SocketName = &GetLoncSocketPath($host); }
1.1 foxr 1535:
1.78 albertel 1536:
1537: unlink($SocketName);
1.58 foxr 1538:
1.1 foxr 1539: my $socket;
1.7 foxr 1540: unless ($socket =IO::Socket::UNIX->new(Local => $SocketName,
1.55 albertel 1541: Listen => 250,
1.1 foxr 1542: Type => SOCK_STREAM)) {
1.64 foxr 1543: if($I_am_child) {
1544: &child_exit(-1, "Failed to create a lonc listener socket");
1545: } else {
1546: die "Failed to create a lonc listner socket";
1547: }
1.1 foxr 1548: }
1.59 foxr 1549: return $socket;
1.1 foxr 1550: }
1551:
1.39 foxr 1552: #
1553: # Toggle transaction logging.
1554: # Implicit inputs:
1555: # LogTransactions
1556: # Implicit Outputs:
1557: # LogTransactions
1558: sub ToggleTransactionLogging {
1559: print STDERR "Toggle transaction logging...\n";
1560: if(!$LogTransactions) {
1561: $LogTransactions = 1;
1562: } else {
1563: $LogTransactions = 0;
1564: }
1565:
1566:
1567: Log("SUCCESS", "Toggled transaction logging: $LogTransactions \n");
1568: }
1569:
1.14 foxr 1570: =pod
1571:
1572: =head2 ChildStatus
1573:
1574: Child USR1 signal handler to report the most recent status
1575: into the status file.
1576:
1.22 foxr 1577: We also use this to reset the retries count in order to allow the
1578: client to retry connections with a previously dead server.
1.69 matthew 1579:
1.14 foxr 1580: =cut
1.46 albertel 1581:
1.14 foxr 1582: sub ChildStatus {
1583: my $event = shift;
1584: my $watcher = $event->w;
1585:
1586: Debug(2, "Reporting child status because : ".$watcher->data);
1587: my $docdir = $perlvar{'lonDocRoot'};
1.67 albertel 1588:
1589: open(LOG,">>$docdir/lon-status/loncstatus.txt");
1590: flock(LOG,LOCK_EX);
1591: print LOG $$."\t".$RemoteHost."\t".$Status."\t".
1.14 foxr 1592: $RecentLogEntry."\n";
1.38 foxr 1593: #
1594: # Write out information about each of the connections:
1595: #
1.46 albertel 1596: if ($DebugLevel > 2) {
1.67 albertel 1597: print LOG "Active connection statuses: \n";
1.46 albertel 1598: my $i = 1;
1599: print STDERR "================================= Socket Status Dump:\n";
1600: foreach my $item (keys %ActiveConnections) {
1601: my $Socket = $ActiveConnections{$item}->data;
1602: my $state = $Socket->GetState();
1.67 albertel 1603: print LOG "Connection $i State: $state\n";
1.46 albertel 1604: print STDERR "---------------------- Connection $i \n";
1.48 foxr 1605: $Socket->Dump(-1); # Ensure it gets dumped..
1.46 albertel 1606: $i++;
1607: }
1.38 foxr 1608: }
1.67 albertel 1609: flock(LOG,LOCK_UN);
1610: close(LOG);
1.22 foxr 1611: $ConnectionRetriesLeft = $ConnectionRetries;
1.70 albertel 1612: UpdateStatus();
1.14 foxr 1613: }
1614:
1.1 foxr 1615: =pod
1.3 albertel 1616:
1.10 foxr 1617: =head2 SignalledToDeath
1618:
1619: Called in response to a signal that causes a chid process to die.
1620:
1621: =cut
1622:
1623:
1624: sub SignalledToDeath {
1.14 foxr 1625: my $event = shift;
1626: my $watcher= $event->w;
1627:
1628: Debug(2,"Signalled to death! via ".$watcher->data);
1.17 foxr 1629: my ($signal) = $watcher->data;
1.10 foxr 1630: chomp($signal);
1631: Log("CRITICAL", "Abnormal exit. Child $$ for $RemoteHost "
1632: ."died through "."\"$signal\"");
1.68 albertel 1633: #LogPerm("F:lonc: $$ on $RemoteHost signalled to death: "
1634: # ."\"$signal\"");
1.12 foxr 1635: exit 0;
1.10 foxr 1636:
1637: }
1.16 foxr 1638:
1.69 matthew 1639: =pod
1640:
1.16 foxr 1641: =head2 ToggleDebug
1642:
1643: This sub toggles trace debugging on and off.
1644:
1645: =cut
1646:
1647: sub ToggleDebug {
1648: my $Current = $DebugLevel;
1649: $DebugLevel = $NextDebugLevel;
1650: $NextDebugLevel = $Current;
1651:
1652: Log("SUCCESS", "New debugging level for $RemoteHost now $DebugLevel");
1653:
1654: }
1655:
1.69 matthew 1656: =pod
1657:
1.1 foxr 1658: =head2 ChildProcess
1659:
1660: This sub implements a child process for a single lonc daemon.
1.61 foxr 1661: Optional parameter:
1662: $socket - if provided, this is a socket already open for listen
1663: on the client socket. Otherwise, a new listen is set up.
1.1 foxr 1664:
1665: =cut
1666:
1667: sub ChildProcess {
1.80 albertel 1668: # We've inherited all the
1.62 foxr 1669: # events of our parent and those have to be cancelled or else
1670: # all holy bloody chaos will result.. trust me, I already made
1671: # >that< mistake.
1672:
1673: my $host = GetServerHost();
1674: foreach my $listener (keys %parent_dispatchers) {
1675: my $watcher = $parent_dispatchers{$listener};
1676: my $s = $watcher->fd;
1677: if ($listener ne $host) { # Close everyone but me.
1678: Debug(5, "Closing listen socket for $listener");
1679: $s->close();
1680: }
1681: Debug(5, "Killing watcher for $listener");
1682:
1683: $watcher->cancel();
1.65 foxr 1684: delete($parent_dispatchers{$listener});
1.62 foxr 1685:
1686: }
1.65 foxr 1687:
1688: # kill off the parent's signal handlers too!
1689: #
1690:
1691: for my $handler (keys %parent_handlers) {
1692: my $watcher = $parent_handlers{$handler};
1693: $watcher->cancel();
1694: delete($parent_handlers{$handler});
1695: }
1696:
1.64 foxr 1697: $I_am_child = 1; # Seems like in spite of it all I may still getting
1698: # parent event dispatches.. flag I'm a child.
1.1 foxr 1699:
1700:
1.14 foxr 1701: #
1702: # Signals must be handled by the Event framework...
1.61 foxr 1703: #
1.14 foxr 1704:
1705: Event->signal(signal => "QUIT",
1706: cb => \&SignalledToDeath,
1707: data => "QUIT");
1708: Event->signal(signal => "HUP",
1709: cb => \&ChildStatus,
1710: data => "HUP");
1711: Event->signal(signal => "USR1",
1712: cb => \&ChildStatus,
1713: data => "USR1");
1.39 foxr 1714: Event->signal(signal => "USR2",
1715: cb => \&ToggleTransactionLogging);
1.16 foxr 1716: Event->signal(signal => "INT",
1717: cb => \&ToggleDebug,
1718: data => "INT");
1.1 foxr 1719:
1.62 foxr 1720: # Figure out if we got passed a socket or need to open one to listen for
1721: # client requests.
1722:
1.61 foxr 1723: my ($socket) = @_;
1724: if (!$socket) {
1725:
1726: $socket = SetupLoncListener();
1727: }
1.62 foxr 1728: # Establish an event to listen for client connection requests.
1729:
1730:
1.59 foxr 1731: Event->io(cb => \&NewClient,
1732: poll => 'r',
1733: desc => 'Lonc Listener Unix Socket',
1734: fd => $socket);
1.1 foxr 1735:
1.76 albertel 1736: $Event::DebugLevel = $DebugLevel;
1.1 foxr 1737:
1738: Debug(9, "Making initial lond connection for ".$RemoteHost);
1739:
1740: # Setup the initial server connection:
1741:
1.62 foxr 1742: # &MakeLondConnection(); // let first work request do it.
1.10 foxr 1743:
1.80 albertel 1744: # need to accept the connection since the event may not fire.
1.62 foxr 1745:
1.80 albertel 1746: &accept_client($socket);
1.5 foxr 1747:
1.1 foxr 1748: Debug(9,"Entering event loop");
1749: my $ret = Event::loop(); # Start the main event loop.
1750:
1751:
1.64 foxr 1752: &child_exit (-1,"Main event loop exited!!!");
1.1 foxr 1753: }
1754:
1755: # Create a new child for host passed in:
1756:
1757: sub CreateChild {
1.81 ! albertel 1758: my ($host, $hostid) = @_;
1.52 foxr 1759:
1.12 foxr 1760: my $sigset = POSIX::SigSet->new(SIGINT);
1761: sigprocmask(SIG_BLOCK, $sigset);
1.1 foxr 1762: $RemoteHost = $host;
1.9 foxr 1763: Log("CRITICAL", "Forking server for ".$host);
1.23 foxr 1764: my $pid = fork;
1.1 foxr 1765: if($pid) { # Parent
1.17 foxr 1766: $RemoteHost = "Parent";
1.27 foxr 1767: $ChildHash{$pid} = $host;
1.12 foxr 1768: sigprocmask(SIG_UNBLOCK, $sigset);
1769:
1.1 foxr 1770: } else { # child.
1.81 ! albertel 1771: $RemoteHostId = $hostid;
1.5 foxr 1772: ShowStatus("Connected to ".$RemoteHost);
1.23 foxr 1773: $SIG{INT} = 'DEFAULT';
1.12 foxr 1774: sigprocmask(SIG_UNBLOCK, $sigset);
1.81 ! albertel 1775: &ChildProcess(); # Does not return.
1.1 foxr 1776: }
1.61 foxr 1777: }
1.1 foxr 1778:
1.61 foxr 1779: # parent_client_connection:
1780: # Event handler that processes client connections for the parent process.
1781: # This sub is called when the parent is listening on a socket and
1782: # a connection request arrives. We must:
1783: # Start a child process to accept the connection request.
1784: # Kill our listen on the socket.
1785: # Parameter:
1786: # event - The event object that was created to monitor this socket.
1787: # event->w->fd is the socket.
1788: # Returns:
1789: # NONE
1790: #
1791: sub parent_client_connection {
1.62 foxr 1792: if ($I_am_child) {
1793: # Should not get here, but seem to anyway:
1794: &Debug(5," Child caught parent client connection event!!");
1795: my ($event) = @_;
1796: my $watcher = $event->w;
1797: $watcher->cancel(); # Try to kill it off again!!
1798: } else {
1799: &Debug(9, "parent_client_connection");
1800: my ($event) = @_;
1801: my $watcher = $event->w;
1802: my $socket = $watcher->fd;
1.81 ! albertel 1803: my $connection = $socket->accept(); # Accept the client connection.
! 1804: Event->io(cb => \&get_remote_hostname,
! 1805: poll => 'r',
! 1806: data => "",
! 1807: fd => $connection);
1.77 albertel 1808: }
1809: }
1810:
1811: sub get_remote_hostname {
1812: my ($event) = @_;
1813: my $watcher = $event->w;
1814: my $socket = $watcher->fd;
1.62 foxr 1815:
1.77 albertel 1816: my $thisread;
1.78 albertel 1817: my $rv = $socket->recv($thisread, POSIX::BUFSIZ, 0);
1.77 albertel 1818: Debug(8, "rcv: data length = ".length($thisread)." read =".$thisread);
1819: if (!defined($rv) || length($thisread) == 0) {
1820: # Likely eof on socket.
1821: Debug(5,"Client Socket closed on lonc for p_c_c");
1822: close($socket);
1823: $watcher->cancel();
1824: return;
1825: }
1826:
1827: my $data = $watcher->data().$thisread;
1828: $watcher->data($data);
1829: if($data =~ /\n$/) { # Request entirely read.
1830: chomp($data);
1831: } else {
1832: return;
1833: }
1.62 foxr 1834:
1.77 albertel 1835: &Debug(5,"Creating child for $data (parent_client_connection)");
1.81 ! albertel 1836: my ($hostname,$lonid) = split(':',$data,2);
! 1837: &CreateChild($hostname,$lonid);
1.62 foxr 1838:
1839: # Clean up the listen since now the child takes over until it exits.
1840: $watcher->cancel(); # Nolonger listening to this event
1.77 albertel 1841: $socket->send("done\n");
1.62 foxr 1842: $socket->close();
1.61 foxr 1843: }
1844:
1845: # parent_listen:
1846: # Opens a socket and starts a listen for the parent process on a client UNIX
1847: # domain socket.
1848: #
1849: # This involves:
1850: # Creating a socket for listen.
1851: # Removing any socket lock file
1852: # Adding an event handler for this socket becoming readable
1853: # To the parent's event dispatcher.
1854: # Parameters:
1855: # loncapa_host - LonCAPA cluster name of the host represented by the client
1856: # socket.
1857: # Returns:
1858: # NONE
1859: #
1860: sub parent_listen {
1861: my ($loncapa_host) = @_;
1862: Debug(5, "parent_listen: $loncapa_host");
1863:
1.78 albertel 1864: my ($socket,$file);
1865: if (!$loncapa_host) {
1866: $loncapa_host = 'common_parent';
1867: $file = $perlvar{'lonSockCreate'};
1868: } else {
1869: $file = &GetLoncSocketPath($loncapa_host);
1870: }
1871: $socket = &SetupLoncListener($loncapa_host,$file);
1872:
1.62 foxr 1873: $listening_to{$socket} = $loncapa_host;
1.61 foxr 1874: if (!$socket) {
1875: die "Unable to create a listen socket for $loncapa_host";
1876: }
1877:
1.78 albertel 1878: my $lock_file = $file.".lock";
1.61 foxr 1879: unlink($lock_file); # No problem if it doesn't exist yet [startup e.g.]
1880:
1.77 albertel 1881: my $watcher =
1882: Event->io(cb => \&parent_client_connection,
1883: poll => 'r',
1884: desc => "Parent listener unix socket ($loncapa_host)",
1885: data => "",
1886: fd => $socket);
1.62 foxr 1887: $parent_dispatchers{$loncapa_host} = $watcher;
1.61 foxr 1888:
1889: }
1890:
1.77 albertel 1891: sub parent_clean_up {
1892: my ($loncapa_host) = @_;
1893: Debug(5, "parent_clean_up: $loncapa_host");
1894:
1895: my $socket_file = &GetLoncSocketPath($loncapa_host);
1896: unlink($socket_file); # No problem if it doesn't exist yet [startup e.g.]
1897: my $lock_file = $socket_file.".lock";
1898: unlink($lock_file); # No problem if it doesn't exist yet [startup e.g.]
1899: }
1900:
1.61 foxr 1901:
1902: # listen_on_all_unix_sockets:
1903: # This sub initiates a listen on all unix domain lonc client sockets.
1904: # This will be called in the case where we are trimming idle processes.
1905: # When idle processes are trimmed, loncnew starts up with no children,
1906: # and only spawns off children when a connection request occurs on the
1907: # client unix socket. The spawned child continues to run until it has
1908: # been idle a while at which point it eventually exits and once more
1909: # the parent picks up the listen.
1910: #
1911: # Parameters:
1912: # NONE
1913: # Implicit Inputs:
1914: # The configuration file that has been read in by LondConnection.
1915: # Returns:
1916: # NONE
1917: #
1918: sub listen_on_all_unix_sockets {
1919: Debug(5, "listen_on_all_unix_sockets");
1920: my $host_iterator = &LondConnection::GetHostIterator();
1921: while (!$host_iterator->end()) {
1922: my $host_entry_ref = $host_iterator->get();
1.74 albertel 1923: my $host_name = $host_entry_ref->[3];
1.61 foxr 1924: Debug(9, "Listen for $host_name");
1925: &parent_listen($host_name);
1926: $host_iterator->next();
1927: }
1.1 foxr 1928: }
1.61 foxr 1929:
1.77 albertel 1930: sub listen_on_common_socket {
1931: Debug(5, "listen_on_common_socket");
1.78 albertel 1932: &parent_listen();
1.77 albertel 1933: }
1934:
1.63 foxr 1935: # server_died is called whenever a child process exits.
1936: # Since this is dispatched via a signal, we must process all
1937: # dead children until there are no more left. The action
1938: # is to:
1939: # - Remove the child from the bookeeping hashes
1940: # - Re-establish a listen on the unix domain socket associated
1941: # with that host.
1942: # Parameters:
1943: # The event, but we don't actually care about it.
1944: sub server_died {
1945: &Debug(9, "server_died called...");
1946:
1947: while(1) { # Loop until waitpid nowait fails.
1948: my $pid = waitpid(-1, WNOHANG);
1949: if($pid <= 0) {
1950: return; # Nothing left to wait for.
1951: }
1952: # need the host to restart:
1953:
1954: my $host = $ChildHash{$pid};
1955: if($host) { # It's for real...
1956: &Debug(9, "Caught sigchild for $host");
1957: delete($ChildHash{$pid});
1.81 ! albertel 1958: &parent_clean_up($host);
! 1959:
1.63 foxr 1960: } else {
1961: &Debug(5, "Caught sigchild for pid not in hosts hash: $pid");
1962: }
1963: }
1964:
1965: }
1966:
1.1 foxr 1967: #
1968: # Parent process logic pass 1:
1969: # For each entry in the hosts table, we will
1970: # fork off an instance of ChildProcess to service the transactions
1971: # to that host. Each pid will be entered in a global hash
1972: # with the value of the key, the host.
1973: # The parent will then enter a loop to wait for process exits.
1974: # Each exit gets logged and the child gets restarted.
1975: #
1976:
1.5 foxr 1977: #
1978: # Fork and start in new session so hang-up isn't going to
1979: # happen without intent.
1980: #
1981:
1982:
1.6 foxr 1983:
1984:
1.8 foxr 1985:
1.6 foxr 1986:
1987: ShowStatus("Forming new session");
1988: my $childpid = fork;
1989: if ($childpid != 0) {
1990: sleep 4; # Give child a chacne to break to
1991: exit 0; # a new sesion.
1992: }
1.8 foxr 1993: #
1994: # Write my pid into the pid file so I can be located
1995: #
1996:
1997: ShowStatus("Parent writing pid file:");
1.23 foxr 1998: my $execdir = $perlvar{'lonDaemons'};
1.8 foxr 1999: open (PIDSAVE, ">$execdir/logs/lonc.pid");
2000: print PIDSAVE "$$\n";
2001: close(PIDSAVE);
1.6 foxr 2002:
1.17 foxr 2003:
2004:
1.6 foxr 2005: if (POSIX::setsid() < 0) {
2006: print "Could not create new session\n";
2007: exit -1;
2008: }
1.5 foxr 2009:
2010: ShowStatus("Forking node servers");
2011:
1.9 foxr 2012: Log("CRITICAL", "--------------- Starting children ---------------");
2013:
1.31 foxr 2014: LondConnection::ReadConfig; # Read standard config files.
1.1 foxr 2015:
1.80 albertel 2016: $RemoteHost = "[parent]";
1.81 ! albertel 2017: &listen_on_common_socket();
1.60 foxr 2018:
1.12 foxr 2019: $RemoteHost = "Parent Server";
1.1 foxr 2020:
2021: # Maintain the population:
1.5 foxr 2022:
2023: ShowStatus("Parent keeping the flock");
1.1 foxr 2024:
1.12 foxr 2025:
1.80 albertel 2026: # We need to setup a SIGChild event to handle the exit (natural or otherwise)
2027: # of the children.
1.61 foxr 2028:
1.80 albertel 2029: Event->signal(cb => \&server_died,
2030: desc => "Child exit handler",
2031: signal => "CHLD");
2032:
2033:
2034: # Set up all the other signals we set up.
2035:
2036: $parent_handlers{INT} = Event->signal(cb => \&Terminate,
2037: desc => "Parent INT handler",
2038: signal => "INT");
2039: $parent_handlers{TERM} = Event->signal(cb => \&Terminate,
2040: desc => "Parent TERM handler",
2041: signal => "TERM");
1.81 ! albertel 2042: $parent_handlers{HUP} = Event->signal(cb => \&KillThemAll,
! 2043: desc => "Parent HUP handler.",
! 2044: signal => "HUP");
1.80 albertel 2045: $parent_handlers{USR1} = Event->signal(cb => \&CheckKids,
2046: desc => "Parent USR1 handler",
2047: signal => "USR1");
2048: $parent_handlers{USR2} = Event->signal(cb => \&UpdateKids,
2049: desc => "Parent USR2 handler.",
2050: signal => "USR2");
2051:
2052: # Start procdesing events.
2053:
2054: $Event::DebugLevel = $DebugLevel;
2055: Debug(9, "Parent entering event loop");
2056: my $ret = Event::loop();
2057: die "Main Event loop exited: $ret";
1.14 foxr 2058:
2059: =pod
2060:
2061: =head1 CheckKids
2062:
2063: Since kids do not die as easily in this implementation
2064: as the previous one, there is no need to restart the
2065: dead ones (all dead kids get restarted when they die!!)
2066: The only thing this function does is to pass USR1 to the
2067: kids so that they report their status.
2068:
2069: =cut
2070:
2071: sub CheckKids {
2072: Debug(2, "Checking status of children");
2073: my $docdir = $perlvar{'lonDocRoot'};
2074: my $fh = IO::File->new(">$docdir/lon-status/loncstatus.txt");
2075: my $now=time;
2076: my $local=localtime($now);
2077: print $fh "LONC status $local - parent $$ \n\n";
1.65 foxr 2078: foreach my $host (keys %parent_dispatchers) {
2079: print $fh "LONC Parent process listening for $host\n";
2080: }
1.23 foxr 2081: foreach my $pid (keys %ChildHash) {
1.14 foxr 2082: Debug(2, "Sending USR1 -> $pid");
2083: kill 'USR1' => $pid; # Tell Child to report status.
2084: }
1.65 foxr 2085:
1.14 foxr 2086: }
1.24 foxr 2087:
2088: =pod
2089:
2090: =head1 UpdateKids
2091:
1.25 foxr 2092: parent's SIGUSR2 handler. This handler:
1.24 foxr 2093:
2094: =item
2095:
2096: Rereads the hosts file.
2097:
2098: =item
2099:
2100: Kills off (via sigint) children for hosts that have disappeared.
2101:
2102: =item
2103:
1.27 foxr 2104: QUITs children for hosts that already exist (this just forces a status display
1.24 foxr 2105: and resets the connection retry count for that host.
2106:
2107: =item
2108:
2109: Starts new children for hosts that have been added to the hosts.tab file since
2110: the start of the master program and maintains them.
2111:
2112: =cut
2113:
2114: sub UpdateKids {
1.27 foxr 2115:
1.25 foxr 2116: Log("INFO", "Updating connections via SIGUSR2");
1.27 foxr 2117:
1.65 foxr 2118: # I'm not sure what I was thinking in the first implementation.
2119: # someone will have to work hard to convince me the effect is any
2120: # different than Restart, especially now that we don't start up
2121: # per host servers automatically, may as well just restart.
2122: # The down side is transactions that are in flight will get timed out
2123: # (lost unless they are critical).
1.27 foxr 2124:
1.81 ! albertel 2125: &KillThemAll();
1.24 foxr 2126: }
2127:
1.14 foxr 2128:
1.13 foxr 2129: =pod
2130:
2131: =head1 Restart
2132:
2133: Signal handler for HUP... all children are killed and
2134: we self restart. This is an el-cheapo way to re read
2135: the config file.
2136:
2137: =cut
2138:
2139: sub Restart {
1.23 foxr 2140: &KillThemAll; # First kill all the children.
1.13 foxr 2141: Log("CRITICAL", "Restarting");
2142: my $execdir = $perlvar{'lonDaemons'};
2143: unlink("$execdir/logs/lonc.pid");
1.65 foxr 2144: exec("$executable");
1.10 foxr 2145: }
1.12 foxr 2146:
2147: =pod
2148:
2149: =head1 KillThemAll
2150:
2151: Signal handler that kills all children by sending them a
1.17 foxr 2152: SIGHUP. Responds to sigint and sigterm.
1.12 foxr 2153:
2154: =cut
2155:
1.10 foxr 2156: sub KillThemAll {
1.12 foxr 2157: Debug(2, "Kill them all!!");
2158: local($SIG{CHLD}) = 'IGNORE'; # Our children >will< die.
1.23 foxr 2159: foreach my $pid (keys %ChildHash) {
1.12 foxr 2160: my $serving = $ChildHash{$pid};
1.52 foxr 2161: ShowStatus("Nicely Killing lonc for $serving pid = $pid");
2162: Log("CRITICAL", "Nicely Killing lonc for $serving pid = $pid");
1.17 foxr 2163: kill 'QUIT' => $pid;
1.12 foxr 2164: }
1.1 foxr 2165: }
1.12 foxr 2166:
1.52 foxr 2167:
2168: #
2169: # Kill all children via KILL. Just in case the
2170: # first shot didn't get them.
2171:
2172: sub really_kill_them_all_dammit
2173: {
2174: Debug(2, "Kill them all Dammit");
2175: local($SIG{CHLD} = 'IGNORE'); # In case some purist reenabled them.
2176: foreach my $pid (keys %ChildHash) {
2177: my $serving = $ChildHash{$pid};
2178: &ShowStatus("Nastily killing lonc for $serving pid = $pid");
2179: Log("CRITICAL", "Nastily killing lonc for $serving pid = $pid");
2180: kill 'KILL' => $pid;
2181: delete($ChildHash{$pid});
2182: my $execdir = $perlvar{'lonDaemons'};
2183: unlink("$execdir/logs/lonc.pid");
2184: }
2185: }
1.69 matthew 2186:
1.14 foxr 2187: =pod
2188:
2189: =head1 Terminate
2190:
2191: Terminate the system.
2192:
2193: =cut
2194:
2195: sub Terminate {
1.52 foxr 2196: &Log("CRITICAL", "Asked to kill children.. first be nice...");
2197: &KillThemAll;
2198: #
2199: # By now they really should all be dead.. but just in case
2200: # send them all SIGKILL's after a bit of waiting:
2201:
2202: sleep(4);
2203: &Log("CRITICAL", "Now kill children nasty");
2204: &really_kill_them_all_dammit;
1.17 foxr 2205: Log("CRITICAL","Master process exiting");
2206: exit 0;
1.14 foxr 2207:
2208: }
1.81 ! albertel 2209:
! 2210: sub my_hostname {
! 2211: use Sys::Hostname;
! 2212: my $name = &hostname();
! 2213: &Debug(9,"Name is $name");
! 2214: return $name;
! 2215: }
! 2216:
1.12 foxr 2217: =pod
1.1 foxr 2218:
2219: =head1 Theory
1.3 albertel 2220:
2221: The event class is used to build this as a single process with an
2222: event driven model. The following events are handled:
1.1 foxr 2223:
2224: =item UNIX Socket connection Received
2225:
2226: =item Request data arrives on UNIX data transfer socket.
2227:
2228: =item lond connection becomes writable.
2229:
2230: =item timer fires at 1 second intervals.
2231:
2232: All sockets are run in non-blocking mode. Timeouts managed by the timer
2233: handler prevents hung connections.
2234:
2235: Key data structures:
2236:
1.3 albertel 2237: =item RequestQueue
2238:
2239: A queue of requests received from UNIX sockets that are
2240: waiting for a chance to be forwarded on a lond connection socket.
2241:
2242: =item ActiveConnections
2243:
2244: A hash of lond connections that have transactions in process that are
2245: available to be timed out.
2246:
2247: =item ActiveTransactions
2248:
2249: A hash indexed by lond connections that contain the client reply
2250: socket for each connection that has an active transaction on it.
2251:
2252: =item IdleConnections
2253:
2254: A hash of lond connections that have no work to do. These connections
2255: can be closed if they are idle for a long enough time.
1.1 foxr 2256:
2257: =cut
FreeBSD-CVSweb <freebsd-cvsweb@FreeBSD.org>