Extending FindBugs: Creating Our Detector Plugin to Find Unclosed SolrQueryRequest

Recently, we found a bug in our Solr related project. Basically the problem is that:
1. we create a SolrQueryRequest but forget to close it when it is no longer needed.
2. We call SolrCore.getSearcher(), but forgot to decref the RefCounted.
This will cause one SolrIndexSearcher(thus its various kinds of cache) left unclosed every time we run a commit, at last will cause OutOfMemoryError.
RefCounted refCounted = req.getCore().getSearcher();
Solr RefCounted: Don't forget to close SolrQueryRequest or decref solrCore.getSearcher
After realized this bug, we searched our code to fix all this kind of bugs. But how we can prevent this same kind of error happens again in the future.

This make me to think to write a findbugs plugin to detect and report this kind of bug. The following is how to do this.
Test-Driven: How to test our findbugs detector

When we learn code or write code that we are not familiar, the best way is to write code, test it, make change and test it again.
So it's important to know how to write test code to test our detector.

Fortunately, there is project: test-driven-detectors4findbugs in github which lets us write test code for our detector easily.
Test Driven Detectors 4 FindBugsIt is for FindBugs 1.3.9, we need make some small change to make it work with FindBugs 2.x. I forked the project and make it work with FindBugs 2.x, and put it at Github.

The following is the test code for NotClosedRequestDetector:


public class NotClosedRequestDetectorTester {
 @Test public void demoDecrefRefCountedSearcher() throws Exception {
  BugReporter bugReporter = DetectorAssert.bugReporterForTesting();
  NotClosedRequestDetector detector = new NotClosedRequestDetector(
    bugReporter);

  DetectorAssert.assertNoBugsReported(DemoClosedSolrRequest.class,
    detector, bugReporter);
 }
 @Test public void demoUnClosedSolrRequest() throws Exception {
  BugReporter bugReporter = DetectorAssert.bugReporterForTesting();
  NotClosedRequestDetector detector = new NotClosedRequestDetector(
    bugReporter);

  DetectorAssert.assertBugReported(DemoUnClosedSolrRequest.class,
    detector, bugReporter);
  printBugReporter(detector, bugReporter);

  assertFindbug(bugReporter,
    NotClosedRequestDetector.NOT_CLOSE_SOLR_REQUEST);
 }
}
Learn how to write custom detector
The best way is to learn from source code of findbugs(and its findbugsTestCases) and fb-contrib projects.
Check where we forgot to close SolrQueryRequest

The idea is simple, if a method initialize a SolrQueryRequest, we increment solrQueryInitCount by one, if it call SolrQueryRequest.close(), we decrease solrQueryInitCount by one.
If solrQueryInitCount is not zero at the end of method, we report a bug.

This implementation is not perfect, but anyway it works. In future we can improve it, also we can add one more detector to make sure the SolrQueryRequest.close and refCounted.decref() is called in a finally block.
The code is like below, the complete source/test code, findbugs.xml and messages.xml can be found at Github.

public class NotClosedRequestDetector extends BytecodeScanningDetector {
 public static final String NOT_CLOSE_SOLR_REQUEST = "NOT_CLOSE_SOLR_REQUEST";
 private int solrQueryInitCount = 0;
 private List<Integer> solrQueryInitPCList = new ArrayList<Integer>();

 private final BugReporter bugReporter;
 private final BugAccumulator bugAccumulator;
 public NotClosedRequestDetector(BugReporter bugReporter) {
  this.bugReporter = bugReporter;
  bugAccumulator = new BugAccumulator(bugReporter);
 }
 @Override public void visit(Code obj) {
  solrQueryInitCount = 0;
  solrQueryInitPCList.clear();
  super.visit(obj);
  if (solrQueryInitCount > 0) {
   for (Integer pc : solrQueryInitPCList) {
    bugAccumulator.accumulateBug(new BugInstance(this,
      NOT_CLOSE_SOLR_REQUEST, HIGH_PRIORITY)
      .addClassAndMethod(this), SourceLineAnnotation
      .fromVisitedInstruction(getClassContext(), this, pc));
   }
   bugAccumulator.reportAccumulatedBugs();
  }
 }
 @Override public void sawOpcode(int seen) {
  try {
   if (seen == INVOKESPECIAL) {
    boolean isSolrRequest = isSolrRequest();
    if (isSolrRequest) {
     if (getNameConstantOperand().equals("<init>")) {
      solrQueryInitCount++;
      solrQueryInitPCList.add(getPC());
     }
    }
   } else if (seen == INVOKEVIRTUAL || seen == INVOKEINTERFACE
     || seen == INVOKEINTERFACE_QUICK) {
    boolean isSolrRequest = isSolrRequest();

    if (isSolrRequest) {
     if (getNameConstantOperand().equals("close")
       && getSigConstantOperand().equals("()V")) {
      solrQueryInitCount--;
     }
    }
   }
  } catch (ClassNotFoundException cnfe) {
   bugReporter.reportMissingClass(cnfe);
  }
 }
 private boolean isSolrRequest() throws ClassNotFoundException {
  String className = getClassConstantOperand();
  if (className == null)
   return false;
  JavaClass classClass = Repository.lookupClass(className);
  JavaClass requestClass = Repository
    .lookupClass("org.apache.solr.request.SolrQueryRequest");
  return classClass.instanceOf(requestClass);
 }
}
Check where we forgot to decref RefCounted
Similarly, I create another class UnDecrefRefCountedSearcherDetector to detect where we forget to decref RefCounted, source code can be found at Github.
How to deploy it

We can directly put the built jar into eclipse\plugins\edu.umd.cs.findbugs.plugin.eclipse_***\plugin, or add the jar in Preferences -> FindBugs -> "Plugins and misc. Settings" tab.
It works

The following picture shows how it looks like after deploy my findbugs plugin.
Resources: 
Post a Comment

Labels

Java (159) Lucene-Solr (110) All (58) Interview (58) J2SE (53) Algorithm (43) Soft Skills (36) Eclipse (34) Code Example (31) Linux (24) JavaScript (23) Spring (22) Windows (22) Web Development (20) Nutch2 (18) Tools (18) Bugs (17) Debug (15) Defects (14) Text Mining (14) J2EE (13) Network (13) PowerShell (11) Chrome (9) Design (9) How to (9) Learning code (9) Performance (9) UIMA (9) html (9) Dynamic Languages (8) Http Client (8) Maven (8) Security (8) Trouble Shooting (8) bat (8) blogger (8) Big Data (7) Continuous Integration (7) Google (7) Guava (7) JSON (7) Problem Solving (7) ANT (6) Coding Skills (6) Database (6) Scala (6) Shell (6) css (6) Algorithm Series (5) Cache (5) IDE (5) Lesson Learned (5) Programmer Skills (5) System Design (5) Tips (5) adsense (5) xml (5) AIX (4) Code Quality (4) GAE (4) Git (4) Good Programming Practices (4) Jackson (4) Memory Usage (4) Miscs (4) OpenNLP (4) Project Managment (4) Python (4) Spark (4) Testing (4) ads (4) regular-expression (4) Android (3) Apache Spark (3) Become a Better You (3) Concurrency (3) Eclipse RCP (3) English (3) Happy Hacking (3) IBM (3) J2SE Knowledge Series (3) JAX-RS (3) Jetty (3) Restful Web Service (3) Script (3) regex (3) seo (3) .Net (2) Android Studio (2) Apache (2) Apache Procrun (2) Architecture (2) Batch (2) Bit Operation (2) Build (2) Building Scalable Web Sites (2) C# (2) C/C++ (2) CSV (2) Career (2) Cassandra (2) Distributed (2) Fiddler (2) Firefox (2) Google Drive (2) Gson (2) Html Parser (2) Http (2) Image Tools (2) JQuery (2) Jersey (2) LDAP (2) Life (2) Logging (2) Software Issues (2) Storage (2) Text Search (2) xml parser (2) AOP (1) Application Design (1) AspectJ (1) Chrome DevTools (1) Cloud (1) Codility (1) Data Mining (1) Data Structure (1) ExceptionUtils (1) Exif (1) Feature Request (1) FindBugs (1) Greasemonkey (1) HTML5 (1) Httpd (1) I18N (1) IBM Java Thread Dump Analyzer (1) JDK Source Code (1) JDK8 (1) JMX (1) Lazy Developer (1) Mac (1) Machine Learning (1) Mobile (1) My Plan for 2010 (1) Netbeans (1) Notes (1) Operating System (1) Perl (1) Problems (1) Product Architecture (1) Programming Life (1) Quality (1) Redhat (1) Redis (1) Review (1) RxJava (1) Solutions logs (1) Team Management (1) Thread Dump Analyzer (1) Troubleshooting (1) Visualization (1) boilerpipe (1) htm (1) ongoing (1) procrun (1) rss (1)

Popular Posts