1: #!/usr/bin/perl
2: # The LearningOnline Network with CAPA
3: # lonc maintains the connections to remote computers
4: #
5: # $Id: loncnew,v 1.9 2003/06/13 02:38:43 foxr 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: #
11: # LON-CAPA is free software; you can redistribute it and/or modify
12: # it under the terms of the GNU General Public License as published by
13: # the Free Software Foundation; either version 2 of the License, or
14: # (at your option) any later version.
15: #
16: # LON-CAPA is distributed in the hope that it will be useful,
17: # but WITHOUT ANY WARRANTY; without even the implied warranty of
18: # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
19: # GNU General Public License for more details.
20: #
21: # You should have received a copy of the GNU General Public License
22: # along with LON-CAPA; if not, write to the Free Software
23: # Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
24: #
25: # /home/httpd/html/adm/gpl.txt
26: #
27: # http://www.lon-capa.org/
28: #
29: #
30: # new lonc handles n requestors spread out bver m connections to londs.
31: # This module is based on the Event class.
32: # Development iterations:
33: # - Setup basic event loop. (done)
34: # - Add timer dispatch. (done)
35: # - Add ability to accept lonc UNIX domain sockets. (done)
36: # - Add ability to create/negotiate lond connections (done).
37: # - Add general logic for dispatching requests and timeouts. (done).
38: # - Add support for the lonc/lond requests. (done).
39: # - Add logging/status monitoring.
40: # - Add Signal handling - HUP restarts. USR1 status report.
41: # - Add Configuration file I/O (done).
42: # - Add management/status request interface.
43: # - Add deferred request capability. (done)
44: # - Detect transmission timeouts.
45: #
46:
47: # Change log:
48: # $Log: loncnew,v $
49: # Revision 1.9 2003/06/13 02:38:43 foxr
50: # Add logging in 'expected format'
51: #
52: # Revision 1.8 2003/06/11 02:04:35 foxr
53: # Support delayed transactions... this is done uniformly by encapsulating
54: # transactions in an object ... a LondTransaction that is implemented by
55: # LondTransaction.pm
56: #
57: # Revision 1.7 2003/06/03 01:59:39 foxr
58: # complete coding to support deferred transactions.
59: #
60: #
61:
62: use lib "/home/httpd/lib/perl/";
63: use lib "/home/foxr/newloncapa/types";
64: use Event qw(:DEFAULT );
65: use POSIX qw(:signal_h);
66: use IO::Socket;
67: use IO::Socket::INET;
68: use IO::Socket::UNIX;
69: use IO::File;
70: use IO::Handle;
71: use Socket;
72: use Crypt::IDEA;
73: use LONCAPA::Queue;
74: use LONCAPA::Stack;
75: use LONCAPA::LondConnection;
76: use LONCAPA::LondTransaction;
77: use LONCAPA::Configuration;
78: use LONCAPA::HashIterator;
79:
80:
81: #
82: # Disable all signals we might receive from outside for now.
83: #
84: $SIG{QUIT} = IGNORE;
85: $SIG{HUP} = IGNORE;
86: $SIG{USR1} = IGNORE;
87: $SIG{INT} = IGNORE;
88: $SIG{CHLD} = IGNORE;
89: $SIG{__DIE__} = IGNORE;
90:
91:
92: # Read the httpd configuration file to get perl variables
93: # normally set in apache modules:
94:
95: my $perlvarref = LONCAPA::Configuration::read_conf('loncapa.conf');
96: my %perlvar = %{$perlvarref};
97:
98: #
99: # parent and shared variables.
100:
101: my %ChildHash; # by pid -> host.
102:
103:
104: my $MaxConnectionCount = 10; # Will get from config later.
105: my $ClientConnection = 0; # Uniquifier for client events.
106:
107: my $DebugLevel = 0;
108: my $IdleTimeout= 3600; # Wait an hour before pruning connections.
109:
110: #
111: # The variables below are only used by the child processes.
112: #
113: my $RemoteHost; # Name of host child is talking to.
114: my $UnixSocketDir= "/home/httpd/sockets";
115: my $IdleConnections = Stack->new(); # Set of idle connections
116: my %ActiveConnections; # Connections to the remote lond.
117: my %ActiveTransactions; # LondTransactions in flight.
118: my %ActiveClients; # Serial numbers of active clients by socket.
119: my $WorkQueue = Queue->new(); # Queue of pending transactions.
120: my $ConnectionCount = 0;
121: my $IdleSeconds = 0; # Number of seconds idle.
122: my $Status = ""; # Current status string.
123:
124:
125: #
126: # The hash below gives the HTML format for log messages
127: # given a severity.
128: #
129: my %LogFormats;
130:
131: $LogFormats{"CRITICAL"} = "<font color=red>CRITICAL: %s</font>";
132: $LogFormats{"SUCCESS"} = "<font color=green>SUCCESS: %s</font>";
133: $LogFormats{"INFO"} = "<font color=yellow>INFO: %s</font>";
134: $LogFormats{"WARNING"} = "<font color=blue>WARNING: %s</font>";
135: $LogFormats{"DEFAULT"} = " %s ";
136:
137: my $lastlog = ''; # Used for status reporting.
138:
139: =pod
140:
141: =head2 Log
142:
143: Logs a message to the log file.
144: Parameters:
145:
146: =item severity
147:
148: One of CRITICAL, WARNING, INFO, SUCCESS used to select the
149: format string used to format the message. if the severity is
150: not a defined severity the Default format string is used.
151:
152: =item message
153:
154: The base message. In addtion to the format string, the message
155: will be appended to a string containing the name of our remote
156: host and the time will be formatted into the message.
157:
158: =cut
159:
160: sub Log {
161: my $severity = shift;
162: my $message = shift;
163:
164: if(!$LogFormats{$severity}) {
165: $severity = "DEFAULT";
166: }
167:
168: my $format = $LogFormats{$severity};
169:
170: # Put the window dressing in in front of the message format:
171:
172: my $now = time;
173: my $local = localtime($now);
174: my $finalformat = "$local ($$) [$RemoteHost] [$Status] ";
175: my $finalformat = $finalformat.$format."\n";
176:
177: # open the file and put the result.
178:
179: my $execdir = $perlvar{'lonDaemons'};
180: my $fh = IO::File->new(">>$execdir/logs/lonc.log");
181: my $msg = sprintf($finalformat, $message);
182: print $fh $msg;
183:
184: }
185:
186:
187: =pod
188:
189: =head2 GetPeerName
190:
191: Returns the name of the host that a socket object is connected to.
192:
193: =cut
194:
195: sub GetPeername {
196: my $connection = shift;
197: my $AdrFamily = shift;
198: my $peer = $connection->peername();
199: my $peerport;
200: my $peerip;
201: if($AdrFamily == AF_INET) {
202: ($peerport, $peerip) = sockaddr_in($peer);
203: my $peername = gethostbyaddr($iaddr, $AdrFamily);
204: return $peername;
205: } elsif ($AdrFamily == AF_UNIX) {
206: my $peerfile;
207: ($peerfile) = sockaddr_un($peer);
208: return $peerfile;
209: }
210: }
211: #----------------------------- Timer management ------------------------
212: =pod
213:
214: =head2 Debug
215:
216: Invoked to issue a debug message.
217:
218: =cut
219:
220: sub Debug {
221: my $level = shift;
222: my $message = shift;
223: if ($level <= $DebugLevel) {
224: print $message." host = ".$RemoteHost."\n";
225: }
226: }
227:
228: sub SocketDump {
229: my $level = shift;
230: my $socket= shift;
231: if($level <= $DebugLevel) {
232: $socket->Dump();
233: }
234: }
235:
236: =pod
237:
238: =head2 ShowStatus
239:
240: Place some text as our pid status.
241:
242: =cut
243: sub ShowStatus {
244: my $status = shift;
245: $0 = "lonc: ".$status;
246: $Status = $status; # Make available for logging.
247:
248: }
249:
250: =pod
251:
252: =head2 Tick
253:
254: Invoked each timer tick.
255:
256: =cut
257:
258:
259: sub Tick {
260: my $client;
261: ShowStatus(GetServerHost()." Connection count: ".$ConnectionCount);
262: Debug(6, "Tick");
263: Debug(6, " Current connection count: ".$ConnectionCount);
264: foreach $client (keys %ActiveClients) {
265: Debug(7, " Have client: with id: ".$ActiveClients{$client});
266: }
267: # Is it time to prune connection count:
268:
269:
270: if($IdleConnections->Count() &&
271: ($WorkQueue->Count() == 0)) { # Idle connections and nothing to do?
272: $IdleSeconds++;
273: if($IdleSeconds > $IdleTimeout) { # Prune a connection...
274: $Socket = $IdleConnections->pop();
275: KillSocket($Socket);
276: }
277: } else {
278: $IdleSeconds = 0; # Reset idle count if not idle.
279: }
280:
281: # Do we have work in the queue, but no connections to service them?
282: # If so, try to make some new connections to get things going again.
283: #
284:
285: my $Requests = $WorkQueue->Count();
286: if (($ConnectionCount == 0) && ($Requests > 0)) {
287: my $Connections = ($Requests <= $MaxConnectionCount) ?
288: $Requests : $MaxConnectionCount;
289: Debug(1,"Work but no connections, starting ".$Connections." of them");
290: for ($i =0; $i < $Connections; $i++) {
291: MakeLondConnection();
292: }
293:
294: }
295: }
296:
297: =pod
298:
299: =head2 SetupTimer
300:
301: Sets up a 1 per sec recurring timer event. The event handler is used to:
302:
303: =item
304:
305: Trigger timeouts on communications along active sockets.
306:
307: =item
308:
309: Trigger disconnections of idle sockets.
310:
311: =cut
312:
313: sub SetupTimer {
314: Debug(6, "SetupTimer");
315: Event->timer(interval => 1, debug => 1, cb => \&Tick );
316: }
317:
318: =pod
319:
320: =head2 ServerToIdle
321:
322: This function is called when a connection to the server is
323: ready for more work.
324:
325: If there is work in the Work queue the top element is dequeued
326: and the connection will start to work on it. If the work queue is
327: empty, the connection is pushed on the idle connection stack where
328: it will either get another work unit, or alternatively, if it sits there
329: long enough, it will be shut down and released.
330:
331: =cut
332:
333: sub ServerToIdle {
334: my $Socket = shift; # Get the socket.
335: delete($ActiveTransactions{$Socket}); # Server has no transaction
336:
337: &Debug(6, "Server to idle");
338:
339: # If there's work to do, start the transaction:
340:
341: $reqdata = $WorkQueue->dequeue(); # This is a LondTransaction
342: unless($reqdata eq undef) {
343: Debug(9, "Queue gave request data: ".$reqdata->getRequest());
344: &StartRequest($Socket, $reqdata);
345:
346: } else {
347:
348: # There's no work waiting, so push the server to idle list.
349: &Debug(8, "No new work requests, server connection going idle");
350: $IdleConnections->push($Socket);
351: }
352: }
353:
354: =pod
355:
356: =head2 ClientWritable
357:
358: Event callback for when a client socket is writable.
359:
360: This callback is established when a transaction reponse is
361: avaiable from lond. The response is forwarded to the unix socket
362: as it becomes writable in this sub.
363:
364: Parameters:
365:
366: =item Event
367:
368: The event that has been triggered. Event->w->data is
369: the data and Event->w->fd is the socket to write.
370:
371: =cut
372:
373: sub ClientWritable {
374: my $Event = shift;
375: my $Watcher = $Event->w;
376: my $Data = $Watcher->data;
377: my $Socket = $Watcher->fd;
378:
379: # Try to send the data:
380:
381: &Debug(6, "ClientWritable writing".$Data);
382: &Debug(9, "Socket is: ".$Socket);
383:
384: if($Socket->connected) {
385: my $result = $Socket->send($Data, 0);
386:
387: # $result undefined: the write failed.
388: # otherwise $result is the number of bytes written.
389: # Remove that preceding string from the data.
390: # If the resulting data is empty, destroy the watcher
391: # and set up a read event handler to accept the next
392: # request.
393:
394: &Debug(9,"Send result is ".$result." Defined: ".defined($result));
395: if(defined($result)) {
396: &Debug(9, "send result was defined");
397: if($result == length($Data)) { # Entire string sent.
398: &Debug(9, "ClientWritable data all written");
399: $Watcher->cancel();
400: #
401: # Set up to read next request from socket:
402:
403: my $descr = sprintf("Connection to lonc client %d",
404: $ActiveClients{$Socket});
405: Event->io(cb => \&ClientRequest,
406: poll => 'r',
407: desc => $descr,
408: data => "",
409: fd => $Socket);
410:
411: } else { # Partial string sent.
412: $Watcher->data(substr($Data, $result));
413: }
414:
415: } else { # Error of some sort...
416:
417: # Some errnos are possible:
418: my $errno = $!;
419: if($errno == POSIX::EWOULDBLOCK ||
420: $errno == POSIX::EAGAIN ||
421: $errno == POSIX::EINTR) {
422: # No action taken?
423: } else { # Unanticipated errno.
424: &Debug(5,"ClientWritable error or peer shutdown".$RemoteHost);
425: $Watcher->cancel; # Stop the watcher.
426: $Socket->shutdown(2); # Kill connection
427: $Socket->close(); # Close the socket.
428: }
429:
430: }
431: } else {
432: $Watcher->cancel(); # A delayed request...just cancel.
433: }
434: }
435:
436: =pod
437:
438: =head2 CompleteTransaction
439:
440: Called when the reply data has been received for a lond
441: transaction. The reply data must now be sent to the
442: ultimate client on the other end of the Unix socket. This is
443: done by setting up a writable event for the socket with the
444: data the reply data.
445:
446: Parameters:
447:
448: =item Socket
449:
450: Socket on which the lond transaction occured. This is a
451: LondConnection. The data received is in the TransactionReply member.
452:
453: =item Transaction
454:
455: The transaction that is being completed.
456:
457: =cut
458:
459: sub CompleteTransaction {
460: &Debug(6,"Complete transaction");
461: my $Socket = shift;
462: my $Transaction = shift;
463:
464: if (!$Transaction->isDeferred()) { # Normal transaction
465: my $data = $Socket->GetReply(); # Data to send.
466: StartClientReply($Transaction, $data);
467: } else { # Delete deferred transaction file.
468: Log("SUCCESS", "A delayed transaction was completed");
469: unlink $Transaction->getFile();
470: }
471: }
472: =pod
473: =head1 StartClientReply
474:
475: Initiates a reply to a client where the reply data is a parameter.
476:
477: =head2 parameters:
478:
479: =item Transaction
480:
481: The transaction for which we are responding to the client.
482:
483: =item data
484:
485: The data to send to apached client.
486:
487: =cut
488: sub StartClientReply {
489: my $Transaction = shift;
490: my $data = shift;
491:
492: my $Client = $Transaction->getClient();
493:
494: &Debug(8," Reply was: ".$data);
495: my $Serial = $ActiveClients{$Client};
496: my $desc = sprintf("Connection to lonc client %d",
497:
498: $Serial);
499: Event->io(fd => $Client,
500: poll => "w",
501: desc => $desc,
502: cb => \&ClientWritable,
503: data => $data);
504: }
505: =pod
506: =head2 FailTransaction
507:
508: Finishes a transaction with failure because the associated lond socket
509: disconnected. There are two possibilities:
510: - The transaction is deferred: in which case we just quietly
511: delete the transaction since there is no client connection.
512: - The transaction is 'live' in which case we initiate the sending
513: of "con_lost" to the client.
514:
515: Deleting the transaction means killing it from the
516: %ActiveTransactions hash.
517:
518: Parameters:
519:
520: =item client
521:
522: The LondTransaction we are failing.
523:
524: =cut
525:
526: sub FailTransaction {
527: my $transaction = shift;
528: my $Lond = $transaction->getServer();
529: if (!$client->isDeferred()) { # If the transaction is deferred we'll get to it.
530: my $client = $transcation->getClient();
531: StartClientReply($client, "con_lost");
532: }
533: # not needed, done elsewhere if active.
534: # delete $ActiveTransactions{$Lond};
535:
536: }
537:
538: =pod
539: =head1 EmptyQueue
540:
541: Fails all items in the work queue with con_lost.
542: Note that each item in the work queue is a transaction.
543:
544: =cut
545: sub EmptyQueue {
546: while($WorkQueue->Count()) {
547: my $request = $Workqueue->dequeue(); # This is a transaction
548: FailTransaction($request);
549: }
550: }
551:
552: =pod
553:
554: =head2 CloseAllLondConnections
555:
556: Close all connections open on lond prior to exit e.g.
557:
558: =cut
559: sub CloseAllLondConnections {
560: foreach $Socket (keys %ActiveConnections) {
561: KillSocket($Socket);
562: }
563: }
564: =cut
565:
566: =pod
567:
568: =head2 KillSocket
569:
570: Destroys a socket. This function can be called either when a socket
571: has died of 'natural' causes or because a socket needs to be pruned due to
572: idleness. If the socket has died naturally, if there are no longer any
573: live connections a new connection is created (in case there are transactions
574: in the queue). If the socket has been pruned, it is never re-created.
575:
576: Parameters:
577:
578: =item Socket
579:
580: The socket to kill off.
581:
582: =item Restart
583:
584: nonzero if we are allowed to create a new connection.
585:
586:
587: =cut
588: sub KillSocket {
589: my $Socket = shift;
590:
591: $Socket->Shutdown();
592:
593: # If the socket came from the active connection set,
594: # delete its transaction... note that FailTransaction should
595: # already have been called!!!
596: # otherwise it came from the idle set.
597: #
598:
599: if(exists($ActiveTransactions{$Socket})) {
600: delete ($ActiveTransactions{$Socket});
601: }
602: if(exists($ActiveConnections{$Socket})) {
603: delete($ActiveConnections{$Socket});
604: }
605: $ConnectionCount--;
606:
607: # If the connection count has gone to zero and there is work in the
608: # work queue, the work all gets failed with con_lost.
609: #
610: if($ConnectionCount == 0) {
611: EmptyQueue;
612: }
613: }
614:
615: =pod
616:
617: =head2 LondReadable
618:
619: This function is called whenever a lond connection
620: is readable. The action is state dependent:
621:
622: =head3 State=Initialized
623:
624: We''re waiting for the challenge, this is a no-op until the
625: state changes.
626:
627: =head3 State=Challenged
628:
629: The challenge has arrived we need to transition to Writable.
630: The connection must echo the challenge back.
631:
632: =head3 State=ChallengeReplied
633:
634: The challenge has been replied to. The we are receiveing the
635: 'ok' from the partner.
636:
637: =head3 State=RequestingKey
638:
639: The ok has been received and we need to send the request for
640: an encryption key. Transition to writable for that.
641:
642: =head3 State=ReceivingKey
643:
644: The the key has been requested, now we are reading the new key.
645:
646: =head3 State=Idle
647:
648: The encryption key has been negotiated or we have finished
649: reading data from the a transaction. If the callback data has
650: a client as well as the socket iformation, then we are
651: doing a transaction and the data received is relayed to the client
652: before the socket is put on the idle list.
653:
654: =head3 State=SendingRequest
655:
656: I do not think this state can be received here, but if it is,
657: the appropriate thing to do is to transition to writable, and send
658: the request.
659:
660: =head3 State=ReceivingReply
661:
662: We finished sending the request to the server and now transition
663: to readable to receive the reply.
664:
665: The parameter to this function are:
666:
667: The event. Implicit in this is the watcher and its data. The data
668: contains at least the lond connection object and, if a
669: transaction is in progress, the socket attached to the local client.
670:
671: =cut
672:
673: sub LondReadable {
674:
675: my $Event = shift;
676: my $Watcher = $Event->w;
677: my $Socket = $Watcher->data;
678: my $client = undef;
679:
680: &Debug(6,"LondReadable called state = ".$State);
681:
682:
683: my $State = $Socket->GetState(); # All action depends on the state.
684:
685: SocketDump(6, $Socket);
686:
687: if($Socket->Readable() != 0) {
688: # bad return from socket read. Currently this means that
689: # The socket has become disconnected. We fail the transaction.
690:
691: if(exists($ActiveTransactions{$Socket})) {
692: Debug(3,"Lond connection lost failing transaction");
693: FailTransaction($ActiveTransactions{$Socket});
694: }
695: $Watcher->cancel();
696: KillSocket($Socket);
697: return;
698: }
699: SocketDump(6,$Socket);
700:
701: $State = $Socket->GetState(); # Update in case of transition.
702: &Debug(6, "After read, state is ".$State);
703:
704: if($State eq "Initialized") {
705:
706:
707: } elsif ($State eq "ChallengeReceived") {
708: # The challenge must be echoed back; The state machine
709: # in the connection takes care of setting that up. Just
710: # need to transition to writable:
711:
712: $Watcher->cb(\&LondWritable);
713: $Watcher->poll("w");
714:
715: } elsif ($State eq "ChallengeReplied") {
716:
717:
718: } elsif ($State eq "RequestingKey") {
719: # The ok was received. Now we need to request the key
720: # That requires us to be writable:
721:
722: $Watcher->cb(\&LondWritable);
723: $Watcher->poll("w");
724:
725: } elsif ($State eq "ReceivingKey") {
726:
727: } elsif ($State eq "Idle") {
728: # If necessary, complete a transaction and then go into the
729: # idle queue.
730: $Watcher->cancel();
731: if(exists($ActiveTransactions{$Socket})) {
732: Debug(8,"Completing transaction!!");
733: CompleteTransaction($Socket,
734: $ActiveTransactions{$Socket});
735: } else {
736: Log("SUCCESS", "Connection ".$ConnectionCount." to "
737: .$RemoteHost." now ready for action");
738: }
739: ServerToIdle($Socket); # Next work unit or idle.
740:
741: } elsif ($State eq "SendingRequest") {
742: # We need to be writable for this and probably don't belong
743: # here inthe first place.
744:
745: Deubg(6, "SendingRequest state encountered in readable");
746: $Watcher->poll("w");
747: $Watcher->cb(\&LondWritable);
748:
749: } elsif ($State eq "ReceivingReply") {
750:
751:
752: } else {
753: # Invalid state.
754: Debug(4, "Invalid state in LondReadable");
755: }
756: }
757:
758: =pod
759:
760: =head2 LondWritable
761:
762: This function is called whenever a lond connection
763: becomes writable while there is a writeable monitoring
764: event. The action taken is very state dependent:
765:
766: =head3 State = Connected
767:
768: The connection is in the process of sending the 'init' hailing to the
769: lond on the remote end. The connection object''s Writable member is
770: called. On error, ConnectionError is called to destroy the connection
771: and remove it from the ActiveConnections hash
772:
773: =head3 Initialized
774:
775: 'init' has been sent, writability monitoring is removed and
776: readability monitoring is started with LondReadable as the callback.
777:
778: =head3 ChallengeReceived
779:
780: The connection has received the who are you challenge from the remote
781: system, and is in the process of sending the challenge
782: response. Writable is called.
783:
784: =head3 ChallengeReplied
785:
786: The connection has replied to the initial challenge The we switch to
787: monitoring readability looking for the server to reply with 'ok'.
788:
789: =head3 RequestingKey
790:
791: The connection is in the process of requesting its encryption key.
792: Writable is called.
793:
794: =head3 ReceivingKey
795:
796: The connection has sent the request for a key. Switch to readability
797: monitoring to accept the key
798:
799: =head3 SendingRequest
800:
801: The connection is in the process of sending a request to the server.
802: This request is part of a client transaction. All the states until
803: now represent the client setup protocol. Writable is called.
804:
805: =head3 ReceivingReply
806:
807: The connection has sent a request. Now it must receive a reply.
808: Readability monitoring is requested.
809:
810: This function is an event handler and therefore receives as
811: a parameter the event that has fired. The data for the watcher
812: of this event is a reference to a list of one or two elements,
813: depending on state. The first (and possibly only) element is the
814: socket. The second (present only if a request is in progress)
815: is the socket on which to return a reply to the caller.
816:
817: =cut
818:
819: sub LondWritable {
820: my $Event = shift;
821: my $Watcher = $Event->w;
822: my $Socket = $Watcher->data;
823: my $State = $Socket->GetState();
824:
825: Debug(6,"LondWritable State = ".$State."\n");
826:
827:
828: # Figure out what to do depending on the state of the socket:
829:
830:
831:
832:
833: SocketDump(6,$Socket);
834:
835: if ($State eq "Connected") {
836:
837: if ($Socket->Writable() != 0) {
838: # The write resulted in an error.
839: # We'll treat this as if the socket got disconnected:
840: Log("WARNING", "Connection to ".$RemoteHost.
841: " has been disconnected");
842: $Watcher->cancel();
843: KillSocket($Socket);
844: return;
845: }
846: # "init" is being sent...
847:
848:
849: } elsif ($State eq "Initialized") {
850:
851: # Now that init was sent, we switch
852: # to watching for readability:
853:
854: $Watcher->cb(\&LondReadable);
855: $Watcher->poll("r");
856:
857: } elsif ($State eq "ChallengeReceived") {
858: # We received the challenge, now we
859: # are echoing it back. This is a no-op,
860: # we're waiting for the state to change
861:
862: if($Socket->Writable() != 0) {
863:
864: $Watcher->cancel();
865: KillSocket($Socket);
866: return;
867: }
868:
869: } elsif ($State eq "ChallengeReplied") {
870: # The echo was sent back, so we switch
871: # to watching readability.
872:
873: $Watcher->cb(\&LondReadable);
874: $Watcher->poll("r");
875:
876: } elsif ($State eq "RequestingKey") {
877: # At this time we're requesting the key.
878: # again, this is essentially a no-op.
879: # we'll write the next chunk until the
880: # state changes.
881:
882: if($Socket->Writable() != 0) {
883: # Write resulted in an error.
884:
885: $Watcher->cancel();
886: KillSocket($Socket);
887: return;
888:
889: }
890: } elsif ($State eq "ReceivingKey") {
891: # Now we need to wait for the key
892: # to come back from the peer:
893:
894: $Watcher->cb(\&LondReadable);
895: $Watcher->poll("r");
896:
897: } elsif ($State eq "SendingRequest") {
898: # At this time we are sending a request to the
899: # peer... write the next chunk:
900:
901: if($Socket->Writable() != 0) {
902:
903: if(exists($ActiveTransactions{$Socket})) {
904: Debug(3, "Lond connection lost, failing transactions");
905: FailTransaction($ActiveTransactions{$Socket});
906: }
907: $Watcher->cancel();
908: KillSocket($Socket);
909: return;
910:
911: }
912:
913: } elsif ($State eq "ReceivingReply") {
914: # The send has completed. Wait for the
915: # data to come in for a reply.
916: Debug(8,"Writable sent request/receiving reply");
917: $Watcher->cb(\&LondReadable);
918: $Watcher->poll("r");
919:
920: } else {
921: # Control only passes here on an error:
922: # the socket state does not match any
923: # of the known states... so an error
924: # must be logged.
925:
926: &Debug(4, "Invalid socket state ".$State."\n");
927: }
928:
929: }
930: =pod
931:
932: =cut
933: sub QueueDelayed {
934: Debug(3,"QueueDelayed called");
935:
936: my $path = "$perlvar{'lonSockDir'}/delayed";
937:
938: Debug(4, "Delayed path: ".$path);
939: opendir(DIRHANDLE, $path);
940:
941: @alldelayed = grep /\.$RemoteHost$/, readdir DIRHANDLE;
942: Debug(4, "Got ".$alldelayed." delayed files");
943: closedir(DIRHANDLE);
944: my $dfname;
945: my $reqfile;
946: foreach $dfname (sort @alldelayed) {
947: $reqfile = "$path/$dfname";
948: Debug(4, "queueing ".$reqfile);
949: my $Handle = IO::File->new($reqfile);
950: my $cmd = <$Handle>;
951: chomp $cmd; # There may or may not be a newline...
952: $cmd = $cmd."\ny"; # now for sure there's exactly one newline.
953: my $Transaction = LondTransaction->new($cmd);
954: $Transaction->SetDeferred($reqfile);
955: QueueTransaction($Transaction);
956: }
957:
958: }
959:
960: =pod
961:
962: =head2 MakeLondConnection
963:
964: Create a new lond connection object, and start it towards its initial
965: idleness. Once idle, it becomes elligible to receive transactions
966: from the work queue. If the work queue is not empty when the
967: connection is completed and becomes idle, it will dequeue an entry and
968: start off on it.
969:
970: =cut
971:
972: sub MakeLondConnection {
973: Debug(4,"MakeLondConnection to ".GetServerHost()." on port "
974: .GetServerPort());
975:
976: my $Connection = LondConnection->new(&GetServerHost(),
977: &GetServerPort());
978:
979: if($Connection == undef) { # Needs to be more robust later.
980: Log("CRITICAL","Failed to make a connection with lond.");
981: } else {
982: # The connection needs to have writability
983: # monitored in order to send the init sequence
984: # that starts the whole authentication/key
985: # exchange underway.
986: #
987: my $Socket = $Connection->GetSocket();
988: if($Socket == undef) {
989: die "did not get a socket from the connection";
990: } else {
991: &Debug(9,"MakeLondConnection got socket: ".$Socket);
992: }
993:
994:
995: $event = Event->io(fd => $Socket,
996: poll => 'w',
997: cb => \&LondWritable,
998: data => $Connection,
999: desc => 'Connection to lond server');
1000: $ActiveConnections{$Connection} = $event;
1001:
1002: $ConnectionCount++;
1003: Debug(4, "Connection count = ".$ConnectionCount);
1004: if($ConnectionCount == 1) { # First Connection:
1005: QueueDelayed;
1006: }
1007: Log("SUCESS", "Created connection ".$ConnectionCount
1008: ." to host ".GetServerHost());
1009: }
1010:
1011: }
1012:
1013: =pod
1014:
1015: =head2 StartRequest
1016:
1017: Starts a lond request going on a specified lond connection.
1018: parameters are:
1019:
1020: =item $Lond
1021:
1022: Connection to the lond that will send the transaction and receive the
1023: reply.
1024:
1025: =item $Client
1026:
1027: Connection to the client that is making this request We got the
1028: request from this socket, and when the request has been relayed to
1029: lond and we get a reply back from lond it will get sent to this
1030: socket.
1031:
1032: =item $Request
1033:
1034: The text of the request to send.
1035:
1036: =cut
1037:
1038: sub StartRequest {
1039: my $Lond = shift;
1040: my $Request = shift; # This is a LondTransaction.
1041:
1042: Debug(6, "StartRequest: ".$Request->getRequest());
1043:
1044: my $Socket = $Lond->GetSocket();
1045:
1046: $Request->Activate($Lond);
1047: $ActiveTransactions{$Lond} = $Request;
1048:
1049: $Lond->InitiateTransaction($Request->getRequest());
1050: $event = Event->io(fd => $Socket,
1051: poll => "w",
1052: cb => \&LondWritable,
1053: data => $Lond,
1054: desc => "lond transaction connection");
1055: $ActiveConnections{$Lond} = $event;
1056: Debug(8," Start Request made watcher data with ".$event->data."\n");
1057: }
1058:
1059: =pod
1060:
1061: =head2 QueueTransaction
1062:
1063: If there is an idle lond connection, it is put to work doing this
1064: transaction. Otherwise, the transaction is placed in the work queue.
1065: If placed in the work queue and the maximum number of connections has
1066: not yet been created, a new connection will be started. Our goal is
1067: to eventually have a sufficient number of connections that the work
1068: queue will typically be empty. parameters are:
1069:
1070: =item Socket
1071:
1072: open on the lonc client.
1073:
1074: =item Request
1075:
1076: data to send to the lond.
1077:
1078: =cut
1079:
1080: sub QueueTransaction {
1081:
1082: my $requestData = shift; # This is a LondTransaction.
1083: my $cmd = $requestData->getRequest();
1084:
1085: Debug(6,"QueueTransaction: ".$cmd);
1086:
1087: my $LondSocket = $IdleConnections->pop();
1088: if(!defined $LondSocket) { # Need to queue request.
1089: Debug(8,"Must queue...");
1090: $WorkQueue->enqueue($requestData);
1091: if($ConnectionCount < $MaxConnectionCount) {
1092: Debug(4,"Starting additional lond connection");
1093: MakeLondConnection();
1094: }
1095: } else { # Can start the request:
1096: Debug(8,"Can start...");
1097: StartRequest($LondSocket, $requestData);
1098: }
1099: }
1100:
1101: #-------------------------- Lonc UNIX socket handling ---------------------
1102:
1103: =pod
1104:
1105: =head2 ClientRequest
1106:
1107: Callback that is called when data can be read from the UNIX domain
1108: socket connecting us with an apache server process.
1109:
1110: =cut
1111:
1112: sub ClientRequest {
1113: Debug(6, "ClientRequest");
1114: my $event = shift;
1115: my $watcher = $event->w;
1116: my $socket = $watcher->fd;
1117: my $data = $watcher->data;
1118: my $thisread;
1119:
1120: Debug(9, " Watcher named: ".$watcher->desc);
1121:
1122: my $rv = $socket->recv($thisread, POSIX::BUFSIZ, 0);
1123: Debug(8, "rcv: data length = ".length($thisread)
1124: ." read =".$thisread);
1125: unless (defined $rv && length($thisread)) {
1126: # Likely eof on socket.
1127: Debug(5,"Client Socket closed on lonc for ".$RemoteHost);
1128: close($socket);
1129: $watcher->cancel();
1130: delete($ActiveClients{$socket});
1131: }
1132: Debug(8,"Data: ".$data." this read: ".$thisread);
1133: $data = $data.$thisread; # Append new data.
1134: $watcher->data($data);
1135: if($data =~ /(.*\n)/) { # Request entirely read.
1136: if($data == "close_connection_exit\n") {
1137: Log("CRITICAL",
1138: "Request Close Connection ... exiting");
1139: CloseAllLondConnections();
1140: exit;
1141: }
1142: Debug(8, "Complete transaction received: ".$data);
1143: my $Transaction = LondTransaction->new($data);
1144: $Transaction->SetClient($socket);
1145: QueueTransaction($Transaction);
1146: $watcher->cancel(); # Done looking for input data.
1147: }
1148:
1149: }
1150:
1151:
1152: =pod
1153:
1154: =head2 NewClient
1155:
1156: Callback that is called when a connection is received on the unix
1157: socket for a new client of lonc. The callback is parameterized by the
1158: event.. which is a-priori assumed to be an io event, and therefore has
1159: an fd member that is the Listener socket. We Accept the connection
1160: and register a new event on the readability of that socket:
1161:
1162: =cut
1163:
1164: sub NewClient {
1165: Debug(6, "NewClient");
1166: my $event = shift; # Get the event parameters.
1167: my $watcher = $event->w;
1168: my $socket = $watcher->fd; # Get the event' socket.
1169: my $connection = $socket->accept(); # Accept the client connection.
1170: Debug(8,"Connection request accepted from "
1171: .GetPeername($connection, AF_UNIX));
1172:
1173:
1174: my $description = sprintf("Connection to lonc client %d",
1175: $ClientConnection);
1176: Debug(9, "Creating event named: ".$description);
1177: Event->io(cb => \&ClientRequest,
1178: poll => 'r',
1179: desc => $description,
1180: data => "",
1181: fd => $connection);
1182: $ActiveClients{$connection} = $ClientConnection;
1183: $ClientConnection++;
1184: }
1185:
1186: =pod
1187:
1188: =head2 GetLoncSocketPath
1189:
1190: Returns the name of the UNIX socket on which to listen for client
1191: connections.
1192:
1193: =cut
1194:
1195: sub GetLoncSocketPath {
1196: return $UnixSocketDir."/".GetServerHost();
1197: }
1198:
1199: =pod
1200:
1201: =head2 GetServerHost
1202:
1203: Returns the host whose lond we talk with.
1204:
1205: =cut
1206:
1207: sub GetServerHost {
1208: return $RemoteHost; # Setup by the fork.
1209: }
1210:
1211: =pod
1212:
1213: =head2 GetServerPort
1214:
1215: Returns the lond port number.
1216:
1217: =cut
1218:
1219: sub GetServerPort {
1220: return $perlvar{londPort};
1221: }
1222:
1223: =pod
1224:
1225: =head2 SetupLoncListener
1226:
1227: Setup a lonc listener event. The event is called when the socket
1228: becomes readable.. that corresponds to the receipt of a new
1229: connection. The event handler established will accept the connection
1230: (creating a communcations channel), that int turn will establish
1231: another event handler to subess requests.
1232:
1233: =cut
1234:
1235: sub SetupLoncListener {
1236:
1237: my $socket;
1238: my $SocketName = GetLoncSocketPath();
1239: unlink($SocketName);
1240: unless ($socket =IO::Socket::UNIX->new(Local => $SocketName,
1241: Listen => 10,
1242: Type => SOCK_STREAM)) {
1243: die "Failed to create a lonc listner socket";
1244: }
1245: Event->io(cb => \&NewClient,
1246: poll => 'r',
1247: desc => 'Lonc listener Unix Socket',
1248: fd => $socket);
1249: }
1250:
1251: =pod
1252:
1253: =head2 ChildProcess
1254:
1255: This sub implements a child process for a single lonc daemon.
1256:
1257: =cut
1258:
1259: sub ChildProcess {
1260:
1261:
1262: # For now turn off signals.
1263:
1264: $SIG{QUIT} = IGNORE;
1265: $SIG{HUP} = IGNORE;
1266: $SIG{USR1} = IGNORE;
1267: $SIG{INT} = IGNORE;
1268: $SIG{CHLD} = IGNORE;
1269: $SIG{__DIE__} = IGNORE;
1270:
1271: SetupTimer();
1272:
1273: SetupLoncListener();
1274:
1275: $Event::Debuglevel = $DebugLevel;
1276:
1277: Debug(9, "Making initial lond connection for ".$RemoteHost);
1278:
1279: # Setup the initial server connection:
1280:
1281: &MakeLondConnection();
1282:
1283: if($ConnectionCount == 0) {
1284: Debug(1,"Could not make initial connection..\n");
1285: Debug(1,"Will retry when there's work to do\n");
1286: }
1287: Debug(9,"Entering event loop");
1288: my $ret = Event::loop(); # Start the main event loop.
1289:
1290:
1291: die "Main event loop exited!!!";
1292: }
1293:
1294: # Create a new child for host passed in:
1295:
1296: sub CreateChild {
1297: my $host = shift;
1298: $RemoteHost = $host;
1299: Log("CRITICAL", "Forking server for ".$host);
1300: $pid = fork;
1301: if($pid) { # Parent
1302: $ChildHash{$pid} = $RemoteHost;
1303: } else { # child.
1304: ShowStatus("Connected to ".$RemoteHost);
1305: ChildProcess;
1306: }
1307:
1308: }
1309: #
1310: # Parent process logic pass 1:
1311: # For each entry in the hosts table, we will
1312: # fork off an instance of ChildProcess to service the transactions
1313: # to that host. Each pid will be entered in a global hash
1314: # with the value of the key, the host.
1315: # The parent will then enter a loop to wait for process exits.
1316: # Each exit gets logged and the child gets restarted.
1317: #
1318:
1319: #
1320: # Fork and start in new session so hang-up isn't going to
1321: # happen without intent.
1322: #
1323:
1324:
1325:
1326:
1327:
1328:
1329: ShowStatus("Forming new session");
1330: my $childpid = fork;
1331: if ($childpid != 0) {
1332: sleep 4; # Give child a chacne to break to
1333: exit 0; # a new sesion.
1334: }
1335: #
1336: # Write my pid into the pid file so I can be located
1337: #
1338:
1339: ShowStatus("Parent writing pid file:");
1340: $execdir = $perlvar{'lonDaemons'};
1341: open (PIDSAVE, ">$execdir/logs/lonc.pid");
1342: print PIDSAVE "$$\n";
1343: close(PIDSAVE);
1344:
1345: if (POSIX::setsid() < 0) {
1346: print "Could not create new session\n";
1347: exit -1;
1348: }
1349:
1350: ShowStatus("Forking node servers");
1351:
1352: Log("CRITICAL", "--------------- Starting children ---------------");
1353:
1354: my $HostIterator = LondConnection::GetHostIterator;
1355: while (! $HostIterator->end()) {
1356:
1357: $hostentryref = $HostIterator->get();
1358: CreateChild($hostentryref->[0]);
1359: $HostIterator->next();
1360: }
1361:
1362: # Maintain the population:
1363:
1364: ShowStatus("Parent keeping the flock");
1365:
1366: while(1) {
1367: $deadchild = wait();
1368: if(exists $ChildHash{$deadchild}) { # need to restart.
1369: $deadhost = $ChildHash{$deadchild};
1370: delete($ChildHash{$deadchild});
1371: Log("WARNING","Lost child pid= ".$deadchild.
1372: "Connected to host ".$deadhost);
1373: Log("INFO", "Restarting child procesing ".$deadhost);
1374: CreateChild($deadhost);
1375: }
1376: }
1377:
1378: =head1 Theory
1379:
1380: The event class is used to build this as a single process with an
1381: event driven model. The following events are handled:
1382:
1383: =item UNIX Socket connection Received
1384:
1385: =item Request data arrives on UNIX data transfer socket.
1386:
1387: =item lond connection becomes writable.
1388:
1389: =item timer fires at 1 second intervals.
1390:
1391: All sockets are run in non-blocking mode. Timeouts managed by the timer
1392: handler prevents hung connections.
1393:
1394: Key data structures:
1395:
1396: =item RequestQueue
1397:
1398: A queue of requests received from UNIX sockets that are
1399: waiting for a chance to be forwarded on a lond connection socket.
1400:
1401: =item ActiveConnections
1402:
1403: A hash of lond connections that have transactions in process that are
1404: available to be timed out.
1405:
1406: =item ActiveTransactions
1407:
1408: A hash indexed by lond connections that contain the client reply
1409: socket for each connection that has an active transaction on it.
1410:
1411: =item IdleConnections
1412:
1413: A hash of lond connections that have no work to do. These connections
1414: can be closed if they are idle for a long enough time.
1415:
1416: =cut
FreeBSD-CVSweb <freebsd-cvsweb@FreeBSD.org>