Annotation of loncom/lonsql, revision 1.48

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.48    ! www         6: # $Id: lonsql,v 1.47 2002/06/18 19:39:13 www Exp $
1.41      harris41    7: #
                      8: # Copyright Michigan State University Board of Trustees
                      9: #
                     10: # This file is part of the LearningOnline Network with CAPA (LON-CAPA).
                     11: #
                     12: # LON-CAPA is free software; you can redistribute it and/or modify
                     13: # it under the terms of the GNU General Public License as published by
                     14: # the Free Software Foundation; either version 2 of the License, or
                     15: # (at your option) any later version.
                     16: #
                     17: # LON-CAPA is distributed in the hope that it will be useful,
                     18: # but WITHOUT ANY WARRANTY; without even the implied warranty of
                     19: # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
                     20: # GNU General Public License for more details.
                     21: #
                     22: # You should have received a copy of the GNU General Public License
                     23: # along with LON-CAPA; if not, write to the Free Software
                     24: # Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA
                     25: #
                     26: # /home/httpd/html/adm/gpl.txt
                     27: #
                     28: # http://www.lon-capa.org/
                     29: #
1.39      harris41   30: # YEAR=2000
1.2       harris41   31: # lonsql-based on the preforker:harsha jagasia:date:5/10/00
1.4       www        32: # 7/25 Gerd Kortemeyer
1.6       harris41   33: # many different dates Scott Harrison
1.39      harris41   34: # YEAR=2001
                     35: # many different dates Scott Harrison
1.7       harris41   36: # 03/22/2001 Scott Harrison
1.36      www        37: # 8/30 Gerd Kortemeyer
1.41      harris41   38: # 10/17,11/28,11/29,12/20 Scott Harrison
1.42      harris41   39: # YEAR=2001
                     40: # 5/11 Scott Harrison
1.39      harris41   41: #
                     42: ###
                     43: 
1.40      harris41   44: ###############################################################################
                     45: ##                                                                           ##
                     46: ## ORGANIZATION OF THIS PERL SCRIPT                                          ##
                     47: ## 1. Modules used                                                           ##
                     48: ## 2. Enable find subroutine                                                 ##
1.43      matthew    49: ## 3. Read httpd config files and get variables                              ##
1.40      harris41   50: ## 4. Make sure that database can be accessed                                ##
                     51: ## 5. Make sure this process is running from user=www                        ##
                     52: ## 6. Check if other instance is running                                     ##
                     53: ## 7. POD (plain old documentation, CPAN style)                              ##
                     54: ##                                                                           ##
                     55: ###############################################################################
1.36      www        56: 
1.42      harris41   57: use lib '/home/httpd/lib/perl/';
                     58: use LONCAPA::Configuration;
                     59: 
1.2       harris41   60: use IO::Socket;
                     61: use Symbol;
1.1       harris41   62: use POSIX;
                     63: use IO::Select;
                     64: use IO::File;
                     65: use Socket;
                     66: use Fcntl;
                     67: use Tie::RefHash;
                     68: use DBI;
                     69: 
1.9       harris41   70: my @metalist;
                     71: # ----------------- Code to enable 'find' subroutine listing of the .meta files
                     72: require "find.pl";
                     73: sub wanted {
                     74:     (($dev,$ino,$mode,$nlink,$uid,$gid) = lstat($_)) &&
                     75:     -f _ &&
1.34      harris41   76:     /^.*\.meta$/ && !/^.+\.\d+\.[^\.]+\.meta$/ &&
1.9       harris41   77:     push(@metalist,"$dir/$_");
                     78: }
                     79: 
1.1       harris41   80: $childmaxattempts=10;
1.2       harris41   81: $run =0;#running counter to generate the query-id
                     82: 
1.43      matthew    83: # -------------------------------- Read loncapa_apache.conf and loncapa.conf
                     84: my $perlvarref=LONCAPA::Configuration::read_conf('loncapa_apache.conf',
                     85:                                                  'loncapa.conf');
1.42      harris41   86: my %perlvar=%{$perlvarref};
1.4       www        87: 
1.31      harris41   88: # ------------------------------------- Make sure that database can be accessed
                     89: {
                     90:     my $dbh;
                     91:     unless (
                     92: 	    $dbh = DBI->connect("DBI:mysql:loncapa","www",$perlvar{'lonSqlAccess'},{ RaiseError =>0,PrintError=>0})
                     93: 	    ) { 
                     94: 	print "Cannot connect to database!\n";
1.38      harris41   95: 	$emailto="$perlvar{'lonAdmEMail'},$perlvar{'lonSysEMail'}";
                     96: 	$subj="LON: $perlvar{'lonHostID'} Cannot connect to database!";
                     97: 	system("echo 'Cannot connect to MySQL database!' |\
                     98:  mailto $emailto -s '$subj' > /dev/null");
                     99: 	exit 1;
1.31      harris41  100:     }
                    101:     else {
                    102: 	$dbh->disconnect;
                    103:     }
                    104: }
                    105: 
1.4       www       106: # --------------------------------------------- Check if other instance running
                    107: 
                    108: my $pidfile="$perlvar{'lonDaemons'}/logs/lonsql.pid";
                    109: 
                    110: if (-e $pidfile) {
                    111:    my $lfh=IO::File->new("$pidfile");
                    112:    my $pide=<$lfh>;
                    113:    chomp($pide);
                    114:    if (kill 0 => $pide) { die "already running"; }
                    115: }
1.1       harris41  116: 
                    117: # ------------------------------------------------------------- Read hosts file
1.2       harris41  118: $PREFORK=4; # number of children to maintain, at least four spare
1.1       harris41  119: 
                    120: open (CONFIG,"$perlvar{'lonTabDir'}/hosts.tab") || die "Can't read host file";
                    121: 
                    122: while ($configline=<CONFIG>) {
                    123:     my ($id,$domain,$role,$name,$ip)=split(/:/,$configline);
                    124:     chomp($ip);
                    125: 
1.2       harris41  126:     $hostip{$ip}=$id;
1.1       harris41  127:     if ($id eq $perlvar{'lonHostID'}) { $thisserver=$name; }
                    128: 
1.2       harris41  129:     $PREFORK++;
1.1       harris41  130: }
                    131: close(CONFIG);
1.36      www       132: 
                    133: $PREFORK=int($PREFORK/4);
1.1       harris41  134: 
1.2       harris41  135: $unixsock = "mysqlsock";
                    136: my $localfile="$perlvar{'lonSockDir'}/$unixsock";
                    137: my $server;
                    138: unlink ($localfile);
                    139: unless ($server=IO::Socket::UNIX->new(Local    =>"$localfile",
                    140: 				  Type    => SOCK_STREAM,
                    141: 				  Listen => 10))
                    142: {
                    143:     print "in socket error:$@\n";
                    144: }
1.1       harris41  145: 
                    146: # -------------------------------------------------------- Routines for forking
                    147: # global variables
1.2       harris41  148: $MAX_CLIENTS_PER_CHILD  = 5;        # number of clients each child should process
1.1       harris41  149: %children               = ();       # keys are current child process IDs
1.2       harris41  150: $children               = 0;        # current number of children
1.1       harris41  151: 
                    152: sub REAPER {                        # takes care of dead children
                    153:     $SIG{CHLD} = \&REAPER;
                    154:     my $pid = wait;
1.2       harris41  155:     $children --;
                    156:     &logthis("Child $pid died");
1.1       harris41  157:     delete $children{$pid};
                    158: }
                    159: 
                    160: sub HUNTSMAN {                      # signal handler for SIGINT
                    161:     local($SIG{CHLD}) = 'IGNORE';   # we're going to kill our children
                    162:     kill 'INT' => keys %children;
                    163:     my $execdir=$perlvar{'lonDaemons'};
                    164:     unlink("$execdir/logs/lonsql.pid");
                    165:     &logthis("<font color=red>CRITICAL: Shutting down</font>");
1.2       harris41  166:     $unixsock = "mysqlsock";
                    167:     my $port="$perlvar{'lonSockDir'}/$unixsock";
                    168:     unlink(port);
1.1       harris41  169:     exit;                           # clean up with dignity
                    170: }
                    171: 
                    172: sub HUPSMAN {                      # signal handler for SIGHUP
                    173:     local($SIG{CHLD}) = 'IGNORE';  # we're going to kill our children
                    174:     kill 'INT' => keys %children;
                    175:     close($server);                # free up socket
                    176:     &logthis("<font color=red>CRITICAL: Restarting</font>");
                    177:     my $execdir=$perlvar{'lonDaemons'};
1.2       harris41  178:     $unixsock = "mysqlsock";
                    179:     my $port="$perlvar{'lonSockDir'}/$unixsock";
                    180:     unlink(port);
1.1       harris41  181:     exec("$execdir/lonsql");         # here we go again
                    182: }
                    183: 
                    184: sub logthis {
                    185:     my $message=shift;
                    186:     my $execdir=$perlvar{'lonDaemons'};
1.2       harris41  187:     my $fh=IO::File->new(">>$execdir/logs/lonsqlfinal.log");
1.1       harris41  188:     my $now=time;
                    189:     my $local=localtime($now);
                    190:     print $fh "$local ($$): $message\n";
                    191: }
1.45      www       192: 
                    193: # ------------------------------------------------------------------ Course log
                    194: 
                    195: sub courselog {
                    196:     my ($path,$command)=@_;
1.46      www       197:     my %filters=();
1.47      www       198:     foreach (split(/\:/,&unescape($command))) {
1.46      www       199: 	my ($name,$value)=split(/\=/,$_);
                    200:         $filters{$name}=$value;
                    201:     }
                    202:     my @results=();
                    203:     open(IN,$path.'/activity.log') or return ('file_error');
                    204:     while ($line=<IN>) {
                    205:         chomp($line);
                    206:         my ($timestamp,$host,$log)=split(/\:/,$line);
                    207:         foreach (split(/\&/,&unescape($log))) {
1.47      www       208: 	    my ($time,$res,$uname,$udom,$action,$values)=split(/\:/,$_);
1.48    ! www       209:             $res=&unescape($res);
        !           210:             $values=&unescape($values);
1.46      www       211:             my $include=1;
1.47      www       212:             if (($filters{'username'}) && ($uname ne $filters{'username'})) 
                    213:                                                                { $include=0; }
                    214:             if (($filters{'domain'}) && ($udom ne $filters{'domain'})) 
                    215:                                                                { $include=0; }
                    216:             if (($filters{'url'}) && ($res!~/$filters{'url'}/)) 
                    217:                                                                { $include=0; }
                    218:             if (($filters{'start'}) && ($time<$filters{'start'})) 
                    219:                                                                { $include=0; }
                    220:             if (($filters{'end'}) && ($time>$filters{'end'})) 
                    221:                                                                { $include=0; }
                    222:             if (($filters{'action'} eq 'view') && ($action)) 
                    223:                                                                { $include=0; }
                    224:             if (($filters{'action'} eq 'submit') && ($action ne 'POST')) 
                    225:                                                                { $include=0; }
                    226:             if (($filters{'action'} eq 'grade') && ($action ne 'CSTORE')) 
                    227:                                                                { $include=0; }
                    228:             if ($include) {
                    229: 	       push(@results,$time.':'.$res.':'.$uname.':'.$udom.':'.
                    230:                                             $action.':'.$values);
                    231:             }
                    232:        }
1.46      www       233:     }
                    234:     close IN;
                    235:     return join('&',sort(@results));
1.45      www       236: }
                    237: 
                    238: # -------------------------------------------------------------------- User log
                    239: 
                    240: sub userlog {
                    241:     my ($path,$command)=@_;
1.46      www       242:     my %filters=();
1.47      www       243:     foreach (split(/\:/,&unescape($command))) {
1.46      www       244: 	my ($name,$value)=split(/\=/,$_);
                    245:         $filters{$name}=$value;
                    246:     }
                    247:     my @results=();
                    248:     open(IN,$path.'/activity.log') or return ('file_error');
                    249:     while ($line=<IN>) {
                    250:         chomp($line);
                    251:         my ($timestamp,$host,$log)=split(/\:/,$line);
                    252:         $log=&unescape($log);
                    253:         my $include=1;
                    254:         if (($filters{'action'} eq 'log') && ($log!~/^Log/)) { $include=0; }
                    255:         if ($include) {
                    256: 	   push(@results,$timestamp.':'.$log);
                    257:         }
                    258:     }
                    259:     close IN;
                    260:     return join('&',sort(@results));
1.45      www       261: }
                    262: 
                    263: 
1.1       harris41  264: # ---------------------------------------------------- Fork once and dissociate
                    265: $fpid=fork;
                    266: exit if $fpid;
                    267: die "Couldn't fork: $!" unless defined ($fpid);
                    268: 
                    269: POSIX::setsid() or die "Can't start new session: $!";
                    270: 
                    271: # ------------------------------------------------------- Write our PID on disk
                    272: 
                    273: $execdir=$perlvar{'lonDaemons'};
                    274: open (PIDSAVE,">$execdir/logs/lonsql.pid");
                    275: print PIDSAVE "$$\n";
                    276: close(PIDSAVE);
                    277: &logthis("<font color=red>CRITICAL: ---------- Starting ----------</font>");
                    278: 
                    279: # ----------------------------- Ignore signals generated during initial startup
                    280: $SIG{HUP}=$SIG{USR1}='IGNORE';
1.2       harris41  281: # ------------------------------------------------------- Now we are on our own    
                    282: # Fork off our children.
                    283: for (1 .. $PREFORK) {
                    284:     make_new_child();
1.1       harris41  285: }
                    286: 
1.2       harris41  287: # Install signal handlers.
1.1       harris41  288: $SIG{CHLD} = \&REAPER;
                    289: $SIG{INT}  = $SIG{TERM} = \&HUNTSMAN;
                    290: $SIG{HUP}  = \&HUPSMAN;
                    291: 
                    292: # And maintain the population.
                    293: while (1) {
                    294:     sleep;                          # wait for a signal (i.e., child's death)
1.2       harris41  295:     for ($i = $children; $i < $PREFORK; $i++) {
                    296:         make_new_child();           # top up the child pool
1.1       harris41  297:     }
                    298: }
                    299: 
1.2       harris41  300: 
1.1       harris41  301: sub make_new_child {
                    302:     my $pid;
                    303:     my $sigset;
1.2       harris41  304:     
1.1       harris41  305:     # block signal for fork
                    306:     $sigset = POSIX::SigSet->new(SIGINT);
                    307:     sigprocmask(SIG_BLOCK, $sigset)
                    308:         or die "Can't block SIGINT for fork: $!\n";
                    309:     
1.2       harris41  310:     die "fork: $!" unless defined ($pid = fork);
                    311:     
1.1       harris41  312:     if ($pid) {
                    313:         # Parent records the child's birth and returns.
                    314:         sigprocmask(SIG_UNBLOCK, $sigset)
                    315:             or die "Can't unblock SIGINT for fork: $!\n";
                    316:         $children{$pid} = 1;
                    317:         $children++;
                    318:         return;
                    319:     } else {
1.2       harris41  320:         # Child can *not* return from this subroutine.
1.1       harris41  321:         $SIG{INT} = 'DEFAULT';      # make SIGINT kill us as it did before
                    322:     
                    323:         # unblock signals
                    324:         sigprocmask(SIG_UNBLOCK, $sigset)
                    325:             or die "Can't unblock SIGINT for fork: $!\n";
1.2       harris41  326: 	
                    327: 	
                    328:         #open database handle
                    329: 	# making dbh global to avoid garbage collector
1.1       harris41  330: 	unless (
1.31      harris41  331: 		$dbh = DBI->connect("DBI:mysql:loncapa","www",$perlvar{'lonSqlAccess'},{ RaiseError =>0,PrintError=>0})
1.1       harris41  332: 		) { 
1.30      harris41  333:   	            sleep(10+int(rand(20)));
1.1       harris41  334: 		    &logthis("<font color=blue>WARNING: Couldn't connect to database  ($st secs): $@</font>");
1.2       harris41  335: 		    print "database handle error\n";
                    336: 		    exit;
                    337: 
                    338: 	  };
                    339: 	# make sure that a database disconnection occurs with ending kill signals
                    340: 	$SIG{TERM}=$SIG{INT}=$SIG{QUIT}=$SIG{__DIE__}=\&DISCONNECT;
                    341: 
1.1       harris41  342:         # handle connections until we've reached $MAX_CLIENTS_PER_CHILD
                    343:         for ($i=0; $i < $MAX_CLIENTS_PER_CHILD; $i++) {
                    344:             $client = $server->accept()     or last;
1.2       harris41  345:             
                    346:             # do something with the connection
1.1       harris41  347: 	    $run = $run+1;
1.2       harris41  348: 	    my $userinput = <$client>;
                    349: 	    chomp($userinput);
                    350: 	    	    
1.45      www       351: 	    my ($conserver,$query,
                    352: 		$arg1,$arg2,$arg3)=split(/&/,$userinput);
                    353: 	    my $query=unescape($query);
1.2       harris41  354: 
                    355:             #send query id which is pid_unixdatetime_runningcounter
                    356: 	    $queryid = $thisserver;
                    357: 	    $queryid .="_".($$)."_";
                    358: 	    $queryid .= time."_";
                    359: 	    $queryid .= $run;
                    360: 	    print $client "$queryid\n";
                    361: 	    
1.47      www       362: 	    &logthis("QUERY: $query - $arg1 - $arg2 - $arg3");
1.25      harris41  363: 	    sleep 1;
1.44      www       364: 
1.45      www       365:             my $result='';
                    366: 
1.44      www       367: # ---------- At this point, query is received, query-ID assigned and sent back 
                    368: # $query eq 'logquery' will mean that this is a query against log-files
                    369: 
1.45      www       370: 
                    371: 	   if (($query eq 'userlog') || ($query eq 'courselog')) {
                    372: # ----------------------------------------------------- beginning of log query
                    373: #
                    374: # this goes against a user's log file
                    375: #
                    376: 	       my $udom=&unescape($arg1);
                    377: 	       my $uname=&unescape($arg2);
                    378:                my $command=&unescape($arg3);
                    379:                my $path=&propath($udom,$uname);
                    380:                if (-e "$path/activity.log") {
                    381: 		   if ($query eq 'userlog') {
                    382:                        $result=&userlog($path,$command);
                    383:                    } else {
                    384:                        $result=&courselog($path,$command);
                    385:                    }
                    386:                } else {
                    387: 		   &logthis('Unable to do log query: '.$uname.'@'.$udom);
                    388: 	           $result='no_such_file';
                    389: 	       }
                    390: # ------------------------------------------------------------ end of log query
                    391:           } else {
1.44      www       392: # -------------------------------------------------------- This is an sql query
1.45      www       393: 	    my $custom=unescape($arg1);
                    394: 	    my $customshow=unescape($arg2);
1.2       harris41  395:             #prepare and execute the query
1.3       harris41  396: 	    my $sth = $dbh->prepare($query);
1.45      www       397: 
1.20      harris41  398: 	    my @files;
1.24      harris41  399: 	    my $subsetflag=0;
1.26      harris41  400: 	    if ($query) {
                    401: 		unless ($sth->execute())
                    402: 		{
                    403: 		    &logthis("<font color=blue>WARNING: Could not retrieve from database: $@</font>");
                    404: 		    $result="";
                    405: 		}
                    406: 		else {
                    407: 		    my $r1=$sth->fetchall_arrayref;
                    408: 		    my @r2;
1.41      harris41  409: 		    foreach (@$r1) {my $a=$_; 
1.26      harris41  410: 			 my @b=map {escape($_)} @$a;
                    411: 			 push @files,@{$a}[3];
                    412: 			 push @r2,join(",", @b)
1.41      harris41  413: 			 }
1.26      harris41  414: 		    $result=join("&",@r2);
                    415: 		}
1.3       harris41  416: 	    }
1.7       harris41  417: 	    # do custom metadata searching here and build into result
1.28      harris41  418: 	    if ($custom or $customshow) {
1.9       harris41  419: 		&logthis("am going to do custom query for $custom");
1.26      harris41  420: 		if ($query) {
1.23      harris41  421: 		    @metalist=map {$perlvar{'lonDocRoot'}.$_.'.meta'} @files;
1.20      harris41  422: 		}
                    423: 		else {
                    424: 		    @metalist=(); pop @metalist;
1.34      harris41  425: 		    opendir(RESOURCES,"$perlvar{'lonDocRoot'}/res/$perlvar{'lonDefDomain'}");
                    426: 		    my @homeusers=grep
                    427: 		          {&ishome("$perlvar{'lonDocRoot'}/res/$perlvar{'lonDefDomain'}/$_")}
                    428: 		          grep {!/^\.\.?$/} readdir(RESOURCES);
                    429: 		    closedir RESOURCES;
                    430: 		    foreach my $user (@homeusers) {
                    431: 			&find("$perlvar{'lonDocRoot'}/res/$perlvar{'lonDefDomain'}/$user");
                    432: 		    }
1.20      harris41  433: 		}
1.23      harris41  434: #		&logthis("FILELIST:" . join(":::",@metalist));
1.10      harris41  435: 		# if file is indicated in sql database and
                    436: 		# not part of sql-relevant query, do not pattern match.
                    437: 		# if file is not in sql database, output error.
                    438: 		# if file is indicated in sql database and is
                    439: 		# part of query result list, then do the pattern match.
1.12      harris41  440: 		my $customresult='';
1.26      harris41  441: 		my @r2;
1.11      harris41  442: 		foreach my $m (@metalist) {
                    443: 		    my $fh=IO::File->new($m);
                    444: 		    my @lines=<$fh>;
                    445: 		    my $stuff=join('',@lines);
                    446: 		    if ($stuff=~/$custom/s) {
1.18      harris41  447: 			foreach my $f ('abstract','author','copyright',
                    448: 				       'creationdate','keywords','language',
                    449: 				       'lastrevisiondate','mime','notes',
                    450: 				       'owner','subject','title') {
1.37      harris41  451: 			    $stuff=~s/\n?\<$f[^\>]*\>.*?<\/$f[^\>]*\>\n?//s;
1.18      harris41  452: 			}
1.19      harris41  453: 			my $m2=$m; my $docroot=$perlvar{'lonDocRoot'};
1.26      harris41  454: 			$m2=~s/^$docroot//;
                    455: 			$m2=~s/\.meta$//;
                    456: 			unless ($query) {
1.35      harris41  457: 			    my $q2="select * from metadata where url like binary '$m2'";
1.27      harris41  458: 			    my $sth = $dbh->prepare($q2);
1.26      harris41  459: 			    $sth->execute();
                    460: 			    my $r1=$sth->fetchall_arrayref;
1.41      harris41  461: 			    foreach (@$r1) {my $a=$_; 
1.26      harris41  462: 				 my @b=map {escape($_)} @$a;
                    463: 				 push @files,@{$a}[3];
                    464: 				 push @r2,join(",", @b)
1.41      harris41  465: 				 }
1.26      harris41  466: 			}
1.20      harris41  467: #			&logthis("found: $stuff");
1.19      harris41  468: 			$customresult.='&custom='.escape($m2).','.escape($stuff);
1.11      harris41  469: 		    }
                    470: 		}
1.26      harris41  471: 		$result=join("&",@r2) unless $query;
1.17      harris41  472: 		$result.=$customresult;
1.9       harris41  473: 	    }
1.44      www       474: # ------------------------------------------------------------ end of sql query
1.46      www       475: 	   }
                    476: 
                    477:             # result does need to be escaped
                    478: 
                    479:             $result=&escape($result);
                    480: 
1.44      www       481: 	    # reply with result, append \n unless already there
1.45      www       482: 
1.44      www       483: 	    $result.="\n" unless ($result=~/\n$/);
1.17      harris41  484:             &reply("queryreply:$queryid:$result",$conserver);
1.2       harris41  485: 
1.1       harris41  486:         }
                    487:     
                    488:         # tidy up gracefully and finish
1.2       harris41  489: 	
                    490:         #close the database handle
                    491: 	$dbh->disconnect
                    492: 	   or &logthis("<font color=blue>WARNING: Couldn't disconnect from database  $DBI::errstr ($st secs): $@</font>");
1.1       harris41  493:     
                    494:         # this exit is VERY important, otherwise the child will become
                    495:         # a producer of more and more children, forking yourself into
                    496:         # process death.
                    497:         exit;
                    498:     }
1.2       harris41  499: }
1.1       harris41  500: 
1.2       harris41  501: sub DISCONNECT {
                    502:     $dbh->disconnect or 
                    503:     &logthis("<font color=blue>WARNING: Couldn't disconnect from database  $DBI::errstr ($st secs): $@</font>");
                    504:     exit;
                    505: }
1.1       harris41  506: 
1.2       harris41  507: # -------------------------------------------------- Non-critical communication
1.1       harris41  508: 
1.2       harris41  509: sub subreply {
                    510:     my ($cmd,$server)=@_;
                    511:     my $peerfile="$perlvar{'lonSockDir'}/$server";
                    512:     my $sclient=IO::Socket::UNIX->new(Peer    =>"$peerfile",
                    513:                                       Type    => SOCK_STREAM,
                    514:                                       Timeout => 10)
                    515:        or return "con_lost";
                    516:     print $sclient "$cmd\n";
                    517:     my $answer=<$sclient>;
                    518:     chomp($answer);
                    519:     if (!$answer) { $answer="con_lost"; }
                    520:     return $answer;
                    521: }
1.1       harris41  522: 
1.2       harris41  523: sub reply {
                    524:   my ($cmd,$server)=@_;
                    525:   my $answer;
                    526:   if ($server ne $perlvar{'lonHostID'}) { 
                    527:     $answer=subreply($cmd,$server);
                    528:     if ($answer eq 'con_lost') {
                    529: 	$answer=subreply("ping",$server);
                    530:         $answer=subreply($cmd,$server);
                    531:     }
                    532:   } else {
                    533:     $answer='self_reply';
1.33      harris41  534:     $answer=subreply($cmd,$server);
1.2       harris41  535:   } 
                    536:   return $answer;
                    537: }
1.1       harris41  538: 
1.3       harris41  539: # -------------------------------------------------------- Escape Special Chars
                    540: 
                    541: sub escape {
                    542:     my $str=shift;
                    543:     $str =~ s/(\W)/"%".unpack('H2',$1)/eg;
                    544:     return $str;
                    545: }
                    546: 
                    547: # ----------------------------------------------------- Un-Escape Special Chars
                    548: 
                    549: sub unescape {
                    550:     my $str=shift;
                    551:     $str =~ s/%([a-fA-F0-9][a-fA-F0-9])/pack("C",hex($1))/eg;
                    552:     return $str;
                    553: }
1.34      harris41  554: 
                    555: # --------------------------------------- Is this the home server of an author?
                    556: # (copied from lond, modification of the return value)
                    557: sub ishome {
                    558:     my $author=shift;
                    559:     $author=~s/\/home\/httpd\/html\/res\/([^\/]*)\/([^\/]*).*/$1\/$2/;
                    560:     my ($udom,$uname)=split(/\//,$author);
                    561:     my $proname=propath($udom,$uname);
                    562:     if (-e $proname) {
                    563: 	return 1;
                    564:     } else {
                    565:         return 0;
                    566:     }
                    567: }
                    568: 
                    569: # -------------------------------------------- Return path to profile directory
                    570: # (copied from lond)
                    571: sub propath {
                    572:     my ($udom,$uname)=@_;
                    573:     $udom=~s/\W//g;
                    574:     $uname=~s/\W//g;
                    575:     my $subdir=$uname.'__';
                    576:     $subdir =~ s/(.)(.)(.).*/$1\/$2\/$3/;
                    577:     my $proname="$perlvar{'lonUsersDir'}/$udom/$subdir/$uname";
                    578:     return $proname;
                    579: } 
1.40      harris41  580: 
                    581: # ----------------------------------- POD (plain old documentation, CPAN style)
                    582: 
                    583: =head1 NAME
                    584: 
                    585: lonsql - LON TCP-MySQL-Server Daemon for handling database requests.
                    586: 
                    587: =head1 SYNOPSIS
                    588: 
                    589: This script should be run as user=www.  The following is an example invocation
                    590: from the loncron script.  Note that a lonsql.pid file contains the pid of
                    591: the parent process.
                    592: 
                    593:     if (-e $lonsqlfile) {
                    594: 	my $lfh=IO::File->new("$lonsqlfile");
                    595: 	my $lonsqlpid=<$lfh>;
                    596: 	chomp($lonsqlpid);
                    597: 	if (kill 0 => $lonsqlpid) {
                    598: 	    print $fh "<h3>lonsql at pid $lonsqlpid responding</h3>";
                    599: 	    $restartflag=0;
                    600: 	} else {
                    601: 	    $errors++; $errors++;
                    602: 	    print $fh "<h3>lonsql at pid $lonsqlpid not responding</h3>";
                    603: 		$restartflag=1;
                    604: 	print $fh 
                    605: 	    "<h3>Decided to clean up stale .pid file and restart lonsql</h3>";
                    606: 	}
                    607:     }
                    608:     if ($restartflag==1) {
                    609: 	$errors++;
                    610: 	         print $fh '<br><font color="red">Killall lonsql: '.
                    611:                     system('killall lonsql').' - ';
                    612:                     sleep 60;
                    613:                     print $fh unlink($lonsqlfile).' - '.
                    614:                               system('killall -9 lonsql').
                    615:                     '</font><br>';
                    616: 	print $fh "<h3>lonsql not running, trying to start</h3>";
                    617: 	system(
                    618:  "$perlvar{'lonDaemons'}/lonsql 2>>$perlvar{'lonDaemons'}/logs/lonsql_errors");
                    619: 	sleep 10;
                    620: 
                    621: =head1 DESCRIPTION
                    622: 
1.41      harris41  623: Not yet written.
1.40      harris41  624: 
                    625: =head1 README
                    626: 
1.41      harris41  627: Not yet written.
1.40      harris41  628: 
                    629: =head1 PREREQUISITES
                    630: 
                    631: IO::Socket
                    632: Symbol
                    633: POSIX
                    634: IO::Select
                    635: IO::File
                    636: Socket
                    637: Fcntl
                    638: Tie::RefHash
                    639: DBI
                    640: 
                    641: =head1 COREQUISITES
                    642: 
                    643: =head1 OSNAMES
                    644: 
                    645: linux
                    646: 
                    647: =head1 SCRIPT CATEGORIES
                    648: 
                    649: Server/Process
                    650: 
                    651: =cut

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