Annotation of loncom/lonsql, revision 1.31

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

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