File:  [LON-CAPA] / loncom / lonsql
Revision 1.61: download - view: text, annotated - select for diffs
Thu May 20 14:15:29 2004 UTC (19 years, 11 months ago) by matthew
Branches: MAIN
CVS tags: version_1_1_99_0, HEAD
Bug 3026: Remove logging spew.

    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.61 2004/05/20 14:15:29 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("queryreply:$queryid:$result",$conserver);
  417:         }
  418:         # tidy up gracefully and finish
  419:         #
  420:         # close the database handle
  421: 	$dbh->disconnect
  422:             or &logthis("<font color='blue'>WARNING: Couldn't disconnect".
  423:                         " from database  $DBI::errstr : $@</font>");
  424:         # this exit is VERY important, otherwise the child will become
  425:         # a producer of more and more children, forking yourself into
  426:         # process death.
  427:         exit;
  428:     }
  429: }
  430: 
  431: ########################################################
  432: ########################################################
  433: 
  434: =pod
  435: 
  436: =item &do_sql_query
  437: 
  438: Runs an sql metadata table query.
  439: 
  440: Inputs: $query, $custom, $customshow
  441: 
  442: Returns: A string containing escaped results.
  443: 
  444: =cut
  445: 
  446: ########################################################
  447: ########################################################
  448: {
  449:     my @metalist;
  450: 
  451: sub process_file {
  452:     if ( -e $_ &&  # file exists
  453:          -f $_ &&  # and is a normal file
  454:          /\.meta$/ &&  # ends in meta
  455:          ! /^.+\.\d+\.[^\.]+\.meta$/  # is not a previous version
  456:          ) {
  457:         push(@metalist,$File::Find::name);
  458:     }
  459: }
  460: 
  461: sub do_sql_query {
  462:     my ($query,$custom,$customshow) = @_;
  463:     $custom     = &unescape($custom);
  464:     $customshow = &unescape($customshow);
  465:     #
  466:     @metalist = ();
  467:     #
  468:     my $result = '';
  469:     my @results = ();
  470:     my @files;
  471:     my $subsetflag=0;
  472:     #
  473:     if ($query) {
  474:         #prepare and execute the query
  475:         my $sth = $dbh->prepare($query);
  476:         unless ($sth->execute()) {
  477:             &logthis('<font color="blue">'.
  478:                      'WARNING: Could not retrieve from database:'.
  479:                      $sth->errstr().'</font>');
  480:         } else {
  481:             my $aref=$sth->fetchall_arrayref;
  482:             foreach my $row (@$aref) {
  483:                 push @files,@{$row}[3] if ($custom or $customshow);
  484:                 my @b=map { &escape($_); } @$row;
  485:                 push @results,join(",", @b);
  486:                 # Build up the @files array with the LON-CAPA urls 
  487:                 # of the resources.
  488:             }
  489:         }
  490:     }
  491:     # do custom metadata searching here and build into result
  492:     return join("&",@results) if (! ($custom or $customshow));
  493:     # Only get here if there is a custom query or custom show request
  494:     &logthis("Doing custom query for $custom");
  495:     if ($query) {
  496:         @metalist=map {
  497:             $perlvar{'lonDocRoot'}.$_.'.meta';
  498:         } @files;
  499:     } else {
  500:         my $dir = "$perlvar{'lonDocRoot'}/res/$perlvar{'lonDefDomain'}";
  501:         @metalist=(); 
  502:         opendir(RESOURCES,$dir);
  503:         my @homeusers=grep {
  504:             &ishome($dir.'/'.$_);
  505:         } grep {!/^\.\.?$/} readdir(RESOURCES);
  506:         closedir RESOURCES;
  507:         # Define the
  508:         foreach my $user (@homeusers) {
  509:             find (\&process_file,$dir.'/'.$user);
  510:         }
  511:     } 
  512:     # if file is indicated in sql database and
  513:     #     not part of sql-relevant query, do not pattern match.
  514:     #
  515:     # if file is not in sql database, output error.
  516:     #
  517:     # if file is indicated in sql database and is
  518:     #     part of query result list, then do the pattern match.
  519:     my $customresult='';
  520:     my @results;
  521:     foreach my $metafile (@metalist) {
  522:         my $fh=IO::File->new($metafile);
  523:         my @lines=<$fh>;
  524:         my $stuff=join('',@lines);
  525:         if ($stuff=~/$custom/s) {
  526:             foreach my $f ('abstract','author','copyright',
  527:                            'creationdate','keywords','language',
  528:                            'lastrevisiondate','mime','notes',
  529:                            'owner','subject','title') {
  530:                 $stuff=~s/\n?\<$f[^\>]*\>.*?<\/$f[^\>]*\>\n?//s;
  531:             }
  532:             my $mfile=$metafile; 
  533:             my $docroot=$perlvar{'lonDocRoot'};
  534:             $mfile=~s/^$docroot//;
  535:             $mfile=~s/\.meta$//;
  536:             unless ($query) {
  537:                 my $q2="SELECT * FROM metadata WHERE url ".
  538:                     " LIKE BINARY '?'";
  539:                 my $sth = $dbh->prepare($q2);
  540:                 $sth->execute($mfile);
  541:                 my $aref=$sth->fetchall_arrayref;
  542:                 foreach my $a (@$aref) {
  543:                     my @b=map { &escape($_)} @$a;
  544:                     push @results,join(",", @b);
  545:                 }
  546:             }
  547:             # &logthis("found: $stuff");
  548:             $customresult.='&custom='.&escape($mfile).','.
  549:                 escape($stuff);
  550:         }
  551:     }
  552:     $result=join("&",@results) unless $query;
  553:     $result.=$customresult;
  554:     #
  555:     return $result;
  556: } # End of &do_sql_query
  557: 
  558: } # End of scoping curly braces for &process_file and &do_sql_query
  559: ########################################################
  560: ########################################################
  561: 
  562: =pod
  563: 
  564: =item &logthis
  565: 
  566: Inputs: $message, the message to log
  567: 
  568: Returns: nothing
  569: 
  570: Writes $message to the logfile.
  571: 
  572: =cut
  573: 
  574: ########################################################
  575: ########################################################
  576: sub logthis {
  577:     my $message=shift;
  578:     my $execdir=$perlvar{'lonDaemons'};
  579:     my $fh=IO::File->new(">>$execdir/logs/lonsql.log");
  580:     my $now=time;
  581:     my $local=localtime($now);
  582:     print $fh "$local ($$): $message\n";
  583: }
  584: 
  585: # -------------------------------------------------- Non-critical communication
  586: 
  587: ########################################################
  588: ########################################################
  589: 
  590: =pod
  591: 
  592: =item &subreply
  593: 
  594: Sends a command to a server.  Called only by &reply.
  595: 
  596: Inputs: $cmd,$server
  597: 
  598: Returns: The results of the message or 'con_lost' on error.
  599: 
  600: =cut
  601: 
  602: ########################################################
  603: ########################################################
  604: sub subreply {
  605:     my ($cmd,$server)=@_;
  606:     my $peerfile="$perlvar{'lonSockDir'}/$server";
  607:     my $sclient=IO::Socket::UNIX->new(Peer    =>"$peerfile",
  608:                                       Type    => SOCK_STREAM,
  609:                                       Timeout => 10)
  610:        or return "con_lost";
  611:     print $sclient "$cmd\n";
  612:     my $answer=<$sclient>;
  613:     chomp($answer);
  614:     $answer="con_lost" if (!$answer);
  615:     return $answer;
  616: }
  617: 
  618: ########################################################
  619: ########################################################
  620: 
  621: =pod
  622: 
  623: =item &reply
  624: 
  625: Sends a command to a server.
  626: 
  627: Inputs: $cmd,$server
  628: 
  629: Returns: The results of the message or 'con_lost' on error.
  630: 
  631: =cut
  632: 
  633: ########################################################
  634: ########################################################
  635: sub reply {
  636:   my ($cmd,$server)=@_;
  637:   my $answer;
  638:   if ($server ne $perlvar{'lonHostID'}) { 
  639:     $answer=subreply($cmd,$server);
  640:     if ($answer eq 'con_lost') {
  641: 	$answer=subreply("ping",$server);
  642:         $answer=subreply($cmd,$server);
  643:     }
  644:   } else {
  645:     $answer='self_reply';
  646:     $answer=subreply($cmd,$server);
  647:   } 
  648:   return $answer;
  649: }
  650: 
  651: ########################################################
  652: ########################################################
  653: 
  654: =pod
  655: 
  656: =item &escape
  657: 
  658: Escape special characters in a string.
  659: 
  660: Inputs: string to escape
  661: 
  662: Returns: The input string with special characters escaped.
  663: 
  664: =cut
  665: 
  666: ########################################################
  667: ########################################################
  668: sub escape {
  669:     my $str=shift;
  670:     $str =~ s/(\W)/"%".unpack('H2',$1)/eg;
  671:     return $str;
  672: }
  673: 
  674: ########################################################
  675: ########################################################
  676: 
  677: =pod
  678: 
  679: =item &unescape
  680: 
  681: Unescape special characters in a string.
  682: 
  683: Inputs: string to unescape
  684: 
  685: Returns: The input string with special characters unescaped.
  686: 
  687: =cut
  688: 
  689: ########################################################
  690: ########################################################
  691: sub unescape {
  692:     my $str=shift;
  693:     $str =~ s/%([a-fA-F0-9][a-fA-F0-9])/pack("C",hex($1))/eg;
  694:     return $str;
  695: }
  696: 
  697: ########################################################
  698: ########################################################
  699: 
  700: =pod
  701: 
  702: =item &ishome
  703: 
  704: Determine if the current machine is the home server for a user.
  705: The determination is made by checking the filesystem for the users information.
  706: 
  707: Inputs: $author
  708: 
  709: Returns: 0 - this is not the authors home server, 1 - this is.
  710: 
  711: =cut
  712: 
  713: ########################################################
  714: ########################################################
  715: sub ishome {
  716:     my $author=shift;
  717:     $author=~s/\/home\/httpd\/html\/res\/([^\/]*)\/([^\/]*).*/$1\/$2/;
  718:     my ($udom,$uname)=split(/\//,$author);
  719:     my $proname=propath($udom,$uname);
  720:     if (-e $proname) {
  721: 	return 1;
  722:     } else {
  723:         return 0;
  724:     }
  725: }
  726: 
  727: ########################################################
  728: ########################################################
  729: 
  730: =pod
  731: 
  732: =item &propath
  733: 
  734: Inputs: user name, user domain
  735: 
  736: Returns: The full path to the users directory.
  737: 
  738: =cut
  739: 
  740: ########################################################
  741: ########################################################
  742: sub propath {
  743:     my ($udom,$uname)=@_;
  744:     $udom=~s/\W//g;
  745:     $uname=~s/\W//g;
  746:     my $subdir=$uname.'__';
  747:     $subdir =~ s/(.)(.)(.).*/$1\/$2\/$3/;
  748:     my $proname="$perlvar{'lonUsersDir'}/$udom/$subdir/$uname";
  749:     return $proname;
  750: } 
  751: 
  752: ########################################################
  753: ########################################################
  754: 
  755: =pod
  756: 
  757: =item &courselog
  758: 
  759: Inputs: $path, $command
  760: 
  761: Returns: unescaped string of values.
  762: 
  763: =cut
  764: 
  765: ########################################################
  766: ########################################################
  767: sub courselog {
  768:     my ($path,$command)=@_;
  769:     my %filters=();
  770:     foreach (split(/\:/,&unescape($command))) {
  771: 	my ($name,$value)=split(/\=/,$_);
  772:         $filters{$name}=$value;
  773:     }
  774:     my @results=();
  775:     open(IN,$path.'/activity.log') or return ('file_error');
  776:     while (my $line=<IN>) {
  777:         chomp($line);
  778:         my ($timestamp,$host,$log)=split(/\:/,$line);
  779: #
  780: # $log has the actual log entries; currently still escaped, and
  781: # %26(timestamp)%3a(url)%3a(user)%3a(domain)
  782: # then additionally
  783: # %3aPOST%3a(name)%3d(value)%3a(name)%3d(value)
  784: # or
  785: # %3aCSTORE%3a(name)%3d(value)%26(name)%3d(value)
  786: #
  787: # get delimiter between timestamped entries to be &&&
  788:         $log=~s/\%26(\d+)\%3a/\&\&\&$1\%3a/g;
  789: # now go over all log entries 
  790:         foreach (split(/\&\&\&/,&unescape($log))) {
  791: 	    my ($time,$res,$uname,$udom,$action,@values)=split(/\:/,$_);
  792:             my $values=&unescape(join(':',@values));
  793:             $values=~s/\&/\:/g;
  794:             $res=&unescape($res);
  795:             my $include=1;
  796:             if (($filters{'username'}) && ($uname ne $filters{'username'})) 
  797:                                                                { $include=0; }
  798:             if (($filters{'domain'}) && ($udom ne $filters{'domain'})) 
  799:                                                                { $include=0; }
  800:             if (($filters{'url'}) && ($res!~/$filters{'url'}/)) 
  801:                                                                { $include=0; }
  802:             if (($filters{'start'}) && ($time<$filters{'start'})) 
  803:                                                                { $include=0; }
  804:             if (($filters{'end'}) && ($time>$filters{'end'})) 
  805:                                                                { $include=0; }
  806:             if (($filters{'action'} eq 'view') && ($action)) 
  807:                                                                { $include=0; }
  808:             if (($filters{'action'} eq 'submit') && ($action ne 'POST')) 
  809:                                                                { $include=0; }
  810:             if (($filters{'action'} eq 'grade') && ($action ne 'CSTORE')) 
  811:                                                                { $include=0; }
  812:             if ($include) {
  813: 	       push(@results,($time<1000000000?'0':'').$time.':'.$res.':'.
  814:                                             $uname.':'.$udom.':'.
  815:                                             $action.':'.$values);
  816:             }
  817:        }
  818:     }
  819:     close IN;
  820:     return join('&',sort(@results));
  821: }
  822: 
  823: ########################################################
  824: ########################################################
  825: 
  826: =pod
  827: 
  828: =item &userlog
  829: 
  830: Inputs: $path, $command
  831: 
  832: Returns: unescaped string of values.
  833: 
  834: =cut
  835: 
  836: ########################################################
  837: ########################################################
  838: sub userlog {
  839:     my ($path,$command)=@_;
  840:     my %filters=();
  841:     foreach (split(/\:/,&unescape($command))) {
  842: 	my ($name,$value)=split(/\=/,$_);
  843:         $filters{$name}=$value;
  844:     }
  845:     my @results=();
  846:     open(IN,$path.'/activity.log') or return ('file_error');
  847:     while (my $line=<IN>) {
  848:         chomp($line);
  849:         my ($timestamp,$host,$log)=split(/\:/,$line);
  850:         $log=&unescape($log);
  851:         my $include=1;
  852:         if (($filters{'start'}) && ($timestamp<$filters{'start'})) 
  853:                                                              { $include=0; }
  854:         if (($filters{'end'}) && ($timestamp>$filters{'end'})) 
  855:                                                              { $include=0; }
  856:         if (($filters{'action'} eq 'log') && ($log!~/^Log/)) { $include=0; }
  857:         if (($filters{'action'} eq 'check') && ($log!~/^Check/)) 
  858:                                                              { $include=0; }
  859:         if ($include) {
  860: 	   push(@results,$timestamp.':'.$log);
  861:         }
  862:     }
  863:     close IN;
  864:     return join('&',sort(@results));
  865: }
  866: 
  867: ########################################################
  868: ########################################################
  869: 
  870: =pod
  871: 
  872: =item Functions required for forking
  873: 
  874: =over 4
  875: 
  876: =item REAPER
  877: 
  878: REAPER takes care of dead children.
  879: 
  880: =item HUNTSMAN
  881: 
  882: Signal handler for SIGINT.
  883: 
  884: =item HUPSMAN
  885: 
  886: Signal handler for SIGHUP
  887: 
  888: =item DISCONNECT
  889: 
  890: Disconnects from database.
  891: 
  892: =back
  893: 
  894: =cut
  895: 
  896: ########################################################
  897: ########################################################
  898: sub REAPER {                   # takes care of dead children
  899:     $SIG{CHLD} = \&REAPER;
  900:     my $pid = wait;
  901:     $children --;
  902:     &logthis("Child $pid died");
  903:     delete $children{$pid};
  904: }
  905: 
  906: sub HUNTSMAN {                      # signal handler for SIGINT
  907:     local($SIG{CHLD}) = 'IGNORE';   # we're going to kill our children
  908:     kill 'INT' => keys %children;
  909:     my $execdir=$perlvar{'lonDaemons'};
  910:     unlink("$execdir/logs/lonsql.pid");
  911:     &logthis("<font color='red'>CRITICAL: Shutting down</font>");
  912:     $unixsock = "mysqlsock";
  913:     my $port="$perlvar{'lonSockDir'}/$unixsock";
  914:     unlink($port);
  915:     exit;                           # clean up with dignity
  916: }
  917: 
  918: sub HUPSMAN {                      # signal handler for SIGHUP
  919:     local($SIG{CHLD}) = 'IGNORE';  # we're going to kill our children
  920:     kill 'INT' => keys %children;
  921:     close($server);                # free up socket
  922:     &logthis("<font color='red'>CRITICAL: Restarting</font>");
  923:     my $execdir=$perlvar{'lonDaemons'};
  924:     $unixsock = "mysqlsock";
  925:     my $port="$perlvar{'lonSockDir'}/$unixsock";
  926:     unlink($port);
  927:     exec("$execdir/lonsql");         # here we go again
  928: }
  929: 
  930: sub DISCONNECT {
  931:     $dbh->disconnect or 
  932:     &logthis("<font color='blue'>WARNING: Couldn't disconnect from database ".
  933:              " $DBI::errstr : $@</font>");
  934:     exit;
  935: }
  936: 
  937: 
  938: =pod
  939: 
  940: =back
  941: 
  942: =cut

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