Autopsy  4.6.0
Graphical digital forensics platform for The Sleuth Kit and other tools.
SolrSearchService.java
Go to the documentation of this file.
1 /*
2  * Autopsy Forensic Browser
3  *
4  * Copyright 2011-2018 Basis Technology Corp.
5  * Contact: carrier <at> sleuthkit <dot> org
6  *
7  * Licensed under the Apache License, Version 2.0 (the "License");
8  * you may not use this file except in compliance with the License.
9  * You may obtain a copy of the License at
10  *
11  * http://www.apache.org/licenses/LICENSE-2.0
12  *
13  * Unless required by applicable law or agreed to in writing, software
14  * distributed under the License is distributed on an "AS IS" BASIS,
15  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
16  * See the License for the specific language governing permissions and
17  * limitations under the License.
18  */
19 package org.sleuthkit.autopsy.keywordsearch;
20 
21 import java.io.File;
22 import java.io.IOException;
23 import java.lang.reflect.InvocationTargetException;
24 import java.net.InetAddress;
25 import java.util.ArrayList;
26 import java.util.List;
27 import java.util.MissingResourceException;
28 import java.util.logging.Level;
29 import javax.swing.JDialog;
30 import javax.swing.JOptionPane;
31 import javax.swing.SwingUtilities;
32 import org.apache.commons.lang.math.NumberUtils;
33 import org.apache.commons.io.FileUtils;
34 import org.apache.solr.client.solrj.SolrServerException;
35 import org.apache.solr.client.solrj.impl.HttpSolrServer;
36 import org.openide.util.NbBundle;
37 import org.openide.util.lookup.ServiceProvider;
38 import org.openide.util.lookup.ServiceProviders;
48 import org.sleuthkit.datamodel.BlackboardArtifact;
49 import org.sleuthkit.datamodel.Content;
50 import org.sleuthkit.datamodel.TskCoreException;
51 
56 @ServiceProviders(value = {
57  @ServiceProvider(service = KeywordSearchService.class)
58  ,
59  @ServiceProvider(service = AutopsyService.class)}
60 )
62 
63  private static final String BAD_IP_ADDRESS_FORMAT = "ioexception occurred when talking to server"; //NON-NLS
64  private static final String SERVER_REFUSED_CONNECTION = "server refused connection"; //NON-NLS
65  private static final int IS_REACHABLE_TIMEOUT_MS = 1000;
66  private static final int LARGE_INDEX_SIZE_GB = 50;
67  private static final int GIANT_INDEX_SIZE_GB = 500;
68  private static final Logger logger = Logger.getLogger(SolrSearchService.class.getName());
69 
78  @Override
79  public void indexArtifact(BlackboardArtifact artifact) throws TskCoreException {
80  if (artifact == null) {
81  return;
82  }
83 
84  // We only support artifact indexing for Autopsy versions that use
85  // the negative range for artifact ids.
86  if (artifact.getArtifactID() > 0) {
87  return;
88  }
89  final Ingester ingester = Ingester.getDefault();
90 
91  try {
92  ingester.indexMetaDataOnly(artifact);
93  ingester.indexText(new ArtifactTextExtractor(), artifact, null);
94  } catch (Ingester.IngesterException ex) {
95  throw new TskCoreException(ex.getCause().getMessage(), ex);
96  }
97  }
98 
104  @Override
105  public void index(Content content) throws TskCoreException {
106  if (content == null) {
107  return;
108  }
109  final Ingester ingester = Ingester.getDefault();
110 
111  try {
112  ingester.indexText(new TikaTextExtractor(), content, null);
113  } catch (Ingester.IngesterException ex) {
114  try {
115  // Try the StringsTextExtractor if Tika extractions fails.
116  ingester.indexText(new StringsTextExtractor(), content, null);
117  } catch (Ingester.IngesterException ex1) {
118  throw new TskCoreException(ex.getCause().getMessage(), ex1);
119  }
120  }
121 
122  // TODO: Review whether this is the right thing to do. We typically use
123  // a combination of autoCommit and the SearchRunner to ensure that data
124  // is committed but that might not be sufficient for reports (or artifacts).
125  ingester.commit();
126  }
127 
136  @Override
137  public void tryConnect(String host, int port) throws KeywordSearchServiceException {
138  HttpSolrServer solrServer = null;
139  if (host == null || host.isEmpty()) {
140  throw new KeywordSearchServiceException(NbBundle.getMessage(SolrSearchService.class, "SolrConnectionCheck.MissingHostname")); //NON-NLS
141  }
142  try {
143  solrServer = new HttpSolrServer("http://" + host + ":" + Integer.toString(port) + "/solr"); //NON-NLS
144  KeywordSearch.getServer().connectToSolrServer(solrServer);
145  } catch (SolrServerException ex) {
146  throw new KeywordSearchServiceException(NbBundle.getMessage(SolrSearchService.class, "SolrConnectionCheck.HostnameOrPort")); //NON-NLS
147  } catch (IOException ex) {
148  String result = NbBundle.getMessage(SolrSearchService.class, "SolrConnectionCheck.HostnameOrPort"); //NON-NLS
149  String message = ex.getCause().getMessage().toLowerCase();
150  if (message.startsWith(SERVER_REFUSED_CONNECTION)) {
151  try {
152  if (InetAddress.getByName(host).isReachable(IS_REACHABLE_TIMEOUT_MS)) {
153  // if we can reach the host, then it's probably port problem
154  result = Bundle.SolrConnectionCheck_Port();
155  } else {
156  result = NbBundle.getMessage(SolrSearchService.class, "SolrConnectionCheck.HostnameOrPort"); //NON-NLS
157  }
158  } catch (IOException | MissingResourceException any) {
159  // it may be anything
160  result = NbBundle.getMessage(SolrSearchService.class, "SolrConnectionCheck.HostnameOrPort"); //NON-NLS
161  }
162  } else if (message.startsWith(BAD_IP_ADDRESS_FORMAT)) {
163  result = NbBundle.getMessage(SolrSearchService.class, "SolrConnectionCheck.Hostname"); //NON-NLS
164  }
165  throw new KeywordSearchServiceException(result);
166  } catch (NumberFormatException ex) {
167  throw new KeywordSearchServiceException(Bundle.SolrConnectionCheck_Port());
168  } catch (IllegalArgumentException ex) {
169  throw new KeywordSearchServiceException(ex.getMessage());
170  } finally {
171  if (null != solrServer) {
172  solrServer.shutdown();
173  }
174  }
175  }
176 
182  @NbBundle.Messages({
183  "# {0} - case directory", "SolrSearchService.exceptionMessage.noIndexMetadata=Unable to create IndexMetaData from case directory: {0}",
184  "SolrSearchService.exceptionMessage.noCurrentSolrCore=IndexMetadata did not contain a current Solr core so could not delete the case",
185  "# {0} - index folder path", "SolrSearchService.exceptionMessage.failedToDeleteIndexFiles=Failed to delete text index files at {0}"
186  })
187  @Override
189  String caseDirectory = metadata.getCaseDirectory();
190  IndexMetadata indexMetadata;
191  try {
192  indexMetadata = new IndexMetadata(caseDirectory);
193  } catch (IndexMetadata.TextIndexMetadataException ex) {
194  logger.log(Level.WARNING, NbBundle.getMessage(SolrSearchService.class, "SolrSearchService.exceptionMessage.noIndexMetadata", caseDirectory), ex);
195  throw new KeywordSearchServiceException(NbBundle.getMessage(SolrSearchService.class, "SolrSearchService.exceptionMessage.noIndexMetadata", caseDirectory), ex);
196  }
197  //find the index for the current version of solr (the one we are connected to) and delete its core using the index name
198  String currentSchema = IndexFinder.getCurrentSchemaVersion();
199  String currentSolr = IndexFinder.getCurrentSolrVersion();
200  for (Index index : indexMetadata.getIndexes()) {
201  if (index.getSolrVersion().equals(currentSolr) && index.getSchemaVersion().equals(currentSchema)) {
202  /*
203  * Unload/delete the core on the server and then delete the text
204  * index files.
205  */
206  KeywordSearch.getServer().deleteCore(index.getIndexName(), metadata);
207  if (!FileUtil.deleteDir(new File(index.getIndexPath()).getParentFile())) {
208  throw new KeywordSearchServiceException(Bundle.SolrSearchService_exceptionMessage_failedToDeleteIndexFiles(index.getIndexPath()));
209  }
210  }
211  return; //only one core exists for each combination of solr and schema version
212  }
213 
214  //this code this code will only execute if an index for the current core was not found
215  logger.log(Level.WARNING, NbBundle.getMessage(SolrSearchService.class,
216  "SolrSearchService.exceptionMessage.noCurrentSolrCore"));
217  throw new KeywordSearchServiceException(NbBundle.getMessage(SolrSearchService.class,
218  "SolrSearchService.exceptionMessage.noCurrentSolrCore"));
219  }
220 
221  @Override
222  public void close() throws IOException {
223  }
224 
225  @Override
226  public String getServiceName() {
227  return NbBundle.getMessage(this.getClass(), "SolrSearchService.ServiceName");
228  }
229 
237  @Override
238  @NbBundle.Messages({
239  "SolrSearch.lookingForMetadata.msg=Looking for text index metadata file",
240  "SolrSearch.readingIndexes.msg=Reading text index metadata file",
241  "SolrSearch.findingIndexes.msg=Looking for existing text index directories",
242  "SolrSearch.creatingNewIndex.msg=Creating new text index",
243  "SolrSearch.checkingForLatestIndex.msg=Looking for text index with latest Solr and schema version",
244  "SolrSearch.indentifyingIndex.msg=Identifying text index to use",
245  "SolrSearch.openCore.msg=Opening text index",
246  "SolrSearch.openLargeCore.msg=Opening text index. This may take several minutes.",
247  "SolrSearch.openGiantCore.msg=Opening text index. Text index for this case is very large and may take long time to load.",
248  "SolrSearch.complete.msg=Text index successfully opened"})
250  if (context.cancelRequested()) {
251  return;
252  }
253 
254  ProgressIndicator progress = context.getProgressIndicator();
255  int totalNumProgressUnits = 7;
256  int progressUnitsCompleted = 0;
257 
258  String caseDirPath = context.getCase().getCaseDirectory();
259  Case theCase = context.getCase();
260  List<Index> indexes = new ArrayList<>();
261  progress.start(Bundle.SolrSearch_lookingForMetadata_msg(), totalNumProgressUnits);
262  if (IndexMetadata.isMetadataFilePresent(caseDirPath)) {
263  try {
264  // metadata file exists, get list of existing Solr cores for this case
265  progressUnitsCompleted++;
266  progress.progress(Bundle.SolrSearch_findingIndexes_msg(), progressUnitsCompleted);
267  IndexMetadata indexMetadata = new IndexMetadata(caseDirPath);
268  indexes = indexMetadata.getIndexes();
269  } catch (IndexMetadata.TextIndexMetadataException ex) {
270  logger.log(Level.SEVERE, String.format("Unable to read text index metadata file"), ex);
271  throw new AutopsyServiceException("Unable to read text index metadata file", ex);
272  }
273  } else {
274  // metadata file doesn't exist.
275  // do case subdirectory search to look for Solr 4 Schema 1.8 indexes
276  progressUnitsCompleted++;
277  progress.progress(Bundle.SolrSearch_findingIndexes_msg(), progressUnitsCompleted);
278  Index oldIndex = IndexFinder.findOldIndexDir(theCase);
279  if (oldIndex != null) {
280  // add index to the list of indexes that exist for this case
281  indexes.add(oldIndex);
282  }
283  }
284 
285  if (context.cancelRequested()) {
286  return;
287  }
288 
289  // check if we found any existing indexes
290  Index currentVersionIndex = null;
291  if (indexes.isEmpty()) {
292  // new case that doesn't have an existing index. create new index folder
293  progressUnitsCompleted++;
294  progress.progress(Bundle.SolrSearch_creatingNewIndex_msg(), progressUnitsCompleted);
295  currentVersionIndex = IndexFinder.createLatestVersionIndexDir(theCase);
296  // add current index to the list of indexes that exist for this case
297  indexes.add(currentVersionIndex);
298  } else {
299  // check if one of the existing indexes is for latest Solr version and schema
300  progressUnitsCompleted++;
301  progress.progress(Bundle.SolrSearch_checkingForLatestIndex_msg(), progressUnitsCompleted);
302  currentVersionIndex = IndexFinder.findLatestVersionIndexDir(indexes);
303  if (currentVersionIndex == null) {
304  // found existing index(es) but none were for latest Solr version and schema version
305  progressUnitsCompleted++;
306  progress.progress(Bundle.SolrSearch_indentifyingIndex_msg(), progressUnitsCompleted);
307  Index indexToUse = IndexFinder.identifyIndexToUse(indexes);
308  if (indexToUse == null) {
309  // unable to find index that can be used
310  throw new AutopsyServiceException("Unable to find index that can be used for this case");
311  }
312 
313  if (context.cancelRequested()) {
314  return;
315  }
316 
317  double currentSolrVersion = NumberUtils.toDouble(IndexFinder.getCurrentSolrVersion());
318  double indexSolrVersion = NumberUtils.toDouble(indexToUse.getSolrVersion());
319  if (indexSolrVersion == currentSolrVersion) {
320  // latest Solr version but not latest schema. index should be used in read-only mode
322  // pop up a message box to indicate the read-only restrictions.
323  JOptionPane optionPane = new JOptionPane(
324  NbBundle.getMessage(this.getClass(), "SolrSearchService.IndexReadOnlyDialog.msg"),
325  JOptionPane.WARNING_MESSAGE,
326  JOptionPane.DEFAULT_OPTION);
327  try {
328  SwingUtilities.invokeAndWait(() -> {
329  JDialog dialog = optionPane.createDialog(NbBundle.getMessage(this.getClass(), "SolrSearchService.IndexReadOnlyDialog.title"));
330  dialog.setVisible(true);
331  });
332  } catch (InterruptedException ex) {
333  // Cancelled
334  return;
335  } catch (InvocationTargetException ex) {
336  throw new AutopsyServiceException("Error displaying limited search features warning dialog", ex);
337  }
338  }
339  // proceed with case open
340  currentVersionIndex = indexToUse;
341  } else {
342  // index needs to be upgraded to latest supported version of Solr
343  throw new AutopsyServiceException("Unable to find index to use for Case open");
344  }
345  }
346  }
347 
348  try {
349  // update text index metadata file
350  if (!indexes.isEmpty()) {
351  IndexMetadata indexMetadata = new IndexMetadata(caseDirPath, indexes);
352  }
353  } catch (IndexMetadata.TextIndexMetadataException ex) {
354  throw new AutopsyServiceException("Failed to save Solr core info in text index metadata file", ex);
355  }
356 
357  // open core
358  try {
359  // check text index size to gauge estimated time to open/load the index
360  long indexSizeInBytes = FileUtils.sizeOfDirectory(new File(currentVersionIndex.getIndexPath()));
361  long sizeInGb = indexSizeInBytes / 1000000000;
362  if (sizeInGb < LARGE_INDEX_SIZE_GB) {
363  progress.progress(Bundle.SolrSearch_openCore_msg(), totalNumProgressUnits - 1);
364  } else if (sizeInGb >= LARGE_INDEX_SIZE_GB && sizeInGb < GIANT_INDEX_SIZE_GB) {
365  progress.switchToIndeterminate(Bundle.SolrSearch_openLargeCore_msg());
366  } else {
367  progress.switchToIndeterminate(Bundle.SolrSearch_openGiantCore_msg());
368  }
369 
370  KeywordSearch.getServer().openCoreForCase(theCase, currentVersionIndex);
371  } catch (KeywordSearchModuleException ex) {
372  throw new AutopsyServiceException(String.format("Failed to open or create core for %s", caseDirPath), ex);
373  }
374 
375  progress.progress(Bundle.SolrSearch_complete_msg(), totalNumProgressUnits);
376  }
377 
385  @Override
387  /*
388  * TODO (JIRA 2525): The following code KeywordSearch.CaseChangeListener
389  * gambles that any BlackboardResultWriters (SwingWorkers) will complete
390  * in less than roughly two seconds. This stuff should be reworked using
391  * an ExecutorService and tasks with Futures.
392  */
393  AdHocSearchChildFactory.BlackboardResultWriter.stopAllWriters();
394  try {
395  Thread.sleep(2000);
396  } catch (InterruptedException ex) {
397  logger.log(Level.SEVERE, "Unexpected interrupt while waiting for BlackboardResultWriters to terminate", ex);
398  }
399 
400  try {
401  KeywordSearch.getServer().closeCore();
402  } catch (KeywordSearchModuleException ex) {
403  throw new AutopsyServiceException(String.format("Failed to close core for %s", context.getCase().getCaseDirectory()), ex);
404  }
405  }
406 }
void start(String message, int totalWorkUnits)
synchronized static Logger getLogger(String name)
Definition: Logger.java:124
static boolean deleteDir(File dirPath)
Definition: FileUtil.java:47

Copyright © 2012-2016 Basis Technology. Generated on: Mon May 7 2018
This work is licensed under a Creative Commons Attribution-Share Alike 3.0 United States License.