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