Annotation of loncom/lonsql, revision 1.66
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.66 ! albertel 6: # $Id: lonsql,v 1.65 2004/08/26 19:29:09 albertel 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.51 matthew 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:
1.56 bowersj2 42: =head1 OVERVIEW
1.51 matthew 43:
1.56 bowersj2 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.
1.51 matthew 95:
96: =head1 Internals
97:
98: =over 4
99:
100: =cut
101:
102: use strict;
1.36 www 103:
1.42 harris41 104: use lib '/home/httpd/lib/perl/';
105: use LONCAPA::Configuration;
1.58 matthew 106: use LONCAPA::lonmetadata();
1.42 harris41 107:
1.2 harris41 108: use IO::Socket;
109: use Symbol;
1.1 harris41 110: use POSIX;
111: use IO::Select;
112: use IO::File;
113: use Socket;
114: use Fcntl;
115: use Tie::RefHash;
116: use DBI;
1.51 matthew 117: use File::Find;
1.62 raeburn 118: use localenroll;
1.51 matthew 119:
120: ########################################################
121: ########################################################
122:
123: =pod
124:
125: =item Global Variables
126:
127: =over 4
128:
129: =item dbh
130:
131: =back
132:
133: =cut
134:
135: ########################################################
136: ########################################################
137: my $dbh;
138:
139: ########################################################
140: ########################################################
141:
142: =pod
143:
144: =item Variables required for forking
1.1 harris41 145:
1.51 matthew 146: =over 4
147:
148: =item $MAX_CLIENTS_PER_CHILD
149:
150: The number of clients each child should process.
151:
152: =item %children
153:
154: The keys to %children are the current child process IDs
155:
156: =item $children
157:
158: The current number of children
159:
160: =back
161:
162: =cut
1.9 harris41 163:
1.51 matthew 164: ########################################################
165: ########################################################
166: my $MAX_CLIENTS_PER_CHILD = 5; # number of clients each child should process
167: my %children = (); # keys are current child process IDs
168: my $children = 0; # current number of children
169:
170: ###################################################################
171: ###################################################################
172:
173: =pod
174:
175: =item Main body of code.
176:
177: =over 4
1.45 www 178:
1.51 matthew 179: =item Read data from loncapa_apache.conf and loncapa.conf.
180:
181: =item Ensure we can access the database.
182:
183: =item Determine if there are other instances of lonsql running.
184:
185: =item Read the hosts file.
186:
187: =item Create a socket for lonsql.
188:
189: =item Fork once and dissociate from parent.
190:
191: =item Write PID to disk.
192:
193: =item Prefork children and maintain the population of children.
194:
195: =back
196:
197: =cut
198:
199: ###################################################################
200: ###################################################################
201: my $childmaxattempts=10;
202: my $run =0; # running counter to generate the query-id
203: #
204: # Read loncapa_apache.conf and loncapa.conf
205: #
1.53 harris41 206: my $perlvarref=LONCAPA::Configuration::read_conf('loncapa.conf');
1.51 matthew 207: my %perlvar=%{$perlvarref};
208: #
1.63 matthew 209: # Write the /home/www/.my.cnf file
210: my $conf_file = '/home/www/.my.cnf';
211: if (! -e $conf_file) {
212: if (open MYCNF, ">$conf_file") {
213: print MYCNF <<"ENDMYCNF";
214: [client]
215: user=www
216: password=$perlvar{'lonSqlAccess'}
217: ENDMYCNF
218: close MYCNF;
219: } else {
220: warn "Unable to write $conf_file, continuing";
221: }
222: }
223:
224:
225: #
1.51 matthew 226: # Make sure that database can be accessed
227: #
228: my $dbh;
229: unless ($dbh = DBI->connect("DBI:mysql:loncapa","www",
230: $perlvar{'lonSqlAccess'},
231: { RaiseError =>0,PrintError=>0})) {
232: print "Cannot connect to database!\n";
233: my $emailto="$perlvar{'lonAdmEMail'},$perlvar{'lonSysEMail'}";
234: my $subj="LON: $perlvar{'lonHostID'} Cannot connect to database!";
235: system("echo 'Cannot connect to MySQL database!' |".
236: " mailto $emailto -s '$subj' > /dev/null");
1.57 www 237:
238: open(SMP,'>/home/httpd/html/lon-status/mysql.txt');
239: print SMP 'time='.time.'&mysql=defunct'."\n";
240: close(SMP);
241:
1.51 matthew 242: exit 1;
243: } else {
244: $dbh->disconnect;
245: }
1.52 matthew 246:
1.51 matthew 247: #
248: # Check if other instance running
249: #
250: my $pidfile="$perlvar{'lonDaemons'}/logs/lonsql.pid";
251: if (-e $pidfile) {
252: my $lfh=IO::File->new("$pidfile");
253: my $pide=<$lfh>;
254: chomp($pide);
255: if (kill 0 => $pide) { die "already running"; }
256: }
1.52 matthew 257:
1.49 www 258: #
1.51 matthew 259: # Read hosts file
1.49 www 260: #
1.51 matthew 261: my $thisserver;
262: my $PREFORK=4; # number of children to maintain, at least four spare
263: open (CONFIG,"$perlvar{'lonTabDir'}/hosts.tab") || die "Can't read host file";
264: while (my $configline=<CONFIG>) {
1.66 ! albertel 265: my ($id,$domain,$role,$name)=split(/:/,$configline);
! 266: $name=~s/\s//g;
1.51 matthew 267: $thisserver=$name if ($id eq $perlvar{'lonHostID'});
1.65 albertel 268: #$PREFORK++;
1.45 www 269: }
1.51 matthew 270: close(CONFIG);
271: #
1.65 albertel 272: #$PREFORK=int($PREFORK/4);
1.52 matthew 273:
1.51 matthew 274: #
275: # Create a socket to talk to lond
276: #
277: my $unixsock = "mysqlsock";
278: my $localfile="$perlvar{'lonSockDir'}/$unixsock";
279: my $server;
280: unlink ($localfile);
281: unless ($server=IO::Socket::UNIX->new(Local =>"$localfile",
282: Type => SOCK_STREAM,
283: Listen => 10)) {
284: print "in socket error:$@\n";
1.45 www 285: }
1.52 matthew 286:
1.51 matthew 287: #
288: # Fork once and dissociate
1.52 matthew 289: #
1.51 matthew 290: my $fpid=fork;
1.1 harris41 291: exit if $fpid;
292: die "Couldn't fork: $!" unless defined ($fpid);
293: POSIX::setsid() or die "Can't start new session: $!";
1.52 matthew 294:
1.51 matthew 295: #
296: # Write our PID on disk
297: my $execdir=$perlvar{'lonDaemons'};
1.1 harris41 298: open (PIDSAVE,">$execdir/logs/lonsql.pid");
299: print PIDSAVE "$$\n";
300: close(PIDSAVE);
1.59 albertel 301: &logthis("<font color='red'>CRITICAL: ---------- Starting ----------</font>");
1.52 matthew 302:
1.51 matthew 303: #
304: # Ignore signals generated during initial startup
1.1 harris41 305: $SIG{HUP}=$SIG{USR1}='IGNORE';
1.51 matthew 306: # Now we are on our own
307: # Fork off our children.
1.2 harris41 308: for (1 .. $PREFORK) {
309: make_new_child();
1.1 harris41 310: }
1.52 matthew 311:
1.51 matthew 312: #
1.2 harris41 313: # Install signal handlers.
1.1 harris41 314: $SIG{CHLD} = \&REAPER;
315: $SIG{INT} = $SIG{TERM} = \&HUNTSMAN;
316: $SIG{HUP} = \&HUPSMAN;
1.52 matthew 317:
1.51 matthew 318: #
1.1 harris41 319: # And maintain the population.
320: while (1) {
321: sleep; # wait for a signal (i.e., child's death)
1.51 matthew 322: for (my $i = $children; $i < $PREFORK; $i++) {
1.2 harris41 323: make_new_child(); # top up the child pool
1.1 harris41 324: }
325: }
326:
1.51 matthew 327: ########################################################
328: ########################################################
329:
330: =pod
331:
332: =item &make_new_child
333:
334: Inputs: None
335:
336: Returns: None
337:
338: =cut
1.2 harris41 339:
1.51 matthew 340: ########################################################
341: ########################################################
1.1 harris41 342: sub make_new_child {
343: my $pid;
344: my $sigset;
1.51 matthew 345: #
1.1 harris41 346: # block signal for fork
347: $sigset = POSIX::SigSet->new(SIGINT);
348: sigprocmask(SIG_BLOCK, $sigset)
349: or die "Can't block SIGINT for fork: $!\n";
1.51 matthew 350: #
1.2 harris41 351: die "fork: $!" unless defined ($pid = fork);
1.51 matthew 352: #
1.1 harris41 353: if ($pid) {
354: # Parent records the child's birth and returns.
355: sigprocmask(SIG_UNBLOCK, $sigset)
356: or die "Can't unblock SIGINT for fork: $!\n";
357: $children{$pid} = 1;
358: $children++;
359: return;
360: } else {
1.2 harris41 361: # Child can *not* return from this subroutine.
1.1 harris41 362: $SIG{INT} = 'DEFAULT'; # make SIGINT kill us as it did before
363: # unblock signals
364: sigprocmask(SIG_UNBLOCK, $sigset)
365: or die "Can't unblock SIGINT for fork: $!\n";
1.2 harris41 366: #open database handle
367: # making dbh global to avoid garbage collector
1.51 matthew 368: unless ($dbh = DBI->connect("DBI:mysql:loncapa","www",
369: $perlvar{'lonSqlAccess'},
370: { RaiseError =>0,PrintError=>0})) {
371: sleep(10+int(rand(20)));
1.59 albertel 372: &logthis("<font color='blue'>WARNING: Couldn't connect to database".
1.51 matthew 373: ": $@</font>");
374: # "($st secs): $@</font>");
375: print "database handle error\n";
376: exit;
377: }
378: # make sure that a database disconnection occurs with
379: # ending kill signals
1.2 harris41 380: $SIG{TERM}=$SIG{INT}=$SIG{QUIT}=$SIG{__DIE__}=\&DISCONNECT;
1.1 harris41 381: # handle connections until we've reached $MAX_CLIENTS_PER_CHILD
1.51 matthew 382: for (my $i=0; $i < $MAX_CLIENTS_PER_CHILD; $i++) {
383: my $client = $server->accept() or last;
1.2 harris41 384: # do something with the connection
1.1 harris41 385: $run = $run+1;
1.2 harris41 386: my $userinput = <$client>;
387: chomp($userinput);
1.51 matthew 388: #
1.45 www 389: my ($conserver,$query,
390: $arg1,$arg2,$arg3)=split(/&/,$userinput);
391: my $query=unescape($query);
1.51 matthew 392: #
1.2 harris41 393: #send query id which is pid_unixdatetime_runningcounter
1.51 matthew 394: my $queryid = $thisserver;
1.2 harris41 395: $queryid .="_".($$)."_";
396: $queryid .= time."_";
397: $queryid .= $run;
398: print $client "$queryid\n";
1.51 matthew 399: #
1.61 matthew 400: # &logthis("QUERY: $query - $arg1 - $arg2 - $arg3");
1.25 harris41 401: sleep 1;
1.51 matthew 402: #
1.45 www 403: my $result='';
1.51 matthew 404: #
405: # At this point, query is received, query-ID assigned and sent
406: # back, $query eq 'logquery' will mean that this is a query
407: # against log-files
408: if (($query eq 'userlog') || ($query eq 'courselog')) {
409: # beginning of log query
410: my $udom = &unescape($arg1);
411: my $uname = &unescape($arg2);
412: my $command = &unescape($arg3);
413: my $path = &propath($udom,$uname);
414: if (-e "$path/activity.log") {
415: if ($query eq 'userlog') {
416: $result=&userlog($path,$command);
417: } else {
418: $result=&courselog($path,$command);
419: }
420: } else {
421: &logthis('Unable to do log query: '.$uname.'@'.$udom);
422: $result='no_such_file';
423: }
424: # end of log query
1.62 raeburn 425: } elsif ($query eq 'fetchenrollment') {
426: # retrieve institutional class lists
427: my $dom = &unescape($arg1);
428: my %affiliates = ();
429: my %replies = ();
430: my $locresult = '';
431: my $querystr = &unescape($arg3);
432: foreach (split/%%/,$querystr) {
433: if (/^(\w+)=([^=]+)$/) {
434: @{$affiliates{$1}} = split/,/,$2;
435: }
436: }
437: $locresult = &localenroll::fetch_enrollment($dom,\%affiliates,\%replies);
438: $result = &escape($locresult.':');
439: if ($locresult) {
440: $result .= &escape(join(':',map{$_.'='.$replies{$_}} keys %replies));
441: }
1.63 matthew 442: } elsif ($query eq 'prepare activity log') {
443: my ($cid,$domain) = map {&unescape($_);} ($arg1,$arg2);
1.64 matthew 444: &logthis('preparing activity log tables for '.$cid);
1.63 matthew 445: my $command =
1.64 matthew 446: qq{$perlvar{'lonDaemons'}/parse_activity_log.pl -course=$cid -domain=$domain};
1.63 matthew 447: system($command);
1.64 matthew 448: &logthis($command);
1.63 matthew 449: my $returnvalue = $?>>8;
450: if ($returnvalue) {
451: $result = 'error: parse_activity_log.pl returned '.
452: $returnvalue;
453: } else {
454: $result = 'success';
455: }
1.51 matthew 456: } else {
457: # Do an sql query
458: $result = &do_sql_query($query,$arg1,$arg2);
459: }
1.50 matthew 460: # result does not need to be escaped because it has already been
461: # escaped.
462: #$result=&escape($result);
1.17 harris41 463: &reply("queryreply:$queryid:$result",$conserver);
1.1 harris41 464: }
465: # tidy up gracefully and finish
1.51 matthew 466: #
467: # close the database handle
1.2 harris41 468: $dbh->disconnect
1.59 albertel 469: or &logthis("<font color='blue'>WARNING: Couldn't disconnect".
1.51 matthew 470: " from database $DBI::errstr : $@</font>");
1.1 harris41 471: # this exit is VERY important, otherwise the child will become
472: # a producer of more and more children, forking yourself into
473: # process death.
474: exit;
475: }
1.2 harris41 476: }
1.1 harris41 477:
1.51 matthew 478: ########################################################
479: ########################################################
480:
481: =pod
482:
483: =item &do_sql_query
484:
485: Runs an sql metadata table query.
486:
487: Inputs: $query, $custom, $customshow
488:
489: Returns: A string containing escaped results.
490:
491: =cut
492:
493: ########################################################
494: ########################################################
495: {
496: my @metalist;
497:
498: sub process_file {
499: if ( -e $_ && # file exists
500: -f $_ && # and is a normal file
501: /\.meta$/ && # ends in meta
502: ! /^.+\.\d+\.[^\.]+\.meta$/ # is not a previous version
503: ) {
504: push(@metalist,$File::Find::name);
505: }
506: }
507:
508: sub do_sql_query {
509: my ($query,$custom,$customshow) = @_;
1.64 matthew 510: &logthis('doing query '.$query);
1.51 matthew 511: $custom = &unescape($custom);
512: $customshow = &unescape($customshow);
513: #
514: @metalist = ();
515: #
516: my $result = '';
517: my @results = ();
518: my @files;
519: my $subsetflag=0;
520: #
521: if ($query) {
522: #prepare and execute the query
523: my $sth = $dbh->prepare($query);
524: unless ($sth->execute()) {
1.59 albertel 525: &logthis('<font color="blue">'.
1.58 matthew 526: 'WARNING: Could not retrieve from database:'.
527: $sth->errstr().'</font>');
1.51 matthew 528: } else {
529: my $aref=$sth->fetchall_arrayref;
530: foreach my $row (@$aref) {
531: push @files,@{$row}[3] if ($custom or $customshow);
532: my @b=map { &escape($_); } @$row;
533: push @results,join(",", @b);
534: # Build up the @files array with the LON-CAPA urls
535: # of the resources.
536: }
537: }
538: }
539: # do custom metadata searching here and build into result
540: return join("&",@results) if (! ($custom or $customshow));
541: # Only get here if there is a custom query or custom show request
542: &logthis("Doing custom query for $custom");
543: if ($query) {
544: @metalist=map {
545: $perlvar{'lonDocRoot'}.$_.'.meta';
546: } @files;
547: } else {
548: my $dir = "$perlvar{'lonDocRoot'}/res/$perlvar{'lonDefDomain'}";
549: @metalist=();
550: opendir(RESOURCES,$dir);
551: my @homeusers=grep {
552: &ishome($dir.'/'.$_);
553: } grep {!/^\.\.?$/} readdir(RESOURCES);
554: closedir RESOURCES;
555: # Define the
556: foreach my $user (@homeusers) {
557: find (\&process_file,$dir.'/'.$user);
558: }
559: }
560: # if file is indicated in sql database and
561: # not part of sql-relevant query, do not pattern match.
562: #
563: # if file is not in sql database, output error.
564: #
565: # if file is indicated in sql database and is
566: # part of query result list, then do the pattern match.
567: my $customresult='';
568: my @results;
569: foreach my $metafile (@metalist) {
570: my $fh=IO::File->new($metafile);
571: my @lines=<$fh>;
572: my $stuff=join('',@lines);
573: if ($stuff=~/$custom/s) {
574: foreach my $f ('abstract','author','copyright',
575: 'creationdate','keywords','language',
576: 'lastrevisiondate','mime','notes',
577: 'owner','subject','title') {
578: $stuff=~s/\n?\<$f[^\>]*\>.*?<\/$f[^\>]*\>\n?//s;
579: }
580: my $mfile=$metafile;
581: my $docroot=$perlvar{'lonDocRoot'};
582: $mfile=~s/^$docroot//;
583: $mfile=~s/\.meta$//;
584: unless ($query) {
585: my $q2="SELECT * FROM metadata WHERE url ".
586: " LIKE BINARY '?'";
587: my $sth = $dbh->prepare($q2);
588: $sth->execute($mfile);
589: my $aref=$sth->fetchall_arrayref;
590: foreach my $a (@$aref) {
591: my @b=map { &escape($_)} @$a;
592: push @results,join(",", @b);
593: }
594: }
595: # &logthis("found: $stuff");
596: $customresult.='&custom='.&escape($mfile).','.
597: escape($stuff);
598: }
599: }
600: $result=join("&",@results) unless $query;
601: $result.=$customresult;
602: #
603: return $result;
604: } # End of &do_sql_query
605:
606: } # End of scoping curly braces for &process_file and &do_sql_query
607: ########################################################
608: ########################################################
609:
610: =pod
611:
612: =item &logthis
613:
614: Inputs: $message, the message to log
615:
616: Returns: nothing
617:
618: Writes $message to the logfile.
619:
620: =cut
621:
622: ########################################################
623: ########################################################
624: sub logthis {
625: my $message=shift;
626: my $execdir=$perlvar{'lonDaemons'};
1.52 matthew 627: my $fh=IO::File->new(">>$execdir/logs/lonsql.log");
1.51 matthew 628: my $now=time;
629: my $local=localtime($now);
630: print $fh "$local ($$): $message\n";
1.2 harris41 631: }
1.1 harris41 632:
1.2 harris41 633: # -------------------------------------------------- Non-critical communication
1.1 harris41 634:
1.51 matthew 635: ########################################################
636: ########################################################
637:
638: =pod
639:
640: =item &subreply
641:
642: Sends a command to a server. Called only by &reply.
643:
644: Inputs: $cmd,$server
645:
646: Returns: The results of the message or 'con_lost' on error.
647:
648: =cut
649:
650: ########################################################
651: ########################################################
1.2 harris41 652: sub subreply {
653: my ($cmd,$server)=@_;
654: my $peerfile="$perlvar{'lonSockDir'}/$server";
655: my $sclient=IO::Socket::UNIX->new(Peer =>"$peerfile",
656: Type => SOCK_STREAM,
657: Timeout => 10)
658: or return "con_lost";
659: print $sclient "$cmd\n";
660: my $answer=<$sclient>;
661: chomp($answer);
1.51 matthew 662: $answer="con_lost" if (!$answer);
1.2 harris41 663: return $answer;
664: }
1.1 harris41 665:
1.51 matthew 666: ########################################################
667: ########################################################
668:
669: =pod
670:
671: =item &reply
672:
673: Sends a command to a server.
674:
675: Inputs: $cmd,$server
676:
677: Returns: The results of the message or 'con_lost' on error.
678:
679: =cut
680:
681: ########################################################
682: ########################################################
1.2 harris41 683: sub reply {
684: my ($cmd,$server)=@_;
685: my $answer;
686: if ($server ne $perlvar{'lonHostID'}) {
687: $answer=subreply($cmd,$server);
688: if ($answer eq 'con_lost') {
689: $answer=subreply("ping",$server);
690: $answer=subreply($cmd,$server);
691: }
692: } else {
693: $answer='self_reply';
1.33 harris41 694: $answer=subreply($cmd,$server);
1.2 harris41 695: }
696: return $answer;
697: }
1.1 harris41 698:
1.51 matthew 699: ########################################################
700: ########################################################
701:
702: =pod
703:
704: =item &escape
705:
706: Escape special characters in a string.
1.3 harris41 707:
1.51 matthew 708: Inputs: string to escape
709:
710: Returns: The input string with special characters escaped.
711:
712: =cut
713:
714: ########################################################
715: ########################################################
1.3 harris41 716: sub escape {
717: my $str=shift;
718: $str =~ s/(\W)/"%".unpack('H2',$1)/eg;
719: return $str;
720: }
721:
1.51 matthew 722: ########################################################
723: ########################################################
724:
725: =pod
726:
727: =item &unescape
728:
729: Unescape special characters in a string.
1.3 harris41 730:
1.51 matthew 731: Inputs: string to unescape
732:
733: Returns: The input string with special characters unescaped.
734:
735: =cut
736:
737: ########################################################
738: ########################################################
1.3 harris41 739: sub unescape {
740: my $str=shift;
741: $str =~ s/%([a-fA-F0-9][a-fA-F0-9])/pack("C",hex($1))/eg;
742: return $str;
743: }
1.34 harris41 744:
1.51 matthew 745: ########################################################
746: ########################################################
747:
748: =pod
749:
750: =item &ishome
751:
752: Determine if the current machine is the home server for a user.
753: The determination is made by checking the filesystem for the users information.
754:
755: Inputs: $author
756:
757: Returns: 0 - this is not the authors home server, 1 - this is.
758:
759: =cut
760:
761: ########################################################
762: ########################################################
1.34 harris41 763: sub ishome {
764: my $author=shift;
765: $author=~s/\/home\/httpd\/html\/res\/([^\/]*)\/([^\/]*).*/$1\/$2/;
766: my ($udom,$uname)=split(/\//,$author);
767: my $proname=propath($udom,$uname);
768: if (-e $proname) {
769: return 1;
770: } else {
771: return 0;
772: }
773: }
774:
1.51 matthew 775: ########################################################
776: ########################################################
777:
778: =pod
779:
780: =item &propath
781:
782: Inputs: user name, user domain
783:
784: Returns: The full path to the users directory.
785:
786: =cut
787:
788: ########################################################
789: ########################################################
1.34 harris41 790: sub propath {
791: my ($udom,$uname)=@_;
792: $udom=~s/\W//g;
793: $uname=~s/\W//g;
794: my $subdir=$uname.'__';
795: $subdir =~ s/(.)(.)(.).*/$1\/$2\/$3/;
796: my $proname="$perlvar{'lonUsersDir'}/$udom/$subdir/$uname";
797: return $proname;
798: }
1.40 harris41 799:
1.51 matthew 800: ########################################################
801: ########################################################
802:
803: =pod
804:
805: =item &courselog
806:
807: Inputs: $path, $command
808:
809: Returns: unescaped string of values.
810:
811: =cut
812:
813: ########################################################
814: ########################################################
815: sub courselog {
816: my ($path,$command)=@_;
817: my %filters=();
818: foreach (split(/\:/,&unescape($command))) {
819: my ($name,$value)=split(/\=/,$_);
820: $filters{$name}=$value;
821: }
822: my @results=();
823: open(IN,$path.'/activity.log') or return ('file_error');
824: while (my $line=<IN>) {
825: chomp($line);
826: my ($timestamp,$host,$log)=split(/\:/,$line);
827: #
828: # $log has the actual log entries; currently still escaped, and
829: # %26(timestamp)%3a(url)%3a(user)%3a(domain)
830: # then additionally
831: # %3aPOST%3a(name)%3d(value)%3a(name)%3d(value)
832: # or
833: # %3aCSTORE%3a(name)%3d(value)%26(name)%3d(value)
834: #
835: # get delimiter between timestamped entries to be &&&
836: $log=~s/\%26(\d+)\%3a/\&\&\&$1\%3a/g;
837: # now go over all log entries
838: foreach (split(/\&\&\&/,&unescape($log))) {
839: my ($time,$res,$uname,$udom,$action,@values)=split(/\:/,$_);
840: my $values=&unescape(join(':',@values));
841: $values=~s/\&/\:/g;
842: $res=&unescape($res);
843: my $include=1;
844: if (($filters{'username'}) && ($uname ne $filters{'username'}))
845: { $include=0; }
846: if (($filters{'domain'}) && ($udom ne $filters{'domain'}))
847: { $include=0; }
848: if (($filters{'url'}) && ($res!~/$filters{'url'}/))
849: { $include=0; }
850: if (($filters{'start'}) && ($time<$filters{'start'}))
851: { $include=0; }
852: if (($filters{'end'}) && ($time>$filters{'end'}))
853: { $include=0; }
854: if (($filters{'action'} eq 'view') && ($action))
855: { $include=0; }
856: if (($filters{'action'} eq 'submit') && ($action ne 'POST'))
857: { $include=0; }
858: if (($filters{'action'} eq 'grade') && ($action ne 'CSTORE'))
859: { $include=0; }
860: if ($include) {
861: push(@results,($time<1000000000?'0':'').$time.':'.$res.':'.
862: $uname.':'.$udom.':'.
863: $action.':'.$values);
864: }
865: }
866: }
867: close IN;
868: return join('&',sort(@results));
869: }
870:
871: ########################################################
872: ########################################################
873:
874: =pod
875:
876: =item &userlog
877:
878: Inputs: $path, $command
879:
880: Returns: unescaped string of values.
1.40 harris41 881:
1.51 matthew 882: =cut
1.40 harris41 883:
1.51 matthew 884: ########################################################
885: ########################################################
886: sub userlog {
887: my ($path,$command)=@_;
888: my %filters=();
889: foreach (split(/\:/,&unescape($command))) {
890: my ($name,$value)=split(/\=/,$_);
891: $filters{$name}=$value;
892: }
893: my @results=();
894: open(IN,$path.'/activity.log') or return ('file_error');
895: while (my $line=<IN>) {
896: chomp($line);
897: my ($timestamp,$host,$log)=split(/\:/,$line);
898: $log=&unescape($log);
899: my $include=1;
900: if (($filters{'start'}) && ($timestamp<$filters{'start'}))
901: { $include=0; }
902: if (($filters{'end'}) && ($timestamp>$filters{'end'}))
903: { $include=0; }
904: if (($filters{'action'} eq 'log') && ($log!~/^Log/)) { $include=0; }
905: if (($filters{'action'} eq 'check') && ($log!~/^Check/))
906: { $include=0; }
907: if ($include) {
908: push(@results,$timestamp.':'.$log);
909: }
910: }
911: close IN;
912: return join('&',sort(@results));
1.52 matthew 913: }
914:
915: ########################################################
916: ########################################################
917:
918: =pod
919:
920: =item Functions required for forking
921:
922: =over 4
923:
924: =item REAPER
925:
926: REAPER takes care of dead children.
927:
928: =item HUNTSMAN
929:
930: Signal handler for SIGINT.
931:
932: =item HUPSMAN
933:
934: Signal handler for SIGHUP
935:
936: =item DISCONNECT
937:
938: Disconnects from database.
939:
940: =back
941:
942: =cut
943:
944: ########################################################
945: ########################################################
946: sub REAPER { # takes care of dead children
947: $SIG{CHLD} = \&REAPER;
948: my $pid = wait;
949: $children --;
950: &logthis("Child $pid died");
951: delete $children{$pid};
952: }
953:
954: sub HUNTSMAN { # signal handler for SIGINT
955: local($SIG{CHLD}) = 'IGNORE'; # we're going to kill our children
956: kill 'INT' => keys %children;
957: my $execdir=$perlvar{'lonDaemons'};
958: unlink("$execdir/logs/lonsql.pid");
1.59 albertel 959: &logthis("<font color='red'>CRITICAL: Shutting down</font>");
1.52 matthew 960: $unixsock = "mysqlsock";
961: my $port="$perlvar{'lonSockDir'}/$unixsock";
962: unlink($port);
963: exit; # clean up with dignity
964: }
965:
966: sub HUPSMAN { # signal handler for SIGHUP
967: local($SIG{CHLD}) = 'IGNORE'; # we're going to kill our children
968: kill 'INT' => keys %children;
969: close($server); # free up socket
1.59 albertel 970: &logthis("<font color='red'>CRITICAL: Restarting</font>");
1.52 matthew 971: my $execdir=$perlvar{'lonDaemons'};
972: $unixsock = "mysqlsock";
973: my $port="$perlvar{'lonSockDir'}/$unixsock";
974: unlink($port);
975: exec("$execdir/lonsql"); # here we go again
976: }
977:
978: sub DISCONNECT {
979: $dbh->disconnect or
1.59 albertel 980: &logthis("<font color='blue'>WARNING: Couldn't disconnect from database ".
1.52 matthew 981: " $DBI::errstr : $@</font>");
982: exit;
1.51 matthew 983: }
1.40 harris41 984:
985:
1.51 matthew 986: =pod
1.40 harris41 987:
1.51 matthew 988: =back
1.40 harris41 989:
990: =cut
FreeBSD-CVSweb <freebsd-cvsweb@FreeBSD.org>