File:  [LON-CAPA] / loncom / lonsql
Revision 1.58: download - view: text, annotated - select for diffs
Mon May 3 16:20:57 2004 UTC (20 years ago) by matthew
Branches: MAIN
CVS tags: HEAD
Removed out of date POD.  Report database errors using $sth->errstr() when
there is an error, instead of using $@.

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

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