File:  [LON-CAPA] / loncom / lonsql
Revision 1.65: download - view: text, annotated - select for diffs
Thu Aug 26 19:29:09 2004 UTC (19 years, 8 months ago) by albertel
Branches: MAIN
CVS tags: version_1_3_X, version_1_3_3, version_1_3_2, version_1_3_1, version_1_3_0, version_1_2_X, version_1_2_99_1, version_1_2_99_0, version_1_2_1, version_1_2_0, HEAD
-  4 is enough

    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.65 2004/08/26 19:29:09 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 %hostip;
  262: my $thisserver;
  263: my $PREFORK=4; # number of children to maintain, at least four spare
  264: open (CONFIG,"$perlvar{'lonTabDir'}/hosts.tab") || die "Can't read host file";
  265: while (my $configline=<CONFIG>) {
  266:     my ($id,$domain,$role,$name,$ip)=split(/:/,$configline);
  267:     chomp($ip);
  268:     $hostip{$ip}=$id;
  269:     $thisserver=$name if ($id eq $perlvar{'lonHostID'});
  270:     #$PREFORK++;
  271: }
  272: close(CONFIG);
  273: #
  274: #$PREFORK=int($PREFORK/4);
  275: 
  276: #
  277: # Create a socket to talk to lond
  278: #
  279: my $unixsock = "mysqlsock";
  280: my $localfile="$perlvar{'lonSockDir'}/$unixsock";
  281: my $server;
  282: unlink ($localfile);
  283: unless ($server=IO::Socket::UNIX->new(Local    =>"$localfile",
  284:                                       Type    => SOCK_STREAM,
  285:                                       Listen => 10)) {
  286:     print "in socket error:$@\n";
  287: }
  288: 
  289: #
  290: # Fork once and dissociate
  291: #
  292: my $fpid=fork;
  293: exit if $fpid;
  294: die "Couldn't fork: $!" unless defined ($fpid);
  295: POSIX::setsid() or die "Can't start new session: $!";
  296: 
  297: #
  298: # Write our PID on disk
  299: my $execdir=$perlvar{'lonDaemons'};
  300: open (PIDSAVE,">$execdir/logs/lonsql.pid");
  301: print PIDSAVE "$$\n";
  302: close(PIDSAVE);
  303: &logthis("<font color='red'>CRITICAL: ---------- Starting ----------</font>");
  304: 
  305: #
  306: # Ignore signals generated during initial startup
  307: $SIG{HUP}=$SIG{USR1}='IGNORE';
  308: # Now we are on our own    
  309: #    Fork off our children.
  310: for (1 .. $PREFORK) {
  311:     make_new_child();
  312: }
  313: 
  314: #
  315: # Install signal handlers.
  316: $SIG{CHLD} = \&REAPER;
  317: $SIG{INT}  = $SIG{TERM} = \&HUNTSMAN;
  318: $SIG{HUP}  = \&HUPSMAN;
  319: 
  320: #
  321: # And maintain the population.
  322: while (1) {
  323:     sleep;                          # wait for a signal (i.e., child's death)
  324:     for (my $i = $children; $i < $PREFORK; $i++) {
  325:         make_new_child();           # top up the child pool
  326:     }
  327: }
  328: 
  329: ########################################################
  330: ########################################################
  331: 
  332: =pod
  333: 
  334: =item &make_new_child
  335: 
  336: Inputs: None
  337: 
  338: Returns: None
  339: 
  340: =cut
  341: 
  342: ########################################################
  343: ########################################################
  344: sub make_new_child {
  345:     my $pid;
  346:     my $sigset;
  347:     #
  348:     # block signal for fork
  349:     $sigset = POSIX::SigSet->new(SIGINT);
  350:     sigprocmask(SIG_BLOCK, $sigset)
  351:         or die "Can't block SIGINT for fork: $!\n";
  352:     #
  353:     die "fork: $!" unless defined ($pid = fork);
  354:     #
  355:     if ($pid) {
  356:         # Parent records the child's birth and returns.
  357:         sigprocmask(SIG_UNBLOCK, $sigset)
  358:             or die "Can't unblock SIGINT for fork: $!\n";
  359:         $children{$pid} = 1;
  360:         $children++;
  361:         return;
  362:     } else {
  363:         # Child can *not* return from this subroutine.
  364:         $SIG{INT} = 'DEFAULT';      # make SIGINT kill us as it did before
  365:         # unblock signals
  366:         sigprocmask(SIG_UNBLOCK, $sigset)
  367:             or die "Can't unblock SIGINT for fork: $!\n";
  368:         #open database handle
  369: 	# making dbh global to avoid garbage collector
  370: 	unless ($dbh = DBI->connect("DBI:mysql:loncapa","www",
  371:                                     $perlvar{'lonSqlAccess'},
  372:                                     { RaiseError =>0,PrintError=>0})) { 
  373:             sleep(10+int(rand(20)));
  374:             &logthis("<font color='blue'>WARNING: Couldn't connect to database".
  375:                      ": $@</font>");
  376:                      #  "($st secs): $@</font>");
  377:             print "database handle error\n";
  378:             exit;
  379:         }
  380: 	# make sure that a database disconnection occurs with 
  381:         # ending kill signals
  382: 	$SIG{TERM}=$SIG{INT}=$SIG{QUIT}=$SIG{__DIE__}=\&DISCONNECT;
  383:         # handle connections until we've reached $MAX_CLIENTS_PER_CHILD
  384:         for (my $i=0; $i < $MAX_CLIENTS_PER_CHILD; $i++) {
  385:             my $client = $server->accept() or last;
  386:             # do something with the connection
  387: 	    $run = $run+1;
  388: 	    my $userinput = <$client>;
  389: 	    chomp($userinput);
  390:             #
  391: 	    my ($conserver,$query,
  392: 		$arg1,$arg2,$arg3)=split(/&/,$userinput);
  393: 	    my $query=unescape($query);
  394:             #
  395:             #send query id which is pid_unixdatetime_runningcounter
  396: 	    my $queryid = $thisserver;
  397: 	    $queryid .="_".($$)."_";
  398: 	    $queryid .= time."_";
  399: 	    $queryid .= $run;
  400: 	    print $client "$queryid\n";
  401: 	    #
  402: 	    # &logthis("QUERY: $query - $arg1 - $arg2 - $arg3");
  403: 	    sleep 1;
  404:             #
  405:             my $result='';
  406:             #
  407:             # At this point, query is received, query-ID assigned and sent 
  408:             # back, $query eq 'logquery' will mean that this is a query 
  409:             # against log-files
  410:             if (($query eq 'userlog') || ($query eq 'courselog')) {
  411:                 # beginning of log query
  412:                 my $udom    = &unescape($arg1);
  413:                 my $uname   = &unescape($arg2);
  414:                 my $command = &unescape($arg3);
  415:                 my $path    = &propath($udom,$uname);
  416:                 if (-e "$path/activity.log") {
  417:                     if ($query eq 'userlog') {
  418:                         $result=&userlog($path,$command);
  419:                     } else {
  420:                         $result=&courselog($path,$command);
  421:                     }
  422:                 } else {
  423:                     &logthis('Unable to do log query: '.$uname.'@'.$udom);
  424:                     $result='no_such_file';
  425:                 }
  426:                 # end of log query
  427:             } elsif ($query eq 'fetchenrollment') {
  428:                 # retrieve institutional class lists
  429:                 my $dom = &unescape($arg1);
  430:                 my %affiliates = ();
  431:                 my %replies = ();
  432:                 my $locresult = '';
  433:                 my $querystr = &unescape($arg3);
  434:                 foreach (split/%%/,$querystr) {
  435:                     if (/^(\w+)=([^=]+)$/) {
  436:                         @{$affiliates{$1}} = split/,/,$2;
  437:                     }
  438:                 }
  439:                 $locresult = &localenroll::fetch_enrollment($dom,\%affiliates,\%replies);
  440:                 $result = &escape($locresult.':');
  441:                 if ($locresult) {
  442:                     $result .= &escape(join(':',map{$_.'='.$replies{$_}} keys %replies));
  443:                 }
  444:             } elsif ($query eq 'prepare activity log') {
  445:                 my ($cid,$domain) = map {&unescape($_);} ($arg1,$arg2);
  446:                 &logthis('preparing activity log tables for '.$cid);
  447:                 my $command = 
  448:                     qq{$perlvar{'lonDaemons'}/parse_activity_log.pl -course=$cid -domain=$domain};
  449:                 system($command);
  450:                 &logthis($command);
  451:                 my $returnvalue = $?>>8;
  452:                 if ($returnvalue) {
  453:                     $result = 'error: parse_activity_log.pl returned '.
  454:                         $returnvalue;
  455:                 } else {
  456:                     $result = 'success';
  457:                 }
  458:             } else {
  459:                 # Do an sql query
  460:                 $result = &do_sql_query($query,$arg1,$arg2);
  461:             }
  462:             # result does not need to be escaped because it has already been
  463:             # escaped.
  464:             #$result=&escape($result);
  465:             &reply("queryreply:$queryid:$result",$conserver);
  466:         }
  467:         # tidy up gracefully and finish
  468:         #
  469:         # close the database handle
  470: 	$dbh->disconnect
  471:             or &logthis("<font color='blue'>WARNING: Couldn't disconnect".
  472:                         " from database  $DBI::errstr : $@</font>");
  473:         # this exit is VERY important, otherwise the child will become
  474:         # a producer of more and more children, forking yourself into
  475:         # process death.
  476:         exit;
  477:     }
  478: }
  479: 
  480: ########################################################
  481: ########################################################
  482: 
  483: =pod
  484: 
  485: =item &do_sql_query
  486: 
  487: Runs an sql metadata table query.
  488: 
  489: Inputs: $query, $custom, $customshow
  490: 
  491: Returns: A string containing escaped results.
  492: 
  493: =cut
  494: 
  495: ########################################################
  496: ########################################################
  497: {
  498:     my @metalist;
  499: 
  500: sub process_file {
  501:     if ( -e $_ &&  # file exists
  502:          -f $_ &&  # and is a normal file
  503:          /\.meta$/ &&  # ends in meta
  504:          ! /^.+\.\d+\.[^\.]+\.meta$/  # is not a previous version
  505:          ) {
  506:         push(@metalist,$File::Find::name);
  507:     }
  508: }
  509: 
  510: sub do_sql_query {
  511:     my ($query,$custom,$customshow) = @_;
  512:     &logthis('doing query '.$query);
  513:     $custom     = &unescape($custom);
  514:     $customshow = &unescape($customshow);
  515:     #
  516:     @metalist = ();
  517:     #
  518:     my $result = '';
  519:     my @results = ();
  520:     my @files;
  521:     my $subsetflag=0;
  522:     #
  523:     if ($query) {
  524:         #prepare and execute the query
  525:         my $sth = $dbh->prepare($query);
  526:         unless ($sth->execute()) {
  527:             &logthis('<font color="blue">'.
  528:                      'WARNING: Could not retrieve from database:'.
  529:                      $sth->errstr().'</font>');
  530:         } else {
  531:             my $aref=$sth->fetchall_arrayref;
  532:             foreach my $row (@$aref) {
  533:                 push @files,@{$row}[3] if ($custom or $customshow);
  534:                 my @b=map { &escape($_); } @$row;
  535:                 push @results,join(",", @b);
  536:                 # Build up the @files array with the LON-CAPA urls 
  537:                 # of the resources.
  538:             }
  539:         }
  540:     }
  541:     # do custom metadata searching here and build into result
  542:     return join("&",@results) if (! ($custom or $customshow));
  543:     # Only get here if there is a custom query or custom show request
  544:     &logthis("Doing custom query for $custom");
  545:     if ($query) {
  546:         @metalist=map {
  547:             $perlvar{'lonDocRoot'}.$_.'.meta';
  548:         } @files;
  549:     } else {
  550:         my $dir = "$perlvar{'lonDocRoot'}/res/$perlvar{'lonDefDomain'}";
  551:         @metalist=(); 
  552:         opendir(RESOURCES,$dir);
  553:         my @homeusers=grep {
  554:             &ishome($dir.'/'.$_);
  555:         } grep {!/^\.\.?$/} readdir(RESOURCES);
  556:         closedir RESOURCES;
  557:         # Define the
  558:         foreach my $user (@homeusers) {
  559:             find (\&process_file,$dir.'/'.$user);
  560:         }
  561:     } 
  562:     # if file is indicated in sql database and
  563:     #     not part of sql-relevant query, do not pattern match.
  564:     #
  565:     # if file is not in sql database, output error.
  566:     #
  567:     # if file is indicated in sql database and is
  568:     #     part of query result list, then do the pattern match.
  569:     my $customresult='';
  570:     my @results;
  571:     foreach my $metafile (@metalist) {
  572:         my $fh=IO::File->new($metafile);
  573:         my @lines=<$fh>;
  574:         my $stuff=join('',@lines);
  575:         if ($stuff=~/$custom/s) {
  576:             foreach my $f ('abstract','author','copyright',
  577:                            'creationdate','keywords','language',
  578:                            'lastrevisiondate','mime','notes',
  579:                            'owner','subject','title') {
  580:                 $stuff=~s/\n?\<$f[^\>]*\>.*?<\/$f[^\>]*\>\n?//s;
  581:             }
  582:             my $mfile=$metafile; 
  583:             my $docroot=$perlvar{'lonDocRoot'};
  584:             $mfile=~s/^$docroot//;
  585:             $mfile=~s/\.meta$//;
  586:             unless ($query) {
  587:                 my $q2="SELECT * FROM metadata WHERE url ".
  588:                     " LIKE BINARY '?'";
  589:                 my $sth = $dbh->prepare($q2);
  590:                 $sth->execute($mfile);
  591:                 my $aref=$sth->fetchall_arrayref;
  592:                 foreach my $a (@$aref) {
  593:                     my @b=map { &escape($_)} @$a;
  594:                     push @results,join(",", @b);
  595:                 }
  596:             }
  597:             # &logthis("found: $stuff");
  598:             $customresult.='&custom='.&escape($mfile).','.
  599:                 escape($stuff);
  600:         }
  601:     }
  602:     $result=join("&",@results) unless $query;
  603:     $result.=$customresult;
  604:     #
  605:     return $result;
  606: } # End of &do_sql_query
  607: 
  608: } # End of scoping curly braces for &process_file and &do_sql_query
  609: ########################################################
  610: ########################################################
  611: 
  612: =pod
  613: 
  614: =item &logthis
  615: 
  616: Inputs: $message, the message to log
  617: 
  618: Returns: nothing
  619: 
  620: Writes $message to the logfile.
  621: 
  622: =cut
  623: 
  624: ########################################################
  625: ########################################################
  626: sub logthis {
  627:     my $message=shift;
  628:     my $execdir=$perlvar{'lonDaemons'};
  629:     my $fh=IO::File->new(">>$execdir/logs/lonsql.log");
  630:     my $now=time;
  631:     my $local=localtime($now);
  632:     print $fh "$local ($$): $message\n";
  633: }
  634: 
  635: # -------------------------------------------------- Non-critical communication
  636: 
  637: ########################################################
  638: ########################################################
  639: 
  640: =pod
  641: 
  642: =item &subreply
  643: 
  644: Sends a command to a server.  Called only by &reply.
  645: 
  646: Inputs: $cmd,$server
  647: 
  648: Returns: The results of the message or 'con_lost' on error.
  649: 
  650: =cut
  651: 
  652: ########################################################
  653: ########################################################
  654: sub subreply {
  655:     my ($cmd,$server)=@_;
  656:     my $peerfile="$perlvar{'lonSockDir'}/$server";
  657:     my $sclient=IO::Socket::UNIX->new(Peer    =>"$peerfile",
  658:                                       Type    => SOCK_STREAM,
  659:                                       Timeout => 10)
  660:        or return "con_lost";
  661:     print $sclient "$cmd\n";
  662:     my $answer=<$sclient>;
  663:     chomp($answer);
  664:     $answer="con_lost" if (!$answer);
  665:     return $answer;
  666: }
  667: 
  668: ########################################################
  669: ########################################################
  670: 
  671: =pod
  672: 
  673: =item &reply
  674: 
  675: Sends a command to a server.
  676: 
  677: Inputs: $cmd,$server
  678: 
  679: Returns: The results of the message or 'con_lost' on error.
  680: 
  681: =cut
  682: 
  683: ########################################################
  684: ########################################################
  685: sub reply {
  686:   my ($cmd,$server)=@_;
  687:   my $answer;
  688:   if ($server ne $perlvar{'lonHostID'}) { 
  689:     $answer=subreply($cmd,$server);
  690:     if ($answer eq 'con_lost') {
  691: 	$answer=subreply("ping",$server);
  692:         $answer=subreply($cmd,$server);
  693:     }
  694:   } else {
  695:     $answer='self_reply';
  696:     $answer=subreply($cmd,$server);
  697:   } 
  698:   return $answer;
  699: }
  700: 
  701: ########################################################
  702: ########################################################
  703: 
  704: =pod
  705: 
  706: =item &escape
  707: 
  708: Escape special characters in a string.
  709: 
  710: Inputs: string to escape
  711: 
  712: Returns: The input string with special characters escaped.
  713: 
  714: =cut
  715: 
  716: ########################################################
  717: ########################################################
  718: sub escape {
  719:     my $str=shift;
  720:     $str =~ s/(\W)/"%".unpack('H2',$1)/eg;
  721:     return $str;
  722: }
  723: 
  724: ########################################################
  725: ########################################################
  726: 
  727: =pod
  728: 
  729: =item &unescape
  730: 
  731: Unescape special characters in a string.
  732: 
  733: Inputs: string to unescape
  734: 
  735: Returns: The input string with special characters unescaped.
  736: 
  737: =cut
  738: 
  739: ########################################################
  740: ########################################################
  741: sub unescape {
  742:     my $str=shift;
  743:     $str =~ s/%([a-fA-F0-9][a-fA-F0-9])/pack("C",hex($1))/eg;
  744:     return $str;
  745: }
  746: 
  747: ########################################################
  748: ########################################################
  749: 
  750: =pod
  751: 
  752: =item &ishome
  753: 
  754: Determine if the current machine is the home server for a user.
  755: The determination is made by checking the filesystem for the users information.
  756: 
  757: Inputs: $author
  758: 
  759: Returns: 0 - this is not the authors home server, 1 - this is.
  760: 
  761: =cut
  762: 
  763: ########################################################
  764: ########################################################
  765: sub ishome {
  766:     my $author=shift;
  767:     $author=~s/\/home\/httpd\/html\/res\/([^\/]*)\/([^\/]*).*/$1\/$2/;
  768:     my ($udom,$uname)=split(/\//,$author);
  769:     my $proname=propath($udom,$uname);
  770:     if (-e $proname) {
  771: 	return 1;
  772:     } else {
  773:         return 0;
  774:     }
  775: }
  776: 
  777: ########################################################
  778: ########################################################
  779: 
  780: =pod
  781: 
  782: =item &propath
  783: 
  784: Inputs: user name, user domain
  785: 
  786: Returns: The full path to the users directory.
  787: 
  788: =cut
  789: 
  790: ########################################################
  791: ########################################################
  792: sub propath {
  793:     my ($udom,$uname)=@_;
  794:     $udom=~s/\W//g;
  795:     $uname=~s/\W//g;
  796:     my $subdir=$uname.'__';
  797:     $subdir =~ s/(.)(.)(.).*/$1\/$2\/$3/;
  798:     my $proname="$perlvar{'lonUsersDir'}/$udom/$subdir/$uname";
  799:     return $proname;
  800: } 
  801: 
  802: ########################################################
  803: ########################################################
  804: 
  805: =pod
  806: 
  807: =item &courselog
  808: 
  809: Inputs: $path, $command
  810: 
  811: Returns: unescaped string of values.
  812: 
  813: =cut
  814: 
  815: ########################################################
  816: ########################################################
  817: sub courselog {
  818:     my ($path,$command)=@_;
  819:     my %filters=();
  820:     foreach (split(/\:/,&unescape($command))) {
  821: 	my ($name,$value)=split(/\=/,$_);
  822:         $filters{$name}=$value;
  823:     }
  824:     my @results=();
  825:     open(IN,$path.'/activity.log') or return ('file_error');
  826:     while (my $line=<IN>) {
  827:         chomp($line);
  828:         my ($timestamp,$host,$log)=split(/\:/,$line);
  829: #
  830: # $log has the actual log entries; currently still escaped, and
  831: # %26(timestamp)%3a(url)%3a(user)%3a(domain)
  832: # then additionally
  833: # %3aPOST%3a(name)%3d(value)%3a(name)%3d(value)
  834: # or
  835: # %3aCSTORE%3a(name)%3d(value)%26(name)%3d(value)
  836: #
  837: # get delimiter between timestamped entries to be &&&
  838:         $log=~s/\%26(\d+)\%3a/\&\&\&$1\%3a/g;
  839: # now go over all log entries 
  840:         foreach (split(/\&\&\&/,&unescape($log))) {
  841: 	    my ($time,$res,$uname,$udom,$action,@values)=split(/\:/,$_);
  842:             my $values=&unescape(join(':',@values));
  843:             $values=~s/\&/\:/g;
  844:             $res=&unescape($res);
  845:             my $include=1;
  846:             if (($filters{'username'}) && ($uname ne $filters{'username'})) 
  847:                                                                { $include=0; }
  848:             if (($filters{'domain'}) && ($udom ne $filters{'domain'})) 
  849:                                                                { $include=0; }
  850:             if (($filters{'url'}) && ($res!~/$filters{'url'}/)) 
  851:                                                                { $include=0; }
  852:             if (($filters{'start'}) && ($time<$filters{'start'})) 
  853:                                                                { $include=0; }
  854:             if (($filters{'end'}) && ($time>$filters{'end'})) 
  855:                                                                { $include=0; }
  856:             if (($filters{'action'} eq 'view') && ($action)) 
  857:                                                                { $include=0; }
  858:             if (($filters{'action'} eq 'submit') && ($action ne 'POST')) 
  859:                                                                { $include=0; }
  860:             if (($filters{'action'} eq 'grade') && ($action ne 'CSTORE')) 
  861:                                                                { $include=0; }
  862:             if ($include) {
  863: 	       push(@results,($time<1000000000?'0':'').$time.':'.$res.':'.
  864:                                             $uname.':'.$udom.':'.
  865:                                             $action.':'.$values);
  866:             }
  867:        }
  868:     }
  869:     close IN;
  870:     return join('&',sort(@results));
  871: }
  872: 
  873: ########################################################
  874: ########################################################
  875: 
  876: =pod
  877: 
  878: =item &userlog
  879: 
  880: Inputs: $path, $command
  881: 
  882: Returns: unescaped string of values.
  883: 
  884: =cut
  885: 
  886: ########################################################
  887: ########################################################
  888: sub userlog {
  889:     my ($path,$command)=@_;
  890:     my %filters=();
  891:     foreach (split(/\:/,&unescape($command))) {
  892: 	my ($name,$value)=split(/\=/,$_);
  893:         $filters{$name}=$value;
  894:     }
  895:     my @results=();
  896:     open(IN,$path.'/activity.log') or return ('file_error');
  897:     while (my $line=<IN>) {
  898:         chomp($line);
  899:         my ($timestamp,$host,$log)=split(/\:/,$line);
  900:         $log=&unescape($log);
  901:         my $include=1;
  902:         if (($filters{'start'}) && ($timestamp<$filters{'start'})) 
  903:                                                              { $include=0; }
  904:         if (($filters{'end'}) && ($timestamp>$filters{'end'})) 
  905:                                                              { $include=0; }
  906:         if (($filters{'action'} eq 'log') && ($log!~/^Log/)) { $include=0; }
  907:         if (($filters{'action'} eq 'check') && ($log!~/^Check/)) 
  908:                                                              { $include=0; }
  909:         if ($include) {
  910: 	   push(@results,$timestamp.':'.$log);
  911:         }
  912:     }
  913:     close IN;
  914:     return join('&',sort(@results));
  915: }
  916: 
  917: ########################################################
  918: ########################################################
  919: 
  920: =pod
  921: 
  922: =item Functions required for forking
  923: 
  924: =over 4
  925: 
  926: =item REAPER
  927: 
  928: REAPER takes care of dead children.
  929: 
  930: =item HUNTSMAN
  931: 
  932: Signal handler for SIGINT.
  933: 
  934: =item HUPSMAN
  935: 
  936: Signal handler for SIGHUP
  937: 
  938: =item DISCONNECT
  939: 
  940: Disconnects from database.
  941: 
  942: =back
  943: 
  944: =cut
  945: 
  946: ########################################################
  947: ########################################################
  948: sub REAPER {                   # takes care of dead children
  949:     $SIG{CHLD} = \&REAPER;
  950:     my $pid = wait;
  951:     $children --;
  952:     &logthis("Child $pid died");
  953:     delete $children{$pid};
  954: }
  955: 
  956: sub HUNTSMAN {                      # signal handler for SIGINT
  957:     local($SIG{CHLD}) = 'IGNORE';   # we're going to kill our children
  958:     kill 'INT' => keys %children;
  959:     my $execdir=$perlvar{'lonDaemons'};
  960:     unlink("$execdir/logs/lonsql.pid");
  961:     &logthis("<font color='red'>CRITICAL: Shutting down</font>");
  962:     $unixsock = "mysqlsock";
  963:     my $port="$perlvar{'lonSockDir'}/$unixsock";
  964:     unlink($port);
  965:     exit;                           # clean up with dignity
  966: }
  967: 
  968: sub HUPSMAN {                      # signal handler for SIGHUP
  969:     local($SIG{CHLD}) = 'IGNORE';  # we're going to kill our children
  970:     kill 'INT' => keys %children;
  971:     close($server);                # free up socket
  972:     &logthis("<font color='red'>CRITICAL: Restarting</font>");
  973:     my $execdir=$perlvar{'lonDaemons'};
  974:     $unixsock = "mysqlsock";
  975:     my $port="$perlvar{'lonSockDir'}/$unixsock";
  976:     unlink($port);
  977:     exec("$execdir/lonsql");         # here we go again
  978: }
  979: 
  980: sub DISCONNECT {
  981:     $dbh->disconnect or 
  982:     &logthis("<font color='blue'>WARNING: Couldn't disconnect from database ".
  983:              " $DBI::errstr : $@</font>");
  984:     exit;
  985: }
  986: 
  987: 
  988: =pod
  989: 
  990: =back
  991: 
  992: =cut

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