File:  [LON-CAPA] / loncom / lonsql
Revision 1.75: download - view: text, annotated - select for diffs
Fri Feb 10 09:47:36 2006 UTC (18 years, 3 months ago) by albertel
Branches: MAIN
CVS tags: HEAD
- eval the new photo routines so lond/sql don't die in the middle of them

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

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