File:  [LON-CAPA] / loncom / lonsql
Revision 1.77: download - view: text, annotated - select for diffs
Thu May 11 17:53:22 2006 UTC (17 years, 11 months ago) by albertel
Branches: MAIN
CVS tags: version_2_3_0, version_2_2_X, version_2_2_99_1, version_2_2_99_0, version_2_2_2, version_2_2_1, version_2_2_0, version_2_1_99_3, version_2_1_99_2, version_2_1_99_1, version_2_1_99_0, HEAD
- removing some code duplication

    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.77 2006/05/11 17:53:22 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;
  106: use LONCAPA::Configuration;
  107: use LONCAPA::lonmetadata();
  108: 
  109: use IO::Socket;
  110: use Symbol;
  111: use POSIX;
  112: use IO::Select;
  113: use IO::File;
  114: use Socket;
  115: use Fcntl;
  116: use Tie::RefHash;
  117: use DBI;
  118: use File::Find;
  119: use localenroll;
  120: 
  121: ########################################################
  122: ########################################################
  123: 
  124: =pod
  125: 
  126: =item Global Variables
  127: 
  128: =over 4
  129: 
  130: =item dbh
  131: 
  132: =back
  133: 
  134: =cut
  135: 
  136: ########################################################
  137: ########################################################
  138: my $dbh;
  139: 
  140: ########################################################
  141: ########################################################
  142: 
  143: =pod 
  144: 
  145: =item Variables required for forking
  146: 
  147: =over 4
  148: 
  149: =item $MAX_CLIENTS_PER_CHILD
  150: 
  151: The number of clients each child should process.
  152: 
  153: =item %children 
  154: 
  155: The keys to %children  are the current child process IDs
  156: 
  157: =item $children
  158: 
  159: The current number of children
  160: 
  161: =back
  162: 
  163: =cut 
  164: 
  165: ########################################################
  166: ########################################################
  167: my $MAX_CLIENTS_PER_CHILD  = 5;   # number of clients each child should process
  168: my %children               = ();  # keys are current child process IDs
  169: my $children               = 0;   # current number of children
  170:                                
  171: ###################################################################
  172: ###################################################################
  173: 
  174: =pod
  175: 
  176: =item Main body of code.
  177: 
  178: =over 4
  179: 
  180: =item Read data from loncapa_apache.conf and loncapa.conf.
  181: 
  182: =item Ensure we can access the database.
  183: 
  184: =item Determine if there are other instances of lonsql running.
  185: 
  186: =item Read the hosts file.
  187: 
  188: =item Create a socket for lonsql.
  189: 
  190: =item Fork once and dissociate from parent.
  191: 
  192: =item Write PID to disk.
  193: 
  194: =item Prefork children and maintain the population of children.
  195: 
  196: =back
  197: 
  198: =cut
  199: 
  200: ###################################################################
  201: ###################################################################
  202: my $childmaxattempts=10;
  203: my $run =0;              # running counter to generate the query-id
  204: #
  205: # Read loncapa_apache.conf and loncapa.conf
  206: #
  207: my $perlvarref=LONCAPA::Configuration::read_conf('loncapa.conf');
  208: my %perlvar=%{$perlvarref};
  209: #
  210: # Write the /home/www/.my.cnf file 
  211: my $conf_file = '/home/www/.my.cnf';
  212: if (! -e $conf_file) {
  213:     if (open MYCNF, ">$conf_file") {
  214:         print MYCNF <<"ENDMYCNF";
  215: [client]
  216: user=www
  217: password=$perlvar{'lonSqlAccess'}
  218: ENDMYCNF
  219:         close MYCNF;
  220:     } else {
  221:         warn "Unable to write $conf_file, continuing";
  222:     }
  223: }
  224: 
  225: 
  226: #
  227: # Make sure that database can be accessed
  228: #
  229: my $dbh;
  230: unless ($dbh = DBI->connect("DBI:mysql:loncapa","www",
  231:                             $perlvar{'lonSqlAccess'},
  232:                             { RaiseError =>0,PrintError=>0})) { 
  233:     print "Cannot connect to database!\n";
  234:     my $emailto="$perlvar{'lonAdmEMail'},$perlvar{'lonSysEMail'}";
  235:     my $subj="LON: $perlvar{'lonHostID'} Cannot connect to database!";
  236:     system("echo 'Cannot connect to MySQL database!' |".
  237:            " mailto $emailto -s '$subj' > /dev/null");
  238: 
  239:     open(SMP,'>/home/httpd/html/lon-status/mysql.txt');
  240:     print SMP 'time='.time.'&mysql=defunct'."\n";
  241:     close(SMP);
  242: 
  243:     exit 1;
  244: } else {
  245:     unlink('/home/httpd/html/lon-status/mysql.txt');
  246:     $dbh->disconnect;
  247: }
  248: 
  249: #
  250: # Check if other instance running
  251: #
  252: my $pidfile="$perlvar{'lonDaemons'}/logs/lonsql.pid";
  253: if (-e $pidfile) {
  254:    my $lfh=IO::File->new("$pidfile");
  255:    my $pide=<$lfh>;
  256:    chomp($pide);
  257:    if (kill 0 => $pide) { die "already running"; }
  258: }
  259: 
  260: #
  261: # Read hosts file
  262: #
  263: my $thisserver;
  264: my %hostname;
  265: my $PREFORK=4; # number of children to maintain, at least four spare
  266: open (CONFIG,"$perlvar{'lonTabDir'}/hosts.tab") || die "Can't read host file";
  267: while (my $configline=<CONFIG>) {
  268:     my ($id,$domain,$role,$name)=split(/:/,$configline);
  269:     $name=~s/\s//g;
  270:     $thisserver=$name if ($id eq $perlvar{'lonHostID'});
  271:     $hostname{$id}=$name;
  272:     #$PREFORK++;
  273: }
  274: close(CONFIG);
  275: #
  276: #$PREFORK=int($PREFORK/4);
  277: 
  278: #
  279: # Create a socket to talk to lond
  280: #
  281: my $unixsock = "mysqlsock";
  282: my $localfile="$perlvar{'lonSockDir'}/$unixsock";
  283: my $server;
  284: unlink ($localfile);
  285: unless ($server=IO::Socket::UNIX->new(Local    =>"$localfile",
  286:                                       Type    => SOCK_STREAM,
  287:                                       Listen => 10)) {
  288:     print "in socket error:$@\n";
  289: }
  290: 
  291: #
  292: # Fork once and dissociate
  293: #
  294: my $fpid=fork;
  295: exit if $fpid;
  296: die "Couldn't fork: $!" unless defined ($fpid);
  297: POSIX::setsid() or die "Can't start new session: $!";
  298: 
  299: #
  300: # Write our PID on disk
  301: my $execdir=$perlvar{'lonDaemons'};
  302: open (PIDSAVE,">$execdir/logs/lonsql.pid");
  303: print PIDSAVE "$$\n";
  304: close(PIDSAVE);
  305: &logthis("<font color='red'>CRITICAL: ---------- Starting ----------</font>");
  306: 
  307: #
  308: # Ignore signals generated during initial startup
  309: $SIG{HUP}=$SIG{USR1}='IGNORE';
  310: # Now we are on our own    
  311: #    Fork off our children.
  312: for (1 .. $PREFORK) {
  313:     make_new_child();
  314: }
  315: 
  316: #
  317: # Install signal handlers.
  318: $SIG{CHLD} = \&REAPER;
  319: $SIG{INT}  = $SIG{TERM} = \&HUNTSMAN;
  320: $SIG{HUP}  = \&HUPSMAN;
  321: 
  322: #
  323: # And maintain the population.
  324: while (1) {
  325:     sleep;                          # wait for a signal (i.e., child's death)
  326:     for (my $i = $children; $i < $PREFORK; $i++) {
  327:         make_new_child();           # top up the child pool
  328:     }
  329: }
  330: 
  331: ########################################################
  332: ########################################################
  333: 
  334: =pod
  335: 
  336: =item &make_new_child
  337: 
  338: Inputs: None
  339: 
  340: Returns: None
  341: 
  342: =cut
  343: 
  344: ########################################################
  345: ########################################################
  346: sub make_new_child {
  347:     my $pid;
  348:     my $sigset;
  349:     #
  350:     # block signal for fork
  351:     $sigset = POSIX::SigSet->new(SIGINT);
  352:     sigprocmask(SIG_BLOCK, $sigset)
  353:         or die "Can't block SIGINT for fork: $!\n";
  354:     #
  355:     die "fork: $!" unless defined ($pid = fork);
  356:     #
  357:     if ($pid) {
  358:         # Parent records the child's birth and returns.
  359:         sigprocmask(SIG_UNBLOCK, $sigset)
  360:             or die "Can't unblock SIGINT for fork: $!\n";
  361:         $children{$pid} = 1;
  362:         $children++;
  363:         return;
  364:     } else {
  365:         # Child can *not* return from this subroutine.
  366:         $SIG{INT} = 'DEFAULT';      # make SIGINT kill us as it did before
  367:         # unblock signals
  368:         sigprocmask(SIG_UNBLOCK, $sigset)
  369:             or die "Can't unblock SIGINT for fork: $!\n";
  370:         #open database handle
  371: 	# making dbh global to avoid garbage collector
  372: 	unless ($dbh = DBI->connect("DBI:mysql:loncapa","www",
  373:                                     $perlvar{'lonSqlAccess'},
  374:                                     { RaiseError =>0,PrintError=>0})) { 
  375:             sleep(10+int(rand(20)));
  376:             &logthis("<font color='blue'>WARNING: Couldn't connect to database".
  377:                      ": $@</font>");
  378:                      #  "($st secs): $@</font>");
  379:             print "database handle error\n";
  380:             exit;
  381:         }
  382: 	# make sure that a database disconnection occurs with 
  383:         # ending kill signals
  384: 	$SIG{TERM}=$SIG{INT}=$SIG{QUIT}=$SIG{__DIE__}=\&DISCONNECT;
  385:         # handle connections until we've reached $MAX_CLIENTS_PER_CHILD
  386:         for (my $i=0; $i < $MAX_CLIENTS_PER_CHILD; $i++) {
  387:             my $client = $server->accept() or last;
  388:             # do something with the connection
  389: 	    $run = $run+1;
  390: 	    my $userinput = <$client>;
  391: 	    chomp($userinput);
  392:             $userinput=~s/\:(\w+)$//;
  393:             my $searchdomain=$1;
  394:             #
  395: 	    my ($conserver,$query,
  396: 		$arg1,$arg2,$arg3)=split(/&/,$userinput);
  397: 	    my $query=unescape($query);
  398:             #
  399:             #send query id which is pid_unixdatetime_runningcounter
  400: 	    my $queryid = $thisserver;
  401: 	    $queryid .="_".($$)."_";
  402: 	    $queryid .= time."_";
  403: 	    $queryid .= $run;
  404: 	    print $client "$queryid\n";
  405: 	    #
  406: 	    # &logthis("QUERY: $query - $arg1 - $arg2 - $arg3");
  407: 	    sleep 1;
  408:             #
  409:             my $result='';
  410:             #
  411:             # At this point, query is received, query-ID assigned and sent 
  412:             # back, $query eq 'logquery' will mean that this is a query 
  413:             # against log-files
  414:             if (($query eq 'userlog') || ($query eq 'courselog')) {
  415:                 # beginning of log query
  416:                 my $udom    = &unescape($arg1);
  417:                 my $uname   = &unescape($arg2);
  418:                 my $command = &unescape($arg3);
  419:                 my $path    = &propath($udom,$uname);
  420:                 if (-e "$path/activity.log") {
  421:                     if ($query eq 'userlog') {
  422:                         $result=&userlog($path,$command);
  423:                     } else {
  424:                         $result=&courselog($path,$command);
  425:                     }
  426:                 } else {
  427:                     &logthis('Unable to do log query: '.$uname.'@'.$udom);
  428:                     $result='no_such_file';
  429:                 }
  430:                 # end of log query
  431:             } elsif (($query eq 'fetchenrollment') || 
  432: 		     ($query eq 'institutionalphotos')) {
  433:                 # retrieve institutional class lists
  434:                 my $dom = &unescape($arg1);
  435:                 my %affiliates = ();
  436:                 my %replies = ();
  437:                 my $locresult = '';
  438:                 my $querystr = &unescape($arg3);
  439:                 foreach (split/%%/,$querystr) {
  440:                     if (/^([^=]+)=([^=]+)$/) {
  441:                         @{$affiliates{$1}} = split/,/,$2;
  442:                     }
  443:                 }
  444:                 if ($query eq 'fetchenrollment') { 
  445:                     $locresult = &localenroll::fetch_enrollment($dom,\%affiliates,\%replies);
  446:                 } elsif ($query eq 'institutionalphotos') {
  447:                     my $crs = &unescape($arg2);
  448: 		    eval {
  449: 			local($SIG{__DIE__})='DEFAULT';
  450: 			$locresult = &localenroll::institutional_photos($dom,$crs,\%affiliates,\%replies,'update');
  451: 		    };
  452: 		    if ($@) {
  453: 			$locresult = 'error';
  454: 		    }
  455:                 }
  456:                 $result = &escape($locresult.':');
  457:                 if ($locresult) {
  458:                     $result .= &escape(join(':',map{$_.'='.$replies{$_}} keys %replies));
  459:                 }
  460:             } elsif ($query eq 'prepare activity log') {
  461:                 my ($cid,$domain) = map {&unescape($_);} ($arg1,$arg2);
  462:                 &logthis('preparing activity log tables for '.$cid);
  463:                 my $command = 
  464:                     qq{$perlvar{'lonDaemons'}/parse_activity_log.pl -course=$cid -domain=$domain};
  465:                 system($command);
  466:                 &logthis($command);
  467:                 my $returnvalue = $?>>8;
  468:                 if ($returnvalue) {
  469:                     $result = 'error: parse_activity_log.pl returned '.
  470:                         $returnvalue;
  471:                 } else {
  472:                     $result = 'success';
  473:                 }
  474:             } else {
  475:                 # Do an sql query
  476:                 $result = &do_sql_query($query,$arg1,$arg2,$searchdomain);
  477:             }
  478:             # result does not need to be escaped because it has already been
  479:             # escaped.
  480:             #$result=&escape($result);
  481:             &reply("queryreply:$queryid:$result",$conserver);
  482:         }
  483:         # tidy up gracefully and finish
  484:         #
  485:         # close the database handle
  486: 	$dbh->disconnect
  487:             or &logthis("<font color='blue'>WARNING: Couldn't disconnect".
  488:                         " from database  $DBI::errstr : $@</font>");
  489:         # this exit is VERY important, otherwise the child will become
  490:         # a producer of more and more children, forking yourself into
  491:         # process death.
  492:         exit;
  493:     }
  494: }
  495: 
  496: ########################################################
  497: ########################################################
  498: 
  499: =pod
  500: 
  501: =item &do_sql_query
  502: 
  503: Runs an sql metadata table query.
  504: 
  505: Inputs: $query, $custom, $customshow
  506: 
  507: Returns: A string containing escaped results.
  508: 
  509: =cut
  510: 
  511: ########################################################
  512: ########################################################
  513: {
  514:     my @metalist;
  515: 
  516: sub process_file {
  517:     if ( -e $_ &&  # file exists
  518:          -f $_ &&  # and is a normal file
  519:          /\.meta$/ &&  # ends in meta
  520:          ! /^.+\.\d+\.[^\.]+\.meta$/  # is not a previous version
  521:          ) {
  522:         push(@metalist,$File::Find::name);
  523:     }
  524: }
  525: 
  526: sub do_sql_query {
  527:     my ($query,$custom,$customshow,$searchdomain) = @_;
  528: 
  529: #
  530: # limit to searchdomain if given and table is metadata
  531: #
  532:     if (($searchdomain) && ($query=~/FROM metadata/)) {
  533: 	$query.=' HAVING (domain="'.$searchdomain.'")';
  534:     }
  535: #    &logthis('doing query ('.$searchdomain.')'.$query);
  536: 
  537: 
  538: 
  539:     $custom     = &unescape($custom);
  540:     $customshow = &unescape($customshow);
  541:     #
  542:     @metalist = ();
  543:     #
  544:     my $result = '';
  545:     my @results = ();
  546:     my @files;
  547:     my $subsetflag=0;
  548:     #
  549:     if ($query) {
  550:         #prepare and execute the 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 &ishome
  733: 
  734: Determine if the current machine is the home server for a user.
  735: The determination is made by checking the filesystem for the users information.
  736: 
  737: Inputs: $author
  738: 
  739: Returns: 0 - this is not the authors home server, 1 - this is.
  740: 
  741: =cut
  742: 
  743: ########################################################
  744: ########################################################
  745: sub ishome {
  746:     my $author=shift;
  747:     $author=~s/\/home\/httpd\/html\/res\/([^\/]*)\/([^\/]*).*/$1\/$2/;
  748:     my ($udom,$uname)=split(/\//,$author);
  749:     my $proname=propath($udom,$uname);
  750:     if (-e $proname) {
  751: 	return 1;
  752:     } else {
  753:         return 0;
  754:     }
  755: }
  756: 
  757: ########################################################
  758: ########################################################
  759: 
  760: =pod
  761: 
  762: =item &propath
  763: 
  764: Inputs: user name, user domain
  765: 
  766: Returns: The full path to the users directory.
  767: 
  768: =cut
  769: 
  770: ########################################################
  771: ########################################################
  772: sub propath {
  773:     my ($udom,$uname)=@_;
  774:     $udom=~s/\W//g;
  775:     $uname=~s/\W//g;
  776:     my $subdir=$uname.'__';
  777:     $subdir =~ s/(.)(.)(.).*/$1\/$2\/$3/;
  778:     my $proname="$perlvar{'lonUsersDir'}/$udom/$subdir/$uname";
  779:     return $proname;
  780: } 
  781: 
  782: ########################################################
  783: ########################################################
  784: 
  785: =pod
  786: 
  787: =item &courselog
  788: 
  789: Inputs: $path, $command
  790: 
  791: Returns: unescaped string of values.
  792: 
  793: =cut
  794: 
  795: ########################################################
  796: ########################################################
  797: sub courselog {
  798:     my ($path,$command)=@_;
  799:     my %filters=();
  800:     foreach (split(/\:/,&unescape($command))) {
  801: 	my ($name,$value)=split(/\=/,$_);
  802:         $filters{$name}=$value;
  803:     }
  804:     my @results=();
  805:     open(IN,$path.'/activity.log') or return ('file_error');
  806:     while (my $line=<IN>) {
  807:         chomp($line);
  808:         my ($timestamp,$host,$log)=split(/\:/,$line);
  809: #
  810: # $log has the actual log entries; currently still escaped, and
  811: # %26(timestamp)%3a(url)%3a(user)%3a(domain)
  812: # then additionally
  813: # %3aPOST%3a(name)%3d(value)%3a(name)%3d(value)
  814: # or
  815: # %3aCSTORE%3a(name)%3d(value)%26(name)%3d(value)
  816: #
  817: # get delimiter between timestamped entries to be &&&
  818:         $log=~s/\%26(\d+)\%3a/\&\&\&$1\%3a/g;
  819: # now go over all log entries 
  820:         foreach (split(/\&\&\&/,&unescape($log))) {
  821: 	    my ($time,$res,$uname,$udom,$action,@values)=split(/\:/,$_);
  822:             my $values=&unescape(join(':',@values));
  823:             $values=~s/\&/\:/g;
  824:             $res=&unescape($res);
  825:             my $include=1;
  826:             if (($filters{'username'}) && ($uname ne $filters{'username'})) 
  827:                                                                { $include=0; }
  828:             if (($filters{'domain'}) && ($udom ne $filters{'domain'})) 
  829:                                                                { $include=0; }
  830:             if (($filters{'url'}) && ($res!~/$filters{'url'}/)) 
  831:                                                                { $include=0; }
  832:             if (($filters{'start'}) && ($time<$filters{'start'})) 
  833:                                                                { $include=0; }
  834:             if (($filters{'end'}) && ($time>$filters{'end'})) 
  835:                                                                { $include=0; }
  836:             if (($filters{'action'} eq 'view') && ($action)) 
  837:                                                                { $include=0; }
  838:             if (($filters{'action'} eq 'submit') && ($action ne 'POST')) 
  839:                                                                { $include=0; }
  840:             if (($filters{'action'} eq 'grade') && ($action ne 'CSTORE')) 
  841:                                                                { $include=0; }
  842:             if ($include) {
  843: 	       push(@results,($time<1000000000?'0':'').$time.':'.$res.':'.
  844:                                             $uname.':'.$udom.':'.
  845:                                             $action.':'.$values);
  846:             }
  847:        }
  848:     }
  849:     close IN;
  850:     return join('&',sort(@results));
  851: }
  852: 
  853: ########################################################
  854: ########################################################
  855: 
  856: =pod
  857: 
  858: =item &userlog
  859: 
  860: Inputs: $path, $command
  861: 
  862: Returns: unescaped string of values.
  863: 
  864: =cut
  865: 
  866: ########################################################
  867: ########################################################
  868: sub userlog {
  869:     my ($path,$command)=@_;
  870:     my %filters=();
  871:     foreach (split(/\:/,&unescape($command))) {
  872: 	my ($name,$value)=split(/\=/,$_);
  873:         $filters{$name}=$value;
  874:     }
  875:     my @results=();
  876:     open(IN,$path.'/activity.log') or return ('file_error');
  877:     while (my $line=<IN>) {
  878:         chomp($line);
  879:         my ($timestamp,$host,$log)=split(/\:/,$line);
  880:         $log=&unescape($log);
  881:         my $include=1;
  882:         if (($filters{'start'}) && ($timestamp<$filters{'start'})) 
  883:                                                              { $include=0; }
  884:         if (($filters{'end'}) && ($timestamp>$filters{'end'})) 
  885:                                                              { $include=0; }
  886:         if (($filters{'action'} eq 'log') && ($log!~/^Log/)) { $include=0; }
  887:         if (($filters{'action'} eq 'check') && ($log!~/^Check/)) 
  888:                                                              { $include=0; }
  889:         if ($include) {
  890: 	   push(@results,$timestamp.':'.$log);
  891:         }
  892:     }
  893:     close IN;
  894:     return join('&',sort(@results));
  895: }
  896: 
  897: ########################################################
  898: ########################################################
  899: 
  900: =pod
  901: 
  902: =item Functions required for forking
  903: 
  904: =over 4
  905: 
  906: =item REAPER
  907: 
  908: REAPER takes care of dead children.
  909: 
  910: =item HUNTSMAN
  911: 
  912: Signal handler for SIGINT.
  913: 
  914: =item HUPSMAN
  915: 
  916: Signal handler for SIGHUP
  917: 
  918: =item DISCONNECT
  919: 
  920: Disconnects from database.
  921: 
  922: =back
  923: 
  924: =cut
  925: 
  926: ########################################################
  927: ########################################################
  928: sub REAPER {                   # takes care of dead children
  929:     $SIG{CHLD} = \&REAPER;
  930:     my $pid = wait;
  931:     $children --;
  932:     &logthis("Child $pid died");
  933:     delete $children{$pid};
  934: }
  935: 
  936: sub HUNTSMAN {                      # signal handler for SIGINT
  937:     local($SIG{CHLD}) = 'IGNORE';   # we're going to kill our children
  938:     kill 'INT' => keys %children;
  939:     my $execdir=$perlvar{'lonDaemons'};
  940:     unlink("$execdir/logs/lonsql.pid");
  941:     &logthis("<font color='red'>CRITICAL: Shutting down</font>");
  942:     $unixsock = "mysqlsock";
  943:     my $port="$perlvar{'lonSockDir'}/$unixsock";
  944:     unlink($port);
  945:     exit;                           # clean up with dignity
  946: }
  947: 
  948: sub HUPSMAN {                      # signal handler for SIGHUP
  949:     local($SIG{CHLD}) = 'IGNORE';  # we're going to kill our children
  950:     kill 'INT' => keys %children;
  951:     close($server);                # free up socket
  952:     &logthis("<font color='red'>CRITICAL: Restarting</font>");
  953:     my $execdir=$perlvar{'lonDaemons'};
  954:     $unixsock = "mysqlsock";
  955:     my $port="$perlvar{'lonSockDir'}/$unixsock";
  956:     unlink($port);
  957:     exec("$execdir/lonsql");         # here we go again
  958: }
  959: 
  960: sub DISCONNECT {
  961:     $dbh->disconnect or 
  962:     &logthis("<font color='blue'>WARNING: Couldn't disconnect from database ".
  963:              " $DBI::errstr : $@</font>");
  964:     exit;
  965: }
  966: 
  967: 
  968: =pod
  969: 
  970: =back
  971: 
  972: =cut

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