Project

General

Profile

1
/**
2
 *  '$RCSfile$'
3
 *  Copyright: 2004 Regents of the University of California and the
4
 *             National Center for Ecological Analysis and Synthesis
5
 *
6
 *   '$Author: tao $'
7
 *     '$Date: 2014-10-14 13:44:55 -0700 (Tue, 14 Oct 2014) $'
8
 * '$Revision: 8896 $'
9
 *
10
 * This program is free software; you can redistribute it and/or modify
11
 * it under the terms of the GNU General Public License as published by
12
 * the Free Software Foundation; either version 2 of the License, or
13
 * (at your option) any later version.
14
 *
15
 * This program is distributed in the hope that it will be useful,
16
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
17
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
18
 * GNU General Public License for more details.
19
 *
20
 * You should have received a copy of the GNU General Public License
21
 * along with this program; if not, write to the Free Software
22
 * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA
23
 */
24
package edu.ucsb.nceas.metacat;
25

    
26
import java.sql.PreparedStatement;
27
import java.sql.ResultSet;
28
import java.sql.SQLException;
29
import java.sql.Timestamp;
30
import java.util.ArrayList;
31
import java.util.Date;
32
import java.util.HashMap;
33
import java.util.List;
34
import java.util.Map;
35
import java.util.Vector;
36

    
37
import org.apache.log4j.Logger;
38
import org.dataone.service.types.v1.Identifier;
39
import org.dataone.service.types.v2.Log;
40
import org.dataone.service.types.v2.LogEntry;
41
import org.dataone.service.types.v1.Event;
42
import org.dataone.service.types.v1.NodeReference;
43
import org.dataone.service.types.v1.Subject;
44
import org.dataone.service.util.DateTimeMarshaller;
45

    
46
import edu.ucsb.nceas.metacat.database.DBConnection;
47
import edu.ucsb.nceas.metacat.database.DBConnectionPool;
48
import edu.ucsb.nceas.metacat.database.DatabaseService;
49
import edu.ucsb.nceas.metacat.index.MetacatSolrIndex;
50
import edu.ucsb.nceas.metacat.properties.PropertyService;
51
import edu.ucsb.nceas.metacat.util.DocumentUtil;
52
import edu.ucsb.nceas.utilities.PropertyNotFoundException;
53

    
54
/**
55
 * EventLog is used to intialize and store a log of events that occur in an
56
 * application. The events are registered with the logger as they occur, but
57
 * EventLog writes them to permenant storage when it is most convenient or
58
 * efficient. EventLog is a Singleton as there should always be only one object
59
 * for these logging events.
60
 * 
61
 * TODO: Logging to the database needn't be synchronous with the event.  
62
 * Instead, a separate thread can be launched that periodically sleeps and only
63
 * wakes periodically to see if metacat is idle.  The log event can be cached
64
 * and inserted later when the thread wakes and finds metacat idle.
65
 * 
66
 * TODO: Write a function that archives a part of the log table to an 
67
 * external text file so that the log table doesn't get to big.  This 
68
 * function should be able to be called manually or on a schedule. 
69
 * 
70
 * TODO: Write an access function that returns an XML report for a
71
 * specific subset of events.  Users should be able to query on
72
 * principal, docid/rev, date, event, and possibly other fields.
73
 * 
74
 * @author jones
75
 */
76
public class EventLog
77
{
78
    public static final String DELETE = "delete";
79
    /**
80
     * The single instance of the event log that is always returned.
81
     */
82
    private static EventLog self = null;
83
    private Logger logMetacat = Logger.getLogger(EventLog.class);
84

    
85
    /**
86
     * A private constructor that initializes the class when getInstance() is
87
     * called.
88
     */
89
    private EventLog()
90
    {
91
    }
92

    
93
    /**
94
     * Return the single instance of the event log after initializing it if it
95
     * wasn't previously initialized.
96
     * 
97
     * @return the single EventLog instance
98
     */
99
    public static EventLog getInstance()
100
    {
101
        if (self == null) {
102
            self = new EventLog();
103
        }
104
        return self;
105
    }
106

    
107
    /**
108
     * Log an event of interest to the application. The information logged can
109
     * include basic identification information about the principal or computer
110
     * that initiated the event.
111
     * 
112
     * @param ipAddress the internet protocol address for the event
113
     * @param userAgent the agent making the request
114
	 * @param principal the principal for the event (a username, etc)
115
	 * @param docid the identifier of the document to which the event applies
116
	 * @param event the string code for the event
117
     */
118
    public void log(String ipAddress, String userAgent, String principal, String docid, String event) {
119
        EventLogData logData = new EventLogData(ipAddress, principal, docid, event);
120
        insertLogEntry(logData);
121
        
122
        // update the event information in the index
123
        try {
124
	        String localId = DocumentUtil.getSmartDocId(docid);
125
			int rev = DocumentUtil.getRevisionFromAccessionNumber(docid);
126
			
127
	        String guid = IdentifierManager.getInstance().getGUID(localId, rev);
128
	        Identifier pid = new Identifier();
129
	        pid.setValue(guid);
130
	        
131
	        // submit for indexing
132
	        MetacatSolrIndex.getInstance().submit(pid, null, this.getIndexFields(pid, event), false);
133
	        
134
        } catch (Exception e) {
135
        	logMetacat.error("Could not update event index information", e);
136
        }
137
    }
138
    
139
    public Map<String, List<Object>> getIndexFields(Identifier pid, String event) {
140
    	// update the search index for the event
141
        try {
142
        	
143
        	if (event != null) {
144
        		
145
	        	String fieldName = event + "_count_i";
146
	        	int eventCount = 0;
147
	        	
148
	        	String docid = IdentifierManager.getInstance().getLocalId(pid.getValue());
149
	        	Log eventLog = this.getD1Report(null, null, new String[] {docid}, event, null, null, false, 0, 0);
150
	        	eventCount = eventLog.getTotal();
151
	
152
		        List<Object> values = new ArrayList<Object>();
153
				values.add(eventCount);
154
		        Map<String, List<Object>> fields = new HashMap<String, List<Object>>();
155
		        fields.put(fieldName, values);
156
		        
157
		        return fields;
158
        	}
159
	        
160
        } catch (Exception e) {
161
        	logMetacat.error("Could not update event index information on pid: " + pid.getValue() + " for event: " + event, e);
162
        }
163
        // default if we can't find the event information
164
    	return null;
165

    
166
    }
167
    
168
    /**
169
     * Insert a single log event record to the database.
170
     * 
171
     * @param logData the data to be logged when an event occurs
172
     */
173
    private void insertLogEntry(EventLogData logData)
174
    {
175
        String insertString = "insert into access_log"
176
                + "(ip_address, user_agent, principal, docid, "
177
                + "event, date_logged) "
178
                + "values ( ?, ?, ?, ?, ?, ? )";
179
 
180
        DBConnection dbConn = null;
181
        int serialNumber = -1;
182
        try {
183
            // Get a database connection from the pool
184
            dbConn = DBConnectionPool.getDBConnection("EventLog.insertLogEntry");
185
            serialNumber = dbConn.getCheckOutSerialNumber();
186
            
187
            // Execute the insert statement
188
            PreparedStatement stmt = dbConn.prepareStatement(insertString);
189
            
190
            stmt.setString(1, logData.getIpAddress());
191
            stmt.setString(2, logData.getUserAgent());
192
            stmt.setString(3, logData.getPrincipal());
193
            stmt.setString(4, logData.getDocid());
194
            stmt.setString(5, logData.getEvent());
195
            stmt.setTimestamp(6, new Timestamp(new Date().getTime()));
196
            stmt.executeUpdate();
197
            stmt.close();
198
        } catch (SQLException e) {
199
        	logMetacat.error("Error while logging event to database: " 
200
                    + e.getMessage());
201
        } finally {
202
            // Return database connection to the pool
203
            DBConnectionPool.returnDBConnection(dbConn, serialNumber);
204
        }
205
    }
206
    
207
    /**
208
     * Get a report of the log events that match a set of filters.  The
209
     * filter parameters can be null; log records are subset based on
210
     * non-null filter parameters.
211
     * 
212
     * @param ipAddress the internet protocol address for the event
213
	 * @param principal the principal for the event (a username, etc)
214
	 * @param docid the identifier of the document to which the event applies
215
	 * @param event the string code for the event
216
	 * @param startDate beginning of date range for query
217
	 * @param endDate end of date range for query
218
	 * @return an XML-formatted report of the access log entries
219
     */
220
    public String getReport(String[] ipAddress, String[] principal, String[] docid,
221
            String[] event, Timestamp startDate, Timestamp endDate, boolean anonymous)
222
    {
223
        StringBuffer resultDoc = new StringBuffer();
224
        StringBuffer query = new StringBuffer();
225
        query.append("select entryid, ip_address, user_agent, principal, docid, "
226
            + "event, date_logged from access_log");
227
//                        + ""
228
//                        + "event, date_logged) " + "values (" + "'"
229
//                        + logData.getIpAddress() + "', " + "'"
230
//                        + logData.getPrincipal() + "', " + "'"
231
//                        + logData.getDocid() + "', " + "'" + logData.getEvent()
232
//                        + "', " + " ? " + ")";
233
        if (ipAddress != null || principal != null || docid != null
234
                        || event != null || startDate != null || endDate != null) {
235
            query.append(" where ");
236
        }
237
        boolean clauseAdded = false;
238
        int startIndex = 0;
239
        int endIndex = 0;
240
        
241
        List<String> paramValues = new ArrayList<String>();
242
        if (ipAddress != null) {
243
        	query.append("ip_address in (");
244
        	for (int i = 0; i < ipAddress.length; i++) {
245
        		if (i > 0) {
246
            		query.append(", ");
247
        		}
248
        		query.append("?");
249
        		paramValues.add(ipAddress[i]);
250
        	}
251
        	query.append(") ");
252
            clauseAdded = true;
253
        }
254
        if (principal != null) {
255
        	if (clauseAdded) {
256
                query.append(" and ");
257
            }
258
        	query.append("principal in (");
259
        	for (int i = 0; i < principal.length; i++) {
260
        		if (i > 0) {
261
            		query.append(", ");
262
        		}
263
        		query.append("?");
264
        		paramValues.add(principal[i]);
265
        	}
266
        	query.append(") ");
267
            clauseAdded = true;
268
        }
269
        if (docid != null) {
270
        	if (clauseAdded) {
271
                query.append(" and ");
272
            }
273
        	query.append("docid in (");
274
        	for (int i = 0; i < docid.length; i++) {
275
        		if (i > 0) {
276
            		query.append(", ");
277
        		}
278
        		query.append("?");
279
        		String fullDocid = docid[i];
280
        		// allow docid without revision - look up latest version
281
        		try {
282
        			fullDocid = DocumentUtil.appendRev(fullDocid);
283
        		} catch (Exception e) {
284
					// just warn about this
285
        			logMetacat.warn("Could not check docid for revision: " + fullDocid, e);
286
				}
287
        		paramValues.add(fullDocid);
288
        	}
289
        	query.append(") ");
290
            clauseAdded = true;
291
        }
292
        if (event != null) {
293
        	if (clauseAdded) {
294
                query.append(" and ");
295
            }
296
        	query.append("event in (");
297
        	for (int i = 0; i < event.length; i++) {
298
        		if (i > 0) {
299
            		query.append(", ");
300
        		}
301
        		query.append("?");
302
        		paramValues.add(event[i]);
303
        	}
304
        	query.append(") ");
305
            clauseAdded = true;
306
        }
307
        if (startDate != null) {
308
            if (clauseAdded) {
309
                query.append(" and ");
310
            }
311
            query.append("date_logged >= ?");
312
            clauseAdded = true;
313
            startIndex++;
314
        }
315
        if (endDate != null) {
316
            if (clauseAdded) {
317
                query.append(" and ");
318
            }
319
            query.append("date_logged < ?");
320
            clauseAdded = true;
321
            endIndex = startIndex + 1;
322
        }
323
        DBConnection dbConn = null;
324
        int serialNumber = -1;
325
        try {
326
            // Get a database connection from the pool
327
            dbConn = DBConnectionPool.getDBConnection("EventLog.getReport");
328
            serialNumber = dbConn.getCheckOutSerialNumber();
329

    
330
            // Execute the query statement
331
            PreparedStatement stmt = dbConn.prepareStatement(query.toString());
332
            //set the param values
333
            int parameterIndex = 1;
334
            for (String val: paramValues) {
335
            	stmt.setString(parameterIndex++, val);
336
            }
337
            if (startDate != null) {
338
                stmt.setTimestamp(parameterIndex++, startDate); 
339
            }
340
            if (endDate != null) {
341
            	stmt.setTimestamp(parameterIndex++, endDate);
342
            }
343
            stmt.execute();
344
            ResultSet rs = stmt.getResultSet();
345
            //process the result and return it as an XML document
346
            resultDoc.append("<?xml version=\"1.0\"?>\n");
347
            resultDoc.append("<log>\n");
348
            while (rs.next()) {
349
                resultDoc.append(
350
                		generateXmlRecord(
351
                				rs.getString(1), //id
352
                				anonymous ? "" : rs.getString(2), //ip
353
                				rs.getString(3), //userAgent	
354
                				anonymous ? "" : rs.getString(4), //principal
355
                                rs.getString(5), 
356
                                rs.getString(6), 
357
                                rs.getTimestamp(7)));
358
            }
359
            resultDoc.append("</log>");
360
            stmt.close();
361
        } catch (SQLException e) {
362
        	logMetacat.info("Error while logging event to database: "
363
                            + e.getMessage());
364
        } finally {
365
            // Return database connection to the pool
366
            DBConnectionPool.returnDBConnection(dbConn, serialNumber);
367
        }
368
        return resultDoc.toString();
369
    }
370
    
371
    /**
372
     * A utility method to determine if the given docid was deleted. 
373
     * @param docid the specified docid
374
     * @return true if there is a delete event for the id; false otherwise.
375
     */
376
    public boolean isDeleted(String docid) {
377
        boolean deleted =false;
378
        if(docid != null || !docid.trim().equals("")) {
379
            String[] docids = new String[1];
380
            docids[0] = docid;
381
            String[] events = new String[1];
382
            events[0]= DELETE;
383
            String[] ipAddress = null;
384
            String[] principal = null;
385
            Timestamp startDate = null;
386
            Timestamp endDate = null;
387
            boolean anonymous = false;
388
            
389
            String report =getReport(ipAddress, principal, docids,
390
                     events, startDate, endDate, anonymous);
391
            //System.out.println("the report is "+report);
392
            if(report != null && report.contains("<event>"+DELETE+"</event>") ){
393
                deleted = true;
394
            }
395
        }
396
        return deleted;
397
    }
398
    
399
    public Log getD1Report(String[] ipAddress, String[] principal, String[] docid,
400
            String event, Timestamp startDate, Timestamp endDate, boolean anonymous, Integer start, Integer count)
401
    {
402
        
403
        Log log = new Log();
404
    	
405
    	NodeReference memberNode = new NodeReference();
406
        String nodeId = "localhost";
407
        try {
408
            nodeId = PropertyService.getProperty("dataone.nodeId");
409
        } catch (PropertyNotFoundException e1) {
410
            // TODO Auto-generated catch block
411
            e1.printStackTrace();
412
        }
413
        memberNode.setValue(nodeId);
414
        
415
        String countClause = "select count(*) ";
416
        String fieldsClause = "select " +
417
        		"entryid, " +
418
        		"id.guid as identifier, " +
419
        		"ip_address, " +
420
        		"user_agent, " +
421
        		"principal, " +
422
        		"case " +
423
        		"	when event = 'insert' then 'create' " +
424
        		"	else event " +
425
        		"end as event, " +
426
        		"date_logged ";
427
        
428
        StringBuffer queryWhereClause = new StringBuffer();
429
        queryWhereClause.append(		 
430
        		"from access_log al, identifier id " +
431
        		"where al.docid = id.docid||'.'||id.rev "
432
        );
433
        
434
        boolean clauseAdded = true;
435
        
436
        List<String> paramValues = new ArrayList<String>();
437
        if (ipAddress != null) {
438
        	if (clauseAdded) {
439
                queryWhereClause.append(" and ");
440
            }
441
        	queryWhereClause.append("ip_address in (");
442
        	for (int i = 0; i < ipAddress.length; i++) {
443
        		if (i > 0) {
444
            		queryWhereClause.append(", ");
445
        		}
446
        		queryWhereClause.append("?");
447
        		paramValues.add(ipAddress[i]);
448
        	}
449
        	queryWhereClause.append(") ");
450
            clauseAdded = true;
451
        }
452
        if (principal != null) {
453
        	if (clauseAdded) {
454
                queryWhereClause.append(" and ");
455
            }
456
        	queryWhereClause.append("principal in (");
457
        	for (int i = 0; i < principal.length; i++) {
458
        		if (i > 0) {
459
            		queryWhereClause.append(", ");
460
        		}
461
        		queryWhereClause.append("?");
462
        		paramValues.add(principal[i]);
463
        	}
464
        	queryWhereClause.append(") ");
465
            clauseAdded = true;
466
        }
467
        if (docid != null) {
468
        	if (clauseAdded) {
469
                queryWhereClause.append(" and ");
470
            }
471
        	queryWhereClause.append("al.docid in (");
472
        	for (int i = 0; i < docid.length; i++) {
473
        		if (i > 0) {
474
            		queryWhereClause.append(", ");
475
        		}
476
        		queryWhereClause.append("?");
477
        		paramValues.add(docid[i]);
478
        	}
479
        	queryWhereClause.append(") ");
480
            clauseAdded = true;
481
        }
482
        if (event != null) {
483
        	if (clauseAdded) {
484
                queryWhereClause.append(" and ");
485
            }
486
        	queryWhereClause.append("event in (");
487
    		queryWhereClause.append("?");
488
    		String eventString = event;
489
    		if (eventString.equals(Event.CREATE.xmlValue())) {
490
    			eventString = "insert";
491
    		}
492
    		paramValues.add(eventString);
493
        	queryWhereClause.append(") ");
494
            clauseAdded = true;
495
        }
496
        
497
        if (startDate != null) {
498
            if (clauseAdded) {
499
                queryWhereClause.append(" and ");
500
            }
501
            queryWhereClause.append("date_logged >= ?");
502
            clauseAdded = true;
503
        }
504
        if (endDate != null) {
505
            if (clauseAdded) {
506
                queryWhereClause.append(" and ");
507
            }
508
            queryWhereClause.append("date_logged < ?");
509
            clauseAdded = true;
510
        }
511

    
512
        // order by
513
        String orderByClause = " order by entryid ";
514

    
515
        // select the count
516
        String countQuery = countClause + queryWhereClause.toString();
517
        
518
		// select the fields
519
        String pagedQuery = DatabaseService.getInstance().getDBAdapter().getPagedQuery(fieldsClause + queryWhereClause.toString() + orderByClause, start, count);
520

    
521
        DBConnection dbConn = null;
522
        int serialNumber = -1;
523
        try {
524
            // Get a database connection from the pool
525
            dbConn = DBConnectionPool.getDBConnection("EventLog.getD1Report");
526
            serialNumber = dbConn.getCheckOutSerialNumber();
527

    
528
            // Execute the query statement
529
            PreparedStatement fieldsStmt = dbConn.prepareStatement(pagedQuery);
530
            PreparedStatement countStmt = dbConn.prepareStatement(countQuery);
531

    
532
            //set the param values
533
            int parameterIndex = 1;
534
            for (String val: paramValues) {
535
            	countStmt.setString(parameterIndex, val);
536
            	fieldsStmt.setString(parameterIndex, val);
537
            	parameterIndex++;
538
            }
539
            if (startDate != null) {
540
            	countStmt.setTimestamp(parameterIndex, startDate); 
541
                fieldsStmt.setTimestamp(parameterIndex, startDate); 
542
            	parameterIndex++;
543
            }
544
            if (endDate != null) {
545
            	countStmt.setTimestamp(parameterIndex, endDate);
546
            	fieldsStmt.setTimestamp(parameterIndex, endDate);
547
            	parameterIndex++;
548
            }
549

    
550
            // for the return Log list
551
            List<LogEntry> logs = new Vector<LogEntry>();
552

    
553
            // get the fields form the query
554
            if (count != 0) {
555
	            fieldsStmt.execute();
556
	            ResultSet rs = fieldsStmt.getResultSet();
557
	            //process the result and return it            
558
	            while (rs.next()) {
559
	            	LogEntry logEntry = new LogEntry();
560
	            	logEntry.setEntryId(rs.getString(1));
561
	            	
562
	            	Identifier identifier = new Identifier();
563
	            	identifier.setValue(rs.getString(2));
564
					logEntry.setIdentifier(identifier);
565
	
566
	            	logEntry.setIpAddress(anonymous ? "N/A" : rs.getString(3));
567
	            	String userAgent = "N/A";
568
	            	if (rs.getString(4) != null) {
569
	            		userAgent = rs.getString(4);
570
	            	}
571
	            	logEntry.setUserAgent(userAgent);
572
	            	
573
	            	Subject subject = new Subject();
574
	            	subject.setValue(anonymous ? "N/A" : rs.getString(5));
575
					logEntry.setSubject(subject);
576
					
577
					String logEventString = rs.getString(6);
578
					logEntry.setEvent(logEventString);
579
					logEntry.setDateLogged(rs.getTimestamp(7));
580
					
581
					logEntry.setNodeIdentifier(memberNode);
582
					logs.add(logEntry);
583
	            }
584
	            fieldsStmt.close();
585
            }
586
            
587
            // set what we have
588
            log.setLogEntryList(logs);
589
		    log.setStart(start);
590
		    log.setCount(logs.size());
591
            			
592
			// get total for out query
593
		    int total = 0;
594
            countStmt.execute();
595
            ResultSet countRs = countStmt.getResultSet();
596
            if (countRs.next()) {
597
            	total = countRs.getInt(1);
598
            }
599
            countStmt.close();
600
		    log.setTotal(total);
601

    
602
        } catch (SQLException e) {
603
        	logMetacat.error("Error while getting log events: " + e.getMessage(), e);
604
        } finally {
605
            // Return database connection to the pool
606
            DBConnectionPool.returnDBConnection(dbConn, serialNumber);
607
        }
608
        return log;
609
    }
610
    
611
    /**
612
     * Format each returned log record as an XML structure.
613
     * 
614
     * @param entryId the identifier of the log entry
615
     * @param ipAddress the internet protocol address for the event
616
     * @param the agent making the request
617
	 * @param principal the principal for the event (a username, etc)
618
	 * @param docid the identifier of the document to which the event applies
619
	 * @param event the string code for the event
620
     * @param dateLogged the date on which the event occurred
621
     * @return String containing the formatted XML
622
     */
623
    private String generateXmlRecord(String entryId, String ipAddress, String userAgent,
624
            String principal, String docid, String event, Timestamp dateLogged)
625
    {
626
        StringBuffer rec = new StringBuffer();
627
        rec.append("<logEntry>");
628
        rec.append(generateXmlElement("entryid", entryId));
629
        rec.append(generateXmlElement("ipAddress", ipAddress));
630
        rec.append(generateXmlElement("userAgent", userAgent));
631
        rec.append(generateXmlElement("principal", principal));
632
        rec.append(generateXmlElement("docid", docid));
633
        rec.append(generateXmlElement("event", event));
634
        rec.append(generateXmlElement("dateLogged", DateTimeMarshaller.serializeDateToUTC(dateLogged)));
635
        rec.append("</logEntry>\n");
636

    
637
        return rec.toString();
638
    }
639
    
640
    /**
641
     * Return an XML formatted element for a given name/value pair.
642
     * 
643
     * @param name the name of the xml element
644
     * @param value the content of the xml element
645
     * @return the formatted XML element as a String
646
     */
647
    private String generateXmlElement(String name, String value)
648
    {
649
        return "<" + name + ">" + value + "</" + name + ">";
650
    }
651
}
(34-34/63)