Annotation of loncom/lonsql, revision 1.76
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.76 ! albertel 6: # $Id: lonsql,v 1.75 2006/02/10 09:47:36 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.73 www 391: $userinput=~s/\:(\w+)$//;
392: my $searchdomain=$1;
1.51 matthew 393: #
1.45 www 394: my ($conserver,$query,
395: $arg1,$arg2,$arg3)=split(/&/,$userinput);
396: my $query=unescape($query);
1.51 matthew 397: #
1.2 harris41 398: #send query id which is pid_unixdatetime_runningcounter
1.51 matthew 399: my $queryid = $thisserver;
1.2 harris41 400: $queryid .="_".($$)."_";
401: $queryid .= time."_";
402: $queryid .= $run;
403: print $client "$queryid\n";
1.51 matthew 404: #
1.61 matthew 405: # &logthis("QUERY: $query - $arg1 - $arg2 - $arg3");
1.25 harris41 406: sleep 1;
1.51 matthew 407: #
1.45 www 408: my $result='';
1.51 matthew 409: #
410: # At this point, query is received, query-ID assigned and sent
411: # back, $query eq 'logquery' will mean that this is a query
412: # against log-files
413: if (($query eq 'userlog') || ($query eq 'courselog')) {
414: # beginning of log query
415: my $udom = &unescape($arg1);
416: my $uname = &unescape($arg2);
417: my $command = &unescape($arg3);
418: my $path = &propath($udom,$uname);
419: if (-e "$path/activity.log") {
420: if ($query eq 'userlog') {
421: $result=&userlog($path,$command);
422: } else {
423: $result=&courselog($path,$command);
424: }
425: } else {
426: &logthis('Unable to do log query: '.$uname.'@'.$udom);
427: $result='no_such_file';
428: }
429: # end of log query
1.70 raeburn 430: } elsif (($query eq 'fetchenrollment') ||
1.71 albertel 431: ($query eq 'institutionalphotos')) {
1.62 raeburn 432: # retrieve institutional class lists
433: my $dom = &unescape($arg1);
434: my %affiliates = ();
435: my %replies = ();
436: my $locresult = '';
437: my $querystr = &unescape($arg3);
438: foreach (split/%%/,$querystr) {
1.68 raeburn 439: if (/^([^=]+)=([^=]+)$/) {
1.62 raeburn 440: @{$affiliates{$1}} = split/,/,$2;
441: }
442: }
1.70 raeburn 443: if ($query eq 'fetchenrollment') {
444: $locresult = &localenroll::fetch_enrollment($dom,\%affiliates,\%replies);
445: } elsif ($query eq 'institutionalphotos') {
446: my $crs = &unescape($arg2);
1.75 albertel 447: eval {
448: local($SIG{__DIE__})='DEFAULT';
449: $locresult = &localenroll::institutional_photos($dom,$crs,\%affiliates,\%replies,'update');
450: };
451: if ($@) {
452: $locresult = 'error';
453: }
1.70 raeburn 454: }
1.62 raeburn 455: $result = &escape($locresult.':');
456: if ($locresult) {
457: $result .= &escape(join(':',map{$_.'='.$replies{$_}} keys %replies));
458: }
1.63 matthew 459: } elsif ($query eq 'prepare activity log') {
460: my ($cid,$domain) = map {&unescape($_);} ($arg1,$arg2);
1.64 matthew 461: &logthis('preparing activity log tables for '.$cid);
1.63 matthew 462: my $command =
1.64 matthew 463: qq{$perlvar{'lonDaemons'}/parse_activity_log.pl -course=$cid -domain=$domain};
1.63 matthew 464: system($command);
1.64 matthew 465: &logthis($command);
1.63 matthew 466: my $returnvalue = $?>>8;
467: if ($returnvalue) {
468: $result = 'error: parse_activity_log.pl returned '.
469: $returnvalue;
470: } else {
471: $result = 'success';
472: }
1.51 matthew 473: } else {
474: # Do an sql query
1.74 www 475: $result = &do_sql_query($query,$arg1,$arg2,$searchdomain);
1.51 matthew 476: }
1.50 matthew 477: # result does not need to be escaped because it has already been
478: # escaped.
479: #$result=&escape($result);
1.17 harris41 480: &reply("queryreply:$queryid:$result",$conserver);
1.1 harris41 481: }
482: # tidy up gracefully and finish
1.51 matthew 483: #
484: # close the database handle
1.2 harris41 485: $dbh->disconnect
1.59 albertel 486: or &logthis("<font color='blue'>WARNING: Couldn't disconnect".
1.51 matthew 487: " from database $DBI::errstr : $@</font>");
1.1 harris41 488: # this exit is VERY important, otherwise the child will become
489: # a producer of more and more children, forking yourself into
490: # process death.
491: exit;
492: }
1.2 harris41 493: }
1.1 harris41 494:
1.51 matthew 495: ########################################################
496: ########################################################
497:
498: =pod
499:
500: =item &do_sql_query
501:
502: Runs an sql metadata table query.
503:
504: Inputs: $query, $custom, $customshow
505:
506: Returns: A string containing escaped results.
507:
508: =cut
509:
510: ########################################################
511: ########################################################
512: {
513: my @metalist;
514:
515: sub process_file {
516: if ( -e $_ && # file exists
517: -f $_ && # and is a normal file
518: /\.meta$/ && # ends in meta
519: ! /^.+\.\d+\.[^\.]+\.meta$/ # is not a previous version
520: ) {
521: push(@metalist,$File::Find::name);
522: }
523: }
524:
525: sub do_sql_query {
1.74 www 526: my ($query,$custom,$customshow,$searchdomain) = @_;
527:
528: #
529: # limit to searchdomain if given and table is metadata
530: #
531: if (($searchdomain) && ($query=~/FROM metadata/)) {
532: $query.=' HAVING (domain="'.$searchdomain.'")';
533: }
534: # &logthis('doing query ('.$searchdomain.')'.$query);
535:
536:
537:
1.51 matthew 538: $custom = &unescape($custom);
539: $customshow = &unescape($customshow);
540: #
541: @metalist = ();
542: #
543: my $result = '';
544: my @results = ();
545: my @files;
546: my $subsetflag=0;
547: #
548: if ($query) {
549: #prepare and execute the query
550: my $sth = $dbh->prepare($query);
551: unless ($sth->execute()) {
1.59 albertel 552: &logthis('<font color="blue">'.
1.58 matthew 553: 'WARNING: Could not retrieve from database:'.
554: $sth->errstr().'</font>');
1.51 matthew 555: } else {
556: my $aref=$sth->fetchall_arrayref;
557: foreach my $row (@$aref) {
558: push @files,@{$row}[3] if ($custom or $customshow);
559: my @b=map { &escape($_); } @$row;
560: push @results,join(",", @b);
561: # Build up the @files array with the LON-CAPA urls
562: # of the resources.
563: }
564: }
565: }
566: # do custom metadata searching here and build into result
567: return join("&",@results) if (! ($custom or $customshow));
568: # Only get here if there is a custom query or custom show request
569: &logthis("Doing custom query for $custom");
570: if ($query) {
571: @metalist=map {
572: $perlvar{'lonDocRoot'}.$_.'.meta';
573: } @files;
574: } else {
575: my $dir = "$perlvar{'lonDocRoot'}/res/$perlvar{'lonDefDomain'}";
576: @metalist=();
577: opendir(RESOURCES,$dir);
578: my @homeusers=grep {
579: &ishome($dir.'/'.$_);
580: } grep {!/^\.\.?$/} readdir(RESOURCES);
581: closedir RESOURCES;
582: # Define the
583: foreach my $user (@homeusers) {
584: find (\&process_file,$dir.'/'.$user);
585: }
586: }
587: # if file is indicated in sql database and
588: # not part of sql-relevant query, do not pattern match.
589: #
590: # if file is not in sql database, output error.
591: #
592: # if file is indicated in sql database and is
593: # part of query result list, then do the pattern match.
594: my $customresult='';
595: my @results;
596: foreach my $metafile (@metalist) {
597: my $fh=IO::File->new($metafile);
598: my @lines=<$fh>;
599: my $stuff=join('',@lines);
600: if ($stuff=~/$custom/s) {
601: foreach my $f ('abstract','author','copyright',
602: 'creationdate','keywords','language',
603: 'lastrevisiondate','mime','notes',
604: 'owner','subject','title') {
605: $stuff=~s/\n?\<$f[^\>]*\>.*?<\/$f[^\>]*\>\n?//s;
606: }
607: my $mfile=$metafile;
608: my $docroot=$perlvar{'lonDocRoot'};
609: $mfile=~s/^$docroot//;
610: $mfile=~s/\.meta$//;
611: unless ($query) {
612: my $q2="SELECT * FROM metadata WHERE url ".
613: " LIKE BINARY '?'";
614: my $sth = $dbh->prepare($q2);
615: $sth->execute($mfile);
616: my $aref=$sth->fetchall_arrayref;
617: foreach my $a (@$aref) {
618: my @b=map { &escape($_)} @$a;
619: push @results,join(",", @b);
620: }
621: }
622: # &logthis("found: $stuff");
623: $customresult.='&custom='.&escape($mfile).','.
624: escape($stuff);
625: }
626: }
627: $result=join("&",@results) unless $query;
628: $result.=$customresult;
629: #
630: return $result;
631: } # End of &do_sql_query
632:
633: } # End of scoping curly braces for &process_file and &do_sql_query
634: ########################################################
635: ########################################################
636:
637: =pod
638:
639: =item &logthis
640:
641: Inputs: $message, the message to log
642:
643: Returns: nothing
644:
645: Writes $message to the logfile.
646:
647: =cut
648:
649: ########################################################
650: ########################################################
651: sub logthis {
652: my $message=shift;
653: my $execdir=$perlvar{'lonDaemons'};
1.52 matthew 654: my $fh=IO::File->new(">>$execdir/logs/lonsql.log");
1.51 matthew 655: my $now=time;
656: my $local=localtime($now);
657: print $fh "$local ($$): $message\n";
1.2 harris41 658: }
1.1 harris41 659:
1.2 harris41 660: # -------------------------------------------------- Non-critical communication
1.1 harris41 661:
1.51 matthew 662: ########################################################
663: ########################################################
664:
665: =pod
666:
667: =item &subreply
668:
669: Sends a command to a server. Called only by &reply.
670:
671: Inputs: $cmd,$server
672:
673: Returns: The results of the message or 'con_lost' on error.
674:
675: =cut
676:
677: ########################################################
678: ########################################################
1.2 harris41 679: sub subreply {
680: my ($cmd,$server)=@_;
1.72 albertel 681: my $peerfile="$perlvar{'lonSockDir'}/".$hostname{$server};
1.2 harris41 682: my $sclient=IO::Socket::UNIX->new(Peer =>"$peerfile",
683: Type => SOCK_STREAM,
684: Timeout => 10)
685: or return "con_lost";
1.72 albertel 686: print $sclient "sethost:$server:$cmd\n";
1.2 harris41 687: my $answer=<$sclient>;
688: chomp($answer);
1.51 matthew 689: $answer="con_lost" if (!$answer);
1.2 harris41 690: return $answer;
691: }
1.1 harris41 692:
1.51 matthew 693: ########################################################
694: ########################################################
695:
696: =pod
697:
698: =item &reply
699:
700: Sends a command to a server.
701:
702: Inputs: $cmd,$server
703:
704: Returns: The results of the message or 'con_lost' on error.
705:
706: =cut
707:
708: ########################################################
709: ########################################################
1.2 harris41 710: sub reply {
711: my ($cmd,$server)=@_;
712: my $answer;
713: if ($server ne $perlvar{'lonHostID'}) {
714: $answer=subreply($cmd,$server);
715: if ($answer eq 'con_lost') {
716: $answer=subreply("ping",$server);
717: $answer=subreply($cmd,$server);
718: }
719: } else {
720: $answer='self_reply';
1.33 harris41 721: $answer=subreply($cmd,$server);
1.2 harris41 722: }
723: return $answer;
724: }
1.1 harris41 725:
1.51 matthew 726: ########################################################
727: ########################################################
728:
729: =pod
730:
731: =item &escape
732:
733: Escape special characters in a string.
1.3 harris41 734:
1.51 matthew 735: Inputs: string to escape
736:
737: Returns: The input string with special characters escaped.
738:
739: =cut
740:
741: ########################################################
742: ########################################################
1.3 harris41 743: sub escape {
744: my $str=shift;
745: $str =~ s/(\W)/"%".unpack('H2',$1)/eg;
746: return $str;
747: }
748:
1.51 matthew 749: ########################################################
750: ########################################################
751:
752: =pod
753:
754: =item &unescape
755:
756: Unescape special characters in a string.
1.3 harris41 757:
1.51 matthew 758: Inputs: string to unescape
759:
760: Returns: The input string with special characters unescaped.
761:
762: =cut
763:
764: ########################################################
765: ########################################################
1.3 harris41 766: sub unescape {
767: my $str=shift;
768: $str =~ s/%([a-fA-F0-9][a-fA-F0-9])/pack("C",hex($1))/eg;
769: return $str;
770: }
1.34 harris41 771:
1.51 matthew 772: ########################################################
773: ########################################################
774:
775: =pod
776:
777: =item &ishome
778:
779: Determine if the current machine is the home server for a user.
780: The determination is made by checking the filesystem for the users information.
781:
782: Inputs: $author
783:
784: Returns: 0 - this is not the authors home server, 1 - this is.
785:
786: =cut
787:
788: ########################################################
789: ########################################################
1.34 harris41 790: sub ishome {
791: my $author=shift;
792: $author=~s/\/home\/httpd\/html\/res\/([^\/]*)\/([^\/]*).*/$1\/$2/;
793: my ($udom,$uname)=split(/\//,$author);
794: my $proname=propath($udom,$uname);
795: if (-e $proname) {
796: return 1;
797: } else {
798: return 0;
799: }
800: }
801:
1.51 matthew 802: ########################################################
803: ########################################################
804:
805: =pod
806:
807: =item &propath
808:
809: Inputs: user name, user domain
810:
811: Returns: The full path to the users directory.
812:
813: =cut
814:
815: ########################################################
816: ########################################################
1.34 harris41 817: sub propath {
818: my ($udom,$uname)=@_;
819: $udom=~s/\W//g;
820: $uname=~s/\W//g;
821: my $subdir=$uname.'__';
822: $subdir =~ s/(.)(.)(.).*/$1\/$2\/$3/;
823: my $proname="$perlvar{'lonUsersDir'}/$udom/$subdir/$uname";
824: return $proname;
825: }
1.40 harris41 826:
1.51 matthew 827: ########################################################
828: ########################################################
829:
830: =pod
831:
832: =item &courselog
833:
834: Inputs: $path, $command
835:
836: Returns: unescaped string of values.
837:
838: =cut
839:
840: ########################################################
841: ########################################################
842: sub courselog {
843: my ($path,$command)=@_;
844: my %filters=();
845: foreach (split(/\:/,&unescape($command))) {
846: my ($name,$value)=split(/\=/,$_);
847: $filters{$name}=$value;
848: }
849: my @results=();
850: open(IN,$path.'/activity.log') or return ('file_error');
851: while (my $line=<IN>) {
852: chomp($line);
853: my ($timestamp,$host,$log)=split(/\:/,$line);
854: #
855: # $log has the actual log entries; currently still escaped, and
856: # %26(timestamp)%3a(url)%3a(user)%3a(domain)
857: # then additionally
858: # %3aPOST%3a(name)%3d(value)%3a(name)%3d(value)
859: # or
860: # %3aCSTORE%3a(name)%3d(value)%26(name)%3d(value)
861: #
862: # get delimiter between timestamped entries to be &&&
863: $log=~s/\%26(\d+)\%3a/\&\&\&$1\%3a/g;
864: # now go over all log entries
865: foreach (split(/\&\&\&/,&unescape($log))) {
866: my ($time,$res,$uname,$udom,$action,@values)=split(/\:/,$_);
867: my $values=&unescape(join(':',@values));
868: $values=~s/\&/\:/g;
869: $res=&unescape($res);
870: my $include=1;
871: if (($filters{'username'}) && ($uname ne $filters{'username'}))
872: { $include=0; }
873: if (($filters{'domain'}) && ($udom ne $filters{'domain'}))
874: { $include=0; }
875: if (($filters{'url'}) && ($res!~/$filters{'url'}/))
876: { $include=0; }
877: if (($filters{'start'}) && ($time<$filters{'start'}))
878: { $include=0; }
879: if (($filters{'end'}) && ($time>$filters{'end'}))
880: { $include=0; }
881: if (($filters{'action'} eq 'view') && ($action))
882: { $include=0; }
883: if (($filters{'action'} eq 'submit') && ($action ne 'POST'))
884: { $include=0; }
885: if (($filters{'action'} eq 'grade') && ($action ne 'CSTORE'))
886: { $include=0; }
887: if ($include) {
888: push(@results,($time<1000000000?'0':'').$time.':'.$res.':'.
889: $uname.':'.$udom.':'.
890: $action.':'.$values);
891: }
892: }
893: }
894: close IN;
895: return join('&',sort(@results));
896: }
897:
898: ########################################################
899: ########################################################
900:
901: =pod
902:
903: =item &userlog
904:
905: Inputs: $path, $command
906:
907: Returns: unescaped string of values.
1.40 harris41 908:
1.51 matthew 909: =cut
1.40 harris41 910:
1.51 matthew 911: ########################################################
912: ########################################################
913: sub userlog {
914: my ($path,$command)=@_;
915: my %filters=();
916: foreach (split(/\:/,&unescape($command))) {
917: my ($name,$value)=split(/\=/,$_);
918: $filters{$name}=$value;
919: }
920: my @results=();
921: open(IN,$path.'/activity.log') or return ('file_error');
922: while (my $line=<IN>) {
923: chomp($line);
924: my ($timestamp,$host,$log)=split(/\:/,$line);
925: $log=&unescape($log);
926: my $include=1;
927: if (($filters{'start'}) && ($timestamp<$filters{'start'}))
928: { $include=0; }
929: if (($filters{'end'}) && ($timestamp>$filters{'end'}))
930: { $include=0; }
931: if (($filters{'action'} eq 'log') && ($log!~/^Log/)) { $include=0; }
932: if (($filters{'action'} eq 'check') && ($log!~/^Check/))
933: { $include=0; }
934: if ($include) {
935: push(@results,$timestamp.':'.$log);
936: }
937: }
938: close IN;
939: return join('&',sort(@results));
1.52 matthew 940: }
941:
942: ########################################################
943: ########################################################
944:
945: =pod
946:
947: =item Functions required for forking
948:
949: =over 4
950:
951: =item REAPER
952:
953: REAPER takes care of dead children.
954:
955: =item HUNTSMAN
956:
957: Signal handler for SIGINT.
958:
959: =item HUPSMAN
960:
961: Signal handler for SIGHUP
962:
963: =item DISCONNECT
964:
965: Disconnects from database.
966:
967: =back
968:
969: =cut
970:
971: ########################################################
972: ########################################################
973: sub REAPER { # takes care of dead children
974: $SIG{CHLD} = \&REAPER;
975: my $pid = wait;
976: $children --;
977: &logthis("Child $pid died");
978: delete $children{$pid};
979: }
980:
981: sub HUNTSMAN { # signal handler for SIGINT
982: local($SIG{CHLD}) = 'IGNORE'; # we're going to kill our children
983: kill 'INT' => keys %children;
984: my $execdir=$perlvar{'lonDaemons'};
985: unlink("$execdir/logs/lonsql.pid");
1.59 albertel 986: &logthis("<font color='red'>CRITICAL: Shutting down</font>");
1.52 matthew 987: $unixsock = "mysqlsock";
988: my $port="$perlvar{'lonSockDir'}/$unixsock";
989: unlink($port);
990: exit; # clean up with dignity
991: }
992:
993: sub HUPSMAN { # signal handler for SIGHUP
994: local($SIG{CHLD}) = 'IGNORE'; # we're going to kill our children
995: kill 'INT' => keys %children;
996: close($server); # free up socket
1.59 albertel 997: &logthis("<font color='red'>CRITICAL: Restarting</font>");
1.52 matthew 998: my $execdir=$perlvar{'lonDaemons'};
999: $unixsock = "mysqlsock";
1000: my $port="$perlvar{'lonSockDir'}/$unixsock";
1001: unlink($port);
1002: exec("$execdir/lonsql"); # here we go again
1003: }
1004:
1005: sub DISCONNECT {
1006: $dbh->disconnect or
1.59 albertel 1007: &logthis("<font color='blue'>WARNING: Couldn't disconnect from database ".
1.52 matthew 1008: " $DBI::errstr : $@</font>");
1009: exit;
1.51 matthew 1010: }
1.40 harris41 1011:
1012:
1.51 matthew 1013: =pod
1.40 harris41 1014:
1.51 matthew 1015: =back
1.40 harris41 1016:
1017: =cut
FreeBSD-CVSweb <freebsd-cvsweb@FreeBSD.org>