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