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