File:  [LON-CAPA] / loncom / lonsql
Revision 1.73: download - view: text, annotated - select for diffs
Wed Feb 8 17:11:46 2006 UTC (18 years, 2 months ago) by www
Branches: MAIN
CVS tags: HEAD
Prepare to do filtering of lonsql results based on the domain that lond is
running under

    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.73 2006/02/08 17:11:46 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);
  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) = @_;
  521: #    &logthis('doing query '.$query);
  522:     $custom     = &unescape($custom);
  523:     $customshow = &unescape($customshow);
  524:     #
  525:     @metalist = ();
  526:     #
  527:     my $result = '';
  528:     my @results = ();
  529:     my @files;
  530:     my $subsetflag=0;
  531:     #
  532:     if ($query) {
  533:         #prepare and execute the query
  534:         my $sth = $dbh->prepare($query);
  535:         unless ($sth->execute()) {
  536:             &logthis('<font color="blue">'.
  537:                      'WARNING: Could not retrieve from database:'.
  538:                      $sth->errstr().'</font>');
  539:         } else {
  540:             my $aref=$sth->fetchall_arrayref;
  541:             foreach my $row (@$aref) {
  542:                 push @files,@{$row}[3] if ($custom or $customshow);
  543:                 my @b=map { &escape($_); } @$row;
  544:                 push @results,join(",", @b);
  545:                 # Build up the @files array with the LON-CAPA urls 
  546:                 # of the resources.
  547:             }
  548:         }
  549:     }
  550:     # do custom metadata searching here and build into result
  551:     return join("&",@results) if (! ($custom or $customshow));
  552:     # Only get here if there is a custom query or custom show request
  553:     &logthis("Doing custom query for $custom");
  554:     if ($query) {
  555:         @metalist=map {
  556:             $perlvar{'lonDocRoot'}.$_.'.meta';
  557:         } @files;
  558:     } else {
  559:         my $dir = "$perlvar{'lonDocRoot'}/res/$perlvar{'lonDefDomain'}";
  560:         @metalist=(); 
  561:         opendir(RESOURCES,$dir);
  562:         my @homeusers=grep {
  563:             &ishome($dir.'/'.$_);
  564:         } grep {!/^\.\.?$/} readdir(RESOURCES);
  565:         closedir RESOURCES;
  566:         # Define the
  567:         foreach my $user (@homeusers) {
  568:             find (\&process_file,$dir.'/'.$user);
  569:         }
  570:     } 
  571:     # if file is indicated in sql database and
  572:     #     not part of sql-relevant query, do not pattern match.
  573:     #
  574:     # if file is not in sql database, output error.
  575:     #
  576:     # if file is indicated in sql database and is
  577:     #     part of query result list, then do the pattern match.
  578:     my $customresult='';
  579:     my @results;
  580:     foreach my $metafile (@metalist) {
  581:         my $fh=IO::File->new($metafile);
  582:         my @lines=<$fh>;
  583:         my $stuff=join('',@lines);
  584:         if ($stuff=~/$custom/s) {
  585:             foreach my $f ('abstract','author','copyright',
  586:                            'creationdate','keywords','language',
  587:                            'lastrevisiondate','mime','notes',
  588:                            'owner','subject','title') {
  589:                 $stuff=~s/\n?\<$f[^\>]*\>.*?<\/$f[^\>]*\>\n?//s;
  590:             }
  591:             my $mfile=$metafile; 
  592:             my $docroot=$perlvar{'lonDocRoot'};
  593:             $mfile=~s/^$docroot//;
  594:             $mfile=~s/\.meta$//;
  595:             unless ($query) {
  596:                 my $q2="SELECT * FROM metadata WHERE url ".
  597:                     " LIKE BINARY '?'";
  598:                 my $sth = $dbh->prepare($q2);
  599:                 $sth->execute($mfile);
  600:                 my $aref=$sth->fetchall_arrayref;
  601:                 foreach my $a (@$aref) {
  602:                     my @b=map { &escape($_)} @$a;
  603:                     push @results,join(",", @b);
  604:                 }
  605:             }
  606:             # &logthis("found: $stuff");
  607:             $customresult.='&custom='.&escape($mfile).','.
  608:                 escape($stuff);
  609:         }
  610:     }
  611:     $result=join("&",@results) unless $query;
  612:     $result.=$customresult;
  613:     #
  614:     return $result;
  615: } # End of &do_sql_query
  616: 
  617: } # End of scoping curly braces for &process_file and &do_sql_query
  618: ########################################################
  619: ########################################################
  620: 
  621: =pod
  622: 
  623: =item &logthis
  624: 
  625: Inputs: $message, the message to log
  626: 
  627: Returns: nothing
  628: 
  629: Writes $message to the logfile.
  630: 
  631: =cut
  632: 
  633: ########################################################
  634: ########################################################
  635: sub logthis {
  636:     my $message=shift;
  637:     my $execdir=$perlvar{'lonDaemons'};
  638:     my $fh=IO::File->new(">>$execdir/logs/lonsql.log");
  639:     my $now=time;
  640:     my $local=localtime($now);
  641:     print $fh "$local ($$): $message\n";
  642: }
  643: 
  644: # -------------------------------------------------- Non-critical communication
  645: 
  646: ########################################################
  647: ########################################################
  648: 
  649: =pod
  650: 
  651: =item &subreply
  652: 
  653: Sends a command to a server.  Called only by &reply.
  654: 
  655: Inputs: $cmd,$server
  656: 
  657: Returns: The results of the message or 'con_lost' on error.
  658: 
  659: =cut
  660: 
  661: ########################################################
  662: ########################################################
  663: sub subreply {
  664:     my ($cmd,$server)=@_;
  665:     my $peerfile="$perlvar{'lonSockDir'}/".$hostname{$server};
  666:     my $sclient=IO::Socket::UNIX->new(Peer    =>"$peerfile",
  667:                                       Type    => SOCK_STREAM,
  668:                                       Timeout => 10)
  669:        or return "con_lost";
  670:     print $sclient "sethost:$server:$cmd\n";
  671:     my $answer=<$sclient>;
  672:     chomp($answer);
  673:     $answer="con_lost" if (!$answer);
  674:     return $answer;
  675: }
  676: 
  677: ########################################################
  678: ########################################################
  679: 
  680: =pod
  681: 
  682: =item &reply
  683: 
  684: Sends a command to a server.
  685: 
  686: Inputs: $cmd,$server
  687: 
  688: Returns: The results of the message or 'con_lost' on error.
  689: 
  690: =cut
  691: 
  692: ########################################################
  693: ########################################################
  694: sub reply {
  695:   my ($cmd,$server)=@_;
  696:   my $answer;
  697:   if ($server ne $perlvar{'lonHostID'}) { 
  698:     $answer=subreply($cmd,$server);
  699:     if ($answer eq 'con_lost') {
  700: 	$answer=subreply("ping",$server);
  701:         $answer=subreply($cmd,$server);
  702:     }
  703:   } else {
  704:     $answer='self_reply';
  705:     $answer=subreply($cmd,$server);
  706:   } 
  707:   return $answer;
  708: }
  709: 
  710: ########################################################
  711: ########################################################
  712: 
  713: =pod
  714: 
  715: =item &escape
  716: 
  717: Escape special characters in a string.
  718: 
  719: Inputs: string to escape
  720: 
  721: Returns: The input string with special characters escaped.
  722: 
  723: =cut
  724: 
  725: ########################################################
  726: ########################################################
  727: sub escape {
  728:     my $str=shift;
  729:     $str =~ s/(\W)/"%".unpack('H2',$1)/eg;
  730:     return $str;
  731: }
  732: 
  733: ########################################################
  734: ########################################################
  735: 
  736: =pod
  737: 
  738: =item &unescape
  739: 
  740: Unescape special characters in a string.
  741: 
  742: Inputs: string to unescape
  743: 
  744: Returns: The input string with special characters unescaped.
  745: 
  746: =cut
  747: 
  748: ########################################################
  749: ########################################################
  750: sub unescape {
  751:     my $str=shift;
  752:     $str =~ s/%([a-fA-F0-9][a-fA-F0-9])/pack("C",hex($1))/eg;
  753:     return $str;
  754: }
  755: 
  756: ########################################################
  757: ########################################################
  758: 
  759: =pod
  760: 
  761: =item &ishome
  762: 
  763: Determine if the current machine is the home server for a user.
  764: The determination is made by checking the filesystem for the users information.
  765: 
  766: Inputs: $author
  767: 
  768: Returns: 0 - this is not the authors home server, 1 - this is.
  769: 
  770: =cut
  771: 
  772: ########################################################
  773: ########################################################
  774: sub ishome {
  775:     my $author=shift;
  776:     $author=~s/\/home\/httpd\/html\/res\/([^\/]*)\/([^\/]*).*/$1\/$2/;
  777:     my ($udom,$uname)=split(/\//,$author);
  778:     my $proname=propath($udom,$uname);
  779:     if (-e $proname) {
  780: 	return 1;
  781:     } else {
  782:         return 0;
  783:     }
  784: }
  785: 
  786: ########################################################
  787: ########################################################
  788: 
  789: =pod
  790: 
  791: =item &propath
  792: 
  793: Inputs: user name, user domain
  794: 
  795: Returns: The full path to the users directory.
  796: 
  797: =cut
  798: 
  799: ########################################################
  800: ########################################################
  801: sub propath {
  802:     my ($udom,$uname)=@_;
  803:     $udom=~s/\W//g;
  804:     $uname=~s/\W//g;
  805:     my $subdir=$uname.'__';
  806:     $subdir =~ s/(.)(.)(.).*/$1\/$2\/$3/;
  807:     my $proname="$perlvar{'lonUsersDir'}/$udom/$subdir/$uname";
  808:     return $proname;
  809: } 
  810: 
  811: ########################################################
  812: ########################################################
  813: 
  814: =pod
  815: 
  816: =item &courselog
  817: 
  818: Inputs: $path, $command
  819: 
  820: Returns: unescaped string of values.
  821: 
  822: =cut
  823: 
  824: ########################################################
  825: ########################################################
  826: sub courselog {
  827:     my ($path,$command)=@_;
  828:     my %filters=();
  829:     foreach (split(/\:/,&unescape($command))) {
  830: 	my ($name,$value)=split(/\=/,$_);
  831:         $filters{$name}=$value;
  832:     }
  833:     my @results=();
  834:     open(IN,$path.'/activity.log') or return ('file_error');
  835:     while (my $line=<IN>) {
  836:         chomp($line);
  837:         my ($timestamp,$host,$log)=split(/\:/,$line);
  838: #
  839: # $log has the actual log entries; currently still escaped, and
  840: # %26(timestamp)%3a(url)%3a(user)%3a(domain)
  841: # then additionally
  842: # %3aPOST%3a(name)%3d(value)%3a(name)%3d(value)
  843: # or
  844: # %3aCSTORE%3a(name)%3d(value)%26(name)%3d(value)
  845: #
  846: # get delimiter between timestamped entries to be &&&
  847:         $log=~s/\%26(\d+)\%3a/\&\&\&$1\%3a/g;
  848: # now go over all log entries 
  849:         foreach (split(/\&\&\&/,&unescape($log))) {
  850: 	    my ($time,$res,$uname,$udom,$action,@values)=split(/\:/,$_);
  851:             my $values=&unescape(join(':',@values));
  852:             $values=~s/\&/\:/g;
  853:             $res=&unescape($res);
  854:             my $include=1;
  855:             if (($filters{'username'}) && ($uname ne $filters{'username'})) 
  856:                                                                { $include=0; }
  857:             if (($filters{'domain'}) && ($udom ne $filters{'domain'})) 
  858:                                                                { $include=0; }
  859:             if (($filters{'url'}) && ($res!~/$filters{'url'}/)) 
  860:                                                                { $include=0; }
  861:             if (($filters{'start'}) && ($time<$filters{'start'})) 
  862:                                                                { $include=0; }
  863:             if (($filters{'end'}) && ($time>$filters{'end'})) 
  864:                                                                { $include=0; }
  865:             if (($filters{'action'} eq 'view') && ($action)) 
  866:                                                                { $include=0; }
  867:             if (($filters{'action'} eq 'submit') && ($action ne 'POST')) 
  868:                                                                { $include=0; }
  869:             if (($filters{'action'} eq 'grade') && ($action ne 'CSTORE')) 
  870:                                                                { $include=0; }
  871:             if ($include) {
  872: 	       push(@results,($time<1000000000?'0':'').$time.':'.$res.':'.
  873:                                             $uname.':'.$udom.':'.
  874:                                             $action.':'.$values);
  875:             }
  876:        }
  877:     }
  878:     close IN;
  879:     return join('&',sort(@results));
  880: }
  881: 
  882: ########################################################
  883: ########################################################
  884: 
  885: =pod
  886: 
  887: =item &userlog
  888: 
  889: Inputs: $path, $command
  890: 
  891: Returns: unescaped string of values.
  892: 
  893: =cut
  894: 
  895: ########################################################
  896: ########################################################
  897: sub userlog {
  898:     my ($path,$command)=@_;
  899:     my %filters=();
  900:     foreach (split(/\:/,&unescape($command))) {
  901: 	my ($name,$value)=split(/\=/,$_);
  902:         $filters{$name}=$value;
  903:     }
  904:     my @results=();
  905:     open(IN,$path.'/activity.log') or return ('file_error');
  906:     while (my $line=<IN>) {
  907:         chomp($line);
  908:         my ($timestamp,$host,$log)=split(/\:/,$line);
  909:         $log=&unescape($log);
  910:         my $include=1;
  911:         if (($filters{'start'}) && ($timestamp<$filters{'start'})) 
  912:                                                              { $include=0; }
  913:         if (($filters{'end'}) && ($timestamp>$filters{'end'})) 
  914:                                                              { $include=0; }
  915:         if (($filters{'action'} eq 'log') && ($log!~/^Log/)) { $include=0; }
  916:         if (($filters{'action'} eq 'check') && ($log!~/^Check/)) 
  917:                                                              { $include=0; }
  918:         if ($include) {
  919: 	   push(@results,$timestamp.':'.$log);
  920:         }
  921:     }
  922:     close IN;
  923:     return join('&',sort(@results));
  924: }
  925: 
  926: ########################################################
  927: ########################################################
  928: 
  929: =pod
  930: 
  931: =item Functions required for forking
  932: 
  933: =over 4
  934: 
  935: =item REAPER
  936: 
  937: REAPER takes care of dead children.
  938: 
  939: =item HUNTSMAN
  940: 
  941: Signal handler for SIGINT.
  942: 
  943: =item HUPSMAN
  944: 
  945: Signal handler for SIGHUP
  946: 
  947: =item DISCONNECT
  948: 
  949: Disconnects from database.
  950: 
  951: =back
  952: 
  953: =cut
  954: 
  955: ########################################################
  956: ########################################################
  957: sub REAPER {                   # takes care of dead children
  958:     $SIG{CHLD} = \&REAPER;
  959:     my $pid = wait;
  960:     $children --;
  961:     &logthis("Child $pid died");
  962:     delete $children{$pid};
  963: }
  964: 
  965: sub HUNTSMAN {                      # signal handler for SIGINT
  966:     local($SIG{CHLD}) = 'IGNORE';   # we're going to kill our children
  967:     kill 'INT' => keys %children;
  968:     my $execdir=$perlvar{'lonDaemons'};
  969:     unlink("$execdir/logs/lonsql.pid");
  970:     &logthis("<font color='red'>CRITICAL: Shutting down</font>");
  971:     $unixsock = "mysqlsock";
  972:     my $port="$perlvar{'lonSockDir'}/$unixsock";
  973:     unlink($port);
  974:     exit;                           # clean up with dignity
  975: }
  976: 
  977: sub HUPSMAN {                      # signal handler for SIGHUP
  978:     local($SIG{CHLD}) = 'IGNORE';  # we're going to kill our children
  979:     kill 'INT' => keys %children;
  980:     close($server);                # free up socket
  981:     &logthis("<font color='red'>CRITICAL: Restarting</font>");
  982:     my $execdir=$perlvar{'lonDaemons'};
  983:     $unixsock = "mysqlsock";
  984:     my $port="$perlvar{'lonSockDir'}/$unixsock";
  985:     unlink($port);
  986:     exec("$execdir/lonsql");         # here we go again
  987: }
  988: 
  989: sub DISCONNECT {
  990:     $dbh->disconnect or 
  991:     &logthis("<font color='blue'>WARNING: Couldn't disconnect from database ".
  992:              " $DBI::errstr : $@</font>");
  993:     exit;
  994: }
  995: 
  996: 
  997: =pod
  998: 
  999: =back
 1000: 
 1001: =cut

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