File:  [LON-CAPA] / loncom / lonsql
Revision 1.81: download - view: text, annotated - select for diffs
Thu Apr 12 00:00:55 2007 UTC (17 years ago) by albertel
Branches: MAIN
CVS tags: version_2_4_X, version_2_4_2, version_2_4_1, version_2_4_0, version_2_3_99_0, HEAD
- switch to using lonnet.pm
- eliminate unneeded code
- remove unused packages

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

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