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