File:  [LON-CAPA] / loncom / lonsql
Revision 1.90: download - view: text, annotated - select for diffs
Tue Mar 11 01:45:47 2008 UTC (16 years ago) by raeburn
Branches: MAIN
CVS tags: version_2_9_X, version_2_9_99_0, version_2_9_1, version_2_9_0, version_2_8_X, version_2_8_99_1, version_2_8_99_0, version_2_8_2, version_2_8_1, version_2_8_0, version_2_7_X, version_2_7_99_1, version_2_7_99_0, version_2_7_1, version_2_7_0, version_2_6_X, version_2_6_99_1, version_2_6_99_0, version_2_6_3, version_2_10_X, version_2_10_1, version_2_10_0_RC2, version_2_10_0_RC1, version_2_10_0, loncapaMITrelate_1, bz6209-base, bz6209, bz5969, bz2851, PRINT_INCOMPLETE_base, PRINT_INCOMPLETE, HEAD, GCI_3, GCI_2, GCI_1, BZ5971-printing-apage, BZ5434-fox
- scope

    1: #!/usr/bin/perl
    2: 
    3: # The LearningOnline Network
    4: # lonsql - LON TCP-MySQL-Server Daemon for handling database requests.
    5: #
    6: # $Id: lonsql,v 1.90 2008/03/11 01:45:47 raeburn Exp $
    7: #
    8: # Copyright Michigan State University Board of Trustees
    9: #
   10: # This file is part of the LearningOnline Network with CAPA (LON-CAPA).
   11: #
   12: # LON-CAPA is free software; you can redistribute it and/or modify
   13: # it under the terms of the GNU General Public License as published by
   14: # the Free Software Foundation; either version 2 of the License, or
   15: # (at your option) any later version.
   16: #
   17: # LON-CAPA is distributed in the hope that it will be useful,
   18: # but WITHOUT ANY WARRANTY; without even the implied warranty of
   19: # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
   20: # GNU General Public License for more details.
   21: #
   22: # You should have received a copy of the GNU General Public License
   23: # along with LON-CAPA; if not, write to the Free Software
   24: # Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA
   25: #
   26: # /home/httpd/html/adm/gpl.txt
   27: #
   28: # http://www.lon-capa.org/
   29: #
   30: 
   31: =pod
   32: 
   33: =head1 NAME
   34: 
   35: lonsql - LON TCP-MySQL-Server Daemon for handling database requests.
   36: 
   37: =head1 SYNOPSIS
   38: 
   39: This script should be run as user=www.  
   40: Note that a lonsql.pid file contains the pid of the parent process.
   41: 
   42: =head1 OVERVIEW
   43: 
   44: =head2 Purpose within LON-CAPA
   45: 
   46: LON-CAPA is meant to distribute A LOT of educational content to A LOT
   47: of people. It is ineffective to directly rely on contents within the
   48: ext2 filesystem to be speedily scanned for on-the-fly searches of
   49: content descriptions. (Simply put, it takes a cumbersome amount of
   50: time to open, read, analyze, and close thousands of files.)
   51: 
   52: The solution is to index various data fields that are descriptive of
   53: the educational resources on a LON-CAPA server machine in a
   54: database. Descriptive data fields are referred to as "metadata". The
   55: question then arises as to how this metadata is handled in terms of
   56: the rest of the LON-CAPA network without burdening client and daemon
   57: processes.
   58: 
   59: The obvious solution, using lonc to send a query to a lond process,
   60: doesn't work so well in general as you can see in the following
   61: example:
   62: 
   63:     lonc= loncapa client process    A-lonc= a lonc process on Server A
   64:     lond= loncapa daemon process
   65: 
   66:                  database command
   67:     A-lonc  --------TCP/IP----------------> B-lond
   68: 
   69: The problem emerges that A-lonc and B-lond are kept waiting for the
   70: MySQL server to "do its stuff", or in other words, perform the
   71: conceivably sophisticated, data-intensive, time-sucking database
   72: transaction.  By tying up a lonc and lond process, this significantly
   73: cripples the capabilities of LON-CAPA servers.
   74: 
   75: The solution is to offload the work onto another process, and use
   76: lonc and lond just for requests and notifications of completed
   77: processing:
   78: 
   79:                 database command
   80: 
   81:   A-lonc  ---------TCP/IP-----------------> B-lond =====> B-lonsql
   82:          <---------------------------------/                |
   83:            "ok, I'll get back to you..."                    |
   84:                                                             |
   85:                                                             /
   86:   A-lond  <-------------------------------  B-lonc   <======
   87:            "Guess what? I have the result!"
   88: 
   89: Of course, depending on success or failure, the messages may vary, but
   90: the principle remains the same where a separate pool of children
   91: processes (lonsql's) handle the MySQL database manipulations.
   92: 
   93: Thus, lonc and lond spend effectively no time waiting on results from
   94: the database.
   95: 
   96: =head1 Internals
   97: 
   98: =over 4
   99: 
  100: =cut
  101: 
  102: use strict;
  103: 
  104: use lib '/home/httpd/lib/perl/';
  105: use LONCAPA;
  106: use LONCAPA::Configuration;
  107: use LONCAPA::lonmetadata();
  108: use Apache::lonnet;
  109: 
  110: use IO::Socket;
  111: use Symbol;
  112: use POSIX;
  113: use IO::Select;
  114: use DBI;
  115: use File::Find;
  116: use localenroll;
  117: use GDBM_File;
  118: 
  119: ########################################################
  120: ########################################################
  121: 
  122: =pod
  123: 
  124: =item Global Variables
  125: 
  126: =over 4
  127: 
  128: =item dbh
  129: 
  130: =back
  131: 
  132: =cut
  133: 
  134: ########################################################
  135: ########################################################
  136: my $dbh;
  137: 
  138: ########################################################
  139: ########################################################
  140: 
  141: =pod 
  142: 
  143: =item Variables required for forking
  144: 
  145: =over 4
  146: 
  147: =item $MAX_CLIENTS_PER_CHILD
  148: 
  149: The number of clients each child should process.
  150: 
  151: =item %children 
  152: 
  153: The keys to %children  are the current child process IDs
  154: 
  155: =item $children
  156: 
  157: The current number of children
  158: 
  159: =back
  160: 
  161: =cut 
  162: 
  163: ########################################################
  164: ########################################################
  165: my $MAX_CLIENTS_PER_CHILD  = 5;   # number of clients each child should process
  166: my %children               = ();  # keys are current child process IDs
  167: my $children               = 0;   # current number of children
  168:                                
  169: ###################################################################
  170: ###################################################################
  171: 
  172: =pod
  173: 
  174: =item Main body of code.
  175: 
  176: =over 4
  177: 
  178: =item Read data from loncapa_apache.conf and loncapa.conf.
  179: 
  180: =item Ensure we can access the database.
  181: 
  182: =item Determine if there are other instances of lonsql running.
  183: 
  184: =item Read the hosts file.
  185: 
  186: =item Create a socket for lonsql.
  187: 
  188: =item Fork once and dissociate from parent.
  189: 
  190: =item Write PID to disk.
  191: 
  192: =item Prefork children and maintain the population of children.
  193: 
  194: =back
  195: 
  196: =cut
  197: 
  198: ###################################################################
  199: ###################################################################
  200: my $childmaxattempts=10;
  201: my $run =0;              # running counter to generate the query-id
  202: #
  203: # Read loncapa_apache.conf and loncapa.conf
  204: #
  205: my %perlvar=%{&LONCAPA::Configuration::read_conf('loncapa.conf')};
  206: #
  207: # Write the /home/www/.my.cnf file 
  208: my $conf_file = '/home/www/.my.cnf';
  209: if (! -e $conf_file) {
  210:     if (open MYCNF, ">$conf_file") {
  211:         print MYCNF <<"ENDMYCNF";
  212: [client]
  213: user=www
  214: password=$perlvar{'lonSqlAccess'}
  215: ENDMYCNF
  216:         close MYCNF;
  217:     } else {
  218:         warn "Unable to write $conf_file, continuing";
  219:     }
  220: }
  221: 
  222: 
  223: #
  224: # Make sure that database can be accessed
  225: #
  226: my $dbh;
  227: unless ($dbh = DBI->connect("DBI:mysql:loncapa","www",
  228:                             $perlvar{'lonSqlAccess'},
  229:                             { RaiseError =>0,PrintError=>0})) { 
  230:     print "Cannot connect to database!\n";
  231:     my $emailto="$perlvar{'lonAdmEMail'},$perlvar{'lonSysEMail'}";
  232:     my $subj="LON: $perlvar{'lonHostID'} Cannot connect to database!";
  233:     system("echo 'Cannot connect to MySQL database!' |".
  234:            " mailto $emailto -s '$subj' > /dev/null");
  235: 
  236:     open(SMP,'>/home/httpd/html/lon-status/mysql.txt');
  237:     print SMP 'time='.time.'&mysql=defunct'."\n";
  238:     close(SMP);
  239: 
  240:     exit 1;
  241: } else {
  242:     unlink('/home/httpd/html/lon-status/mysql.txt');
  243:     $dbh->disconnect;
  244: }
  245: 
  246: #
  247: # Check if other instance running
  248: #
  249: my $pidfile="$perlvar{'lonDaemons'}/logs/lonsql.pid";
  250: if (-e $pidfile) {
  251:    open(my $lfh,"$pidfile");
  252:    my $pide=<$lfh>;
  253:    chomp($pide);
  254:    if (kill 0 => $pide) { die "already running"; }
  255: }
  256: 
  257: my $PREFORK=4; # number of children to maintain, at least four spare
  258: #
  259: #$PREFORK=int($PREFORK/4);
  260: 
  261: #
  262: # Create a socket to talk to lond
  263: #
  264: my $unixsock = "mysqlsock";
  265: my $localfile="$perlvar{'lonSockDir'}/$unixsock";
  266: my $server;
  267: unlink ($localfile);
  268: unless ($server=IO::Socket::UNIX->new(Local    =>"$localfile",
  269:                                       Type    => SOCK_STREAM,
  270:                                       Listen => 10)) {
  271:     print "in socket error:$@\n";
  272: }
  273: 
  274: #
  275: # Fork once and dissociate
  276: #
  277: my $fpid=fork;
  278: exit if $fpid;
  279: die "Couldn't fork: $!" unless defined ($fpid);
  280: POSIX::setsid() or die "Can't start new session: $!";
  281: 
  282: #
  283: # Write our PID on disk
  284: my $execdir=$perlvar{'lonDaemons'};
  285: open (PIDSAVE,">$execdir/logs/lonsql.pid");
  286: print PIDSAVE "$$\n";
  287: close(PIDSAVE);
  288: &logthis("<font color='red'>CRITICAL: ---------- Starting ----------</font>");
  289: 
  290: #
  291: # Ignore signals generated during initial startup
  292: $SIG{HUP}=$SIG{USR1}='IGNORE';
  293: # Now we are on our own    
  294: #    Fork off our children.
  295: for (1 .. $PREFORK) {
  296:     make_new_child();
  297: }
  298: 
  299: #
  300: # Install signal handlers.
  301: $SIG{CHLD} = \&REAPER;
  302: $SIG{INT}  = $SIG{TERM} = \&HUNTSMAN;
  303: $SIG{HUP}  = \&HUPSMAN;
  304: 
  305: #
  306: # And maintain the population.
  307: while (1) {
  308:     sleep;                          # wait for a signal (i.e., child's death)
  309:     for (my $i = $children; $i < $PREFORK; $i++) {
  310:         make_new_child();           # top up the child pool
  311:     }
  312: }
  313: 
  314: ########################################################
  315: ########################################################
  316: 
  317: =pod
  318: 
  319: =item &make_new_child
  320: 
  321: Inputs: None
  322: 
  323: Returns: None
  324: 
  325: =cut
  326: 
  327: ########################################################
  328: ########################################################
  329: sub make_new_child {
  330:     my $pid;
  331:     my $sigset;
  332:     #
  333:     # block signal for fork
  334:     $sigset = POSIX::SigSet->new(SIGINT);
  335:     sigprocmask(SIG_BLOCK, $sigset)
  336:         or die "Can't block SIGINT for fork: $!\n";
  337:     #
  338:     die "fork: $!" unless defined ($pid = fork);
  339:     #
  340:     if ($pid) {
  341:         # Parent records the child's birth and returns.
  342:         sigprocmask(SIG_UNBLOCK, $sigset)
  343:             or die "Can't unblock SIGINT for fork: $!\n";
  344:         $children{$pid} = 1;
  345:         $children++;
  346:         return;
  347:     } else {
  348:         # Child can *not* return from this subroutine.
  349:         $SIG{INT} = 'DEFAULT';      # make SIGINT kill us as it did before
  350:         # unblock signals
  351:         sigprocmask(SIG_UNBLOCK, $sigset)
  352:             or die "Can't unblock SIGINT for fork: $!\n";
  353:         #open database handle
  354: 	# making dbh global to avoid garbage collector
  355: 	unless ($dbh = DBI->connect("DBI:mysql:loncapa","www",
  356:                                     $perlvar{'lonSqlAccess'},
  357:                                     { RaiseError =>0,PrintError=>0})) { 
  358:             sleep(10+int(rand(20)));
  359:             &logthis("<font color='blue'>WARNING: Couldn't connect to database".
  360:                      ": $@</font>");
  361:                      #  "($st secs): $@</font>");
  362:             print "database handle error\n";
  363:             exit;
  364:         }
  365: 	# make sure that a database disconnection occurs with 
  366:         # ending kill signals
  367: 	$SIG{TERM}=$SIG{INT}=$SIG{QUIT}=$SIG{__DIE__}=\&DISCONNECT;
  368:         # handle connections until we've reached $MAX_CLIENTS_PER_CHILD
  369:         for (my $i=0; $i < $MAX_CLIENTS_PER_CHILD; $i++) {
  370:             my $client = $server->accept() or last;
  371:             # do something with the connection
  372: 	    $run = $run+1;
  373: 	    my $userinput = <$client>;
  374: 	    chomp($userinput);
  375:             $userinput=~s/\:($LONCAPA::domain_re)$//;
  376:             my $searchdomain=$1;
  377:             #
  378: 	    my ($conserver,$query,
  379: 		$arg1,$arg2,$arg3)=split(/&/,$userinput);
  380: 	    my $query=unescape($query);
  381:             #
  382:             #send query id which is pid_unixdatetime_runningcounter
  383: 	    my $queryid = &Apache::lonnet::hostname($perlvar{'lonHostID'});
  384: 	    $queryid .="_".($$)."_";
  385: 	    $queryid .= time."_";
  386: 	    $queryid .= $run;
  387: 	    print $client "$queryid\n";
  388: 	    #
  389: 	    # &logthis("QUERY: $query - $arg1 - $arg2 - $arg3 - $queryid");
  390: 	    # sleep 1;
  391:             #
  392:             my $result='';
  393:             #
  394:             # At this point, query is received, query-ID assigned and sent 
  395:             # back, $query eq 'logquery' will mean that this is a query 
  396:             # against log-files
  397:             if (($query eq 'userlog') || ($query eq 'courselog')) {
  398:                 # beginning of log query
  399:                 my $udom    = &unescape($arg1);
  400:                 my $uname   = &unescape($arg2);
  401:                 my $command = &unescape($arg3);
  402:                 my $path    = &propath($udom,$uname);
  403:                 if (-e "$path/activity.log") {
  404:                     if ($query eq 'userlog') {
  405:                         $result=&userlog($path,$command);
  406:                     } else {
  407:                         $result=&courselog($path,$command);
  408:                     }
  409:                     $result = &escape($result);
  410:                 } else {
  411:                     &logthis('Unable to do log query: '.$uname.'@'.$udom);
  412:                     $result='no_such_file';
  413:                 }
  414:                 # end of log query
  415:             } elsif (($query eq 'fetchenrollment') || 
  416: 		     ($query eq 'institutionalphotos')) {
  417:                 # retrieve institutional class lists
  418:                 my $dom = &unescape($arg1);
  419:                 my %affiliates = ();
  420:                 my %replies = ();
  421:                 my $locresult = '';
  422:                 my $querystr = &unescape($arg3);
  423:                 foreach (split/%%/,$querystr) {
  424:                     if (/^([^=]+)=([^=]+)$/) {
  425:                         @{$affiliates{$1}} = split/,/,$2;
  426:                     }
  427:                 }
  428:                 if ($query eq 'fetchenrollment') { 
  429:                     $locresult = &localenroll::fetch_enrollment($dom,\%affiliates,\%replies);
  430:                 } elsif ($query eq 'institutionalphotos') {
  431:                     my $crs = &unescape($arg2);
  432: 		    eval {
  433: 			local($SIG{__DIE__})='DEFAULT';
  434: 			$locresult = &localenroll::institutional_photos($dom,$crs,\%affiliates,\%replies,'update');
  435: 		    };
  436: 		    if ($@) {
  437: 			$locresult = 'error';
  438: 		    }
  439:                 }
  440:                 $result = &escape($locresult.':');
  441:                 if ($locresult) {
  442:                     $result .= &escape(join(':',map{$_.'='.$replies{$_}} keys %replies));
  443:                 }
  444:             } elsif ($query eq 'usersearch') {
  445:                 my ($srchby,$srchtype,$srchterm);
  446:                 if ((&unescape($arg1) eq $searchdomain) &&
  447:                     ($arg2 =~ /\%\%/)) {
  448:                     ($srchby,$srchtype) =
  449:                         map {&unescape($_);} (split(/\%\%/,$arg2));
  450:                     $srchterm = &unescape($arg3);
  451:                 } else {
  452:                     ($srchby,$srchtype,$srchterm) =
  453:                         map {&unescape($_);} ($arg1,$arg2,$arg3);
  454:                 }
  455:                 $result = &do_user_search($searchdomain,$srchby,
  456:                                           $srchtype,$srchterm);
  457: 	    } elsif ($query eq 'instdirsearch') {
  458: 		$result = &do_inst_dir_search($searchdomain,$arg1,$arg2,$arg3);
  459:             } elsif ($query eq 'getinstuser') {
  460:                 $result = &get_inst_user($searchdomain,$arg1,$arg2);
  461:             } elsif ($query eq 'prepare activity log') {
  462:                 my ($cid,$domain) = map {&unescape($_);} ($arg1,$arg2);
  463:                 &logthis('preparing activity log tables for '.$cid);
  464:                 my $command = 
  465:                     qq{$perlvar{'lonDaemons'}/parse_activity_log.pl -course=$cid -domain=$domain};
  466:                 system($command);
  467:                 &logthis($command);
  468:                 my $returnvalue = $?>>8;
  469:                 if ($returnvalue) {
  470:                     $result = 'error: parse_activity_log.pl returned '.
  471:                         $returnvalue;
  472:                 } else {
  473:                     $result = 'success';
  474:                 }
  475:             } elsif (($query eq 'portfolio_metadata') || 
  476:                     ($query eq 'portfolio_access')) {
  477:                 $result = &portfolio_table_update($query,$arg1,$arg2,
  478:                                                   $arg3);
  479:             } elsif ($query eq 'allusers') {
  480:                 my ($uname,$udom) = map {&unescape($_);} ($arg1,$arg2);
  481:                 my %userdata;
  482:                 my (@data) = split(/\%\%/,$arg3);
  483:                 foreach my $item (@data) {
  484:                     my ($key,$value) = split(/=/,$item);
  485:                     $userdata{$key} = &unescape($value);
  486:                 }
  487:                 $userdata{'username'} = $uname;
  488:                 $userdata{'domain'} = $udom;
  489:                 $result = &allusers_table_update($query,$uname,$udom,\%userdata);
  490:             } else {
  491:                 # Do an sql query
  492:                 $result = &do_sql_query($query,$arg1,$arg2,$searchdomain);
  493:             }
  494:             # result does not need to be escaped because it has already been
  495:             # escaped.
  496:             #$result=&escape($result);
  497:             &Apache::lonnet::reply("queryreply:$queryid:$result",$conserver);
  498:         }
  499:         # tidy up gracefully and finish
  500:         #
  501:         # close the database handle
  502: 	$dbh->disconnect
  503:             or &logthis("<font color='blue'>WARNING: Couldn't disconnect".
  504:                         " from database  $DBI::errstr : $@</font>");
  505:         # this exit is VERY important, otherwise the child will become
  506:         # a producer of more and more children, forking yourself into
  507:         # process death.
  508:         exit;
  509:     }
  510: }
  511: 
  512: sub do_user_search {
  513:     my ($domain,$srchby,$srchtype,$srchterm) = @_;
  514:     my $result;
  515:     my $quoted_dom = $dbh->quote( $domain );
  516:     my ($query,$quoted_srchterm,@fields);
  517:     my ($table_columns,$table_indices) =
  518:         &LONCAPA::lonmetadata::describe_metadata_storage('allusers');
  519:     foreach my $coldata (@{$table_columns}) {
  520:         push(@fields,$coldata->{'name'});
  521:     }
  522:     my $fieldlist = join(',',@fields);
  523:     $query = "SELECT $fieldlist FROM allusers WHERE (domain = $quoted_dom AND ";
  524:     if ($srchby eq 'lastfirst') {
  525:         my ($fraglast,$fragfirst) = split(/,/,$srchterm);
  526:         $fragfirst =~ s/^\s+//;
  527:         $fraglast =~ s/\s+$//;
  528:         if ($srchtype eq 'exact') {
  529:             $query .= 'lastname = '.$dbh->quote($fraglast).
  530:                       ' AND firstname = '.$dbh->quote($fragfirst);
  531:         } elsif ($srchtype eq 'begins') {
  532:             $query .= 'lastname LIKE '.$dbh->quote($fraglast.'%').
  533:                       ' AND firstname LIKE '.$dbh->quote($fragfirst.'%');
  534:         } else {
  535:             $query .= 'lastname LIKE '.$dbh->quote('%'.$fraglast.'%').
  536:                       ' AND firstname LIKE '.$dbh->quote('%'.$fragfirst.'%');
  537:         }
  538:     } else {
  539:         my %srchfield = (
  540:                           uname    => 'username',
  541:                           lastname => 'lastname',
  542:                         );
  543:         if ($srchtype eq 'exact') {
  544:             $query .= $srchfield{$srchby}.' = '.$dbh->quote($srchterm);
  545:         } elsif ($srchtype eq 'begins') {
  546:              $query .= $srchfield{$srchby}.' LIKE '.$dbh->quote($srchterm.'%');
  547:         } else {
  548:              $query .= $srchfield{$srchby}.' LIKE '.$dbh->quote('%'.$srchterm.'%');
  549:         }
  550:     }
  551:     $query .= ") ORDER BY username ";
  552:     my $sth = $dbh->prepare($query);
  553:     if ($sth->execute()) {
  554:         my @results;
  555:         while (my @row = $sth->fetchrow_array) {
  556:             my @items;
  557:             for (my $i=0; $i<@row; $i++) {
  558:                 push(@items,&escape($fields[$i]).'='.&escape($row[$i]));
  559:             }
  560:             my $userstr = join(':', @items);
  561:             push(@results,&escape($userstr));
  562:         }
  563:         $sth->finish;
  564:         $result = join('&',@results);
  565:     } else {
  566:         &logthis('<font color="blue">'.
  567:                 'WARNING: Could not retrieve from database:'.
  568:         $sth->errstr().'</font>');
  569:     }
  570:     return $result;
  571: }
  572: 
  573: sub do_inst_dir_search {
  574:     my ($domain,$srchby,$srchterm,$srchtype) = @_;
  575:     $srchby   = &unescape($srchby);
  576:     $srchterm = &unescape($srchterm);
  577:     $srchtype = &unescape($srchtype);
  578:     my (%instusers,%instids,$result,$response);
  579:     eval {
  580:         local($SIG{__DIE__})='DEFAULT';
  581:         $result=&localenroll::get_userinfo($domain,undef,undef,\%instusers,
  582: 					   \%instids,undef,$srchby,$srchterm,
  583: 					   $srchtype);
  584:     };
  585:     if ($result eq 'ok') {
  586:         if (%instusers) {
  587:             foreach my $key (keys(%instusers)) {
  588:                 my $usrstr = &Apache::lonnet::freeze_escape($instusers{$key});
  589:                 $response .=&escape(&escape($key).'='.$usrstr).'&';
  590:             }
  591:         }
  592:         $response=~s/\&$//;
  593:     } else {
  594:         $response = 'unavailable';
  595:     }
  596:     return $response;
  597: }
  598: 
  599: sub get_inst_user {
  600:     my ($domain,$uname,$id) = @_;
  601:     $uname = &unescape($uname);
  602:     $id = &unescape($id);
  603:     my (%instusers,%instids,$result,$response);
  604:     eval {
  605:         local($SIG{__DIE__})='DEFAULT';
  606:         $result=&localenroll::get_userinfo($domain,$uname,$id,\%instusers,
  607:                                            \%instids);
  608:     };
  609:     if ($result eq 'ok') {
  610:         if (keys(%instusers) > 0) {
  611:             foreach my $key (keys(%instusers)) {
  612:                 my $usrstr = &Apache::lonnet::freeze_escape($instusers{$key});
  613:                 $response .= &escape(&escape($key).'='.$usrstr).'&';
  614:             }
  615:         }
  616:         $response=~s/\&$//;
  617:     } else {
  618:         $response = 'unavailable';
  619:     }
  620:     return $response;
  621: }
  622: 
  623: ########################################################
  624: ########################################################
  625: 
  626: =pod
  627: 
  628: =item &do_sql_query
  629: 
  630: Runs an sql metadata table query.
  631: 
  632: Inputs: $query, $custom, $customshow
  633: 
  634: Returns: A string containing escaped results.
  635: 
  636: =cut
  637: 
  638: ########################################################
  639: ########################################################
  640: {
  641:     my @metalist;
  642: 
  643: sub process_file {
  644:     if ( -e $_ &&  # file exists
  645:          -f $_ &&  # and is a normal file
  646:          /\.meta$/ &&  # ends in meta
  647:          ! /^.+\.\d+\.[^\.]+\.meta$/  # is not a previous version
  648:          ) {
  649:         push(@metalist,$File::Find::name);
  650:     }
  651: }
  652: 
  653: sub do_sql_query {
  654:     my ($query,$custom,$customshow,$searchdomain) = @_;
  655: 
  656: #
  657: # limit to searchdomain if given and table is metadata
  658: #
  659:     if (($searchdomain) && ($query=~/FROM metadata/)) {
  660: 	$query.=' HAVING (domain="'.$searchdomain.'")';
  661:     }
  662: #    &logthis('doing query ('.$searchdomain.')'.$query);
  663: 
  664: 
  665: 
  666:     $custom     = &unescape($custom);
  667:     $customshow = &unescape($customshow);
  668:     #
  669:     @metalist = ();
  670:     #
  671:     my $result = '';
  672:     my @results = ();
  673:     my @files;
  674:     my $subsetflag=0;
  675:     #
  676:     if ($query) {
  677:         #prepare and execute the query
  678:         my $sth = $dbh->prepare($query);
  679:         unless ($sth->execute()) {
  680:             &logthis('<font color="blue">'.
  681:                      'WARNING: Could not retrieve from database:'.
  682:                      $sth->errstr().'</font>');
  683:         } else {
  684:             my $aref=$sth->fetchall_arrayref;
  685:             foreach my $row (@$aref) {
  686:                 push @files,@{$row}[3] if ($custom or $customshow);
  687:                 my @b=map { &escape($_); } @$row;
  688:                 push @results,join(",", @b);
  689:                 # Build up the @files array with the LON-CAPA urls 
  690:                 # of the resources.
  691:             }
  692:         }
  693:     }
  694:     # do custom metadata searching here and build into result
  695:     return join("&",@results) if (! ($custom or $customshow));
  696:     # Only get here if there is a custom query or custom show request
  697:     &logthis("Doing custom query for $custom");
  698:     if ($query) {
  699:         @metalist=map {
  700:             $perlvar{'lonDocRoot'}.$_.'.meta';
  701:         } @files;
  702:     } else {
  703:         my $dir = "$perlvar{'lonDocRoot'}/res/$perlvar{'lonDefDomain'}";
  704:         @metalist=(); 
  705:         opendir(RESOURCES,$dir);
  706:         my @homeusers=grep {
  707:             &ishome($dir.'/'.$_);
  708:         } grep {!/^\.\.?$/} readdir(RESOURCES);
  709:         closedir RESOURCES;
  710:         # Define the
  711:         foreach my $user (@homeusers) {
  712:             find (\&process_file,$dir.'/'.$user);
  713:         }
  714:     } 
  715:     # if file is indicated in sql database and
  716:     #     not part of sql-relevant query, do not pattern match.
  717:     #
  718:     # if file is not in sql database, output error.
  719:     #
  720:     # if file is indicated in sql database and is
  721:     #     part of query result list, then do the pattern match.
  722:     my $customresult='';
  723:     my @results;
  724:     foreach my $metafile (@metalist) {
  725:         open(my $fh,$metafile);
  726:         my @lines=<$fh>;
  727:         my $stuff=join('',@lines);
  728:         if ($stuff=~/$custom/s) {
  729:             foreach my $f ('abstract','author','copyright',
  730:                            'creationdate','keywords','language',
  731:                            'lastrevisiondate','mime','notes',
  732:                            'owner','subject','title') {
  733:                 $stuff=~s/\n?\<$f[^\>]*\>.*?<\/$f[^\>]*\>\n?//s;
  734:             }
  735:             my $mfile=$metafile; 
  736:             my $docroot=$perlvar{'lonDocRoot'};
  737:             $mfile=~s/^$docroot//;
  738:             $mfile=~s/\.meta$//;
  739:             unless ($query) {
  740:                 my $q2="SELECT * FROM metadata WHERE url ".
  741:                     " LIKE BINARY '?'";
  742:                 my $sth = $dbh->prepare($q2);
  743:                 $sth->execute($mfile);
  744:                 my $aref=$sth->fetchall_arrayref;
  745:                 foreach my $a (@$aref) {
  746:                     my @b=map { &escape($_)} @$a;
  747:                     push @results,join(",", @b);
  748:                 }
  749:             }
  750:             # &logthis("found: $stuff");
  751:             $customresult.='&custom='.&escape($mfile).','.
  752:                 escape($stuff);
  753:         }
  754:     }
  755:     $result=join("&",@results) unless $query;
  756:     $result.=$customresult;
  757:     #
  758:     return $result;
  759: } # End of &do_sql_query
  760: 
  761: } # End of scoping curly braces for &process_file and &do_sql_query
  762: 
  763: sub portfolio_table_update { 
  764:     my ($query,$arg1,$arg2,$arg3) = @_;
  765:     my %tablenames = (
  766:                        'portfolio'   => 'portfolio_metadata',
  767:                        'access'      => 'portfolio_access',
  768:                        'addedfields' => 'portfolio_addedfields',
  769:                      );
  770:     my $result = 'ok';
  771:     my $tablechk = &check_table($query);
  772:     if ($tablechk == 0) {
  773:         my $request =
  774:    &LONCAPA::lonmetadata::create_metadata_storage($query,$query);
  775:         $dbh->do($request);
  776:         if ($dbh->err) {
  777:             &logthis("create $query".
  778:                      " ERROR: ".$dbh->errstr);
  779:                      $result = 'error';
  780:         }
  781:     }
  782:     if ($result eq 'ok') {
  783:         my ($uname,$udom,$group) = split(/:/,&unescape($arg1));
  784:         my $file_name = &unescape($arg2);
  785:         my $action = $arg3;
  786:         my $is_course = 0;
  787:         if ($group ne '') {
  788:             $is_course = 1;
  789:         }
  790:         my $urlstart = '/uploaded/'.$udom.'/'.$uname;
  791:         my $pathstart = &propath($udom,$uname).'/userfiles';
  792:         my ($fullpath,$url);
  793:         if ($is_course) {
  794:             $fullpath = $pathstart.'/groups/'.$group.'/portfolio'.
  795:                         $file_name;
  796:             $url = $urlstart.'/groups/'.$group.'/portfolio'.$file_name;
  797:         } else {
  798:             $fullpath = $pathstart.'/portfolio'.$file_name;
  799:             $url = $urlstart.'/portfolio'.$file_name;
  800:         }
  801:         if ($query eq 'portfolio_metadata') {
  802:             if ($action eq 'delete') {
  803:                 my %loghash = &LONCAPA::lonmetadata::process_portfolio_metadata($dbh,undef,\%tablenames,$url,$fullpath,$is_course,$udom,$uname,$group,'update');
  804:             } elsif (-e $fullpath.'.meta') {
  805:                 my %loghash = &LONCAPA::lonmetadata::process_portfolio_metadata($dbh,undef,\%tablenames,$url,$fullpath,$is_course,$udom,$uname,$group,'update');
  806:                 if (keys(%loghash) > 0) {
  807:                     &portfolio_logging(%loghash);
  808:                 }
  809:             }
  810:         } elsif ($query eq 'portfolio_access') {
  811:             my %access = &get_access_hash($uname,$udom,$group.$file_name);
  812:             my %loghash =
  813:      &LONCAPA::lonmetadata::process_portfolio_access_data($dbh,undef,
  814:          \%tablenames,$url,$fullpath,\%access,'update');
  815:             if (keys(%loghash) > 0) {
  816:                 &portfolio_logging(%loghash);
  817:             } else {
  818:                 my $available = 0;
  819:                 foreach my $key (keys(%access)) {
  820:                     my ($num,$scope,$end,$start) =
  821:                         ($key =~ /^([^:]+):([a-z]+)_(\d*)_?(\d*)$/);
  822:                     if ($scope eq 'public' || $scope eq 'guest') {
  823:                         $available = 1;
  824:                         last;
  825:                     }
  826:                 }
  827:                 if ($available) {
  828:                     # Retrieve current values
  829:                     my $condition = 'url='.$dbh->quote("$url");
  830:                     my ($error,$row) =
  831:     &LONCAPA::lonmetadata::lookup_metadata($dbh,$condition,undef,
  832:                                            'portfolio_metadata');
  833:                     if (!$error) {
  834:                         if (!(ref($row->[0]) eq 'ARRAY')) {  
  835:                             my %loghash =
  836:      &LONCAPA::lonmetadata::process_portfolio_metadata($dbh,undef,
  837:          \%tablenames,$url,$fullpath,$is_course,$udom,$uname,$group);
  838:                             if (keys(%loghash) > 0) {
  839:                                 &portfolio_logging(%loghash);
  840:                             }
  841:                         } 
  842:                     }
  843:                 }
  844:             }
  845:         }
  846:     }
  847:     return $result;
  848: }
  849: 
  850: sub get_access_hash {
  851:     my ($uname,$udom,$file) = @_;
  852:     my $hashref = &tie_user_hash($udom,$uname,'file_permissions',
  853:                                  &GDBM_READER());
  854:     my %curr_perms;
  855:     my %access; 
  856:     if ($hashref) {
  857:         while (my ($key,$value) = each(%$hashref)) {
  858:             $key = &unescape($key);
  859:             next if ($key =~ /^error: 2 /);
  860:             $curr_perms{$key}=&Apache::lonnet::thaw_unescape($value);
  861:         }
  862:         if (!&untie_user_hash($hashref)) {
  863:             &logthis("error: ".($!+0)." untie (GDBM) Failed");
  864:         }
  865:     } else {
  866:         &logthis("error: ".($!+0)." tie (GDBM) Failed");
  867:     }
  868:     if (keys(%curr_perms) > 0) {
  869:         if (ref($curr_perms{$file."\0".'accesscontrol'}) eq 'HASH') {
  870:             foreach my $acl (keys(%{$curr_perms{$file."\0".'accesscontrol'}})) {
  871:                 $access{$acl} = $curr_perms{$file."\0".$acl};
  872:             }
  873:         }
  874:     }
  875:     return %access;
  876: }
  877: 
  878: sub allusers_table_update {
  879:     my ($query,$uname,$udom,$userdata) = @_;
  880:     my %tablenames = (
  881:                        'allusers'   => 'allusers',
  882:                      );
  883:     my $result = 'ok';
  884:     my $tablechk = &check_table($query);
  885:     if ($tablechk == 0) {
  886:         my $request =
  887:    &LONCAPA::lonmetadata::create_metadata_storage($query,$query);
  888:         $dbh->do($request);
  889:         if ($dbh->err) {
  890:             &logthis("create $query".
  891:                      " ERROR: ".$dbh->errstr);
  892:                      $result = 'error';
  893:         }
  894:     }
  895:     if ($result eq 'ok') {
  896:         my %loghash = 
  897:             &LONCAPA::lonmetadata::process_allusers_data($dbh,undef,
  898:                 \%tablenames,$uname,$udom,$userdata,'update');
  899:         foreach my $key (keys(%loghash)) {
  900:             &logthis($loghash{$key});
  901:         }
  902:     }
  903:     return $result;
  904: }
  905: 
  906: ###########################################
  907: sub check_table {
  908:     my ($table_id) = @_;
  909:     my $sth=$dbh->prepare('SHOW TABLES');
  910:     $sth->execute();
  911:     my $aref = $sth->fetchall_arrayref;
  912:     $sth->finish();
  913:     if ($sth->err()) {
  914:         &logthis("fetchall_arrayref after SHOW TABLES".
  915:             " ERROR: ".$sth->errstr);
  916:         return undef;
  917:     }
  918:     my $result = 0;
  919:     foreach my $table (@{$aref}) {
  920:         if ($table->[0] eq $table_id) { 
  921:             $result = 1;
  922:             last;
  923:         }
  924:     }
  925:     return $result;
  926: }
  927: 
  928: ###########################################
  929: 
  930: sub portfolio_logging {
  931:     my (%portlog) = @_;
  932:     foreach my $key (keys(%portlog)) {
  933:         if (ref($portlog{$key}) eq 'HASH') {
  934:             foreach my $item (keys(%{$portlog{$key}})) {
  935:                 &logthis($portlog{$key}{$item});
  936:             }
  937:         }
  938:     }
  939: }
  940: 
  941: 
  942: ########################################################
  943: ########################################################
  944: 
  945: =pod
  946: 
  947: =item &logthis
  948: 
  949: Inputs: $message, the message to log
  950: 
  951: Returns: nothing
  952: 
  953: Writes $message to the logfile.
  954: 
  955: =cut
  956: 
  957: ########################################################
  958: ########################################################
  959: sub logthis {
  960:     my $message=shift;
  961:     my $execdir=$perlvar{'lonDaemons'};
  962:     open(my $fh,">>$execdir/logs/lonsql.log");
  963:     my $now=time;
  964:     my $local=localtime($now);
  965:     print $fh "$local ($$): $message\n";
  966: }
  967: 
  968: ########################################################
  969: ########################################################
  970: 
  971: =pod
  972: 
  973: =item &ishome
  974: 
  975: Determine if the current machine is the home server for a user.
  976: The determination is made by checking the filesystem for the users information.
  977: 
  978: Inputs: $author
  979: 
  980: Returns: 0 - this is not the authors home server, 1 - this is.
  981: 
  982: =cut
  983: 
  984: ########################################################
  985: ########################################################
  986: sub ishome {
  987:     my $author=shift;
  988:     $author=~s/\/home\/httpd\/html\/res\/([^\/]*)\/([^\/]*).*/$1\/$2/;
  989:     my ($udom,$uname)=split(/\//,$author);
  990:     my $proname=propath($udom,$uname);
  991:     if (-e $proname) {
  992: 	return 1;
  993:     } else {
  994:         return 0;
  995:     }
  996: }
  997: 
  998: ########################################################
  999: ########################################################
 1000: 
 1001: =pod
 1002: 
 1003: =item &courselog
 1004: 
 1005: Inputs: $path, $command
 1006: 
 1007: Returns: unescaped string of values.
 1008: 
 1009: =cut
 1010: 
 1011: ########################################################
 1012: ########################################################
 1013: sub courselog {
 1014:     my ($path,$command)=@_;
 1015:     my %filters=();
 1016:     foreach (split(/\:/,&unescape($command))) {
 1017: 	my ($name,$value)=split(/\=/,$_);
 1018:         $filters{$name}=$value;
 1019:     }
 1020:     my @results=();
 1021:     open(IN,$path.'/activity.log') or return ('file_error');
 1022:     while (my $line=<IN>) {
 1023:         chomp($line);
 1024:         my ($timestamp,$host,$log)=split(/\:/,$line);
 1025: #
 1026: # $log has the actual log entries; currently still escaped, and
 1027: # %26(timestamp)%3a(url)%3a(user)%3a(domain)
 1028: # then additionally
 1029: # %3aPOST%3a(name)%3d(value)%3a(name)%3d(value)
 1030: # or
 1031: # %3aCSTORE%3a(name)%3d(value)%26(name)%3d(value)
 1032: #
 1033: # get delimiter between timestamped entries to be &&&
 1034:         $log=~s/\%26(\d+)\%3a/\&\&\&$1\%3a/g;
 1035: # now go over all log entries 
 1036:         foreach (split(/\&\&\&/,&unescape($log))) {
 1037: 	    my ($time,$res,$uname,$udom,$action,@values)=split(/\:/,$_);
 1038:             my $values=&unescape(join(':',@values));
 1039:             $values=~s/\&/\:/g;
 1040:             $res=&unescape($res);
 1041:             my $include=1;
 1042:             if (($filters{'username'}) && ($uname ne $filters{'username'})) 
 1043:                                                                { $include=0; }
 1044:             if (($filters{'domain'}) && ($udom ne $filters{'domain'})) 
 1045:                                                                { $include=0; }
 1046:             if (($filters{'url'}) && ($res!~/$filters{'url'}/)) 
 1047:                                                                { $include=0; }
 1048:             if (($filters{'start'}) && ($time<$filters{'start'})) 
 1049:                                                                { $include=0; }
 1050:             if (($filters{'end'}) && ($time>$filters{'end'})) 
 1051:                                                                { $include=0; }
 1052:             if (($filters{'action'} eq 'view') && ($action)) 
 1053:                                                                { $include=0; }
 1054:             if (($filters{'action'} eq 'submit') && ($action ne 'POST')) 
 1055:                                                                { $include=0; }
 1056:             if (($filters{'action'} eq 'grade') && ($action ne 'CSTORE')) 
 1057:                                                                { $include=0; }
 1058:             if ($include) {
 1059: 	       push(@results,($time<1000000000?'0':'').$time.':'.$res.':'.
 1060:                                             $uname.':'.$udom.':'.
 1061:                                             $action.':'.$values);
 1062:             }
 1063:        }
 1064:     }
 1065:     close IN;
 1066:     return join('&',sort(@results));
 1067: }
 1068: 
 1069: ########################################################
 1070: ########################################################
 1071: 
 1072: =pod
 1073: 
 1074: =item &userlog
 1075: 
 1076: Inputs: $path, $command
 1077: 
 1078: Returns: unescaped string of values.
 1079: 
 1080: =cut
 1081: 
 1082: ########################################################
 1083: ########################################################
 1084: sub userlog {
 1085:     my ($path,$command)=@_;
 1086:     my %filters=();
 1087:     foreach (split(/\:/,&unescape($command))) {
 1088: 	my ($name,$value)=split(/\=/,$_);
 1089:         $filters{$name}=$value;
 1090:     }
 1091:     my @results=();
 1092:     open(IN,$path.'/activity.log') or return ('file_error');
 1093:     while (my $line=<IN>) {
 1094:         chomp($line);
 1095:         my ($timestamp,$host,$log)=split(/\:/,$line);
 1096:         $log=&unescape($log);
 1097:         my $include=1;
 1098:         if (($filters{'start'}) && ($timestamp<$filters{'start'})) 
 1099:                                                              { $include=0; }
 1100:         if (($filters{'end'}) && ($timestamp>$filters{'end'})) 
 1101:                                                              { $include=0; }
 1102:         if (($filters{'action'} eq 'Role') && ($log !~/^Role/))
 1103:                                                              { $include=0; }
 1104:         if (($filters{'action'} eq 'log') && ($log!~/^Log/)) { $include=0; }
 1105:         if (($filters{'action'} eq 'check') && ($log!~/^Check/)) 
 1106:                                                              { $include=0; }
 1107:         if ($include) {
 1108: 	   push(@results,$timestamp.':'.$host.':'.&escape($log));
 1109:         }
 1110:     }
 1111:     close IN;
 1112:     return join('&',sort(@results));
 1113: }
 1114: 
 1115: ########################################################
 1116: ########################################################
 1117: 
 1118: =pod
 1119: 
 1120: =item Functions required for forking
 1121: 
 1122: =over 4
 1123: 
 1124: =item REAPER
 1125: 
 1126: REAPER takes care of dead children.
 1127: 
 1128: =item HUNTSMAN
 1129: 
 1130: Signal handler for SIGINT.
 1131: 
 1132: =item HUPSMAN
 1133: 
 1134: Signal handler for SIGHUP
 1135: 
 1136: =item DISCONNECT
 1137: 
 1138: Disconnects from database.
 1139: 
 1140: =back
 1141: 
 1142: =cut
 1143: 
 1144: ########################################################
 1145: ########################################################
 1146: sub REAPER {                   # takes care of dead children
 1147:     $SIG{CHLD} = \&REAPER;
 1148:     my $pid = wait;
 1149:     $children --;
 1150:     &logthis("Child $pid died");
 1151:     delete $children{$pid};
 1152: }
 1153: 
 1154: sub HUNTSMAN {                      # signal handler for SIGINT
 1155:     local($SIG{CHLD}) = 'IGNORE';   # we're going to kill our children
 1156:     kill 'INT' => keys %children;
 1157:     my $execdir=$perlvar{'lonDaemons'};
 1158:     unlink("$execdir/logs/lonsql.pid");
 1159:     &logthis("<font color='red'>CRITICAL: Shutting down</font>");
 1160:     $unixsock = "mysqlsock";
 1161:     my $port="$perlvar{'lonSockDir'}/$unixsock";
 1162:     unlink($port);
 1163:     exit;                           # clean up with dignity
 1164: }
 1165: 
 1166: sub HUPSMAN {                      # signal handler for SIGHUP
 1167:     local($SIG{CHLD}) = 'IGNORE';  # we're going to kill our children
 1168:     kill 'INT' => keys %children;
 1169:     close($server);                # free up socket
 1170:     &logthis("<font color='red'>CRITICAL: Restarting</font>");
 1171:     my $execdir=$perlvar{'lonDaemons'};
 1172:     $unixsock = "mysqlsock";
 1173:     my $port="$perlvar{'lonSockDir'}/$unixsock";
 1174:     unlink($port);
 1175:     exec("$execdir/lonsql");         # here we go again
 1176: }
 1177: 
 1178: sub DISCONNECT {
 1179:     $dbh->disconnect or 
 1180:     &logthis("<font color='blue'>WARNING: Couldn't disconnect from database ".
 1181:              " $DBI::errstr : $@</font>");
 1182:     exit;
 1183: }
 1184: 
 1185: 
 1186: =pod
 1187: 
 1188: =back
 1189: 
 1190: =cut

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