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