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