Annotation of loncom/lonsql, revision 1.96
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.96 ! raeburn 6: # $Id: lonsql,v 1.95 2015/08/09 21:43: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: =cut
99:
100: use strict;
1.36 www 101:
1.42 harris41 102: use lib '/home/httpd/lib/perl/';
1.77 albertel 103: use LONCAPA;
1.42 harris41 104: use LONCAPA::Configuration;
1.58 matthew 105: use LONCAPA::lonmetadata();
1.81 albertel 106: use Apache::lonnet;
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 DBI;
1.51 matthew 113: use File::Find;
1.62 raeburn 114: use localenroll;
1.78 raeburn 115: use GDBM_File;
1.51 matthew 116:
117: ########################################################
118: ########################################################
119:
120: =pod
121:
1.93 raeburn 122: =over 4
123:
1.51 matthew 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:
1.91 raeburn 236: open(SMP,">$perlvar{'lonDocRoot'}/lon-status/mysql.txt");
1.57 www 237: print SMP 'time='.time.'&mysql=defunct'."\n";
238: close(SMP);
239:
1.51 matthew 240: exit 1;
241: } else {
1.91 raeburn 242: unlink("$perlvar{'lonDocRoot'}/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') {
1.88 raeburn 445: my ($srchby,$srchtype,$srchterm);
446: if ((&unescape($arg1) eq $searchdomain) &&
447: ($arg2 =~ /\%\%/)) {
448: ($srchby,$srchtype) =
449: map {&unescape($_);} (split(/\%\%/,$arg2));
1.90 raeburn 450: $srchterm = &unescape($arg3);
1.82 raeburn 451: } else {
1.88 raeburn 452: ($srchby,$srchtype,$srchterm) =
453: map {&unescape($_);} ($arg1,$arg2,$arg3);
1.82 raeburn 454: }
1.88 raeburn 455: $result = &do_user_search($searchdomain,$srchby,
456: $srchtype,$srchterm);
1.84 albertel 457: } elsif ($query eq 'instdirsearch') {
458: $result = &do_inst_dir_search($searchdomain,$arg1,$arg2,$arg3);
1.89 raeburn 459: } elsif ($query eq 'getinstuser') {
460: $result = &get_inst_user($searchdomain,$arg1,$arg2);
1.94 raeburn 461: } elsif ($query eq 'getmultinstusers') {
462: $result = &get_multiple_instusers($searchdomain,$arg3);
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.82 raeburn 481: } elsif ($query eq 'allusers') {
482: my ($uname,$udom) = map {&unescape($_);} ($arg1,$arg2);
483: my %userdata;
484: my (@data) = split(/\%\%/,$arg3);
485: foreach my $item (@data) {
486: my ($key,$value) = split(/=/,$item);
487: $userdata{$key} = &unescape($value);
488: }
489: $userdata{'username'} = $uname;
490: $userdata{'domain'} = $udom;
491: $result = &allusers_table_update($query,$uname,$udom,\%userdata);
1.51 matthew 492: } else {
1.96 ! raeburn 493: # Sanity checking of $query needed.
1.51 matthew 494: # Do an sql query
1.92 raeburn 495: $result = &do_sql_query($query,$arg1,$arg2,$arg3,$searchdomain);
1.51 matthew 496: }
1.50 matthew 497: # result does not need to be escaped because it has already been
498: # escaped.
499: #$result=&escape($result);
1.81 albertel 500: &Apache::lonnet::reply("queryreply:$queryid:$result",$conserver);
1.1 harris41 501: }
502: # tidy up gracefully and finish
1.51 matthew 503: #
504: # close the database handle
1.2 harris41 505: $dbh->disconnect
1.59 albertel 506: or &logthis("<font color='blue'>WARNING: Couldn't disconnect".
1.51 matthew 507: " from database $DBI::errstr : $@</font>");
1.1 harris41 508: # this exit is VERY important, otherwise the child will become
509: # a producer of more and more children, forking yourself into
510: # process death.
511: exit;
512: }
1.2 harris41 513: }
1.1 harris41 514:
1.88 raeburn 515: sub do_user_search {
516: my ($domain,$srchby,$srchtype,$srchterm) = @_;
517: my $result;
518: my $quoted_dom = $dbh->quote( $domain );
519: my ($query,$quoted_srchterm,@fields);
520: my ($table_columns,$table_indices) =
521: &LONCAPA::lonmetadata::describe_metadata_storage('allusers');
522: foreach my $coldata (@{$table_columns}) {
523: push(@fields,$coldata->{'name'});
524: }
525: my $fieldlist = join(',',@fields);
526: $query = "SELECT $fieldlist FROM allusers WHERE (domain = $quoted_dom AND ";
527: if ($srchby eq 'lastfirst') {
528: my ($fraglast,$fragfirst) = split(/,/,$srchterm);
529: $fragfirst =~ s/^\s+//;
530: $fraglast =~ s/\s+$//;
531: if ($srchtype eq 'exact') {
532: $query .= 'lastname = '.$dbh->quote($fraglast).
533: ' AND firstname = '.$dbh->quote($fragfirst);
534: } elsif ($srchtype eq 'begins') {
535: $query .= 'lastname LIKE '.$dbh->quote($fraglast.'%').
536: ' AND firstname LIKE '.$dbh->quote($fragfirst.'%');
537: } else {
538: $query .= 'lastname LIKE '.$dbh->quote('%'.$fraglast.'%').
539: ' AND firstname LIKE '.$dbh->quote('%'.$fragfirst.'%');
540: }
541: } else {
542: my %srchfield = (
543: uname => 'username',
544: lastname => 'lastname',
1.96 ! raeburn 545: email => 'permanentemail',
1.88 raeburn 546: );
1.96 ! raeburn 547: if (exists($srchfield{$srchby})) {
! 548: if ($srchtype eq 'exact') {
! 549: $query .= $srchfield{$srchby}.' = '.$dbh->quote($srchterm);
! 550: } elsif ($srchtype eq 'begins') {
! 551: $query .= $srchfield{$srchby}.' LIKE '.$dbh->quote($srchterm.'%');
! 552: } else {
! 553: $query .= $srchfield{$srchby}.' LIKE '.$dbh->quote('%'.$srchterm.'%');
! 554: }
1.88 raeburn 555: } else {
1.96 ! raeburn 556: &logthis('<font color="blue">'.
! 557: 'WARNING: Invalid srchby: '.$srchby.'</font>');
! 558: return $result;
1.88 raeburn 559: }
560: }
561: $query .= ") ORDER BY username ";
562: my $sth = $dbh->prepare($query);
563: if ($sth->execute()) {
564: my @results;
565: while (my @row = $sth->fetchrow_array) {
566: my @items;
567: for (my $i=0; $i<@row; $i++) {
568: push(@items,&escape($fields[$i]).'='.&escape($row[$i]));
569: }
570: my $userstr = join(':', @items);
571: push(@results,&escape($userstr));
572: }
573: $sth->finish;
574: $result = join('&',@results);
575: } else {
576: &logthis('<font color="blue">'.
577: 'WARNING: Could not retrieve from database:'.
578: $sth->errstr().'</font>');
579: }
580: return $result;
581: }
582:
1.84 albertel 583: sub do_inst_dir_search {
584: my ($domain,$srchby,$srchterm,$srchtype) = @_;
585: $srchby = &unescape($srchby);
586: $srchterm = &unescape($srchterm);
587: $srchtype = &unescape($srchtype);
588: my (%instusers,%instids,$result,$response);
589: eval {
590: local($SIG{__DIE__})='DEFAULT';
591: $result=&localenroll::get_userinfo($domain,undef,undef,\%instusers,
592: \%instids,undef,$srchby,$srchterm,
593: $srchtype);
594: };
595: if ($result eq 'ok') {
596: if (%instusers) {
597: foreach my $key (keys(%instusers)) {
598: my $usrstr = &Apache::lonnet::freeze_escape($instusers{$key});
599: $response .=&escape(&escape($key).'='.$usrstr).'&';
600: }
601: }
602: $response=~s/\&$//;
1.87 raeburn 603: } else {
604: $response = 'unavailable';
1.84 albertel 605: }
606: return $response;
607: }
608:
1.89 raeburn 609: sub get_inst_user {
610: my ($domain,$uname,$id) = @_;
611: $uname = &unescape($uname);
612: $id = &unescape($id);
613: my (%instusers,%instids,$result,$response);
614: eval {
615: local($SIG{__DIE__})='DEFAULT';
616: $result=&localenroll::get_userinfo($domain,$uname,$id,\%instusers,
617: \%instids);
618: };
619: if ($result eq 'ok') {
620: if (keys(%instusers) > 0) {
621: foreach my $key (keys(%instusers)) {
622: my $usrstr = &Apache::lonnet::freeze_escape($instusers{$key});
623: $response .= &escape(&escape($key).'='.$usrstr).'&';
624: }
625: }
626: $response=~s/\&$//;
627: } else {
628: $response = 'unavailable';
629: }
630: return $response;
631: }
632:
1.94 raeburn 633: sub get_multiple_instusers {
634: my ($domain,$data) = @_;
635: my ($type,$users) = split(/=/,$data,2);
636: my $requested = &Apache::lonnet::thaw_unescape($users);
637: my $response;
638: if (ref($requested) eq 'HASH') {
639: my (%instusers,%instids,$result);
640: eval {
641: local($SIG{__DIE__})='DEFAULT';
642: $result=&localenroll::get_multusersinfo($domain,$type,$requested,\%instusers,
643: \%instids);
644: };
645: if ($@) {
646: $response = 'error';
647: } elsif ($result eq 'ok') {
1.95 raeburn 648: $response = $result;
1.94 raeburn 649: if (keys(%instusers)) {
1.95 raeburn 650: $response .= '='.&Apache::lonnet::freeze_escape(\%instusers);
1.94 raeburn 651: }
1.95 raeburn 652: } elsif ($result eq 'unavailable') {
653: $response = $result;
1.94 raeburn 654: }
655: } else {
656: $response = 'invalid';
657: }
658: return $response;
659: }
660:
1.51 matthew 661: ########################################################
662: ########################################################
663:
664: =pod
665:
666: =item &do_sql_query
667:
668: Runs an sql metadata table query.
669:
670: Inputs: $query, $custom, $customshow
671:
672: Returns: A string containing escaped results.
673:
674: =cut
675:
676: ########################################################
677: ########################################################
678: {
679: my @metalist;
680:
681: sub process_file {
682: if ( -e $_ && # file exists
683: -f $_ && # and is a normal file
684: /\.meta$/ && # ends in meta
685: ! /^.+\.\d+\.[^\.]+\.meta$/ # is not a previous version
686: ) {
687: push(@metalist,$File::Find::name);
688: }
689: }
690:
691: sub do_sql_query {
1.92 raeburn 692: my ($query,$custom,$customshow,$domainstr,$searchdomain) = @_;
1.74 www 693:
694: #
695: # limit to searchdomain if given and table is metadata
696: #
1.92 raeburn 697: if ($domainstr && ($query=~/FROM metadata/)) {
698: my $havingstr;
699: $domainstr = &unescape($domainstr);
700: if ($domainstr =~ /,/) {
701: foreach my $dom (split(/,/,$domainstr)) {
702: if ($dom =~ /^$LONCAPA::domain_re$/) {
703: $havingstr .= 'domain="'.$dom.'" OR ';
704: }
705: }
706: $havingstr =~ s/ OR $//;
707: } else {
708: if ($domainstr =~ /^$LONCAPA::domain_re$/) {
709: $havingstr = 'domain="'.$domainstr.'"';
710: }
711: }
712: if ($havingstr) {
713: $query.=' HAVING ('.$havingstr.')';
714: }
715: } elsif (($searchdomain) && ($query=~/FROM metadata/)) {
1.74 www 716: $query.=' HAVING (domain="'.$searchdomain.'")';
717: }
718: # &logthis('doing query ('.$searchdomain.')'.$query);
719:
720:
721:
1.51 matthew 722: $custom = &unescape($custom);
723: $customshow = &unescape($customshow);
724: #
725: @metalist = ();
726: #
727: my $result = '';
728: my @results = ();
729: my @files;
730: my $subsetflag=0;
731: #
732: if ($query) {
733: #prepare and execute the query
734: my $sth = $dbh->prepare($query);
735: unless ($sth->execute()) {
1.59 albertel 736: &logthis('<font color="blue">'.
1.58 matthew 737: 'WARNING: Could not retrieve from database:'.
738: $sth->errstr().'</font>');
1.51 matthew 739: } else {
740: my $aref=$sth->fetchall_arrayref;
741: foreach my $row (@$aref) {
742: push @files,@{$row}[3] if ($custom or $customshow);
743: my @b=map { &escape($_); } @$row;
744: push @results,join(",", @b);
745: # Build up the @files array with the LON-CAPA urls
746: # of the resources.
747: }
748: }
749: }
750: # do custom metadata searching here and build into result
751: return join("&",@results) if (! ($custom or $customshow));
752: # Only get here if there is a custom query or custom show request
753: &logthis("Doing custom query for $custom");
754: if ($query) {
755: @metalist=map {
756: $perlvar{'lonDocRoot'}.$_.'.meta';
757: } @files;
758: } else {
759: my $dir = "$perlvar{'lonDocRoot'}/res/$perlvar{'lonDefDomain'}";
760: @metalist=();
761: opendir(RESOURCES,$dir);
762: my @homeusers=grep {
763: &ishome($dir.'/'.$_);
764: } grep {!/^\.\.?$/} readdir(RESOURCES);
765: closedir RESOURCES;
766: # Define the
767: foreach my $user (@homeusers) {
768: find (\&process_file,$dir.'/'.$user);
769: }
770: }
771: # if file is indicated in sql database and
772: # not part of sql-relevant query, do not pattern match.
773: #
774: # if file is not in sql database, output error.
775: #
776: # if file is indicated in sql database and is
777: # part of query result list, then do the pattern match.
778: my $customresult='';
779: my @results;
780: foreach my $metafile (@metalist) {
1.81 albertel 781: open(my $fh,$metafile);
1.51 matthew 782: my @lines=<$fh>;
783: my $stuff=join('',@lines);
784: if ($stuff=~/$custom/s) {
785: foreach my $f ('abstract','author','copyright',
786: 'creationdate','keywords','language',
787: 'lastrevisiondate','mime','notes',
788: 'owner','subject','title') {
789: $stuff=~s/\n?\<$f[^\>]*\>.*?<\/$f[^\>]*\>\n?//s;
790: }
791: my $mfile=$metafile;
792: my $docroot=$perlvar{'lonDocRoot'};
793: $mfile=~s/^$docroot//;
794: $mfile=~s/\.meta$//;
795: unless ($query) {
796: my $q2="SELECT * FROM metadata WHERE url ".
797: " LIKE BINARY '?'";
798: my $sth = $dbh->prepare($q2);
799: $sth->execute($mfile);
800: my $aref=$sth->fetchall_arrayref;
801: foreach my $a (@$aref) {
802: my @b=map { &escape($_)} @$a;
803: push @results,join(",", @b);
804: }
805: }
806: # &logthis("found: $stuff");
807: $customresult.='&custom='.&escape($mfile).','.
808: escape($stuff);
809: }
810: }
811: $result=join("&",@results) unless $query;
812: $result.=$customresult;
813: #
814: return $result;
815: } # End of &do_sql_query
816:
817: } # End of scoping curly braces for &process_file and &do_sql_query
1.78 raeburn 818:
819: sub portfolio_table_update {
820: my ($query,$arg1,$arg2,$arg3) = @_;
821: my %tablenames = (
822: 'portfolio' => 'portfolio_metadata',
823: 'access' => 'portfolio_access',
824: 'addedfields' => 'portfolio_addedfields',
825: );
826: my $result = 'ok';
827: my $tablechk = &check_table($query);
828: if ($tablechk == 0) {
829: my $request =
830: &LONCAPA::lonmetadata::create_metadata_storage($query,$query);
831: $dbh->do($request);
832: if ($dbh->err) {
833: &logthis("create $query".
834: " ERROR: ".$dbh->errstr);
835: $result = 'error';
836: }
837: }
838: if ($result eq 'ok') {
1.79 raeburn 839: my ($uname,$udom,$group) = split(/:/,&unescape($arg1));
1.78 raeburn 840: my $file_name = &unescape($arg2);
1.79 raeburn 841: my $action = $arg3;
1.78 raeburn 842: my $is_course = 0;
843: if ($group ne '') {
844: $is_course = 1;
845: }
846: my $urlstart = '/uploaded/'.$udom.'/'.$uname;
847: my $pathstart = &propath($udom,$uname).'/userfiles';
848: my ($fullpath,$url);
849: if ($is_course) {
850: $fullpath = $pathstart.'/groups/'.$group.'/portfolio'.
851: $file_name;
852: $url = $urlstart.'/groups/'.$group.'/portfolio'.$file_name;
853: } else {
854: $fullpath = $pathstart.'/portfolio'.$file_name;
855: $url = $urlstart.'/portfolio'.$file_name;
856: }
857: if ($query eq 'portfolio_metadata') {
1.79 raeburn 858: if ($action eq 'delete') {
859: my %loghash = &LONCAPA::lonmetadata::process_portfolio_metadata($dbh,undef,\%tablenames,$url,$fullpath,$is_course,$udom,$uname,$group,'update');
860: } elsif (-e $fullpath.'.meta') {
1.78 raeburn 861: my %loghash = &LONCAPA::lonmetadata::process_portfolio_metadata($dbh,undef,\%tablenames,$url,$fullpath,$is_course,$udom,$uname,$group,'update');
862: if (keys(%loghash) > 0) {
863: &portfolio_logging(%loghash);
864: }
865: }
866: } elsif ($query eq 'portfolio_access') {
1.79 raeburn 867: my %access = &get_access_hash($uname,$udom,$group.$file_name);
1.78 raeburn 868: my %loghash =
869: &LONCAPA::lonmetadata::process_portfolio_access_data($dbh,undef,
870: \%tablenames,$url,$fullpath,\%access,'update');
871: if (keys(%loghash) > 0) {
872: &portfolio_logging(%loghash);
873: } else {
874: my $available = 0;
875: foreach my $key (keys(%access)) {
876: my ($num,$scope,$end,$start) =
877: ($key =~ /^([^:]+):([a-z]+)_(\d*)_?(\d*)$/);
878: if ($scope eq 'public' || $scope eq 'guest') {
879: $available = 1;
880: last;
881: }
882: }
883: if ($available) {
884: # Retrieve current values
885: my $condition = 'url='.$dbh->quote("$url");
886: my ($error,$row) =
887: &LONCAPA::lonmetadata::lookup_metadata($dbh,$condition,undef,
888: 'portfolio_metadata');
889: if (!$error) {
890: if (!(ref($row->[0]) eq 'ARRAY')) {
891: my %loghash =
892: &LONCAPA::lonmetadata::process_portfolio_metadata($dbh,undef,
893: \%tablenames,$url,$fullpath,$is_course,$udom,$uname,$group);
894: if (keys(%loghash) > 0) {
895: &portfolio_logging(%loghash);
896: }
897: }
898: }
899: }
900: }
901: }
902: }
903: return $result;
904: }
905:
906: sub get_access_hash {
907: my ($uname,$udom,$file) = @_;
908: my $hashref = &tie_user_hash($udom,$uname,'file_permissions',
909: &GDBM_READER());
910: my %curr_perms;
911: my %access;
912: if ($hashref) {
913: while (my ($key,$value) = each(%$hashref)) {
914: $key = &unescape($key);
915: next if ($key =~ /^error: 2 /);
1.81 albertel 916: $curr_perms{$key}=&Apache::lonnet::thaw_unescape($value);
1.78 raeburn 917: }
918: if (!&untie_user_hash($hashref)) {
919: &logthis("error: ".($!+0)." untie (GDBM) Failed");
920: }
921: } else {
922: &logthis("error: ".($!+0)." tie (GDBM) Failed");
923: }
924: if (keys(%curr_perms) > 0) {
925: if (ref($curr_perms{$file."\0".'accesscontrol'}) eq 'HASH') {
926: foreach my $acl (keys(%{$curr_perms{$file."\0".'accesscontrol'}})) {
927: $access{$acl} = $curr_perms{$file."\0".$acl};
928: }
929: }
930: }
931: return %access;
932: }
933:
1.82 raeburn 934: sub allusers_table_update {
935: my ($query,$uname,$udom,$userdata) = @_;
936: my %tablenames = (
937: 'allusers' => 'allusers',
938: );
939: my $result = 'ok';
940: my $tablechk = &check_table($query);
941: if ($tablechk == 0) {
942: my $request =
943: &LONCAPA::lonmetadata::create_metadata_storage($query,$query);
944: $dbh->do($request);
945: if ($dbh->err) {
946: &logthis("create $query".
947: " ERROR: ".$dbh->errstr);
948: $result = 'error';
949: }
950: }
951: if ($result eq 'ok') {
952: my %loghash =
953: &LONCAPA::lonmetadata::process_allusers_data($dbh,undef,
954: \%tablenames,$uname,$udom,$userdata,'update');
955: foreach my $key (keys(%loghash)) {
956: &logthis($loghash{$key});
957: }
958: }
959: return $result;
960: }
961:
1.78 raeburn 962: ###########################################
963: sub check_table {
964: my ($table_id) = @_;
965: my $sth=$dbh->prepare('SHOW TABLES');
966: $sth->execute();
967: my $aref = $sth->fetchall_arrayref;
968: $sth->finish();
969: if ($sth->err()) {
970: &logthis("fetchall_arrayref after SHOW TABLES".
971: " ERROR: ".$sth->errstr);
972: return undef;
973: }
974: my $result = 0;
975: foreach my $table (@{$aref}) {
976: if ($table->[0] eq $table_id) {
977: $result = 1;
978: last;
979: }
980: }
981: return $result;
982: }
983:
984: ###########################################
985:
986: sub portfolio_logging {
987: my (%portlog) = @_;
988: foreach my $key (keys(%portlog)) {
989: if (ref($portlog{$key}) eq 'HASH') {
990: foreach my $item (keys(%{$portlog{$key}})) {
991: &logthis($portlog{$key}{$item});
992: }
993: }
994: }
995: }
996:
997:
1.51 matthew 998: ########################################################
999: ########################################################
1000:
1001: =pod
1002:
1003: =item &logthis
1004:
1005: Inputs: $message, the message to log
1006:
1007: Returns: nothing
1008:
1009: Writes $message to the logfile.
1010:
1011: =cut
1012:
1013: ########################################################
1014: ########################################################
1015: sub logthis {
1016: my $message=shift;
1017: my $execdir=$perlvar{'lonDaemons'};
1.81 albertel 1018: open(my $fh,">>$execdir/logs/lonsql.log");
1.51 matthew 1019: my $now=time;
1020: my $local=localtime($now);
1021: print $fh "$local ($$): $message\n";
1.2 harris41 1022: }
1.1 harris41 1023:
1.51 matthew 1024: ########################################################
1025: ########################################################
1026:
1027: =pod
1028:
1029: =item &ishome
1030:
1031: Determine if the current machine is the home server for a user.
1032: The determination is made by checking the filesystem for the users information.
1033:
1034: Inputs: $author
1035:
1036: Returns: 0 - this is not the authors home server, 1 - this is.
1037:
1038: =cut
1039:
1040: ########################################################
1041: ########################################################
1.34 harris41 1042: sub ishome {
1043: my $author=shift;
1044: $author=~s/\/home\/httpd\/html\/res\/([^\/]*)\/([^\/]*).*/$1\/$2/;
1045: my ($udom,$uname)=split(/\//,$author);
1046: my $proname=propath($udom,$uname);
1047: if (-e $proname) {
1048: return 1;
1049: } else {
1050: return 0;
1051: }
1052: }
1053:
1.51 matthew 1054: ########################################################
1055: ########################################################
1056:
1057: =pod
1058:
1059: =item &courselog
1060:
1061: Inputs: $path, $command
1062:
1063: Returns: unescaped string of values.
1064:
1065: =cut
1066:
1067: ########################################################
1068: ########################################################
1069: sub courselog {
1070: my ($path,$command)=@_;
1071: my %filters=();
1072: foreach (split(/\:/,&unescape($command))) {
1073: my ($name,$value)=split(/\=/,$_);
1074: $filters{$name}=$value;
1075: }
1076: my @results=();
1077: open(IN,$path.'/activity.log') or return ('file_error');
1078: while (my $line=<IN>) {
1079: chomp($line);
1080: my ($timestamp,$host,$log)=split(/\:/,$line);
1081: #
1082: # $log has the actual log entries; currently still escaped, and
1083: # %26(timestamp)%3a(url)%3a(user)%3a(domain)
1084: # then additionally
1085: # %3aPOST%3a(name)%3d(value)%3a(name)%3d(value)
1086: # or
1087: # %3aCSTORE%3a(name)%3d(value)%26(name)%3d(value)
1088: #
1089: # get delimiter between timestamped entries to be &&&
1090: $log=~s/\%26(\d+)\%3a/\&\&\&$1\%3a/g;
1091: # now go over all log entries
1092: foreach (split(/\&\&\&/,&unescape($log))) {
1093: my ($time,$res,$uname,$udom,$action,@values)=split(/\:/,$_);
1094: my $values=&unescape(join(':',@values));
1095: $values=~s/\&/\:/g;
1096: $res=&unescape($res);
1097: my $include=1;
1098: if (($filters{'username'}) && ($uname ne $filters{'username'}))
1099: { $include=0; }
1100: if (($filters{'domain'}) && ($udom ne $filters{'domain'}))
1101: { $include=0; }
1102: if (($filters{'url'}) && ($res!~/$filters{'url'}/))
1103: { $include=0; }
1104: if (($filters{'start'}) && ($time<$filters{'start'}))
1105: { $include=0; }
1106: if (($filters{'end'}) && ($time>$filters{'end'}))
1107: { $include=0; }
1108: if (($filters{'action'} eq 'view') && ($action))
1109: { $include=0; }
1110: if (($filters{'action'} eq 'submit') && ($action ne 'POST'))
1111: { $include=0; }
1112: if (($filters{'action'} eq 'grade') && ($action ne 'CSTORE'))
1113: { $include=0; }
1114: if ($include) {
1115: push(@results,($time<1000000000?'0':'').$time.':'.$res.':'.
1116: $uname.':'.$udom.':'.
1117: $action.':'.$values);
1118: }
1119: }
1120: }
1121: close IN;
1122: return join('&',sort(@results));
1123: }
1124:
1125: ########################################################
1126: ########################################################
1127:
1128: =pod
1129:
1130: =item &userlog
1131:
1132: Inputs: $path, $command
1133:
1134: Returns: unescaped string of values.
1.40 harris41 1135:
1.51 matthew 1136: =cut
1.40 harris41 1137:
1.51 matthew 1138: ########################################################
1139: ########################################################
1140: sub userlog {
1141: my ($path,$command)=@_;
1142: my %filters=();
1143: foreach (split(/\:/,&unescape($command))) {
1144: my ($name,$value)=split(/\=/,$_);
1145: $filters{$name}=$value;
1146: }
1147: my @results=();
1148: open(IN,$path.'/activity.log') or return ('file_error');
1149: while (my $line=<IN>) {
1150: chomp($line);
1151: my ($timestamp,$host,$log)=split(/\:/,$line);
1152: $log=&unescape($log);
1153: my $include=1;
1154: if (($filters{'start'}) && ($timestamp<$filters{'start'}))
1155: { $include=0; }
1156: if (($filters{'end'}) && ($timestamp>$filters{'end'}))
1157: { $include=0; }
1.80 raeburn 1158: if (($filters{'action'} eq 'Role') && ($log !~/^Role/))
1159: { $include=0; }
1.51 matthew 1160: if (($filters{'action'} eq 'log') && ($log!~/^Log/)) { $include=0; }
1161: if (($filters{'action'} eq 'check') && ($log!~/^Check/))
1162: { $include=0; }
1163: if ($include) {
1.80 raeburn 1164: push(@results,$timestamp.':'.$host.':'.&escape($log));
1.51 matthew 1165: }
1166: }
1167: close IN;
1168: return join('&',sort(@results));
1.52 matthew 1169: }
1170:
1171: ########################################################
1172: ########################################################
1173:
1174: =pod
1175:
1176: =item Functions required for forking
1177:
1178: =over 4
1179:
1180: =item REAPER
1181:
1182: REAPER takes care of dead children.
1183:
1184: =item HUNTSMAN
1185:
1186: Signal handler for SIGINT.
1187:
1188: =item HUPSMAN
1189:
1190: Signal handler for SIGHUP
1191:
1192: =item DISCONNECT
1193:
1194: Disconnects from database.
1195:
1196: =back
1197:
1198: =cut
1199:
1200: ########################################################
1201: ########################################################
1202: sub REAPER { # takes care of dead children
1203: $SIG{CHLD} = \&REAPER;
1204: my $pid = wait;
1205: $children --;
1206: &logthis("Child $pid died");
1207: delete $children{$pid};
1208: }
1209:
1210: sub HUNTSMAN { # signal handler for SIGINT
1211: local($SIG{CHLD}) = 'IGNORE'; # we're going to kill our children
1212: kill 'INT' => keys %children;
1213: my $execdir=$perlvar{'lonDaemons'};
1214: unlink("$execdir/logs/lonsql.pid");
1.59 albertel 1215: &logthis("<font color='red'>CRITICAL: Shutting down</font>");
1.52 matthew 1216: $unixsock = "mysqlsock";
1217: my $port="$perlvar{'lonSockDir'}/$unixsock";
1218: unlink($port);
1219: exit; # clean up with dignity
1220: }
1221:
1222: sub HUPSMAN { # signal handler for SIGHUP
1223: local($SIG{CHLD}) = 'IGNORE'; # we're going to kill our children
1224: kill 'INT' => keys %children;
1225: close($server); # free up socket
1.59 albertel 1226: &logthis("<font color='red'>CRITICAL: Restarting</font>");
1.52 matthew 1227: my $execdir=$perlvar{'lonDaemons'};
1228: $unixsock = "mysqlsock";
1229: my $port="$perlvar{'lonSockDir'}/$unixsock";
1230: unlink($port);
1231: exec("$execdir/lonsql"); # here we go again
1232: }
1233:
1234: sub DISCONNECT {
1235: $dbh->disconnect or
1.59 albertel 1236: &logthis("<font color='blue'>WARNING: Couldn't disconnect from database ".
1.52 matthew 1237: " $DBI::errstr : $@</font>");
1238: exit;
1.51 matthew 1239: }
1.40 harris41 1240:
1241:
1.51 matthew 1242: =pod
1.40 harris41 1243:
1.51 matthew 1244: =back
1.40 harris41 1245:
1246: =cut
FreeBSD-CVSweb <freebsd-cvsweb@FreeBSD.org>