Annotation of loncom/lonsql, revision 1.75

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.75    ! albertel    6: # $Id: lonsql,v 1.74 2006/02/08 21:17:53 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;
1.62      raeburn   118: use localenroll;
1.51      matthew   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
1.1       harris41  145: 
1.51      matthew   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 
1.9       harris41  163: 
1.51      matthew   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
1.45      www       178: 
1.51      matthew   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: #
1.53      harris41  206: my $perlvarref=LONCAPA::Configuration::read_conf('loncapa.conf');
1.51      matthew   207: my %perlvar=%{$perlvarref};
                    208: #
1.63      matthew   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: #
1.51      matthew   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");
1.57      www       237: 
                    238:     open(SMP,'>/home/httpd/html/lon-status/mysql.txt');
                    239:     print SMP 'time='.time.'&mysql=defunct'."\n";
                    240:     close(SMP);
                    241: 
1.51      matthew   242:     exit 1;
                    243: } else {
1.67      albertel  244:     unlink('/home/httpd/html/lon-status/mysql.txt');
1.51      matthew   245:     $dbh->disconnect;
                    246: }
1.52      matthew   247: 
1.51      matthew   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: }
1.52      matthew   258: 
1.49      www       259: #
1.51      matthew   260: # Read hosts file
1.49      www       261: #
1.51      matthew   262: my $thisserver;
1.72      albertel  263: my %hostname;
1.51      matthew   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>) {
1.66      albertel  267:     my ($id,$domain,$role,$name)=split(/:/,$configline);
                    268:     $name=~s/\s//g;
1.51      matthew   269:     $thisserver=$name if ($id eq $perlvar{'lonHostID'});
1.72      albertel  270:     $hostname{$id}=$name;
1.65      albertel  271:     #$PREFORK++;
1.45      www       272: }
1.51      matthew   273: close(CONFIG);
                    274: #
1.65      albertel  275: #$PREFORK=int($PREFORK/4);
1.52      matthew   276: 
1.51      matthew   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";
1.45      www       288: }
1.52      matthew   289: 
1.51      matthew   290: #
                    291: # Fork once and dissociate
1.52      matthew   292: #
1.51      matthew   293: my $fpid=fork;
1.1       harris41  294: exit if $fpid;
                    295: die "Couldn't fork: $!" unless defined ($fpid);
                    296: POSIX::setsid() or die "Can't start new session: $!";
1.52      matthew   297: 
1.51      matthew   298: #
                    299: # Write our PID on disk
                    300: my $execdir=$perlvar{'lonDaemons'};
1.1       harris41  301: open (PIDSAVE,">$execdir/logs/lonsql.pid");
                    302: print PIDSAVE "$$\n";
                    303: close(PIDSAVE);
1.59      albertel  304: &logthis("<font color='red'>CRITICAL: ---------- Starting ----------</font>");
1.52      matthew   305: 
1.51      matthew   306: #
                    307: # Ignore signals generated during initial startup
1.1       harris41  308: $SIG{HUP}=$SIG{USR1}='IGNORE';
1.51      matthew   309: # Now we are on our own    
                    310: #    Fork off our children.
1.2       harris41  311: for (1 .. $PREFORK) {
                    312:     make_new_child();
1.1       harris41  313: }
1.52      matthew   314: 
1.51      matthew   315: #
1.2       harris41  316: # Install signal handlers.
1.1       harris41  317: $SIG{CHLD} = \&REAPER;
                    318: $SIG{INT}  = $SIG{TERM} = \&HUNTSMAN;
                    319: $SIG{HUP}  = \&HUPSMAN;
1.52      matthew   320: 
1.51      matthew   321: #
1.1       harris41  322: # And maintain the population.
                    323: while (1) {
                    324:     sleep;                          # wait for a signal (i.e., child's death)
1.51      matthew   325:     for (my $i = $children; $i < $PREFORK; $i++) {
1.2       harris41  326:         make_new_child();           # top up the child pool
1.1       harris41  327:     }
                    328: }
                    329: 
1.51      matthew   330: ########################################################
                    331: ########################################################
                    332: 
                    333: =pod
                    334: 
                    335: =item &make_new_child
                    336: 
                    337: Inputs: None
                    338: 
                    339: Returns: None
                    340: 
                    341: =cut
1.2       harris41  342: 
1.51      matthew   343: ########################################################
                    344: ########################################################
1.1       harris41  345: sub make_new_child {
                    346:     my $pid;
                    347:     my $sigset;
1.51      matthew   348:     #
1.1       harris41  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";
1.51      matthew   353:     #
1.2       harris41  354:     die "fork: $!" unless defined ($pid = fork);
1.51      matthew   355:     #
1.1       harris41  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 {
1.2       harris41  364:         # Child can *not* return from this subroutine.
1.1       harris41  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";
1.2       harris41  369:         #open database handle
                    370: 	# making dbh global to avoid garbage collector
1.51      matthew   371: 	unless ($dbh = DBI->connect("DBI:mysql:loncapa","www",
                    372:                                     $perlvar{'lonSqlAccess'},
                    373:                                     { RaiseError =>0,PrintError=>0})) { 
                    374:             sleep(10+int(rand(20)));
1.59      albertel  375:             &logthis("<font color='blue'>WARNING: Couldn't connect to database".
1.51      matthew   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
1.2       harris41  383: 	$SIG{TERM}=$SIG{INT}=$SIG{QUIT}=$SIG{__DIE__}=\&DISCONNECT;
1.1       harris41  384:         # handle connections until we've reached $MAX_CLIENTS_PER_CHILD
1.51      matthew   385:         for (my $i=0; $i < $MAX_CLIENTS_PER_CHILD; $i++) {
                    386:             my $client = $server->accept() or last;
1.2       harris41  387:             # do something with the connection
1.1       harris41  388: 	    $run = $run+1;
1.2       harris41  389: 	    my $userinput = <$client>;
                    390: 	    chomp($userinput);
1.73      www       391:             $userinput=~s/\:(\w+)$//;
                    392:             my $searchdomain=$1;
1.51      matthew   393:             #
1.45      www       394: 	    my ($conserver,$query,
                    395: 		$arg1,$arg2,$arg3)=split(/&/,$userinput);
                    396: 	    my $query=unescape($query);
1.51      matthew   397:             #
1.2       harris41  398:             #send query id which is pid_unixdatetime_runningcounter
1.51      matthew   399: 	    my $queryid = $thisserver;
1.2       harris41  400: 	    $queryid .="_".($$)."_";
                    401: 	    $queryid .= time."_";
                    402: 	    $queryid .= $run;
                    403: 	    print $client "$queryid\n";
1.51      matthew   404: 	    #
1.61      matthew   405: 	    # &logthis("QUERY: $query - $arg1 - $arg2 - $arg3");
1.25      harris41  406: 	    sleep 1;
1.51      matthew   407:             #
1.45      www       408:             my $result='';
1.51      matthew   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
1.70      raeburn   430:             } elsif (($query eq 'fetchenrollment') || 
1.71      albertel  431: 		     ($query eq 'institutionalphotos')) {
1.62      raeburn   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) {
1.68      raeburn   439:                     if (/^([^=]+)=([^=]+)$/) {
1.62      raeburn   440:                         @{$affiliates{$1}} = split/,/,$2;
                    441:                     }
                    442:                 }
1.70      raeburn   443:                 if ($query eq 'fetchenrollment') { 
                    444:                     $locresult = &localenroll::fetch_enrollment($dom,\%affiliates,\%replies);
                    445:                 } elsif ($query eq 'institutionalphotos') {
                    446:                     my $crs = &unescape($arg2);
1.75    ! albertel  447: 		    eval {
        !           448: 			local($SIG{__DIE__})='DEFAULT';
        !           449: 			$locresult = &localenroll::institutional_photos($dom,$crs,\%affiliates,\%replies,'update');
        !           450: 		    };
        !           451: 		    if ($@) {
        !           452: 			$locresult = 'error';
        !           453: 		    }
1.70      raeburn   454:                 }
1.62      raeburn   455:                 $result = &escape($locresult.':');
                    456:                 if ($locresult) {
                    457:                     $result .= &escape(join(':',map{$_.'='.$replies{$_}} keys %replies));
                    458:                 }
1.63      matthew   459:             } elsif ($query eq 'prepare activity log') {
                    460:                 my ($cid,$domain) = map {&unescape($_);} ($arg1,$arg2);
1.64      matthew   461:                 &logthis('preparing activity log tables for '.$cid);
1.63      matthew   462:                 my $command = 
1.64      matthew   463:                     qq{$perlvar{'lonDaemons'}/parse_activity_log.pl -course=$cid -domain=$domain};
1.63      matthew   464:                 system($command);
1.64      matthew   465:                 &logthis($command);
1.63      matthew   466:                 my $returnvalue = $?>>8;
                    467:                 if ($returnvalue) {
                    468:                     $result = 'error: parse_activity_log.pl returned '.
                    469:                         $returnvalue;
                    470:                 } else {
                    471:                     $result = 'success';
                    472:                 }
1.51      matthew   473:             } else {
                    474:                 # Do an sql query
1.74      www       475:                 $result = &do_sql_query($query,$arg1,$arg2,$searchdomain);
1.51      matthew   476:             }
1.50      matthew   477:             # result does not need to be escaped because it has already been
                    478:             # escaped.
                    479:             #$result=&escape($result);
1.17      harris41  480:             &reply("queryreply:$queryid:$result",$conserver);
1.1       harris41  481:         }
                    482:         # tidy up gracefully and finish
1.51      matthew   483:         #
                    484:         # close the database handle
1.2       harris41  485: 	$dbh->disconnect
1.59      albertel  486:             or &logthis("<font color='blue'>WARNING: Couldn't disconnect".
1.51      matthew   487:                         " from database  $DBI::errstr : $@</font>");
1.1       harris41  488:         # this exit is VERY important, otherwise the child will become
                    489:         # a producer of more and more children, forking yourself into
                    490:         # process death.
                    491:         exit;
                    492:     }
1.2       harris41  493: }
1.1       harris41  494: 
1.51      matthew   495: ########################################################
                    496: ########################################################
                    497: 
                    498: =pod
                    499: 
                    500: =item &do_sql_query
                    501: 
                    502: Runs an sql metadata table query.
                    503: 
                    504: Inputs: $query, $custom, $customshow
                    505: 
                    506: Returns: A string containing escaped results.
                    507: 
                    508: =cut
                    509: 
                    510: ########################################################
                    511: ########################################################
                    512: {
                    513:     my @metalist;
                    514: 
                    515: sub process_file {
                    516:     if ( -e $_ &&  # file exists
                    517:          -f $_ &&  # and is a normal file
                    518:          /\.meta$/ &&  # ends in meta
                    519:          ! /^.+\.\d+\.[^\.]+\.meta$/  # is not a previous version
                    520:          ) {
                    521:         push(@metalist,$File::Find::name);
                    522:     }
                    523: }
                    524: 
                    525: sub do_sql_query {
1.74      www       526:     my ($query,$custom,$customshow,$searchdomain) = @_;
                    527: 
                    528: #
                    529: # limit to searchdomain if given and table is metadata
                    530: #
                    531:     if (($searchdomain) && ($query=~/FROM metadata/)) {
                    532: 	$query.=' HAVING (domain="'.$searchdomain.'")';
                    533:     }
                    534: #    &logthis('doing query ('.$searchdomain.')'.$query);
                    535: 
                    536: 
                    537: 
1.51      matthew   538:     $custom     = &unescape($custom);
                    539:     $customshow = &unescape($customshow);
                    540:     #
                    541:     @metalist = ();
                    542:     #
                    543:     my $result = '';
                    544:     my @results = ();
                    545:     my @files;
                    546:     my $subsetflag=0;
                    547:     #
                    548:     if ($query) {
                    549:         #prepare and execute the query
1.75    ! albertel  550: 	&logthis($query);
1.51      matthew   551:         my $sth = $dbh->prepare($query);
                    552:         unless ($sth->execute()) {
1.59      albertel  553:             &logthis('<font color="blue">'.
1.58      matthew   554:                      'WARNING: Could not retrieve from database:'.
                    555:                      $sth->errstr().'</font>');
1.51      matthew   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'};
1.52      matthew   655:     my $fh=IO::File->new(">>$execdir/logs/lonsql.log");
1.51      matthew   656:     my $now=time;
                    657:     my $local=localtime($now);
                    658:     print $fh "$local ($$): $message\n";
1.2       harris41  659: }
1.1       harris41  660: 
1.2       harris41  661: # -------------------------------------------------- Non-critical communication
1.1       harris41  662: 
1.51      matthew   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: ########################################################
1.2       harris41  680: sub subreply {
                    681:     my ($cmd,$server)=@_;
1.72      albertel  682:     my $peerfile="$perlvar{'lonSockDir'}/".$hostname{$server};
1.2       harris41  683:     my $sclient=IO::Socket::UNIX->new(Peer    =>"$peerfile",
                    684:                                       Type    => SOCK_STREAM,
                    685:                                       Timeout => 10)
                    686:        or return "con_lost";
1.72      albertel  687:     print $sclient "sethost:$server:$cmd\n";
1.2       harris41  688:     my $answer=<$sclient>;
                    689:     chomp($answer);
1.51      matthew   690:     $answer="con_lost" if (!$answer);
1.2       harris41  691:     return $answer;
                    692: }
1.1       harris41  693: 
1.51      matthew   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: ########################################################
1.2       harris41  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';
1.33      harris41  722:     $answer=subreply($cmd,$server);
1.2       harris41  723:   } 
                    724:   return $answer;
                    725: }
1.1       harris41  726: 
1.51      matthew   727: ########################################################
                    728: ########################################################
                    729: 
                    730: =pod
                    731: 
                    732: =item &escape
                    733: 
                    734: Escape special characters in a string.
1.3       harris41  735: 
1.51      matthew   736: Inputs: string to escape
                    737: 
                    738: Returns: The input string with special characters escaped.
                    739: 
                    740: =cut
                    741: 
                    742: ########################################################
                    743: ########################################################
1.3       harris41  744: sub escape {
                    745:     my $str=shift;
                    746:     $str =~ s/(\W)/"%".unpack('H2',$1)/eg;
                    747:     return $str;
                    748: }
                    749: 
1.51      matthew   750: ########################################################
                    751: ########################################################
                    752: 
                    753: =pod
                    754: 
                    755: =item &unescape
                    756: 
                    757: Unescape special characters in a string.
1.3       harris41  758: 
1.51      matthew   759: Inputs: string to unescape
                    760: 
                    761: Returns: The input string with special characters unescaped.
                    762: 
                    763: =cut
                    764: 
                    765: ########################################################
                    766: ########################################################
1.3       harris41  767: sub unescape {
                    768:     my $str=shift;
                    769:     $str =~ s/%([a-fA-F0-9][a-fA-F0-9])/pack("C",hex($1))/eg;
                    770:     return $str;
                    771: }
1.34      harris41  772: 
1.51      matthew   773: ########################################################
                    774: ########################################################
                    775: 
                    776: =pod
                    777: 
                    778: =item &ishome
                    779: 
                    780: Determine if the current machine is the home server for a user.
                    781: The determination is made by checking the filesystem for the users information.
                    782: 
                    783: Inputs: $author
                    784: 
                    785: Returns: 0 - this is not the authors home server, 1 - this is.
                    786: 
                    787: =cut
                    788: 
                    789: ########################################################
                    790: ########################################################
1.34      harris41  791: sub ishome {
                    792:     my $author=shift;
                    793:     $author=~s/\/home\/httpd\/html\/res\/([^\/]*)\/([^\/]*).*/$1\/$2/;
                    794:     my ($udom,$uname)=split(/\//,$author);
                    795:     my $proname=propath($udom,$uname);
                    796:     if (-e $proname) {
                    797: 	return 1;
                    798:     } else {
                    799:         return 0;
                    800:     }
                    801: }
                    802: 
1.51      matthew   803: ########################################################
                    804: ########################################################
                    805: 
                    806: =pod
                    807: 
                    808: =item &propath
                    809: 
                    810: Inputs: user name, user domain
                    811: 
                    812: Returns: The full path to the users directory.
                    813: 
                    814: =cut
                    815: 
                    816: ########################################################
                    817: ########################################################
1.34      harris41  818: sub propath {
                    819:     my ($udom,$uname)=@_;
                    820:     $udom=~s/\W//g;
                    821:     $uname=~s/\W//g;
                    822:     my $subdir=$uname.'__';
                    823:     $subdir =~ s/(.)(.)(.).*/$1\/$2\/$3/;
                    824:     my $proname="$perlvar{'lonUsersDir'}/$udom/$subdir/$uname";
                    825:     return $proname;
                    826: } 
1.40      harris41  827: 
1.51      matthew   828: ########################################################
                    829: ########################################################
                    830: 
                    831: =pod
                    832: 
                    833: =item &courselog
                    834: 
                    835: Inputs: $path, $command
                    836: 
                    837: Returns: unescaped string of values.
                    838: 
                    839: =cut
                    840: 
                    841: ########################################################
                    842: ########################################################
                    843: sub courselog {
                    844:     my ($path,$command)=@_;
                    845:     my %filters=();
                    846:     foreach (split(/\:/,&unescape($command))) {
                    847: 	my ($name,$value)=split(/\=/,$_);
                    848:         $filters{$name}=$value;
                    849:     }
                    850:     my @results=();
                    851:     open(IN,$path.'/activity.log') or return ('file_error');
                    852:     while (my $line=<IN>) {
                    853:         chomp($line);
                    854:         my ($timestamp,$host,$log)=split(/\:/,$line);
                    855: #
                    856: # $log has the actual log entries; currently still escaped, and
                    857: # %26(timestamp)%3a(url)%3a(user)%3a(domain)
                    858: # then additionally
                    859: # %3aPOST%3a(name)%3d(value)%3a(name)%3d(value)
                    860: # or
                    861: # %3aCSTORE%3a(name)%3d(value)%26(name)%3d(value)
                    862: #
                    863: # get delimiter between timestamped entries to be &&&
                    864:         $log=~s/\%26(\d+)\%3a/\&\&\&$1\%3a/g;
                    865: # now go over all log entries 
                    866:         foreach (split(/\&\&\&/,&unescape($log))) {
                    867: 	    my ($time,$res,$uname,$udom,$action,@values)=split(/\:/,$_);
                    868:             my $values=&unescape(join(':',@values));
                    869:             $values=~s/\&/\:/g;
                    870:             $res=&unescape($res);
                    871:             my $include=1;
                    872:             if (($filters{'username'}) && ($uname ne $filters{'username'})) 
                    873:                                                                { $include=0; }
                    874:             if (($filters{'domain'}) && ($udom ne $filters{'domain'})) 
                    875:                                                                { $include=0; }
                    876:             if (($filters{'url'}) && ($res!~/$filters{'url'}/)) 
                    877:                                                                { $include=0; }
                    878:             if (($filters{'start'}) && ($time<$filters{'start'})) 
                    879:                                                                { $include=0; }
                    880:             if (($filters{'end'}) && ($time>$filters{'end'})) 
                    881:                                                                { $include=0; }
                    882:             if (($filters{'action'} eq 'view') && ($action)) 
                    883:                                                                { $include=0; }
                    884:             if (($filters{'action'} eq 'submit') && ($action ne 'POST')) 
                    885:                                                                { $include=0; }
                    886:             if (($filters{'action'} eq 'grade') && ($action ne 'CSTORE')) 
                    887:                                                                { $include=0; }
                    888:             if ($include) {
                    889: 	       push(@results,($time<1000000000?'0':'').$time.':'.$res.':'.
                    890:                                             $uname.':'.$udom.':'.
                    891:                                             $action.':'.$values);
                    892:             }
                    893:        }
                    894:     }
                    895:     close IN;
                    896:     return join('&',sort(@results));
                    897: }
                    898: 
                    899: ########################################################
                    900: ########################################################
                    901: 
                    902: =pod
                    903: 
                    904: =item &userlog
                    905: 
                    906: Inputs: $path, $command
                    907: 
                    908: Returns: unescaped string of values.
1.40      harris41  909: 
1.51      matthew   910: =cut
1.40      harris41  911: 
1.51      matthew   912: ########################################################
                    913: ########################################################
                    914: sub userlog {
                    915:     my ($path,$command)=@_;
                    916:     my %filters=();
                    917:     foreach (split(/\:/,&unescape($command))) {
                    918: 	my ($name,$value)=split(/\=/,$_);
                    919:         $filters{$name}=$value;
                    920:     }
                    921:     my @results=();
                    922:     open(IN,$path.'/activity.log') or return ('file_error');
                    923:     while (my $line=<IN>) {
                    924:         chomp($line);
                    925:         my ($timestamp,$host,$log)=split(/\:/,$line);
                    926:         $log=&unescape($log);
                    927:         my $include=1;
                    928:         if (($filters{'start'}) && ($timestamp<$filters{'start'})) 
                    929:                                                              { $include=0; }
                    930:         if (($filters{'end'}) && ($timestamp>$filters{'end'})) 
                    931:                                                              { $include=0; }
                    932:         if (($filters{'action'} eq 'log') && ($log!~/^Log/)) { $include=0; }
                    933:         if (($filters{'action'} eq 'check') && ($log!~/^Check/)) 
                    934:                                                              { $include=0; }
                    935:         if ($include) {
                    936: 	   push(@results,$timestamp.':'.$log);
                    937:         }
                    938:     }
                    939:     close IN;
                    940:     return join('&',sort(@results));
1.52      matthew   941: }
                    942: 
                    943: ########################################################
                    944: ########################################################
                    945: 
                    946: =pod
                    947: 
                    948: =item Functions required for forking
                    949: 
                    950: =over 4
                    951: 
                    952: =item REAPER
                    953: 
                    954: REAPER takes care of dead children.
                    955: 
                    956: =item HUNTSMAN
                    957: 
                    958: Signal handler for SIGINT.
                    959: 
                    960: =item HUPSMAN
                    961: 
                    962: Signal handler for SIGHUP
                    963: 
                    964: =item DISCONNECT
                    965: 
                    966: Disconnects from database.
                    967: 
                    968: =back
                    969: 
                    970: =cut
                    971: 
                    972: ########################################################
                    973: ########################################################
                    974: sub REAPER {                   # takes care of dead children
                    975:     $SIG{CHLD} = \&REAPER;
                    976:     my $pid = wait;
                    977:     $children --;
                    978:     &logthis("Child $pid died");
                    979:     delete $children{$pid};
                    980: }
                    981: 
                    982: sub HUNTSMAN {                      # signal handler for SIGINT
                    983:     local($SIG{CHLD}) = 'IGNORE';   # we're going to kill our children
                    984:     kill 'INT' => keys %children;
                    985:     my $execdir=$perlvar{'lonDaemons'};
                    986:     unlink("$execdir/logs/lonsql.pid");
1.59      albertel  987:     &logthis("<font color='red'>CRITICAL: Shutting down</font>");
1.52      matthew   988:     $unixsock = "mysqlsock";
                    989:     my $port="$perlvar{'lonSockDir'}/$unixsock";
                    990:     unlink($port);
                    991:     exit;                           # clean up with dignity
                    992: }
                    993: 
                    994: sub HUPSMAN {                      # signal handler for SIGHUP
                    995:     local($SIG{CHLD}) = 'IGNORE';  # we're going to kill our children
                    996:     kill 'INT' => keys %children;
                    997:     close($server);                # free up socket
1.59      albertel  998:     &logthis("<font color='red'>CRITICAL: Restarting</font>");
1.52      matthew   999:     my $execdir=$perlvar{'lonDaemons'};
                   1000:     $unixsock = "mysqlsock";
                   1001:     my $port="$perlvar{'lonSockDir'}/$unixsock";
                   1002:     unlink($port);
                   1003:     exec("$execdir/lonsql");         # here we go again
                   1004: }
                   1005: 
                   1006: sub DISCONNECT {
                   1007:     $dbh->disconnect or 
1.59      albertel 1008:     &logthis("<font color='blue'>WARNING: Couldn't disconnect from database ".
1.52      matthew  1009:              " $DBI::errstr : $@</font>");
                   1010:     exit;
1.51      matthew  1011: }
1.40      harris41 1012: 
                   1013: 
1.51      matthew  1014: =pod
1.40      harris41 1015: 
1.51      matthew  1016: =back
1.40      harris41 1017: 
                   1018: =cut

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