Annotation of loncom/lonsql, revision 1.58

1.1       harris41    1: #!/usr/bin/perl
1.39      harris41    2: 
                      3: # The LearningOnline Network
1.40      harris41    4: # lonsql - LON TCP-MySQL-Server Daemon for handling database requests.
1.39      harris41    5: #
1.58    ! matthew     6: # $Id: lonsql,v 1.57 2003/07/30 16:49:27 www Exp $
1.41      harris41    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: #
1.51      matthew    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: 
1.56      bowersj2   42: =head1 OVERVIEW
1.51      matthew    43: 
1.56      bowersj2   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.
1.51      matthew    95: 
                     96: =head1 Internals
                     97: 
                     98: =over 4
                     99: 
                    100: =cut
                    101: 
                    102: use strict;
1.36      www       103: 
1.42      harris41  104: use lib '/home/httpd/lib/perl/';
                    105: use LONCAPA::Configuration;
1.58    ! matthew   106: use LONCAPA::lonmetadata();
1.42      harris41  107: 
1.2       harris41  108: use IO::Socket;
                    109: use Symbol;
1.1       harris41  110: use POSIX;
                    111: use IO::Select;
                    112: use IO::File;
                    113: use Socket;
                    114: use Fcntl;
                    115: use Tie::RefHash;
                    116: use DBI;
1.51      matthew   117: use File::Find;
                    118: 
                    119: ########################################################
                    120: ########################################################
                    121: 
                    122: =pod
                    123: 
                    124: =item Global Variables
                    125: 
                    126: =over 4
                    127: 
                    128: =item dbh
                    129: 
                    130: =back
                    131: 
                    132: =cut
                    133: 
                    134: ########################################################
                    135: ########################################################
                    136: my $dbh;
                    137: 
                    138: ########################################################
                    139: ########################################################
                    140: 
                    141: =pod 
                    142: 
                    143: =item Variables required for forking
1.1       harris41  144: 
1.51      matthew   145: =over 4
                    146: 
                    147: =item $MAX_CLIENTS_PER_CHILD
                    148: 
                    149: The number of clients each child should process.
                    150: 
                    151: =item %children 
                    152: 
                    153: The keys to %children  are the current child process IDs
                    154: 
                    155: =item $children
                    156: 
                    157: The current number of children
                    158: 
                    159: =back
                    160: 
                    161: =cut 
1.9       harris41  162: 
1.51      matthew   163: ########################################################
                    164: ########################################################
                    165: my $MAX_CLIENTS_PER_CHILD  = 5;   # number of clients each child should process
                    166: my %children               = ();  # keys are current child process IDs
                    167: my $children               = 0;   # current number of children
                    168:                                
                    169: ###################################################################
                    170: ###################################################################
                    171: 
                    172: =pod
                    173: 
                    174: =item Main body of code.
                    175: 
                    176: =over 4
1.45      www       177: 
1.51      matthew   178: =item Read data from loncapa_apache.conf and loncapa.conf.
                    179: 
                    180: =item Ensure we can access the database.
                    181: 
                    182: =item Determine if there are other instances of lonsql running.
                    183: 
                    184: =item Read the hosts file.
                    185: 
                    186: =item Create a socket for lonsql.
                    187: 
                    188: =item Fork once and dissociate from parent.
                    189: 
                    190: =item Write PID to disk.
                    191: 
                    192: =item Prefork children and maintain the population of children.
                    193: 
                    194: =back
                    195: 
                    196: =cut
                    197: 
                    198: ###################################################################
                    199: ###################################################################
                    200: my $childmaxattempts=10;
                    201: my $run =0;              # running counter to generate the query-id
                    202: #
                    203: # Read loncapa_apache.conf and loncapa.conf
                    204: #
1.53      harris41  205: my $perlvarref=LONCAPA::Configuration::read_conf('loncapa.conf');
1.51      matthew   206: my %perlvar=%{$perlvarref};
                    207: #
                    208: # Make sure that database can be accessed
                    209: #
                    210: my $dbh;
                    211: unless ($dbh = DBI->connect("DBI:mysql:loncapa","www",
                    212:                             $perlvar{'lonSqlAccess'},
                    213:                             { RaiseError =>0,PrintError=>0})) { 
                    214:     print "Cannot connect to database!\n";
                    215:     my $emailto="$perlvar{'lonAdmEMail'},$perlvar{'lonSysEMail'}";
                    216:     my $subj="LON: $perlvar{'lonHostID'} Cannot connect to database!";
                    217:     system("echo 'Cannot connect to MySQL database!' |".
                    218:            " mailto $emailto -s '$subj' > /dev/null");
1.57      www       219: 
                    220:     open(SMP,'>/home/httpd/html/lon-status/mysql.txt');
                    221:     print SMP 'time='.time.'&mysql=defunct'."\n";
                    222:     close(SMP);
                    223: 
1.51      matthew   224:     exit 1;
                    225: } else {
                    226:     $dbh->disconnect;
                    227: }
1.52      matthew   228: 
1.51      matthew   229: #
                    230: # Check if other instance running
                    231: #
                    232: my $pidfile="$perlvar{'lonDaemons'}/logs/lonsql.pid";
                    233: if (-e $pidfile) {
                    234:    my $lfh=IO::File->new("$pidfile");
                    235:    my $pide=<$lfh>;
                    236:    chomp($pide);
                    237:    if (kill 0 => $pide) { die "already running"; }
                    238: }
1.52      matthew   239: 
1.49      www       240: #
1.51      matthew   241: # Read hosts file
1.49      www       242: #
1.51      matthew   243: my %hostip;
                    244: my $thisserver;
                    245: my $PREFORK=4; # number of children to maintain, at least four spare
                    246: open (CONFIG,"$perlvar{'lonTabDir'}/hosts.tab") || die "Can't read host file";
                    247: while (my $configline=<CONFIG>) {
                    248:     my ($id,$domain,$role,$name,$ip)=split(/:/,$configline);
                    249:     chomp($ip);
                    250:     $hostip{$ip}=$id;
                    251:     $thisserver=$name if ($id eq $perlvar{'lonHostID'});
                    252:     $PREFORK++;
1.45      www       253: }
1.51      matthew   254: close(CONFIG);
                    255: #
                    256: $PREFORK=int($PREFORK/4);
1.52      matthew   257: 
1.51      matthew   258: #
                    259: # Create a socket to talk to lond
                    260: #
                    261: my $unixsock = "mysqlsock";
                    262: my $localfile="$perlvar{'lonSockDir'}/$unixsock";
                    263: my $server;
                    264: unlink ($localfile);
                    265: unless ($server=IO::Socket::UNIX->new(Local    =>"$localfile",
                    266:                                       Type    => SOCK_STREAM,
                    267:                                       Listen => 10)) {
                    268:     print "in socket error:$@\n";
1.45      www       269: }
1.52      matthew   270: 
1.51      matthew   271: #
                    272: # Fork once and dissociate
1.52      matthew   273: #
1.51      matthew   274: my $fpid=fork;
1.1       harris41  275: exit if $fpid;
                    276: die "Couldn't fork: $!" unless defined ($fpid);
                    277: POSIX::setsid() or die "Can't start new session: $!";
1.52      matthew   278: 
1.51      matthew   279: #
                    280: # Write our PID on disk
                    281: my $execdir=$perlvar{'lonDaemons'};
1.1       harris41  282: open (PIDSAVE,">$execdir/logs/lonsql.pid");
                    283: print PIDSAVE "$$\n";
                    284: close(PIDSAVE);
                    285: &logthis("<font color=red>CRITICAL: ---------- Starting ----------</font>");
1.52      matthew   286: 
1.51      matthew   287: #
                    288: # Ignore signals generated during initial startup
1.1       harris41  289: $SIG{HUP}=$SIG{USR1}='IGNORE';
1.51      matthew   290: # Now we are on our own    
                    291: #    Fork off our children.
1.2       harris41  292: for (1 .. $PREFORK) {
                    293:     make_new_child();
1.1       harris41  294: }
1.52      matthew   295: 
1.51      matthew   296: #
1.2       harris41  297: # Install signal handlers.
1.1       harris41  298: $SIG{CHLD} = \&REAPER;
                    299: $SIG{INT}  = $SIG{TERM} = \&HUNTSMAN;
                    300: $SIG{HUP}  = \&HUPSMAN;
1.52      matthew   301: 
1.51      matthew   302: #
1.1       harris41  303: # And maintain the population.
                    304: while (1) {
                    305:     sleep;                          # wait for a signal (i.e., child's death)
1.51      matthew   306:     for (my $i = $children; $i < $PREFORK; $i++) {
1.2       harris41  307:         make_new_child();           # top up the child pool
1.1       harris41  308:     }
                    309: }
                    310: 
1.51      matthew   311: ########################################################
                    312: ########################################################
                    313: 
                    314: =pod
                    315: 
                    316: =item &make_new_child
                    317: 
                    318: Inputs: None
                    319: 
                    320: Returns: None
                    321: 
                    322: =cut
1.2       harris41  323: 
1.51      matthew   324: ########################################################
                    325: ########################################################
1.1       harris41  326: sub make_new_child {
                    327:     my $pid;
                    328:     my $sigset;
1.51      matthew   329:     #
1.1       harris41  330:     # block signal for fork
                    331:     $sigset = POSIX::SigSet->new(SIGINT);
                    332:     sigprocmask(SIG_BLOCK, $sigset)
                    333:         or die "Can't block SIGINT for fork: $!\n";
1.51      matthew   334:     #
1.2       harris41  335:     die "fork: $!" unless defined ($pid = fork);
1.51      matthew   336:     #
1.1       harris41  337:     if ($pid) {
                    338:         # Parent records the child's birth and returns.
                    339:         sigprocmask(SIG_UNBLOCK, $sigset)
                    340:             or die "Can't unblock SIGINT for fork: $!\n";
                    341:         $children{$pid} = 1;
                    342:         $children++;
                    343:         return;
                    344:     } else {
1.2       harris41  345:         # Child can *not* return from this subroutine.
1.1       harris41  346:         $SIG{INT} = 'DEFAULT';      # make SIGINT kill us as it did before
                    347:         # unblock signals
                    348:         sigprocmask(SIG_UNBLOCK, $sigset)
                    349:             or die "Can't unblock SIGINT for fork: $!\n";
1.2       harris41  350:         #open database handle
                    351: 	# making dbh global to avoid garbage collector
1.51      matthew   352: 	unless ($dbh = DBI->connect("DBI:mysql:loncapa","www",
                    353:                                     $perlvar{'lonSqlAccess'},
                    354:                                     { RaiseError =>0,PrintError=>0})) { 
                    355:             sleep(10+int(rand(20)));
                    356:             &logthis("<font color=blue>WARNING: Couldn't connect to database".
                    357:                      ": $@</font>");
                    358:                      #  "($st secs): $@</font>");
                    359:             print "database handle error\n";
                    360:             exit;
                    361:         }
                    362: 	# make sure that a database disconnection occurs with 
                    363:         # ending kill signals
1.2       harris41  364: 	$SIG{TERM}=$SIG{INT}=$SIG{QUIT}=$SIG{__DIE__}=\&DISCONNECT;
1.1       harris41  365:         # handle connections until we've reached $MAX_CLIENTS_PER_CHILD
1.51      matthew   366:         for (my $i=0; $i < $MAX_CLIENTS_PER_CHILD; $i++) {
                    367:             my $client = $server->accept() or last;
1.2       harris41  368:             # do something with the connection
1.1       harris41  369: 	    $run = $run+1;
1.2       harris41  370: 	    my $userinput = <$client>;
                    371: 	    chomp($userinput);
1.51      matthew   372:             #
1.45      www       373: 	    my ($conserver,$query,
                    374: 		$arg1,$arg2,$arg3)=split(/&/,$userinput);
                    375: 	    my $query=unescape($query);
1.51      matthew   376:             #
1.2       harris41  377:             #send query id which is pid_unixdatetime_runningcounter
1.51      matthew   378: 	    my $queryid = $thisserver;
1.2       harris41  379: 	    $queryid .="_".($$)."_";
                    380: 	    $queryid .= time."_";
                    381: 	    $queryid .= $run;
                    382: 	    print $client "$queryid\n";
1.51      matthew   383: 	    #
1.47      www       384: 	    &logthis("QUERY: $query - $arg1 - $arg2 - $arg3");
1.25      harris41  385: 	    sleep 1;
1.51      matthew   386:             #
1.45      www       387:             my $result='';
1.51      matthew   388:             #
                    389:             # At this point, query is received, query-ID assigned and sent 
                    390:             # back, $query eq 'logquery' will mean that this is a query 
                    391:             # against log-files
                    392:             if (($query eq 'userlog') || ($query eq 'courselog')) {
                    393:                 # beginning of log query
                    394:                 my $udom    = &unescape($arg1);
                    395:                 my $uname   = &unescape($arg2);
                    396:                 my $command = &unescape($arg3);
                    397:                 my $path    = &propath($udom,$uname);
                    398:                 if (-e "$path/activity.log") {
                    399:                     if ($query eq 'userlog') {
                    400:                         $result=&userlog($path,$command);
                    401:                     } else {
                    402:                         $result=&courselog($path,$command);
                    403:                     }
                    404:                 } else {
                    405:                     &logthis('Unable to do log query: '.$uname.'@'.$udom);
                    406:                     $result='no_such_file';
                    407:                 }
                    408:                 # end of log query
                    409:             } else {
                    410:                 # Do an sql query
                    411:                 $result = &do_sql_query($query,$arg1,$arg2);
                    412:             }
1.50      matthew   413:             # result does not need to be escaped because it has already been
                    414:             # escaped.
                    415:             #$result=&escape($result);
1.51      matthew   416:             # reply with result, append \n unless already there
1.44      www       417: 	    $result.="\n" unless ($result=~/\n$/);
1.17      harris41  418:             &reply("queryreply:$queryid:$result",$conserver);
1.1       harris41  419:         }
                    420:         # tidy up gracefully and finish
1.51      matthew   421:         #
                    422:         # close the database handle
1.2       harris41  423: 	$dbh->disconnect
1.51      matthew   424:             or &logthis("<font color=blue>WARNING: Couldn't disconnect".
                    425:                         " from database  $DBI::errstr : $@</font>");
1.1       harris41  426:         # this exit is VERY important, otherwise the child will become
                    427:         # a producer of more and more children, forking yourself into
                    428:         # process death.
                    429:         exit;
                    430:     }
1.2       harris41  431: }
1.1       harris41  432: 
1.51      matthew   433: ########################################################
                    434: ########################################################
                    435: 
                    436: =pod
                    437: 
                    438: =item &do_sql_query
                    439: 
                    440: Runs an sql metadata table query.
                    441: 
                    442: Inputs: $query, $custom, $customshow
                    443: 
                    444: Returns: A string containing escaped results.
                    445: 
                    446: =cut
                    447: 
                    448: ########################################################
                    449: ########################################################
                    450: {
                    451:     my @metalist;
                    452: 
                    453: sub process_file {
                    454:     if ( -e $_ &&  # file exists
                    455:          -f $_ &&  # and is a normal file
                    456:          /\.meta$/ &&  # ends in meta
                    457:          ! /^.+\.\d+\.[^\.]+\.meta$/  # is not a previous version
                    458:          ) {
                    459:         push(@metalist,$File::Find::name);
                    460:     }
                    461: }
                    462: 
                    463: sub do_sql_query {
                    464:     my ($query,$custom,$customshow) = @_;
                    465:     $custom     = &unescape($custom);
                    466:     $customshow = &unescape($customshow);
                    467:     #
                    468:     @metalist = ();
                    469:     #
                    470:     my $result = '';
                    471:     my @results = ();
                    472:     my @files;
                    473:     my $subsetflag=0;
                    474:     #
                    475:     if ($query) {
                    476:         #prepare and execute the query
                    477:         my $sth = $dbh->prepare($query);
                    478:         unless ($sth->execute()) {
1.58    ! matthew   479:             &logthis('<font color=blue>'.
        !           480:                      'WARNING: Could not retrieve from database:'.
        !           481:                      $sth->errstr().'</font>');
1.51      matthew   482:         } else {
                    483:             my $aref=$sth->fetchall_arrayref;
                    484:             foreach my $row (@$aref) {
                    485:                 push @files,@{$row}[3] if ($custom or $customshow);
                    486:                 my @b=map { &escape($_); } @$row;
                    487:                 push @results,join(",", @b);
                    488:                 # Build up the @files array with the LON-CAPA urls 
                    489:                 # of the resources.
                    490:             }
                    491:         }
                    492:     }
                    493:     # do custom metadata searching here and build into result
                    494:     return join("&",@results) if (! ($custom or $customshow));
                    495:     # Only get here if there is a custom query or custom show request
                    496:     &logthis("Doing custom query for $custom");
                    497:     if ($query) {
                    498:         @metalist=map {
                    499:             $perlvar{'lonDocRoot'}.$_.'.meta';
                    500:         } @files;
                    501:     } else {
                    502:         my $dir = "$perlvar{'lonDocRoot'}/res/$perlvar{'lonDefDomain'}";
                    503:         @metalist=(); 
                    504:         opendir(RESOURCES,$dir);
                    505:         my @homeusers=grep {
                    506:             &ishome($dir.'/'.$_);
                    507:         } grep {!/^\.\.?$/} readdir(RESOURCES);
                    508:         closedir RESOURCES;
                    509:         # Define the
                    510:         foreach my $user (@homeusers) {
                    511:             find (\&process_file,$dir.'/'.$user);
                    512:         }
                    513:     } 
                    514:     # if file is indicated in sql database and
                    515:     #     not part of sql-relevant query, do not pattern match.
                    516:     #
                    517:     # if file is not in sql database, output error.
                    518:     #
                    519:     # if file is indicated in sql database and is
                    520:     #     part of query result list, then do the pattern match.
                    521:     my $customresult='';
                    522:     my @results;
                    523:     foreach my $metafile (@metalist) {
                    524:         my $fh=IO::File->new($metafile);
                    525:         my @lines=<$fh>;
                    526:         my $stuff=join('',@lines);
                    527:         if ($stuff=~/$custom/s) {
                    528:             foreach my $f ('abstract','author','copyright',
                    529:                            'creationdate','keywords','language',
                    530:                            'lastrevisiondate','mime','notes',
                    531:                            'owner','subject','title') {
                    532:                 $stuff=~s/\n?\<$f[^\>]*\>.*?<\/$f[^\>]*\>\n?//s;
                    533:             }
                    534:             my $mfile=$metafile; 
                    535:             my $docroot=$perlvar{'lonDocRoot'};
                    536:             $mfile=~s/^$docroot//;
                    537:             $mfile=~s/\.meta$//;
                    538:             unless ($query) {
                    539:                 my $q2="SELECT * FROM metadata WHERE url ".
                    540:                     " LIKE BINARY '?'";
                    541:                 my $sth = $dbh->prepare($q2);
                    542:                 $sth->execute($mfile);
                    543:                 my $aref=$sth->fetchall_arrayref;
                    544:                 foreach my $a (@$aref) {
                    545:                     my @b=map { &escape($_)} @$a;
                    546:                     push @results,join(",", @b);
                    547:                 }
                    548:             }
                    549:             # &logthis("found: $stuff");
                    550:             $customresult.='&custom='.&escape($mfile).','.
                    551:                 escape($stuff);
                    552:         }
                    553:     }
                    554:     $result=join("&",@results) unless $query;
                    555:     $result.=$customresult;
                    556:     #
                    557:     return $result;
                    558: } # End of &do_sql_query
                    559: 
                    560: } # End of scoping curly braces for &process_file and &do_sql_query
                    561: ########################################################
                    562: ########################################################
                    563: 
                    564: =pod
                    565: 
                    566: =item &logthis
                    567: 
                    568: Inputs: $message, the message to log
                    569: 
                    570: Returns: nothing
                    571: 
                    572: Writes $message to the logfile.
                    573: 
                    574: =cut
                    575: 
                    576: ########################################################
                    577: ########################################################
                    578: sub logthis {
                    579:     my $message=shift;
                    580:     my $execdir=$perlvar{'lonDaemons'};
1.52      matthew   581:     my $fh=IO::File->new(">>$execdir/logs/lonsql.log");
1.51      matthew   582:     my $now=time;
                    583:     my $local=localtime($now);
                    584:     print $fh "$local ($$): $message\n";
1.2       harris41  585: }
1.1       harris41  586: 
1.2       harris41  587: # -------------------------------------------------- Non-critical communication
1.1       harris41  588: 
1.51      matthew   589: ########################################################
                    590: ########################################################
                    591: 
                    592: =pod
                    593: 
                    594: =item &subreply
                    595: 
                    596: Sends a command to a server.  Called only by &reply.
                    597: 
                    598: Inputs: $cmd,$server
                    599: 
                    600: Returns: The results of the message or 'con_lost' on error.
                    601: 
                    602: =cut
                    603: 
                    604: ########################################################
                    605: ########################################################
1.2       harris41  606: sub subreply {
                    607:     my ($cmd,$server)=@_;
                    608:     my $peerfile="$perlvar{'lonSockDir'}/$server";
                    609:     my $sclient=IO::Socket::UNIX->new(Peer    =>"$peerfile",
                    610:                                       Type    => SOCK_STREAM,
                    611:                                       Timeout => 10)
                    612:        or return "con_lost";
                    613:     print $sclient "$cmd\n";
                    614:     my $answer=<$sclient>;
                    615:     chomp($answer);
1.51      matthew   616:     $answer="con_lost" if (!$answer);
1.2       harris41  617:     return $answer;
                    618: }
1.1       harris41  619: 
1.51      matthew   620: ########################################################
                    621: ########################################################
                    622: 
                    623: =pod
                    624: 
                    625: =item &reply
                    626: 
                    627: Sends a command to a server.
                    628: 
                    629: Inputs: $cmd,$server
                    630: 
                    631: Returns: The results of the message or 'con_lost' on error.
                    632: 
                    633: =cut
                    634: 
                    635: ########################################################
                    636: ########################################################
1.2       harris41  637: sub reply {
                    638:   my ($cmd,$server)=@_;
                    639:   my $answer;
                    640:   if ($server ne $perlvar{'lonHostID'}) { 
                    641:     $answer=subreply($cmd,$server);
                    642:     if ($answer eq 'con_lost') {
                    643: 	$answer=subreply("ping",$server);
                    644:         $answer=subreply($cmd,$server);
                    645:     }
                    646:   } else {
                    647:     $answer='self_reply';
1.33      harris41  648:     $answer=subreply($cmd,$server);
1.2       harris41  649:   } 
                    650:   return $answer;
                    651: }
1.1       harris41  652: 
1.51      matthew   653: ########################################################
                    654: ########################################################
                    655: 
                    656: =pod
                    657: 
                    658: =item &escape
                    659: 
                    660: Escape special characters in a string.
1.3       harris41  661: 
1.51      matthew   662: Inputs: string to escape
                    663: 
                    664: Returns: The input string with special characters escaped.
                    665: 
                    666: =cut
                    667: 
                    668: ########################################################
                    669: ########################################################
1.3       harris41  670: sub escape {
                    671:     my $str=shift;
                    672:     $str =~ s/(\W)/"%".unpack('H2',$1)/eg;
                    673:     return $str;
                    674: }
                    675: 
1.51      matthew   676: ########################################################
                    677: ########################################################
                    678: 
                    679: =pod
                    680: 
                    681: =item &unescape
                    682: 
                    683: Unescape special characters in a string.
1.3       harris41  684: 
1.51      matthew   685: Inputs: string to unescape
                    686: 
                    687: Returns: The input string with special characters unescaped.
                    688: 
                    689: =cut
                    690: 
                    691: ########################################################
                    692: ########################################################
1.3       harris41  693: sub unescape {
                    694:     my $str=shift;
                    695:     $str =~ s/%([a-fA-F0-9][a-fA-F0-9])/pack("C",hex($1))/eg;
                    696:     return $str;
                    697: }
1.34      harris41  698: 
1.51      matthew   699: ########################################################
                    700: ########################################################
                    701: 
                    702: =pod
                    703: 
                    704: =item &ishome
                    705: 
                    706: Determine if the current machine is the home server for a user.
                    707: The determination is made by checking the filesystem for the users information.
                    708: 
                    709: Inputs: $author
                    710: 
                    711: Returns: 0 - this is not the authors home server, 1 - this is.
                    712: 
                    713: =cut
                    714: 
                    715: ########################################################
                    716: ########################################################
1.34      harris41  717: sub ishome {
                    718:     my $author=shift;
                    719:     $author=~s/\/home\/httpd\/html\/res\/([^\/]*)\/([^\/]*).*/$1\/$2/;
                    720:     my ($udom,$uname)=split(/\//,$author);
                    721:     my $proname=propath($udom,$uname);
                    722:     if (-e $proname) {
                    723: 	return 1;
                    724:     } else {
                    725:         return 0;
                    726:     }
                    727: }
                    728: 
1.51      matthew   729: ########################################################
                    730: ########################################################
                    731: 
                    732: =pod
                    733: 
                    734: =item &propath
                    735: 
                    736: Inputs: user name, user domain
                    737: 
                    738: Returns: The full path to the users directory.
                    739: 
                    740: =cut
                    741: 
                    742: ########################################################
                    743: ########################################################
1.34      harris41  744: sub propath {
                    745:     my ($udom,$uname)=@_;
                    746:     $udom=~s/\W//g;
                    747:     $uname=~s/\W//g;
                    748:     my $subdir=$uname.'__';
                    749:     $subdir =~ s/(.)(.)(.).*/$1\/$2\/$3/;
                    750:     my $proname="$perlvar{'lonUsersDir'}/$udom/$subdir/$uname";
                    751:     return $proname;
                    752: } 
1.40      harris41  753: 
1.51      matthew   754: ########################################################
                    755: ########################################################
                    756: 
                    757: =pod
                    758: 
                    759: =item &courselog
                    760: 
                    761: Inputs: $path, $command
                    762: 
                    763: Returns: unescaped string of values.
                    764: 
                    765: =cut
                    766: 
                    767: ########################################################
                    768: ########################################################
                    769: sub courselog {
                    770:     my ($path,$command)=@_;
                    771:     my %filters=();
                    772:     foreach (split(/\:/,&unescape($command))) {
                    773: 	my ($name,$value)=split(/\=/,$_);
                    774:         $filters{$name}=$value;
                    775:     }
                    776:     my @results=();
                    777:     open(IN,$path.'/activity.log') or return ('file_error');
                    778:     while (my $line=<IN>) {
                    779:         chomp($line);
                    780:         my ($timestamp,$host,$log)=split(/\:/,$line);
                    781: #
                    782: # $log has the actual log entries; currently still escaped, and
                    783: # %26(timestamp)%3a(url)%3a(user)%3a(domain)
                    784: # then additionally
                    785: # %3aPOST%3a(name)%3d(value)%3a(name)%3d(value)
                    786: # or
                    787: # %3aCSTORE%3a(name)%3d(value)%26(name)%3d(value)
                    788: #
                    789: # get delimiter between timestamped entries to be &&&
                    790:         $log=~s/\%26(\d+)\%3a/\&\&\&$1\%3a/g;
                    791: # now go over all log entries 
                    792:         foreach (split(/\&\&\&/,&unescape($log))) {
                    793: 	    my ($time,$res,$uname,$udom,$action,@values)=split(/\:/,$_);
                    794:             my $values=&unescape(join(':',@values));
                    795:             $values=~s/\&/\:/g;
                    796:             $res=&unescape($res);
                    797:             my $include=1;
                    798:             if (($filters{'username'}) && ($uname ne $filters{'username'})) 
                    799:                                                                { $include=0; }
                    800:             if (($filters{'domain'}) && ($udom ne $filters{'domain'})) 
                    801:                                                                { $include=0; }
                    802:             if (($filters{'url'}) && ($res!~/$filters{'url'}/)) 
                    803:                                                                { $include=0; }
                    804:             if (($filters{'start'}) && ($time<$filters{'start'})) 
                    805:                                                                { $include=0; }
                    806:             if (($filters{'end'}) && ($time>$filters{'end'})) 
                    807:                                                                { $include=0; }
                    808:             if (($filters{'action'} eq 'view') && ($action)) 
                    809:                                                                { $include=0; }
                    810:             if (($filters{'action'} eq 'submit') && ($action ne 'POST')) 
                    811:                                                                { $include=0; }
                    812:             if (($filters{'action'} eq 'grade') && ($action ne 'CSTORE')) 
                    813:                                                                { $include=0; }
                    814:             if ($include) {
                    815: 	       push(@results,($time<1000000000?'0':'').$time.':'.$res.':'.
                    816:                                             $uname.':'.$udom.':'.
                    817:                                             $action.':'.$values);
                    818:             }
                    819:        }
                    820:     }
                    821:     close IN;
                    822:     return join('&',sort(@results));
                    823: }
                    824: 
                    825: ########################################################
                    826: ########################################################
                    827: 
                    828: =pod
                    829: 
                    830: =item &userlog
                    831: 
                    832: Inputs: $path, $command
                    833: 
                    834: Returns: unescaped string of values.
1.40      harris41  835: 
1.51      matthew   836: =cut
1.40      harris41  837: 
1.51      matthew   838: ########################################################
                    839: ########################################################
                    840: sub userlog {
                    841:     my ($path,$command)=@_;
                    842:     my %filters=();
                    843:     foreach (split(/\:/,&unescape($command))) {
                    844: 	my ($name,$value)=split(/\=/,$_);
                    845:         $filters{$name}=$value;
                    846:     }
                    847:     my @results=();
                    848:     open(IN,$path.'/activity.log') or return ('file_error');
                    849:     while (my $line=<IN>) {
                    850:         chomp($line);
                    851:         my ($timestamp,$host,$log)=split(/\:/,$line);
                    852:         $log=&unescape($log);
                    853:         my $include=1;
                    854:         if (($filters{'start'}) && ($timestamp<$filters{'start'})) 
                    855:                                                              { $include=0; }
                    856:         if (($filters{'end'}) && ($timestamp>$filters{'end'})) 
                    857:                                                              { $include=0; }
                    858:         if (($filters{'action'} eq 'log') && ($log!~/^Log/)) { $include=0; }
                    859:         if (($filters{'action'} eq 'check') && ($log!~/^Check/)) 
                    860:                                                              { $include=0; }
                    861:         if ($include) {
                    862: 	   push(@results,$timestamp.':'.$log);
                    863:         }
                    864:     }
                    865:     close IN;
                    866:     return join('&',sort(@results));
1.52      matthew   867: }
                    868: 
                    869: ########################################################
                    870: ########################################################
                    871: 
                    872: =pod
                    873: 
                    874: =item Functions required for forking
                    875: 
                    876: =over 4
                    877: 
                    878: =item REAPER
                    879: 
                    880: REAPER takes care of dead children.
                    881: 
                    882: =item HUNTSMAN
                    883: 
                    884: Signal handler for SIGINT.
                    885: 
                    886: =item HUPSMAN
                    887: 
                    888: Signal handler for SIGHUP
                    889: 
                    890: =item DISCONNECT
                    891: 
                    892: Disconnects from database.
                    893: 
                    894: =back
                    895: 
                    896: =cut
                    897: 
                    898: ########################################################
                    899: ########################################################
                    900: sub REAPER {                   # takes care of dead children
                    901:     $SIG{CHLD} = \&REAPER;
                    902:     my $pid = wait;
                    903:     $children --;
                    904:     &logthis("Child $pid died");
                    905:     delete $children{$pid};
                    906: }
                    907: 
                    908: sub HUNTSMAN {                      # signal handler for SIGINT
                    909:     local($SIG{CHLD}) = 'IGNORE';   # we're going to kill our children
                    910:     kill 'INT' => keys %children;
                    911:     my $execdir=$perlvar{'lonDaemons'};
                    912:     unlink("$execdir/logs/lonsql.pid");
                    913:     &logthis("<font color=red>CRITICAL: Shutting down</font>");
                    914:     $unixsock = "mysqlsock";
                    915:     my $port="$perlvar{'lonSockDir'}/$unixsock";
                    916:     unlink($port);
                    917:     exit;                           # clean up with dignity
                    918: }
                    919: 
                    920: sub HUPSMAN {                      # signal handler for SIGHUP
                    921:     local($SIG{CHLD}) = 'IGNORE';  # we're going to kill our children
                    922:     kill 'INT' => keys %children;
                    923:     close($server);                # free up socket
                    924:     &logthis("<font color=red>CRITICAL: Restarting</font>");
                    925:     my $execdir=$perlvar{'lonDaemons'};
                    926:     $unixsock = "mysqlsock";
                    927:     my $port="$perlvar{'lonSockDir'}/$unixsock";
                    928:     unlink($port);
                    929:     exec("$execdir/lonsql");         # here we go again
                    930: }
                    931: 
                    932: sub DISCONNECT {
                    933:     $dbh->disconnect or 
                    934:     &logthis("<font color=blue>WARNING: Couldn't disconnect from database ".
                    935:              " $DBI::errstr : $@</font>");
                    936:     exit;
1.51      matthew   937: }
1.40      harris41  938: 
                    939: 
1.51      matthew   940: =pod
1.40      harris41  941: 
1.51      matthew   942: =back
1.40      harris41  943: 
                    944: =cut

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