Annotation of loncom/lonsql, revision 1.71.2.1

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.71.2.1! albertel    6: # $Id: lonsql,v 1.71 2006/02/07 16:20:39 albertel 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;
                    263: my $PREFORK=4; # number of children to maintain, at least four spare
                    264: open (CONFIG,"$perlvar{'lonTabDir'}/hosts.tab") || die "Can't read host file";
                    265: while (my $configline=<CONFIG>) {
1.66      albertel  266:     my ($id,$domain,$role,$name)=split(/:/,$configline);
                    267:     $name=~s/\s//g;
1.51      matthew   268:     $thisserver=$name if ($id eq $perlvar{'lonHostID'});
1.65      albertel  269:     #$PREFORK++;
1.45      www       270: }
1.51      matthew   271: close(CONFIG);
                    272: #
1.65      albertel  273: #$PREFORK=int($PREFORK/4);
1.52      matthew   274: 
1.51      matthew   275: #
                    276: # Create a socket to talk to lond
                    277: #
                    278: my $unixsock = "mysqlsock";
                    279: my $localfile="$perlvar{'lonSockDir'}/$unixsock";
                    280: my $server;
                    281: unlink ($localfile);
                    282: unless ($server=IO::Socket::UNIX->new(Local    =>"$localfile",
                    283:                                       Type    => SOCK_STREAM,
                    284:                                       Listen => 10)) {
                    285:     print "in socket error:$@\n";
1.45      www       286: }
1.52      matthew   287: 
1.51      matthew   288: #
                    289: # Fork once and dissociate
1.52      matthew   290: #
1.51      matthew   291: my $fpid=fork;
1.1       harris41  292: exit if $fpid;
                    293: die "Couldn't fork: $!" unless defined ($fpid);
                    294: POSIX::setsid() or die "Can't start new session: $!";
1.52      matthew   295: 
1.51      matthew   296: #
                    297: # Write our PID on disk
                    298: my $execdir=$perlvar{'lonDaemons'};
1.1       harris41  299: open (PIDSAVE,">$execdir/logs/lonsql.pid");
                    300: print PIDSAVE "$$\n";
                    301: close(PIDSAVE);
1.59      albertel  302: &logthis("<font color='red'>CRITICAL: ---------- Starting ----------</font>");
1.52      matthew   303: 
1.51      matthew   304: #
                    305: # Ignore signals generated during initial startup
1.1       harris41  306: $SIG{HUP}=$SIG{USR1}='IGNORE';
1.51      matthew   307: # Now we are on our own    
                    308: #    Fork off our children.
1.2       harris41  309: for (1 .. $PREFORK) {
                    310:     make_new_child();
1.1       harris41  311: }
1.52      matthew   312: 
1.51      matthew   313: #
1.2       harris41  314: # Install signal handlers.
1.1       harris41  315: $SIG{CHLD} = \&REAPER;
                    316: $SIG{INT}  = $SIG{TERM} = \&HUNTSMAN;
                    317: $SIG{HUP}  = \&HUPSMAN;
1.52      matthew   318: 
1.51      matthew   319: #
1.1       harris41  320: # And maintain the population.
                    321: while (1) {
                    322:     sleep;                          # wait for a signal (i.e., child's death)
1.51      matthew   323:     for (my $i = $children; $i < $PREFORK; $i++) {
1.2       harris41  324:         make_new_child();           # top up the child pool
1.1       harris41  325:     }
                    326: }
                    327: 
1.51      matthew   328: ########################################################
                    329: ########################################################
                    330: 
                    331: =pod
                    332: 
                    333: =item &make_new_child
                    334: 
                    335: Inputs: None
                    336: 
                    337: Returns: None
                    338: 
                    339: =cut
1.2       harris41  340: 
1.51      matthew   341: ########################################################
                    342: ########################################################
1.1       harris41  343: sub make_new_child {
                    344:     my $pid;
                    345:     my $sigset;
1.51      matthew   346:     #
1.1       harris41  347:     # block signal for fork
                    348:     $sigset = POSIX::SigSet->new(SIGINT);
                    349:     sigprocmask(SIG_BLOCK, $sigset)
                    350:         or die "Can't block SIGINT for fork: $!\n";
1.51      matthew   351:     #
1.2       harris41  352:     die "fork: $!" unless defined ($pid = fork);
1.51      matthew   353:     #
1.1       harris41  354:     if ($pid) {
                    355:         # Parent records the child's birth and returns.
                    356:         sigprocmask(SIG_UNBLOCK, $sigset)
                    357:             or die "Can't unblock SIGINT for fork: $!\n";
                    358:         $children{$pid} = 1;
                    359:         $children++;
                    360:         return;
                    361:     } else {
1.2       harris41  362:         # Child can *not* return from this subroutine.
1.1       harris41  363:         $SIG{INT} = 'DEFAULT';      # make SIGINT kill us as it did before
                    364:         # unblock signals
                    365:         sigprocmask(SIG_UNBLOCK, $sigset)
                    366:             or die "Can't unblock SIGINT for fork: $!\n";
1.2       harris41  367:         #open database handle
                    368: 	# making dbh global to avoid garbage collector
1.51      matthew   369: 	unless ($dbh = DBI->connect("DBI:mysql:loncapa","www",
                    370:                                     $perlvar{'lonSqlAccess'},
                    371:                                     { RaiseError =>0,PrintError=>0})) { 
                    372:             sleep(10+int(rand(20)));
1.59      albertel  373:             &logthis("<font color='blue'>WARNING: Couldn't connect to database".
1.51      matthew   374:                      ": $@</font>");
                    375:                      #  "($st secs): $@</font>");
                    376:             print "database handle error\n";
                    377:             exit;
                    378:         }
                    379: 	# make sure that a database disconnection occurs with 
                    380:         # ending kill signals
1.2       harris41  381: 	$SIG{TERM}=$SIG{INT}=$SIG{QUIT}=$SIG{__DIE__}=\&DISCONNECT;
1.1       harris41  382:         # handle connections until we've reached $MAX_CLIENTS_PER_CHILD
1.51      matthew   383:         for (my $i=0; $i < $MAX_CLIENTS_PER_CHILD; $i++) {
                    384:             my $client = $server->accept() or last;
1.2       harris41  385:             # do something with the connection
1.1       harris41  386: 	    $run = $run+1;
1.2       harris41  387: 	    my $userinput = <$client>;
                    388: 	    chomp($userinput);
1.51      matthew   389:             #
1.45      www       390: 	    my ($conserver,$query,
                    391: 		$arg1,$arg2,$arg3)=split(/&/,$userinput);
                    392: 	    my $query=unescape($query);
1.51      matthew   393:             #
1.2       harris41  394:             #send query id which is pid_unixdatetime_runningcounter
1.51      matthew   395: 	    my $queryid = $thisserver;
1.2       harris41  396: 	    $queryid .="_".($$)."_";
                    397: 	    $queryid .= time."_";
                    398: 	    $queryid .= $run;
                    399: 	    print $client "$queryid\n";
1.51      matthew   400: 	    #
1.61      matthew   401: 	    # &logthis("QUERY: $query - $arg1 - $arg2 - $arg3");
1.25      harris41  402: 	    sleep 1;
1.51      matthew   403:             #
1.45      www       404:             my $result='';
1.51      matthew   405:             #
                    406:             # At this point, query is received, query-ID assigned and sent 
                    407:             # back, $query eq 'logquery' will mean that this is a query 
                    408:             # against log-files
                    409:             if (($query eq 'userlog') || ($query eq 'courselog')) {
                    410:                 # beginning of log query
                    411:                 my $udom    = &unescape($arg1);
                    412:                 my $uname   = &unescape($arg2);
                    413:                 my $command = &unescape($arg3);
                    414:                 my $path    = &propath($udom,$uname);
                    415:                 if (-e "$path/activity.log") {
                    416:                     if ($query eq 'userlog') {
                    417:                         $result=&userlog($path,$command);
                    418:                     } else {
                    419:                         $result=&courselog($path,$command);
                    420:                     }
                    421:                 } else {
                    422:                     &logthis('Unable to do log query: '.$uname.'@'.$udom);
                    423:                     $result='no_such_file';
                    424:                 }
                    425:                 # end of log query
1.70      raeburn   426:             } elsif (($query eq 'fetchenrollment') || 
1.71      albertel  427: 		     ($query eq 'institutionalphotos')) {
1.62      raeburn   428:                 # retrieve institutional class lists
                    429:                 my $dom = &unescape($arg1);
                    430:                 my %affiliates = ();
                    431:                 my %replies = ();
                    432:                 my $locresult = '';
                    433:                 my $querystr = &unescape($arg3);
                    434:                 foreach (split/%%/,$querystr) {
1.68      raeburn   435:                     if (/^([^=]+)=([^=]+)$/) {
1.62      raeburn   436:                         @{$affiliates{$1}} = split/,/,$2;
                    437:                     }
                    438:                 }
1.70      raeburn   439:                 if ($query eq 'fetchenrollment') { 
                    440:                     $locresult = &localenroll::fetch_enrollment($dom,\%affiliates,\%replies);
                    441:                 } elsif ($query eq 'institutionalphotos') {
                    442:                     my $crs = &unescape($arg2);
1.71.2.1! albertel  443: 		    eval {
        !           444: 			local($SIG{__DIE__})='DEFAULT';
        !           445: 			$locresult = &localenroll::institutional_photos($dom,$crs,\%affiliates,\%replies,'update');
        !           446: 		    };
        !           447: 		    if ($@) {
        !           448: 			$locresult = 'error';
        !           449: 		    }
1.70      raeburn   450:                 }
1.62      raeburn   451:                 $result = &escape($locresult.':');
                    452:                 if ($locresult) {
                    453:                     $result .= &escape(join(':',map{$_.'='.$replies{$_}} keys %replies));
                    454:                 }
1.63      matthew   455:             } elsif ($query eq 'prepare activity log') {
                    456:                 my ($cid,$domain) = map {&unescape($_);} ($arg1,$arg2);
1.64      matthew   457:                 &logthis('preparing activity log tables for '.$cid);
1.63      matthew   458:                 my $command = 
1.64      matthew   459:                     qq{$perlvar{'lonDaemons'}/parse_activity_log.pl -course=$cid -domain=$domain};
1.63      matthew   460:                 system($command);
1.64      matthew   461:                 &logthis($command);
1.63      matthew   462:                 my $returnvalue = $?>>8;
                    463:                 if ($returnvalue) {
                    464:                     $result = 'error: parse_activity_log.pl returned '.
                    465:                         $returnvalue;
                    466:                 } else {
                    467:                     $result = 'success';
                    468:                 }
1.51      matthew   469:             } else {
                    470:                 # Do an sql query
                    471:                 $result = &do_sql_query($query,$arg1,$arg2);
                    472:             }
1.50      matthew   473:             # result does not need to be escaped because it has already been
                    474:             # escaped.
                    475:             #$result=&escape($result);
1.17      harris41  476:             &reply("queryreply:$queryid:$result",$conserver);
1.1       harris41  477:         }
                    478:         # tidy up gracefully and finish
1.51      matthew   479:         #
                    480:         # close the database handle
1.2       harris41  481: 	$dbh->disconnect
1.59      albertel  482:             or &logthis("<font color='blue'>WARNING: Couldn't disconnect".
1.51      matthew   483:                         " from database  $DBI::errstr : $@</font>");
1.1       harris41  484:         # this exit is VERY important, otherwise the child will become
                    485:         # a producer of more and more children, forking yourself into
                    486:         # process death.
                    487:         exit;
                    488:     }
1.2       harris41  489: }
1.1       harris41  490: 
1.51      matthew   491: ########################################################
                    492: ########################################################
                    493: 
                    494: =pod
                    495: 
                    496: =item &do_sql_query
                    497: 
                    498: Runs an sql metadata table query.
                    499: 
                    500: Inputs: $query, $custom, $customshow
                    501: 
                    502: Returns: A string containing escaped results.
                    503: 
                    504: =cut
                    505: 
                    506: ########################################################
                    507: ########################################################
                    508: {
                    509:     my @metalist;
                    510: 
                    511: sub process_file {
                    512:     if ( -e $_ &&  # file exists
                    513:          -f $_ &&  # and is a normal file
                    514:          /\.meta$/ &&  # ends in meta
                    515:          ! /^.+\.\d+\.[^\.]+\.meta$/  # is not a previous version
                    516:          ) {
                    517:         push(@metalist,$File::Find::name);
                    518:     }
                    519: }
                    520: 
                    521: sub do_sql_query {
                    522:     my ($query,$custom,$customshow) = @_;
1.69      www       523: #    &logthis('doing query '.$query);
1.51      matthew   524:     $custom     = &unescape($custom);
                    525:     $customshow = &unescape($customshow);
                    526:     #
                    527:     @metalist = ();
                    528:     #
                    529:     my $result = '';
                    530:     my @results = ();
                    531:     my @files;
                    532:     my $subsetflag=0;
                    533:     #
                    534:     if ($query) {
                    535:         #prepare and execute the query
                    536:         my $sth = $dbh->prepare($query);
                    537:         unless ($sth->execute()) {
1.59      albertel  538:             &logthis('<font color="blue">'.
1.58      matthew   539:                      'WARNING: Could not retrieve from database:'.
                    540:                      $sth->errstr().'</font>');
1.51      matthew   541:         } else {
                    542:             my $aref=$sth->fetchall_arrayref;
                    543:             foreach my $row (@$aref) {
                    544:                 push @files,@{$row}[3] if ($custom or $customshow);
                    545:                 my @b=map { &escape($_); } @$row;
                    546:                 push @results,join(",", @b);
                    547:                 # Build up the @files array with the LON-CAPA urls 
                    548:                 # of the resources.
                    549:             }
                    550:         }
                    551:     }
                    552:     # do custom metadata searching here and build into result
                    553:     return join("&",@results) if (! ($custom or $customshow));
                    554:     # Only get here if there is a custom query or custom show request
                    555:     &logthis("Doing custom query for $custom");
                    556:     if ($query) {
                    557:         @metalist=map {
                    558:             $perlvar{'lonDocRoot'}.$_.'.meta';
                    559:         } @files;
                    560:     } else {
                    561:         my $dir = "$perlvar{'lonDocRoot'}/res/$perlvar{'lonDefDomain'}";
                    562:         @metalist=(); 
                    563:         opendir(RESOURCES,$dir);
                    564:         my @homeusers=grep {
                    565:             &ishome($dir.'/'.$_);
                    566:         } grep {!/^\.\.?$/} readdir(RESOURCES);
                    567:         closedir RESOURCES;
                    568:         # Define the
                    569:         foreach my $user (@homeusers) {
                    570:             find (\&process_file,$dir.'/'.$user);
                    571:         }
                    572:     } 
                    573:     # if file is indicated in sql database and
                    574:     #     not part of sql-relevant query, do not pattern match.
                    575:     #
                    576:     # if file is not in sql database, output error.
                    577:     #
                    578:     # if file is indicated in sql database and is
                    579:     #     part of query result list, then do the pattern match.
                    580:     my $customresult='';
                    581:     my @results;
                    582:     foreach my $metafile (@metalist) {
                    583:         my $fh=IO::File->new($metafile);
                    584:         my @lines=<$fh>;
                    585:         my $stuff=join('',@lines);
                    586:         if ($stuff=~/$custom/s) {
                    587:             foreach my $f ('abstract','author','copyright',
                    588:                            'creationdate','keywords','language',
                    589:                            'lastrevisiondate','mime','notes',
                    590:                            'owner','subject','title') {
                    591:                 $stuff=~s/\n?\<$f[^\>]*\>.*?<\/$f[^\>]*\>\n?//s;
                    592:             }
                    593:             my $mfile=$metafile; 
                    594:             my $docroot=$perlvar{'lonDocRoot'};
                    595:             $mfile=~s/^$docroot//;
                    596:             $mfile=~s/\.meta$//;
                    597:             unless ($query) {
                    598:                 my $q2="SELECT * FROM metadata WHERE url ".
                    599:                     " LIKE BINARY '?'";
                    600:                 my $sth = $dbh->prepare($q2);
                    601:                 $sth->execute($mfile);
                    602:                 my $aref=$sth->fetchall_arrayref;
                    603:                 foreach my $a (@$aref) {
                    604:                     my @b=map { &escape($_)} @$a;
                    605:                     push @results,join(",", @b);
                    606:                 }
                    607:             }
                    608:             # &logthis("found: $stuff");
                    609:             $customresult.='&custom='.&escape($mfile).','.
                    610:                 escape($stuff);
                    611:         }
                    612:     }
                    613:     $result=join("&",@results) unless $query;
                    614:     $result.=$customresult;
                    615:     #
                    616:     return $result;
                    617: } # End of &do_sql_query
                    618: 
                    619: } # End of scoping curly braces for &process_file and &do_sql_query
                    620: ########################################################
                    621: ########################################################
                    622: 
                    623: =pod
                    624: 
                    625: =item &logthis
                    626: 
                    627: Inputs: $message, the message to log
                    628: 
                    629: Returns: nothing
                    630: 
                    631: Writes $message to the logfile.
                    632: 
                    633: =cut
                    634: 
                    635: ########################################################
                    636: ########################################################
                    637: sub logthis {
                    638:     my $message=shift;
                    639:     my $execdir=$perlvar{'lonDaemons'};
1.52      matthew   640:     my $fh=IO::File->new(">>$execdir/logs/lonsql.log");
1.51      matthew   641:     my $now=time;
                    642:     my $local=localtime($now);
                    643:     print $fh "$local ($$): $message\n";
1.2       harris41  644: }
1.1       harris41  645: 
1.2       harris41  646: # -------------------------------------------------- Non-critical communication
1.1       harris41  647: 
1.51      matthew   648: ########################################################
                    649: ########################################################
                    650: 
                    651: =pod
                    652: 
                    653: =item &subreply
                    654: 
                    655: Sends a command to a server.  Called only by &reply.
                    656: 
                    657: Inputs: $cmd,$server
                    658: 
                    659: Returns: The results of the message or 'con_lost' on error.
                    660: 
                    661: =cut
                    662: 
                    663: ########################################################
                    664: ########################################################
1.2       harris41  665: sub subreply {
                    666:     my ($cmd,$server)=@_;
                    667:     my $peerfile="$perlvar{'lonSockDir'}/$server";
                    668:     my $sclient=IO::Socket::UNIX->new(Peer    =>"$peerfile",
                    669:                                       Type    => SOCK_STREAM,
                    670:                                       Timeout => 10)
                    671:        or return "con_lost";
                    672:     print $sclient "$cmd\n";
                    673:     my $answer=<$sclient>;
                    674:     chomp($answer);
1.51      matthew   675:     $answer="con_lost" if (!$answer);
1.2       harris41  676:     return $answer;
                    677: }
1.1       harris41  678: 
1.51      matthew   679: ########################################################
                    680: ########################################################
                    681: 
                    682: =pod
                    683: 
                    684: =item &reply
                    685: 
                    686: Sends a command to a server.
                    687: 
                    688: Inputs: $cmd,$server
                    689: 
                    690: Returns: The results of the message or 'con_lost' on error.
                    691: 
                    692: =cut
                    693: 
                    694: ########################################################
                    695: ########################################################
1.2       harris41  696: sub reply {
                    697:   my ($cmd,$server)=@_;
                    698:   my $answer;
                    699:   if ($server ne $perlvar{'lonHostID'}) { 
                    700:     $answer=subreply($cmd,$server);
                    701:     if ($answer eq 'con_lost') {
                    702: 	$answer=subreply("ping",$server);
                    703:         $answer=subreply($cmd,$server);
                    704:     }
                    705:   } else {
                    706:     $answer='self_reply';
1.33      harris41  707:     $answer=subreply($cmd,$server);
1.2       harris41  708:   } 
                    709:   return $answer;
                    710: }
1.1       harris41  711: 
1.51      matthew   712: ########################################################
                    713: ########################################################
                    714: 
                    715: =pod
                    716: 
                    717: =item &escape
                    718: 
                    719: Escape special characters in a string.
1.3       harris41  720: 
1.51      matthew   721: Inputs: string to escape
                    722: 
                    723: Returns: The input string with special characters escaped.
                    724: 
                    725: =cut
                    726: 
                    727: ########################################################
                    728: ########################################################
1.3       harris41  729: sub escape {
                    730:     my $str=shift;
                    731:     $str =~ s/(\W)/"%".unpack('H2',$1)/eg;
                    732:     return $str;
                    733: }
                    734: 
1.51      matthew   735: ########################################################
                    736: ########################################################
                    737: 
                    738: =pod
                    739: 
                    740: =item &unescape
                    741: 
                    742: Unescape special characters in a string.
1.3       harris41  743: 
1.51      matthew   744: Inputs: string to unescape
                    745: 
                    746: Returns: The input string with special characters unescaped.
                    747: 
                    748: =cut
                    749: 
                    750: ########################################################
                    751: ########################################################
1.3       harris41  752: sub unescape {
                    753:     my $str=shift;
                    754:     $str =~ s/%([a-fA-F0-9][a-fA-F0-9])/pack("C",hex($1))/eg;
                    755:     return $str;
                    756: }
1.34      harris41  757: 
1.51      matthew   758: ########################################################
                    759: ########################################################
                    760: 
                    761: =pod
                    762: 
                    763: =item &ishome
                    764: 
                    765: Determine if the current machine is the home server for a user.
                    766: The determination is made by checking the filesystem for the users information.
                    767: 
                    768: Inputs: $author
                    769: 
                    770: Returns: 0 - this is not the authors home server, 1 - this is.
                    771: 
                    772: =cut
                    773: 
                    774: ########################################################
                    775: ########################################################
1.34      harris41  776: sub ishome {
                    777:     my $author=shift;
                    778:     $author=~s/\/home\/httpd\/html\/res\/([^\/]*)\/([^\/]*).*/$1\/$2/;
                    779:     my ($udom,$uname)=split(/\//,$author);
                    780:     my $proname=propath($udom,$uname);
                    781:     if (-e $proname) {
                    782: 	return 1;
                    783:     } else {
                    784:         return 0;
                    785:     }
                    786: }
                    787: 
1.51      matthew   788: ########################################################
                    789: ########################################################
                    790: 
                    791: =pod
                    792: 
                    793: =item &propath
                    794: 
                    795: Inputs: user name, user domain
                    796: 
                    797: Returns: The full path to the users directory.
                    798: 
                    799: =cut
                    800: 
                    801: ########################################################
                    802: ########################################################
1.34      harris41  803: sub propath {
                    804:     my ($udom,$uname)=@_;
                    805:     $udom=~s/\W//g;
                    806:     $uname=~s/\W//g;
                    807:     my $subdir=$uname.'__';
                    808:     $subdir =~ s/(.)(.)(.).*/$1\/$2\/$3/;
                    809:     my $proname="$perlvar{'lonUsersDir'}/$udom/$subdir/$uname";
                    810:     return $proname;
                    811: } 
1.40      harris41  812: 
1.51      matthew   813: ########################################################
                    814: ########################################################
                    815: 
                    816: =pod
                    817: 
                    818: =item &courselog
                    819: 
                    820: Inputs: $path, $command
                    821: 
                    822: Returns: unescaped string of values.
                    823: 
                    824: =cut
                    825: 
                    826: ########################################################
                    827: ########################################################
                    828: sub courselog {
                    829:     my ($path,$command)=@_;
                    830:     my %filters=();
                    831:     foreach (split(/\:/,&unescape($command))) {
                    832: 	my ($name,$value)=split(/\=/,$_);
                    833:         $filters{$name}=$value;
                    834:     }
                    835:     my @results=();
                    836:     open(IN,$path.'/activity.log') or return ('file_error');
                    837:     while (my $line=<IN>) {
                    838:         chomp($line);
                    839:         my ($timestamp,$host,$log)=split(/\:/,$line);
                    840: #
                    841: # $log has the actual log entries; currently still escaped, and
                    842: # %26(timestamp)%3a(url)%3a(user)%3a(domain)
                    843: # then additionally
                    844: # %3aPOST%3a(name)%3d(value)%3a(name)%3d(value)
                    845: # or
                    846: # %3aCSTORE%3a(name)%3d(value)%26(name)%3d(value)
                    847: #
                    848: # get delimiter between timestamped entries to be &&&
                    849:         $log=~s/\%26(\d+)\%3a/\&\&\&$1\%3a/g;
                    850: # now go over all log entries 
                    851:         foreach (split(/\&\&\&/,&unescape($log))) {
                    852: 	    my ($time,$res,$uname,$udom,$action,@values)=split(/\:/,$_);
                    853:             my $values=&unescape(join(':',@values));
                    854:             $values=~s/\&/\:/g;
                    855:             $res=&unescape($res);
                    856:             my $include=1;
                    857:             if (($filters{'username'}) && ($uname ne $filters{'username'})) 
                    858:                                                                { $include=0; }
                    859:             if (($filters{'domain'}) && ($udom ne $filters{'domain'})) 
                    860:                                                                { $include=0; }
                    861:             if (($filters{'url'}) && ($res!~/$filters{'url'}/)) 
                    862:                                                                { $include=0; }
                    863:             if (($filters{'start'}) && ($time<$filters{'start'})) 
                    864:                                                                { $include=0; }
                    865:             if (($filters{'end'}) && ($time>$filters{'end'})) 
                    866:                                                                { $include=0; }
                    867:             if (($filters{'action'} eq 'view') && ($action)) 
                    868:                                                                { $include=0; }
                    869:             if (($filters{'action'} eq 'submit') && ($action ne 'POST')) 
                    870:                                                                { $include=0; }
                    871:             if (($filters{'action'} eq 'grade') && ($action ne 'CSTORE')) 
                    872:                                                                { $include=0; }
                    873:             if ($include) {
                    874: 	       push(@results,($time<1000000000?'0':'').$time.':'.$res.':'.
                    875:                                             $uname.':'.$udom.':'.
                    876:                                             $action.':'.$values);
                    877:             }
                    878:        }
                    879:     }
                    880:     close IN;
                    881:     return join('&',sort(@results));
                    882: }
                    883: 
                    884: ########################################################
                    885: ########################################################
                    886: 
                    887: =pod
                    888: 
                    889: =item &userlog
                    890: 
                    891: Inputs: $path, $command
                    892: 
                    893: Returns: unescaped string of values.
1.40      harris41  894: 
1.51      matthew   895: =cut
1.40      harris41  896: 
1.51      matthew   897: ########################################################
                    898: ########################################################
                    899: sub userlog {
                    900:     my ($path,$command)=@_;
                    901:     my %filters=();
                    902:     foreach (split(/\:/,&unescape($command))) {
                    903: 	my ($name,$value)=split(/\=/,$_);
                    904:         $filters{$name}=$value;
                    905:     }
                    906:     my @results=();
                    907:     open(IN,$path.'/activity.log') or return ('file_error');
                    908:     while (my $line=<IN>) {
                    909:         chomp($line);
                    910:         my ($timestamp,$host,$log)=split(/\:/,$line);
                    911:         $log=&unescape($log);
                    912:         my $include=1;
                    913:         if (($filters{'start'}) && ($timestamp<$filters{'start'})) 
                    914:                                                              { $include=0; }
                    915:         if (($filters{'end'}) && ($timestamp>$filters{'end'})) 
                    916:                                                              { $include=0; }
                    917:         if (($filters{'action'} eq 'log') && ($log!~/^Log/)) { $include=0; }
                    918:         if (($filters{'action'} eq 'check') && ($log!~/^Check/)) 
                    919:                                                              { $include=0; }
                    920:         if ($include) {
                    921: 	   push(@results,$timestamp.':'.$log);
                    922:         }
                    923:     }
                    924:     close IN;
                    925:     return join('&',sort(@results));
1.52      matthew   926: }
                    927: 
                    928: ########################################################
                    929: ########################################################
                    930: 
                    931: =pod
                    932: 
                    933: =item Functions required for forking
                    934: 
                    935: =over 4
                    936: 
                    937: =item REAPER
                    938: 
                    939: REAPER takes care of dead children.
                    940: 
                    941: =item HUNTSMAN
                    942: 
                    943: Signal handler for SIGINT.
                    944: 
                    945: =item HUPSMAN
                    946: 
                    947: Signal handler for SIGHUP
                    948: 
                    949: =item DISCONNECT
                    950: 
                    951: Disconnects from database.
                    952: 
                    953: =back
                    954: 
                    955: =cut
                    956: 
                    957: ########################################################
                    958: ########################################################
                    959: sub REAPER {                   # takes care of dead children
                    960:     $SIG{CHLD} = \&REAPER;
                    961:     my $pid = wait;
                    962:     $children --;
                    963:     &logthis("Child $pid died");
                    964:     delete $children{$pid};
                    965: }
                    966: 
                    967: sub HUNTSMAN {                      # signal handler for SIGINT
                    968:     local($SIG{CHLD}) = 'IGNORE';   # we're going to kill our children
                    969:     kill 'INT' => keys %children;
                    970:     my $execdir=$perlvar{'lonDaemons'};
                    971:     unlink("$execdir/logs/lonsql.pid");
1.59      albertel  972:     &logthis("<font color='red'>CRITICAL: Shutting down</font>");
1.52      matthew   973:     $unixsock = "mysqlsock";
                    974:     my $port="$perlvar{'lonSockDir'}/$unixsock";
                    975:     unlink($port);
                    976:     exit;                           # clean up with dignity
                    977: }
                    978: 
                    979: sub HUPSMAN {                      # signal handler for SIGHUP
                    980:     local($SIG{CHLD}) = 'IGNORE';  # we're going to kill our children
                    981:     kill 'INT' => keys %children;
                    982:     close($server);                # free up socket
1.59      albertel  983:     &logthis("<font color='red'>CRITICAL: Restarting</font>");
1.52      matthew   984:     my $execdir=$perlvar{'lonDaemons'};
                    985:     $unixsock = "mysqlsock";
                    986:     my $port="$perlvar{'lonSockDir'}/$unixsock";
                    987:     unlink($port);
                    988:     exec("$execdir/lonsql");         # here we go again
                    989: }
                    990: 
                    991: sub DISCONNECT {
                    992:     $dbh->disconnect or 
1.59      albertel  993:     &logthis("<font color='blue'>WARNING: Couldn't disconnect from database ".
1.52      matthew   994:              " $DBI::errstr : $@</font>");
                    995:     exit;
1.51      matthew   996: }
1.40      harris41  997: 
                    998: 
1.51      matthew   999: =pod
1.40      harris41 1000: 
1.51      matthew  1001: =back
1.40      harris41 1002: 
                   1003: =cut

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