File:  [LON-CAPA] / loncom / lonsql
Revision 1.37: download - view: text, annotated - select for diffs
Wed Oct 17 02:15:59 2001 UTC (22 years, 6 months ago) by harris41
Branches: MAIN
CVS tags: stable_2001_fall, HEAD
never output regular metadata in custom metadata output...
single or multiple lines...

    1: #!/usr/bin/perl
    2: # lonsql-based on the preforker:harsha jagasia:date:5/10/00
    3: # 7/25 Gerd Kortemeyer
    4: # many different dates Scott Harrison
    5: # 03/22/2001 Scott Harrison
    6: # 8/30 Gerd Kortemeyer
    7: 
    8: use IO::Socket;
    9: use Symbol;
   10: use POSIX;
   11: use IO::Select;
   12: use IO::File;
   13: use Socket;
   14: use Fcntl;
   15: use Tie::RefHash;
   16: use DBI;
   17: 
   18: my @metalist;
   19: # ----------------- Code to enable 'find' subroutine listing of the .meta files
   20: require "find.pl";
   21: sub wanted {
   22:     (($dev,$ino,$mode,$nlink,$uid,$gid) = lstat($_)) &&
   23:     -f _ &&
   24:     /^.*\.meta$/ && !/^.+\.\d+\.[^\.]+\.meta$/ &&
   25:     push(@metalist,"$dir/$_");
   26: }
   27: 
   28: $childmaxattempts=10;
   29: $run =0;#running counter to generate the query-id
   30: 
   31: # ------------------------------------ Read httpd access.conf and get variables
   32: open (CONFIG,"/etc/httpd/conf/access.conf") || die "Can't read access.conf";
   33: 
   34: while ($configline=<CONFIG>) {
   35:     if ($configline =~ /PerlSetVar/) {
   36: 	my ($dummy,$varname,$varvalue)=split(/\s+/,$configline);
   37:         chomp($varvalue);
   38:         $perlvar{$varname}=$varvalue;
   39:     }
   40: }
   41: close(CONFIG);
   42: 
   43: # ------------------------------------- Make sure that database can be accessed
   44: {
   45:     my $dbh;
   46:     unless (
   47: 	    $dbh = DBI->connect("DBI:mysql:loncapa","www",$perlvar{'lonSqlAccess'},{ RaiseError =>0,PrintError=>0})
   48: 	    ) { 
   49: 	print "Cannot connect to database!\n";
   50: 	exit;
   51:     }
   52:     else {
   53: 	$dbh->disconnect;
   54:     }
   55: }
   56: 
   57: # --------------------------------------------- Check if other instance running
   58: 
   59: my $pidfile="$perlvar{'lonDaemons'}/logs/lonsql.pid";
   60: 
   61: if (-e $pidfile) {
   62:    my $lfh=IO::File->new("$pidfile");
   63:    my $pide=<$lfh>;
   64:    chomp($pide);
   65:    if (kill 0 => $pide) { die "already running"; }
   66: }
   67: 
   68: # ------------------------------------------------------------- Read hosts file
   69: $PREFORK=4; # number of children to maintain, at least four spare
   70: 
   71: open (CONFIG,"$perlvar{'lonTabDir'}/hosts.tab") || die "Can't read host file";
   72: 
   73: while ($configline=<CONFIG>) {
   74:     my ($id,$domain,$role,$name,$ip)=split(/:/,$configline);
   75:     chomp($ip);
   76: 
   77:     $hostip{$ip}=$id;
   78:     if ($id eq $perlvar{'lonHostID'}) { $thisserver=$name; }
   79: 
   80:     $PREFORK++;
   81: }
   82: close(CONFIG);
   83: 
   84: $PREFORK=int($PREFORK/4);
   85: 
   86: $unixsock = "mysqlsock";
   87: my $localfile="$perlvar{'lonSockDir'}/$unixsock";
   88: my $server;
   89: unlink ($localfile);
   90: unless ($server=IO::Socket::UNIX->new(Local    =>"$localfile",
   91: 				  Type    => SOCK_STREAM,
   92: 				  Listen => 10))
   93: {
   94:     print "in socket error:$@\n";
   95: }
   96: 
   97: # -------------------------------------------------------- Routines for forking
   98: # global variables
   99: $MAX_CLIENTS_PER_CHILD  = 5;        # number of clients each child should process
  100: %children               = ();       # keys are current child process IDs
  101: $children               = 0;        # current number of children
  102: 
  103: sub REAPER {                        # takes care of dead children
  104:     $SIG{CHLD} = \&REAPER;
  105:     my $pid = wait;
  106:     $children --;
  107:     &logthis("Child $pid died");
  108:     delete $children{$pid};
  109: }
  110: 
  111: sub HUNTSMAN {                      # signal handler for SIGINT
  112:     local($SIG{CHLD}) = 'IGNORE';   # we're going to kill our children
  113:     kill 'INT' => keys %children;
  114:     my $execdir=$perlvar{'lonDaemons'};
  115:     unlink("$execdir/logs/lonsql.pid");
  116:     &logthis("<font color=red>CRITICAL: Shutting down</font>");
  117:     $unixsock = "mysqlsock";
  118:     my $port="$perlvar{'lonSockDir'}/$unixsock";
  119:     unlink(port);
  120:     exit;                           # clean up with dignity
  121: }
  122: 
  123: sub HUPSMAN {                      # signal handler for SIGHUP
  124:     local($SIG{CHLD}) = 'IGNORE';  # we're going to kill our children
  125:     kill 'INT' => keys %children;
  126:     close($server);                # free up socket
  127:     &logthis("<font color=red>CRITICAL: Restarting</font>");
  128:     my $execdir=$perlvar{'lonDaemons'};
  129:     $unixsock = "mysqlsock";
  130:     my $port="$perlvar{'lonSockDir'}/$unixsock";
  131:     unlink(port);
  132:     exec("$execdir/lonsql");         # here we go again
  133: }
  134: 
  135: sub logthis {
  136:     my $message=shift;
  137:     my $execdir=$perlvar{'lonDaemons'};
  138:     my $fh=IO::File->new(">>$execdir/logs/lonsqlfinal.log");
  139:     my $now=time;
  140:     my $local=localtime($now);
  141:     print $fh "$local ($$): $message\n";
  142: }
  143: # ---------------------------------------------------- Fork once and dissociate
  144: $fpid=fork;
  145: exit if $fpid;
  146: die "Couldn't fork: $!" unless defined ($fpid);
  147: 
  148: POSIX::setsid() or die "Can't start new session: $!";
  149: 
  150: # ------------------------------------------------------- Write our PID on disk
  151: 
  152: $execdir=$perlvar{'lonDaemons'};
  153: open (PIDSAVE,">$execdir/logs/lonsql.pid");
  154: print PIDSAVE "$$\n";
  155: close(PIDSAVE);
  156: &logthis("<font color=red>CRITICAL: ---------- Starting ----------</font>");
  157: 
  158: # ----------------------------- Ignore signals generated during initial startup
  159: $SIG{HUP}=$SIG{USR1}='IGNORE';
  160: # ------------------------------------------------------- Now we are on our own    
  161: # Fork off our children.
  162: for (1 .. $PREFORK) {
  163:     make_new_child();
  164: }
  165: 
  166: # Install signal handlers.
  167: $SIG{CHLD} = \&REAPER;
  168: $SIG{INT}  = $SIG{TERM} = \&HUNTSMAN;
  169: $SIG{HUP}  = \&HUPSMAN;
  170: 
  171: # And maintain the population.
  172: while (1) {
  173:     sleep;                          # wait for a signal (i.e., child's death)
  174:     for ($i = $children; $i < $PREFORK; $i++) {
  175:         make_new_child();           # top up the child pool
  176:     }
  177: }
  178: 
  179: 
  180: sub make_new_child {
  181:     my $pid;
  182:     my $sigset;
  183:     
  184:     # block signal for fork
  185:     $sigset = POSIX::SigSet->new(SIGINT);
  186:     sigprocmask(SIG_BLOCK, $sigset)
  187:         or die "Can't block SIGINT for fork: $!\n";
  188:     
  189:     die "fork: $!" unless defined ($pid = fork);
  190:     
  191:     if ($pid) {
  192:         # Parent records the child's birth and returns.
  193:         sigprocmask(SIG_UNBLOCK, $sigset)
  194:             or die "Can't unblock SIGINT for fork: $!\n";
  195:         $children{$pid} = 1;
  196:         $children++;
  197:         return;
  198:     } else {
  199:         # Child can *not* return from this subroutine.
  200:         $SIG{INT} = 'DEFAULT';      # make SIGINT kill us as it did before
  201:     
  202:         # unblock signals
  203:         sigprocmask(SIG_UNBLOCK, $sigset)
  204:             or die "Can't unblock SIGINT for fork: $!\n";
  205: 	
  206: 	
  207:         #open database handle
  208: 	# making dbh global to avoid garbage collector
  209: 	unless (
  210: 		$dbh = DBI->connect("DBI:mysql:loncapa","www",$perlvar{'lonSqlAccess'},{ RaiseError =>0,PrintError=>0})
  211: 		) { 
  212:   	            sleep(10+int(rand(20)));
  213: 		    &logthis("<font color=blue>WARNING: Couldn't connect to database  ($st secs): $@</font>");
  214: 		    print "database handle error\n";
  215: 		    exit;
  216: 
  217: 	  };
  218: 	# make sure that a database disconnection occurs with ending kill signals
  219: 	$SIG{TERM}=$SIG{INT}=$SIG{QUIT}=$SIG{__DIE__}=\&DISCONNECT;
  220: 
  221:         # handle connections until we've reached $MAX_CLIENTS_PER_CHILD
  222:         for ($i=0; $i < $MAX_CLIENTS_PER_CHILD; $i++) {
  223:             $client = $server->accept()     or last;
  224:             
  225:             # do something with the connection
  226: 	    $run = $run+1;
  227: 	    my $userinput = <$client>;
  228: 	    chomp($userinput);
  229: 	    	    
  230: 	    my ($conserver,$querytmp,
  231: 		$customtmp,$customshowtmp)=split(/&/,$userinput);
  232: 	    my $query=unescape($querytmp);
  233: 	    my $custom=unescape($customtmp);
  234: 	    my $customshow=unescape($customshowtmp);
  235: 
  236:             #send query id which is pid_unixdatetime_runningcounter
  237: 	    $queryid = $thisserver;
  238: 	    $queryid .="_".($$)."_";
  239: 	    $queryid .= time."_";
  240: 	    $queryid .= $run;
  241: 	    print $client "$queryid\n";
  242: 	    
  243: 	    &logthis("QUERY: $query");
  244: 	    &logthis("QUERY: $query");
  245: 	    sleep 1;
  246:             #prepare and execute the query
  247: 	    my $sth = $dbh->prepare($query);
  248: 	    my $result;
  249: 	    my @files;
  250: 	    my $subsetflag=0;
  251: 	    if ($query) {
  252: 		unless ($sth->execute())
  253: 		{
  254: 		    &logthis("<font color=blue>WARNING: Could not retrieve from database: $@</font>");
  255: 		    $result="";
  256: 		}
  257: 		else {
  258: 		    my $r1=$sth->fetchall_arrayref;
  259: 		    my @r2;
  260: 		    map {my $a=$_; 
  261: 			 my @b=map {escape($_)} @$a;
  262: 			 push @files,@{$a}[3];
  263: 			 push @r2,join(",", @b)
  264: 			 } (@$r1);
  265: 		    $result=join("&",@r2);
  266: 		}
  267: 	    }
  268: 	    # do custom metadata searching here and build into result
  269: 	    if ($custom or $customshow) {
  270: 		&logthis("am going to do custom query for $custom");
  271: 		if ($query) {
  272: 		    @metalist=map {$perlvar{'lonDocRoot'}.$_.'.meta'} @files;
  273: 		}
  274: 		else {
  275: 		    @metalist=(); pop @metalist;
  276: 		    opendir(RESOURCES,"$perlvar{'lonDocRoot'}/res/$perlvar{'lonDefDomain'}");
  277: 		    my @homeusers=grep
  278: 		          {&ishome("$perlvar{'lonDocRoot'}/res/$perlvar{'lonDefDomain'}/$_")}
  279: 		          grep {!/^\.\.?$/} readdir(RESOURCES);
  280: 		    closedir RESOURCES;
  281: 		    foreach my $user (@homeusers) {
  282: 			&find("$perlvar{'lonDocRoot'}/res/$perlvar{'lonDefDomain'}/$user");
  283: 		    }
  284: 		}
  285: #		&logthis("FILELIST:" . join(":::",@metalist));
  286: 		# if file is indicated in sql database and
  287: 		# not part of sql-relevant query, do not pattern match.
  288: 		# if file is not in sql database, output error.
  289: 		# if file is indicated in sql database and is
  290: 		# part of query result list, then do the pattern match.
  291: 		my $customresult='';
  292: 		my @r2;
  293: 		foreach my $m (@metalist) {
  294: 		    my $fh=IO::File->new($m);
  295: 		    my @lines=<$fh>;
  296: 		    my $stuff=join('',@lines);
  297: 		    if ($stuff=~/$custom/s) {
  298: 			foreach my $f ('abstract','author','copyright',
  299: 				       'creationdate','keywords','language',
  300: 				       'lastrevisiondate','mime','notes',
  301: 				       'owner','subject','title') {
  302: 			    $stuff=~s/\n?\<$f[^\>]*\>.*?<\/$f[^\>]*\>\n?//s;
  303: 			}
  304: 			my $m2=$m; my $docroot=$perlvar{'lonDocRoot'};
  305: 			$m2=~s/^$docroot//;
  306: 			$m2=~s/\.meta$//;
  307: 			unless ($query) {
  308: 			    my $q2="select * from metadata where url like binary '$m2'";
  309: 			    my $sth = $dbh->prepare($q2);
  310: 			    $sth->execute();
  311: 			    my $r1=$sth->fetchall_arrayref;
  312: 			    map {my $a=$_; 
  313: 				 my @b=map {escape($_)} @$a;
  314: 				 push @files,@{$a}[3];
  315: 				 push @r2,join(",", @b)
  316: 				 } (@$r1);
  317: 			}
  318: #			&logthis("found: $stuff");
  319: 			$customresult.='&custom='.escape($m2).','.escape($stuff);
  320: 		    }
  321: 		}
  322: 		$result=join("&",@r2) unless $query;
  323: 		$result.=$customresult;
  324: 	    }
  325: 	    # reply with result
  326: 	    $result.="\n" if $result;
  327:             &reply("queryreply:$queryid:$result",$conserver);
  328: 
  329:         }
  330:     
  331:         # tidy up gracefully and finish
  332: 	
  333:         #close the database handle
  334: 	$dbh->disconnect
  335: 	   or &logthis("<font color=blue>WARNING: Couldn't disconnect from database  $DBI::errstr ($st secs): $@</font>");
  336:     
  337:         # this exit is VERY important, otherwise the child will become
  338:         # a producer of more and more children, forking yourself into
  339:         # process death.
  340:         exit;
  341:     }
  342: }
  343: 
  344: sub DISCONNECT {
  345:     $dbh->disconnect or 
  346:     &logthis("<font color=blue>WARNING: Couldn't disconnect from database  $DBI::errstr ($st secs): $@</font>");
  347:     exit;
  348: }
  349: 
  350: # -------------------------------------------------- Non-critical communication
  351: 
  352: sub subreply {
  353:     my ($cmd,$server)=@_;
  354:     my $peerfile="$perlvar{'lonSockDir'}/$server";
  355:     my $sclient=IO::Socket::UNIX->new(Peer    =>"$peerfile",
  356:                                       Type    => SOCK_STREAM,
  357:                                       Timeout => 10)
  358:        or return "con_lost";
  359:     print $sclient "$cmd\n";
  360:     my $answer=<$sclient>;
  361:     chomp($answer);
  362:     if (!$answer) { $answer="con_lost"; }
  363:     return $answer;
  364: }
  365: 
  366: sub reply {
  367:   my ($cmd,$server)=@_;
  368:   my $answer;
  369:   if ($server ne $perlvar{'lonHostID'}) { 
  370:     $answer=subreply($cmd,$server);
  371:     if ($answer eq 'con_lost') {
  372: 	$answer=subreply("ping",$server);
  373:         $answer=subreply($cmd,$server);
  374:     }
  375:   } else {
  376:     $answer='self_reply';
  377:     $answer=subreply($cmd,$server);
  378:   } 
  379:   return $answer;
  380: }
  381: 
  382: # -------------------------------------------------------- Escape Special Chars
  383: 
  384: sub escape {
  385:     my $str=shift;
  386:     $str =~ s/(\W)/"%".unpack('H2',$1)/eg;
  387:     return $str;
  388: }
  389: 
  390: # ----------------------------------------------------- Un-Escape Special Chars
  391: 
  392: sub unescape {
  393:     my $str=shift;
  394:     $str =~ s/%([a-fA-F0-9][a-fA-F0-9])/pack("C",hex($1))/eg;
  395:     return $str;
  396: }
  397: 
  398: # --------------------------------------- Is this the home server of an author?
  399: # (copied from lond, modification of the return value)
  400: sub ishome {
  401:     my $author=shift;
  402:     $author=~s/\/home\/httpd\/html\/res\/([^\/]*)\/([^\/]*).*/$1\/$2/;
  403:     my ($udom,$uname)=split(/\//,$author);
  404:     my $proname=propath($udom,$uname);
  405:     if (-e $proname) {
  406: 	return 1;
  407:     } else {
  408:         return 0;
  409:     }
  410: }
  411: 
  412: # -------------------------------------------- Return path to profile directory
  413: # (copied from lond)
  414: sub propath {
  415:     my ($udom,$uname)=@_;
  416:     $udom=~s/\W//g;
  417:     $uname=~s/\W//g;
  418:     my $subdir=$uname.'__';
  419:     $subdir =~ s/(.)(.)(.).*/$1\/$2\/$3/;
  420:     my $proname="$perlvar{'lonUsersDir'}/$udom/$subdir/$uname";
  421:     return $proname;
  422: } 

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