File:  [LON-CAPA] / loncom / lonsql
Revision 1.74: download - view: text, annotated - select for diffs
Wed Feb 8 21:17:53 2006 UTC (18 years, 3 months ago) by www
Branches: MAIN
CVS tags: HEAD
Bug #4531: limit search to queried domain on multidomain machines

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

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