File:  [LON-CAPA] / loncom / lonsql
Revision 1.66: download - view: text, annotated - select for diffs
Wed Feb 9 20:39:47 2005 UTC (19 years, 2 months ago) by albertel
Branches: MAIN
CVS tags: HEAD
- IP removal from hosts.tab

    1: #!/usr/bin/perl
    2: 
    3: # The LearningOnline Network
    4: # lonsql - LON TCP-MySQL-Server Daemon for handling database requests.
    5: #
    6: # $Id: lonsql,v 1.66 2005/02/09 20:39:47 albertel Exp $
    7: #
    8: # Copyright Michigan State University Board of Trustees
    9: #
   10: # This file is part of the LearningOnline Network with CAPA (LON-CAPA).
   11: #
   12: # LON-CAPA is free software; you can redistribute it and/or modify
   13: # it under the terms of the GNU General Public License as published by
   14: # the Free Software Foundation; either version 2 of the License, or
   15: # (at your option) any later version.
   16: #
   17: # LON-CAPA is distributed in the hope that it will be useful,
   18: # but WITHOUT ANY WARRANTY; without even the implied warranty of
   19: # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
   20: # GNU General Public License for more details.
   21: #
   22: # You should have received a copy of the GNU General Public License
   23: # along with LON-CAPA; if not, write to the Free Software
   24: # Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA
   25: #
   26: # /home/httpd/html/adm/gpl.txt
   27: #
   28: # http://www.lon-capa.org/
   29: #
   30: 
   31: =pod
   32: 
   33: =head1 NAME
   34: 
   35: lonsql - LON TCP-MySQL-Server Daemon for handling database requests.
   36: 
   37: =head1 SYNOPSIS
   38: 
   39: This script should be run as user=www.  
   40: Note that a lonsql.pid file contains the pid of the parent process.
   41: 
   42: =head1 OVERVIEW
   43: 
   44: =head2 Purpose within LON-CAPA
   45: 
   46: LON-CAPA is meant to distribute A LOT of educational content to A LOT
   47: of people. It is ineffective to directly rely on contents within the
   48: ext2 filesystem to be speedily scanned for on-the-fly searches of
   49: content descriptions. (Simply put, it takes a cumbersome amount of
   50: time to open, read, analyze, and close thousands of files.)
   51: 
   52: The solution is to index various data fields that are descriptive of
   53: the educational resources on a LON-CAPA server machine in a
   54: database. Descriptive data fields are referred to as "metadata". The
   55: question then arises as to how this metadata is handled in terms of
   56: the rest of the LON-CAPA network without burdening client and daemon
   57: processes.
   58: 
   59: The obvious solution, using lonc to send a query to a lond process,
   60: doesn't work so well in general as you can see in the following
   61: example:
   62: 
   63:     lonc= loncapa client process    A-lonc= a lonc process on Server A
   64:     lond= loncapa daemon process
   65: 
   66:                  database command
   67:     A-lonc  --------TCP/IP----------------> B-lond
   68: 
   69: The problem emerges that A-lonc and B-lond are kept waiting for the
   70: MySQL server to "do its stuff", or in other words, perform the
   71: conceivably sophisticated, data-intensive, time-sucking database
   72: transaction.  By tying up a lonc and lond process, this significantly
   73: cripples the capabilities of LON-CAPA servers.
   74: 
   75: The solution is to offload the work onto another process, and use
   76: lonc and lond just for requests and notifications of completed
   77: processing:
   78: 
   79:                 database command
   80: 
   81:   A-lonc  ---------TCP/IP-----------------> B-lond =====> B-lonsql
   82:          <---------------------------------/                |
   83:            "ok, I'll get back to you..."                    |
   84:                                                             |
   85:                                                             /
   86:   A-lond  <-------------------------------  B-lonc   <======
   87:            "Guess what? I have the result!"
   88: 
   89: Of course, depending on success or failure, the messages may vary, but
   90: the principle remains the same where a separate pool of children
   91: processes (lonsql's) handle the MySQL database manipulations.
   92: 
   93: Thus, lonc and lond spend effectively no time waiting on results from
   94: the database.
   95: 
   96: =head1 Internals
   97: 
   98: =over 4
   99: 
  100: =cut
  101: 
  102: use strict;
  103: 
  104: use lib '/home/httpd/lib/perl/';
  105: use LONCAPA::Configuration;
  106: use LONCAPA::lonmetadata();
  107: 
  108: use IO::Socket;
  109: use Symbol;
  110: use POSIX;
  111: use IO::Select;
  112: use IO::File;
  113: use Socket;
  114: use Fcntl;
  115: use Tie::RefHash;
  116: use DBI;
  117: use File::Find;
  118: use localenroll;
  119: 
  120: ########################################################
  121: ########################################################
  122: 
  123: =pod
  124: 
  125: =item Global Variables
  126: 
  127: =over 4
  128: 
  129: =item dbh
  130: 
  131: =back
  132: 
  133: =cut
  134: 
  135: ########################################################
  136: ########################################################
  137: my $dbh;
  138: 
  139: ########################################################
  140: ########################################################
  141: 
  142: =pod 
  143: 
  144: =item Variables required for forking
  145: 
  146: =over 4
  147: 
  148: =item $MAX_CLIENTS_PER_CHILD
  149: 
  150: The number of clients each child should process.
  151: 
  152: =item %children 
  153: 
  154: The keys to %children  are the current child process IDs
  155: 
  156: =item $children
  157: 
  158: The current number of children
  159: 
  160: =back
  161: 
  162: =cut 
  163: 
  164: ########################################################
  165: ########################################################
  166: my $MAX_CLIENTS_PER_CHILD  = 5;   # number of clients each child should process
  167: my %children               = ();  # keys are current child process IDs
  168: my $children               = 0;   # current number of children
  169:                                
  170: ###################################################################
  171: ###################################################################
  172: 
  173: =pod
  174: 
  175: =item Main body of code.
  176: 
  177: =over 4
  178: 
  179: =item Read data from loncapa_apache.conf and loncapa.conf.
  180: 
  181: =item Ensure we can access the database.
  182: 
  183: =item Determine if there are other instances of lonsql running.
  184: 
  185: =item Read the hosts file.
  186: 
  187: =item Create a socket for lonsql.
  188: 
  189: =item Fork once and dissociate from parent.
  190: 
  191: =item Write PID to disk.
  192: 
  193: =item Prefork children and maintain the population of children.
  194: 
  195: =back
  196: 
  197: =cut
  198: 
  199: ###################################################################
  200: ###################################################################
  201: my $childmaxattempts=10;
  202: my $run =0;              # running counter to generate the query-id
  203: #
  204: # Read loncapa_apache.conf and loncapa.conf
  205: #
  206: my $perlvarref=LONCAPA::Configuration::read_conf('loncapa.conf');
  207: my %perlvar=%{$perlvarref};
  208: #
  209: # Write the /home/www/.my.cnf file 
  210: my $conf_file = '/home/www/.my.cnf';
  211: if (! -e $conf_file) {
  212:     if (open MYCNF, ">$conf_file") {
  213:         print MYCNF <<"ENDMYCNF";
  214: [client]
  215: user=www
  216: password=$perlvar{'lonSqlAccess'}
  217: ENDMYCNF
  218:         close MYCNF;
  219:     } else {
  220:         warn "Unable to write $conf_file, continuing";
  221:     }
  222: }
  223: 
  224: 
  225: #
  226: # Make sure that database can be accessed
  227: #
  228: my $dbh;
  229: unless ($dbh = DBI->connect("DBI:mysql:loncapa","www",
  230:                             $perlvar{'lonSqlAccess'},
  231:                             { RaiseError =>0,PrintError=>0})) { 
  232:     print "Cannot connect to database!\n";
  233:     my $emailto="$perlvar{'lonAdmEMail'},$perlvar{'lonSysEMail'}";
  234:     my $subj="LON: $perlvar{'lonHostID'} Cannot connect to database!";
  235:     system("echo 'Cannot connect to MySQL database!' |".
  236:            " mailto $emailto -s '$subj' > /dev/null");
  237: 
  238:     open(SMP,'>/home/httpd/html/lon-status/mysql.txt');
  239:     print SMP 'time='.time.'&mysql=defunct'."\n";
  240:     close(SMP);
  241: 
  242:     exit 1;
  243: } else {
  244:     $dbh->disconnect;
  245: }
  246: 
  247: #
  248: # Check if other instance running
  249: #
  250: my $pidfile="$perlvar{'lonDaemons'}/logs/lonsql.pid";
  251: if (-e $pidfile) {
  252:    my $lfh=IO::File->new("$pidfile");
  253:    my $pide=<$lfh>;
  254:    chomp($pide);
  255:    if (kill 0 => $pide) { die "already running"; }
  256: }
  257: 
  258: #
  259: # Read hosts file
  260: #
  261: my $thisserver;
  262: my $PREFORK=4; # number of children to maintain, at least four spare
  263: open (CONFIG,"$perlvar{'lonTabDir'}/hosts.tab") || die "Can't read host file";
  264: while (my $configline=<CONFIG>) {
  265:     my ($id,$domain,$role,$name)=split(/:/,$configline);
  266:     $name=~s/\s//g;
  267:     $thisserver=$name if ($id eq $perlvar{'lonHostID'});
  268:     #$PREFORK++;
  269: }
  270: close(CONFIG);
  271: #
  272: #$PREFORK=int($PREFORK/4);
  273: 
  274: #
  275: # Create a socket to talk to lond
  276: #
  277: my $unixsock = "mysqlsock";
  278: my $localfile="$perlvar{'lonSockDir'}/$unixsock";
  279: my $server;
  280: unlink ($localfile);
  281: unless ($server=IO::Socket::UNIX->new(Local    =>"$localfile",
  282:                                       Type    => SOCK_STREAM,
  283:                                       Listen => 10)) {
  284:     print "in socket error:$@\n";
  285: }
  286: 
  287: #
  288: # Fork once and dissociate
  289: #
  290: my $fpid=fork;
  291: exit if $fpid;
  292: die "Couldn't fork: $!" unless defined ($fpid);
  293: POSIX::setsid() or die "Can't start new session: $!";
  294: 
  295: #
  296: # Write our PID on disk
  297: my $execdir=$perlvar{'lonDaemons'};
  298: open (PIDSAVE,">$execdir/logs/lonsql.pid");
  299: print PIDSAVE "$$\n";
  300: close(PIDSAVE);
  301: &logthis("<font color='red'>CRITICAL: ---------- Starting ----------</font>");
  302: 
  303: #
  304: # Ignore signals generated during initial startup
  305: $SIG{HUP}=$SIG{USR1}='IGNORE';
  306: # Now we are on our own    
  307: #    Fork off our children.
  308: for (1 .. $PREFORK) {
  309:     make_new_child();
  310: }
  311: 
  312: #
  313: # Install signal handlers.
  314: $SIG{CHLD} = \&REAPER;
  315: $SIG{INT}  = $SIG{TERM} = \&HUNTSMAN;
  316: $SIG{HUP}  = \&HUPSMAN;
  317: 
  318: #
  319: # And maintain the population.
  320: while (1) {
  321:     sleep;                          # wait for a signal (i.e., child's death)
  322:     for (my $i = $children; $i < $PREFORK; $i++) {
  323:         make_new_child();           # top up the child pool
  324:     }
  325: }
  326: 
  327: ########################################################
  328: ########################################################
  329: 
  330: =pod
  331: 
  332: =item &make_new_child
  333: 
  334: Inputs: None
  335: 
  336: Returns: None
  337: 
  338: =cut
  339: 
  340: ########################################################
  341: ########################################################
  342: sub make_new_child {
  343:     my $pid;
  344:     my $sigset;
  345:     #
  346:     # block signal for fork
  347:     $sigset = POSIX::SigSet->new(SIGINT);
  348:     sigprocmask(SIG_BLOCK, $sigset)
  349:         or die "Can't block SIGINT for fork: $!\n";
  350:     #
  351:     die "fork: $!" unless defined ($pid = fork);
  352:     #
  353:     if ($pid) {
  354:         # Parent records the child's birth and returns.
  355:         sigprocmask(SIG_UNBLOCK, $sigset)
  356:             or die "Can't unblock SIGINT for fork: $!\n";
  357:         $children{$pid} = 1;
  358:         $children++;
  359:         return;
  360:     } else {
  361:         # Child can *not* return from this subroutine.
  362:         $SIG{INT} = 'DEFAULT';      # make SIGINT kill us as it did before
  363:         # unblock signals
  364:         sigprocmask(SIG_UNBLOCK, $sigset)
  365:             or die "Can't unblock SIGINT for fork: $!\n";
  366:         #open database handle
  367: 	# making dbh global to avoid garbage collector
  368: 	unless ($dbh = DBI->connect("DBI:mysql:loncapa","www",
  369:                                     $perlvar{'lonSqlAccess'},
  370:                                     { RaiseError =>0,PrintError=>0})) { 
  371:             sleep(10+int(rand(20)));
  372:             &logthis("<font color='blue'>WARNING: Couldn't connect to database".
  373:                      ": $@</font>");
  374:                      #  "($st secs): $@</font>");
  375:             print "database handle error\n";
  376:             exit;
  377:         }
  378: 	# make sure that a database disconnection occurs with 
  379:         # ending kill signals
  380: 	$SIG{TERM}=$SIG{INT}=$SIG{QUIT}=$SIG{__DIE__}=\&DISCONNECT;
  381:         # handle connections until we've reached $MAX_CLIENTS_PER_CHILD
  382:         for (my $i=0; $i < $MAX_CLIENTS_PER_CHILD; $i++) {
  383:             my $client = $server->accept() or last;
  384:             # do something with the connection
  385: 	    $run = $run+1;
  386: 	    my $userinput = <$client>;
  387: 	    chomp($userinput);
  388:             #
  389: 	    my ($conserver,$query,
  390: 		$arg1,$arg2,$arg3)=split(/&/,$userinput);
  391: 	    my $query=unescape($query);
  392:             #
  393:             #send query id which is pid_unixdatetime_runningcounter
  394: 	    my $queryid = $thisserver;
  395: 	    $queryid .="_".($$)."_";
  396: 	    $queryid .= time."_";
  397: 	    $queryid .= $run;
  398: 	    print $client "$queryid\n";
  399: 	    #
  400: 	    # &logthis("QUERY: $query - $arg1 - $arg2 - $arg3");
  401: 	    sleep 1;
  402:             #
  403:             my $result='';
  404:             #
  405:             # At this point, query is received, query-ID assigned and sent 
  406:             # back, $query eq 'logquery' will mean that this is a query 
  407:             # against log-files
  408:             if (($query eq 'userlog') || ($query eq 'courselog')) {
  409:                 # beginning of log query
  410:                 my $udom    = &unescape($arg1);
  411:                 my $uname   = &unescape($arg2);
  412:                 my $command = &unescape($arg3);
  413:                 my $path    = &propath($udom,$uname);
  414:                 if (-e "$path/activity.log") {
  415:                     if ($query eq 'userlog') {
  416:                         $result=&userlog($path,$command);
  417:                     } else {
  418:                         $result=&courselog($path,$command);
  419:                     }
  420:                 } else {
  421:                     &logthis('Unable to do log query: '.$uname.'@'.$udom);
  422:                     $result='no_such_file';
  423:                 }
  424:                 # end of log query
  425:             } elsif ($query eq 'fetchenrollment') {
  426:                 # retrieve institutional class lists
  427:                 my $dom = &unescape($arg1);
  428:                 my %affiliates = ();
  429:                 my %replies = ();
  430:                 my $locresult = '';
  431:                 my $querystr = &unescape($arg3);
  432:                 foreach (split/%%/,$querystr) {
  433:                     if (/^(\w+)=([^=]+)$/) {
  434:                         @{$affiliates{$1}} = split/,/,$2;
  435:                     }
  436:                 }
  437:                 $locresult = &localenroll::fetch_enrollment($dom,\%affiliates,\%replies);
  438:                 $result = &escape($locresult.':');
  439:                 if ($locresult) {
  440:                     $result .= &escape(join(':',map{$_.'='.$replies{$_}} keys %replies));
  441:                 }
  442:             } elsif ($query eq 'prepare activity log') {
  443:                 my ($cid,$domain) = map {&unescape($_);} ($arg1,$arg2);
  444:                 &logthis('preparing activity log tables for '.$cid);
  445:                 my $command = 
  446:                     qq{$perlvar{'lonDaemons'}/parse_activity_log.pl -course=$cid -domain=$domain};
  447:                 system($command);
  448:                 &logthis($command);
  449:                 my $returnvalue = $?>>8;
  450:                 if ($returnvalue) {
  451:                     $result = 'error: parse_activity_log.pl returned '.
  452:                         $returnvalue;
  453:                 } else {
  454:                     $result = 'success';
  455:                 }
  456:             } else {
  457:                 # Do an sql query
  458:                 $result = &do_sql_query($query,$arg1,$arg2);
  459:             }
  460:             # result does not need to be escaped because it has already been
  461:             # escaped.
  462:             #$result=&escape($result);
  463:             &reply("queryreply:$queryid:$result",$conserver);
  464:         }
  465:         # tidy up gracefully and finish
  466:         #
  467:         # close the database handle
  468: 	$dbh->disconnect
  469:             or &logthis("<font color='blue'>WARNING: Couldn't disconnect".
  470:                         " from database  $DBI::errstr : $@</font>");
  471:         # this exit is VERY important, otherwise the child will become
  472:         # a producer of more and more children, forking yourself into
  473:         # process death.
  474:         exit;
  475:     }
  476: }
  477: 
  478: ########################################################
  479: ########################################################
  480: 
  481: =pod
  482: 
  483: =item &do_sql_query
  484: 
  485: Runs an sql metadata table query.
  486: 
  487: Inputs: $query, $custom, $customshow
  488: 
  489: Returns: A string containing escaped results.
  490: 
  491: =cut
  492: 
  493: ########################################################
  494: ########################################################
  495: {
  496:     my @metalist;
  497: 
  498: sub process_file {
  499:     if ( -e $_ &&  # file exists
  500:          -f $_ &&  # and is a normal file
  501:          /\.meta$/ &&  # ends in meta
  502:          ! /^.+\.\d+\.[^\.]+\.meta$/  # is not a previous version
  503:          ) {
  504:         push(@metalist,$File::Find::name);
  505:     }
  506: }
  507: 
  508: sub do_sql_query {
  509:     my ($query,$custom,$customshow) = @_;
  510:     &logthis('doing query '.$query);
  511:     $custom     = &unescape($custom);
  512:     $customshow = &unescape($customshow);
  513:     #
  514:     @metalist = ();
  515:     #
  516:     my $result = '';
  517:     my @results = ();
  518:     my @files;
  519:     my $subsetflag=0;
  520:     #
  521:     if ($query) {
  522:         #prepare and execute the query
  523:         my $sth = $dbh->prepare($query);
  524:         unless ($sth->execute()) {
  525:             &logthis('<font color="blue">'.
  526:                      'WARNING: Could not retrieve from database:'.
  527:                      $sth->errstr().'</font>');
  528:         } else {
  529:             my $aref=$sth->fetchall_arrayref;
  530:             foreach my $row (@$aref) {
  531:                 push @files,@{$row}[3] if ($custom or $customshow);
  532:                 my @b=map { &escape($_); } @$row;
  533:                 push @results,join(",", @b);
  534:                 # Build up the @files array with the LON-CAPA urls 
  535:                 # of the resources.
  536:             }
  537:         }
  538:     }
  539:     # do custom metadata searching here and build into result
  540:     return join("&",@results) if (! ($custom or $customshow));
  541:     # Only get here if there is a custom query or custom show request
  542:     &logthis("Doing custom query for $custom");
  543:     if ($query) {
  544:         @metalist=map {
  545:             $perlvar{'lonDocRoot'}.$_.'.meta';
  546:         } @files;
  547:     } else {
  548:         my $dir = "$perlvar{'lonDocRoot'}/res/$perlvar{'lonDefDomain'}";
  549:         @metalist=(); 
  550:         opendir(RESOURCES,$dir);
  551:         my @homeusers=grep {
  552:             &ishome($dir.'/'.$_);
  553:         } grep {!/^\.\.?$/} readdir(RESOURCES);
  554:         closedir RESOURCES;
  555:         # Define the
  556:         foreach my $user (@homeusers) {
  557:             find (\&process_file,$dir.'/'.$user);
  558:         }
  559:     } 
  560:     # if file is indicated in sql database and
  561:     #     not part of sql-relevant query, do not pattern match.
  562:     #
  563:     # if file is not in sql database, output error.
  564:     #
  565:     # if file is indicated in sql database and is
  566:     #     part of query result list, then do the pattern match.
  567:     my $customresult='';
  568:     my @results;
  569:     foreach my $metafile (@metalist) {
  570:         my $fh=IO::File->new($metafile);
  571:         my @lines=<$fh>;
  572:         my $stuff=join('',@lines);
  573:         if ($stuff=~/$custom/s) {
  574:             foreach my $f ('abstract','author','copyright',
  575:                            'creationdate','keywords','language',
  576:                            'lastrevisiondate','mime','notes',
  577:                            'owner','subject','title') {
  578:                 $stuff=~s/\n?\<$f[^\>]*\>.*?<\/$f[^\>]*\>\n?//s;
  579:             }
  580:             my $mfile=$metafile; 
  581:             my $docroot=$perlvar{'lonDocRoot'};
  582:             $mfile=~s/^$docroot//;
  583:             $mfile=~s/\.meta$//;
  584:             unless ($query) {
  585:                 my $q2="SELECT * FROM metadata WHERE url ".
  586:                     " LIKE BINARY '?'";
  587:                 my $sth = $dbh->prepare($q2);
  588:                 $sth->execute($mfile);
  589:                 my $aref=$sth->fetchall_arrayref;
  590:                 foreach my $a (@$aref) {
  591:                     my @b=map { &escape($_)} @$a;
  592:                     push @results,join(",", @b);
  593:                 }
  594:             }
  595:             # &logthis("found: $stuff");
  596:             $customresult.='&custom='.&escape($mfile).','.
  597:                 escape($stuff);
  598:         }
  599:     }
  600:     $result=join("&",@results) unless $query;
  601:     $result.=$customresult;
  602:     #
  603:     return $result;
  604: } # End of &do_sql_query
  605: 
  606: } # End of scoping curly braces for &process_file and &do_sql_query
  607: ########################################################
  608: ########################################################
  609: 
  610: =pod
  611: 
  612: =item &logthis
  613: 
  614: Inputs: $message, the message to log
  615: 
  616: Returns: nothing
  617: 
  618: Writes $message to the logfile.
  619: 
  620: =cut
  621: 
  622: ########################################################
  623: ########################################################
  624: sub logthis {
  625:     my $message=shift;
  626:     my $execdir=$perlvar{'lonDaemons'};
  627:     my $fh=IO::File->new(">>$execdir/logs/lonsql.log");
  628:     my $now=time;
  629:     my $local=localtime($now);
  630:     print $fh "$local ($$): $message\n";
  631: }
  632: 
  633: # -------------------------------------------------- Non-critical communication
  634: 
  635: ########################################################
  636: ########################################################
  637: 
  638: =pod
  639: 
  640: =item &subreply
  641: 
  642: Sends a command to a server.  Called only by &reply.
  643: 
  644: Inputs: $cmd,$server
  645: 
  646: Returns: The results of the message or 'con_lost' on error.
  647: 
  648: =cut
  649: 
  650: ########################################################
  651: ########################################################
  652: sub subreply {
  653:     my ($cmd,$server)=@_;
  654:     my $peerfile="$perlvar{'lonSockDir'}/$server";
  655:     my $sclient=IO::Socket::UNIX->new(Peer    =>"$peerfile",
  656:                                       Type    => SOCK_STREAM,
  657:                                       Timeout => 10)
  658:        or return "con_lost";
  659:     print $sclient "$cmd\n";
  660:     my $answer=<$sclient>;
  661:     chomp($answer);
  662:     $answer="con_lost" if (!$answer);
  663:     return $answer;
  664: }
  665: 
  666: ########################################################
  667: ########################################################
  668: 
  669: =pod
  670: 
  671: =item &reply
  672: 
  673: Sends a command to a server.
  674: 
  675: Inputs: $cmd,$server
  676: 
  677: Returns: The results of the message or 'con_lost' on error.
  678: 
  679: =cut
  680: 
  681: ########################################################
  682: ########################################################
  683: sub reply {
  684:   my ($cmd,$server)=@_;
  685:   my $answer;
  686:   if ($server ne $perlvar{'lonHostID'}) { 
  687:     $answer=subreply($cmd,$server);
  688:     if ($answer eq 'con_lost') {
  689: 	$answer=subreply("ping",$server);
  690:         $answer=subreply($cmd,$server);
  691:     }
  692:   } else {
  693:     $answer='self_reply';
  694:     $answer=subreply($cmd,$server);
  695:   } 
  696:   return $answer;
  697: }
  698: 
  699: ########################################################
  700: ########################################################
  701: 
  702: =pod
  703: 
  704: =item &escape
  705: 
  706: Escape special characters in a string.
  707: 
  708: Inputs: string to escape
  709: 
  710: Returns: The input string with special characters escaped.
  711: 
  712: =cut
  713: 
  714: ########################################################
  715: ########################################################
  716: sub escape {
  717:     my $str=shift;
  718:     $str =~ s/(\W)/"%".unpack('H2',$1)/eg;
  719:     return $str;
  720: }
  721: 
  722: ########################################################
  723: ########################################################
  724: 
  725: =pod
  726: 
  727: =item &unescape
  728: 
  729: Unescape special characters in a string.
  730: 
  731: Inputs: string to unescape
  732: 
  733: Returns: The input string with special characters unescaped.
  734: 
  735: =cut
  736: 
  737: ########################################################
  738: ########################################################
  739: sub unescape {
  740:     my $str=shift;
  741:     $str =~ s/%([a-fA-F0-9][a-fA-F0-9])/pack("C",hex($1))/eg;
  742:     return $str;
  743: }
  744: 
  745: ########################################################
  746: ########################################################
  747: 
  748: =pod
  749: 
  750: =item &ishome
  751: 
  752: Determine if the current machine is the home server for a user.
  753: The determination is made by checking the filesystem for the users information.
  754: 
  755: Inputs: $author
  756: 
  757: Returns: 0 - this is not the authors home server, 1 - this is.
  758: 
  759: =cut
  760: 
  761: ########################################################
  762: ########################################################
  763: sub ishome {
  764:     my $author=shift;
  765:     $author=~s/\/home\/httpd\/html\/res\/([^\/]*)\/([^\/]*).*/$1\/$2/;
  766:     my ($udom,$uname)=split(/\//,$author);
  767:     my $proname=propath($udom,$uname);
  768:     if (-e $proname) {
  769: 	return 1;
  770:     } else {
  771:         return 0;
  772:     }
  773: }
  774: 
  775: ########################################################
  776: ########################################################
  777: 
  778: =pod
  779: 
  780: =item &propath
  781: 
  782: Inputs: user name, user domain
  783: 
  784: Returns: The full path to the users directory.
  785: 
  786: =cut
  787: 
  788: ########################################################
  789: ########################################################
  790: sub propath {
  791:     my ($udom,$uname)=@_;
  792:     $udom=~s/\W//g;
  793:     $uname=~s/\W//g;
  794:     my $subdir=$uname.'__';
  795:     $subdir =~ s/(.)(.)(.).*/$1\/$2\/$3/;
  796:     my $proname="$perlvar{'lonUsersDir'}/$udom/$subdir/$uname";
  797:     return $proname;
  798: } 
  799: 
  800: ########################################################
  801: ########################################################
  802: 
  803: =pod
  804: 
  805: =item &courselog
  806: 
  807: Inputs: $path, $command
  808: 
  809: Returns: unescaped string of values.
  810: 
  811: =cut
  812: 
  813: ########################################################
  814: ########################################################
  815: sub courselog {
  816:     my ($path,$command)=@_;
  817:     my %filters=();
  818:     foreach (split(/\:/,&unescape($command))) {
  819: 	my ($name,$value)=split(/\=/,$_);
  820:         $filters{$name}=$value;
  821:     }
  822:     my @results=();
  823:     open(IN,$path.'/activity.log') or return ('file_error');
  824:     while (my $line=<IN>) {
  825:         chomp($line);
  826:         my ($timestamp,$host,$log)=split(/\:/,$line);
  827: #
  828: # $log has the actual log entries; currently still escaped, and
  829: # %26(timestamp)%3a(url)%3a(user)%3a(domain)
  830: # then additionally
  831: # %3aPOST%3a(name)%3d(value)%3a(name)%3d(value)
  832: # or
  833: # %3aCSTORE%3a(name)%3d(value)%26(name)%3d(value)
  834: #
  835: # get delimiter between timestamped entries to be &&&
  836:         $log=~s/\%26(\d+)\%3a/\&\&\&$1\%3a/g;
  837: # now go over all log entries 
  838:         foreach (split(/\&\&\&/,&unescape($log))) {
  839: 	    my ($time,$res,$uname,$udom,$action,@values)=split(/\:/,$_);
  840:             my $values=&unescape(join(':',@values));
  841:             $values=~s/\&/\:/g;
  842:             $res=&unescape($res);
  843:             my $include=1;
  844:             if (($filters{'username'}) && ($uname ne $filters{'username'})) 
  845:                                                                { $include=0; }
  846:             if (($filters{'domain'}) && ($udom ne $filters{'domain'})) 
  847:                                                                { $include=0; }
  848:             if (($filters{'url'}) && ($res!~/$filters{'url'}/)) 
  849:                                                                { $include=0; }
  850:             if (($filters{'start'}) && ($time<$filters{'start'})) 
  851:                                                                { $include=0; }
  852:             if (($filters{'end'}) && ($time>$filters{'end'})) 
  853:                                                                { $include=0; }
  854:             if (($filters{'action'} eq 'view') && ($action)) 
  855:                                                                { $include=0; }
  856:             if (($filters{'action'} eq 'submit') && ($action ne 'POST')) 
  857:                                                                { $include=0; }
  858:             if (($filters{'action'} eq 'grade') && ($action ne 'CSTORE')) 
  859:                                                                { $include=0; }
  860:             if ($include) {
  861: 	       push(@results,($time<1000000000?'0':'').$time.':'.$res.':'.
  862:                                             $uname.':'.$udom.':'.
  863:                                             $action.':'.$values);
  864:             }
  865:        }
  866:     }
  867:     close IN;
  868:     return join('&',sort(@results));
  869: }
  870: 
  871: ########################################################
  872: ########################################################
  873: 
  874: =pod
  875: 
  876: =item &userlog
  877: 
  878: Inputs: $path, $command
  879: 
  880: Returns: unescaped string of values.
  881: 
  882: =cut
  883: 
  884: ########################################################
  885: ########################################################
  886: sub userlog {
  887:     my ($path,$command)=@_;
  888:     my %filters=();
  889:     foreach (split(/\:/,&unescape($command))) {
  890: 	my ($name,$value)=split(/\=/,$_);
  891:         $filters{$name}=$value;
  892:     }
  893:     my @results=();
  894:     open(IN,$path.'/activity.log') or return ('file_error');
  895:     while (my $line=<IN>) {
  896:         chomp($line);
  897:         my ($timestamp,$host,$log)=split(/\:/,$line);
  898:         $log=&unescape($log);
  899:         my $include=1;
  900:         if (($filters{'start'}) && ($timestamp<$filters{'start'})) 
  901:                                                              { $include=0; }
  902:         if (($filters{'end'}) && ($timestamp>$filters{'end'})) 
  903:                                                              { $include=0; }
  904:         if (($filters{'action'} eq 'log') && ($log!~/^Log/)) { $include=0; }
  905:         if (($filters{'action'} eq 'check') && ($log!~/^Check/)) 
  906:                                                              { $include=0; }
  907:         if ($include) {
  908: 	   push(@results,$timestamp.':'.$log);
  909:         }
  910:     }
  911:     close IN;
  912:     return join('&',sort(@results));
  913: }
  914: 
  915: ########################################################
  916: ########################################################
  917: 
  918: =pod
  919: 
  920: =item Functions required for forking
  921: 
  922: =over 4
  923: 
  924: =item REAPER
  925: 
  926: REAPER takes care of dead children.
  927: 
  928: =item HUNTSMAN
  929: 
  930: Signal handler for SIGINT.
  931: 
  932: =item HUPSMAN
  933: 
  934: Signal handler for SIGHUP
  935: 
  936: =item DISCONNECT
  937: 
  938: Disconnects from database.
  939: 
  940: =back
  941: 
  942: =cut
  943: 
  944: ########################################################
  945: ########################################################
  946: sub REAPER {                   # takes care of dead children
  947:     $SIG{CHLD} = \&REAPER;
  948:     my $pid = wait;
  949:     $children --;
  950:     &logthis("Child $pid died");
  951:     delete $children{$pid};
  952: }
  953: 
  954: sub HUNTSMAN {                      # signal handler for SIGINT
  955:     local($SIG{CHLD}) = 'IGNORE';   # we're going to kill our children
  956:     kill 'INT' => keys %children;
  957:     my $execdir=$perlvar{'lonDaemons'};
  958:     unlink("$execdir/logs/lonsql.pid");
  959:     &logthis("<font color='red'>CRITICAL: Shutting down</font>");
  960:     $unixsock = "mysqlsock";
  961:     my $port="$perlvar{'lonSockDir'}/$unixsock";
  962:     unlink($port);
  963:     exit;                           # clean up with dignity
  964: }
  965: 
  966: sub HUPSMAN {                      # signal handler for SIGHUP
  967:     local($SIG{CHLD}) = 'IGNORE';  # we're going to kill our children
  968:     kill 'INT' => keys %children;
  969:     close($server);                # free up socket
  970:     &logthis("<font color='red'>CRITICAL: Restarting</font>");
  971:     my $execdir=$perlvar{'lonDaemons'};
  972:     $unixsock = "mysqlsock";
  973:     my $port="$perlvar{'lonSockDir'}/$unixsock";
  974:     unlink($port);
  975:     exec("$execdir/lonsql");         # here we go again
  976: }
  977: 
  978: sub DISCONNECT {
  979:     $dbh->disconnect or 
  980:     &logthis("<font color='blue'>WARNING: Couldn't disconnect from database ".
  981:              " $DBI::errstr : $@</font>");
  982:     exit;
  983: }
  984: 
  985: 
  986: =pod
  987: 
  988: =back
  989: 
  990: =cut

FreeBSD-CVSweb <freebsd-cvsweb@FreeBSD.org>