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