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