Annotation of loncom/lonsql, revision 1.74

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

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