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