/**
   * Handle "UNLOAD" Action
   *
   * @param req
   * @param rsp
   * @return true if a modification has resulted that requires persistance of the CoreContainer
   *     configuration.
   */
  protected boolean handleUnloadAction(SolrQueryRequest req, SolrQueryResponse rsp)
      throws SolrException {
    SolrParams params = req.getParams();
    String cname = params.get(CoreAdminParams.CORE);
    SolrCore core = coreContainer.remove(cname);
    if (core == null) {
      throw new SolrException(
          SolrException.ErrorCode.BAD_REQUEST, "No such core exists '" + cname + "'");
    }
    if (params.getBool(CoreAdminParams.DELETE_INDEX, false)) {
      core.addCloseHook(
          new CloseHook() {
            @Override
            public void preClose(SolrCore core) {}

            @Override
            public void postClose(SolrCore core) {
              File dataDir = new File(core.getIndexDir());
              for (File file : dataDir.listFiles()) {
                if (!file.delete()) {
                  log.error(file.getAbsolutePath() + " could not be deleted on core unload");
                }
              }
              if (!dataDir.delete())
                log.error(dataDir.getAbsolutePath() + " could not be deleted on core unload");
            }
          });
    }
    core.close();
    return coreContainer.isPersistent();
  }
  @Test
  public void testRace() throws Exception {
    final List<SolrCore> theCores = new ArrayList<>();
    final CoreContainer cc = init();
    try {

      Thread[] threads = new Thread[15];
      for (int idx = 0; idx < threads.length; idx++) {
        threads[idx] =
            new Thread() {
              @Override
              public void run() {
                SolrCore core = cc.getCore("collectionLazy3");
                synchronized (theCores) {
                  theCores.add(core);
                }
              }
            };
        threads[idx].start();
      }
      for (Thread thread : threads) {
        thread.join();
      }
      for (int idx = 0; idx < theCores.size() - 1; ++idx) {
        assertEquals("Cores should be the same!", theCores.get(idx), theCores.get(idx + 1));
      }
      for (SolrCore core : theCores) {
        core.close();
      }

    } finally {
      cc.shutdown();
    }
  }
  @Test
  public void testCreateSame() throws Exception {
    final CoreContainer cc = init();
    try {
      // First, try all 4 combinations of load on startup and transient
      final CoreAdminHandler admin = new CoreAdminHandler(cc);
      SolrCore lc2 = cc.getCore("collectionLazy2");
      SolrCore lc4 = cc.getCore("collectionLazy4");
      SolrCore lc5 = cc.getCore("collectionLazy5");
      SolrCore lc6 = cc.getCore("collectionLazy6");

      copyMinConf(new File(solrHomeDirectory, "t2"));
      copyMinConf(new File(solrHomeDirectory, "t4"));
      copyMinConf(new File(solrHomeDirectory, "t5"));
      copyMinConf(new File(solrHomeDirectory, "t6"));

      // Should also fail with the same name
      tryCreateFail(
          admin, "collectionLazy2", "t12", "Core with name", "collectionLazy2", "already exists");
      tryCreateFail(
          admin, "collectionLazy4", "t14", "Core with name", "collectionLazy4", "already exists");
      tryCreateFail(
          admin, "collectionLazy5", "t15", "Core with name", "collectionLazy5", "already exists");
      tryCreateFail(
          admin, "collectionLazy6", "t16", "Core with name", "collectionLazy6", "already exists");

      lc2.close();
      lc4.close();
      lc5.close();
      lc6.close();

    } finally {
      cc.shutdown();
    }
  }
    @Override
    public Query rewrite(IndexReader reader) throws IOException {
      SolrRequestInfo info = SolrRequestInfo.getRequestInfo();

      CoreContainer container = info.getReq().getCore().getCoreDescriptor().getCoreContainer();

      final SolrCore fromCore = container.getCore(fromIndex);

      if (fromCore == null) {
        throw new SolrException(
            SolrException.ErrorCode.BAD_REQUEST, "Cross-core join: no such core " + fromIndex);
      }
      RefCounted<SolrIndexSearcher> fromHolder = null;
      fromHolder = fromCore.getRegisteredSearcher();
      final Query joinQuery;
      try {
        joinQuery =
            JoinUtil.createJoinQuery(
                fromField, true, toField, fromQuery, fromHolder.get(), scoreMode);
      } finally {
        fromCore.close();
        fromHolder.decref();
      }
      return joinQuery.rewrite(reader);
    }
示例#5
0
  /**
   * This constructor is designed to make it easy for JNI embedded applications to setup the entire
   * solr environment with a simple interface. It takes three parameters: <code>instanceDir:</code>
   * The solr instance directory. If null, it will check the standard places first
   * (JNDI,properties,"solr" directory) <code>dataDir:</code> where the index is stored. <code>
   * loggingPath:</code> Path to a java.util.logging.config.file. If the path represents an absolute
   * path or is relative to the CWD, it will use that. Next it will try a path relative to the
   * instanceDir. If none of these files exist, it will error.
   */
  public DirectSolrConnection(String instanceDir, String dataDir, String loggingPath) {
    // If a loggingPath is specified, try using that (this needs to happen first)
    if (loggingPath != null) {
      File loggingConfig = new File(loggingPath);
      if (!loggingConfig.exists() && instanceDir != null) {
        loggingConfig = new File(new File(instanceDir), loggingPath);
      }
      if (loggingConfig.exists()) {
        System.setProperty("java.util.logging.config.file", loggingConfig.getAbsolutePath());
      } else {
        throw new SolrException(
            SolrException.ErrorCode.SERVER_ERROR, "can not find logging file: " + loggingConfig);
      }
    }

    if (instanceDir == null) {
      instanceDir = SolrResourceLoader.locateInstanceDir();
    }

    // Initialize
    try {
      CoreContainer cores = new CoreContainer(new SolrResourceLoader(instanceDir));
      SolrConfig solrConfig = new SolrConfig(instanceDir, SolrConfig.DEFAULT_CONF_FILE, null);
      CoreDescriptor dcore =
          new CoreDescriptor(cores, "", solrConfig.getResourceLoader().getInstanceDir());
      IndexSchema indexSchema = new IndexSchema(solrConfig, instanceDir + "/conf/schema.xml", null);
      core = new SolrCore(null, dataDir, solrConfig, indexSchema, dcore);
      cores.register("", core, false);
      parser = new SolrRequestParsers(solrConfig);
    } catch (Exception ee) {
      throw new RuntimeException(ee);
    }
  }
示例#6
0
  @Test
  public void testRefCount() throws Exception {
    SolrCore core = h.getCore();
    assertTrue("Refcount != 1", core.getOpenCount() == 1);

    final CoreContainer cores = h.getCoreContainer();
    SolrCore c1 = cores.getCore(SolrTestCaseJ4.DEFAULT_TEST_CORENAME);
    assertTrue("Refcount != 2", core.getOpenCount() == 2);

    ClosingRequestHandler handler1 = new ClosingRequestHandler();
    handler1.inform(core);

    String path = "/this/is A path /that won't be registered!";
    SolrRequestHandler old = core.registerRequestHandler(path, handler1);
    assertNull(old); // should not be anything...
    assertEquals(core.getRequestHandlers().get(path), handler1);

    SolrCore c2 = cores.getCore(SolrTestCaseJ4.DEFAULT_TEST_CORENAME);
    c1.close();
    assertTrue("Refcount < 1", core.getOpenCount() >= 1);
    assertTrue("Handler is closed", handler1.closed == false);

    c1 = cores.getCore(SolrTestCaseJ4.DEFAULT_TEST_CORENAME);
    assertTrue("Refcount < 2", core.getOpenCount() >= 2);
    assertTrue("Handler is closed", handler1.closed == false);

    c2.close();
    assertTrue("Refcount < 1", core.getOpenCount() >= 1);
    assertTrue("Handler is closed", handler1.closed == false);

    c1.close();
    cores.shutdown();
    assertTrue("Refcount != 0", core.getOpenCount() == 0);
    assertTrue("Handler not closed", core.isClosed() && handler1.closed == true);
  }
示例#7
0
 private SolrCore checkProps(ZkNodeProps zkProps) {
   String corename;
   SolrCore core = null;
   if (cores.getZkController().getNodeName().equals(zkProps.getStr(NODE_NAME_PROP))) {
     corename = zkProps.getStr(CORE_NAME_PROP);
     core = cores.getCore(corename);
   }
   return core;
 }
示例#8
0
 protected SolrServer getEmbeddedSolrServer(String solrCore)
     throws IOException, ParserConfigurationException, SAXException, SolrServerException {
   String solrHomeDir = System.getProperty(SOLR_HOME);
   File home = new File(solrHomeDir);
   File f = new File(home, "solr.xml");
   CoreContainer container = new CoreContainer();
   container.load();
   return new EmbeddedSolrServer(container, solrCore);
 }
  // Write out the cores' config files, both bad schema files, bad config files as well as some good
  // cores.
  private CoreContainer initGoodAndBad(
      List<String> goodCores, List<String> badSchemaCores, List<String> badConfigCores)
      throws Exception {

    // Don't pollute the log with exception traces when they're expected.
    ignoreException(Pattern.quote("SAXParseException"));

    if (solrHomeDirectory.exists()) {
      FileUtils.deleteDirectory(solrHomeDirectory);
    }
    assertTrue("Failed to mkdirs workDir", solrHomeDirectory.mkdirs());

    // Create the cores that should be fine.
    for (String coreName : goodCores) {
      File coreRoot = new File(solrHomeDirectory, coreName);
      copyMinConf(coreRoot, "name=" + coreName);
    }

    // Collect the files that we'll write to the config directories.
    String top = SolrTestCaseJ4.TEST_HOME() + "/collection1/conf";
    String min_schema =
        FileUtils.readFileToString(new File(top, "schema-tiny.xml"), Charsets.UTF_8.toString());
    String min_config =
        FileUtils.readFileToString(
            new File(top, "solrconfig-minimal.xml"), Charsets.UTF_8.toString());
    String rand_snip =
        FileUtils.readFileToString(
            new File(top, "solrconfig.snippet.randomindexconfig.xml"), Charsets.UTF_8.toString());

    // Now purposely mess up the config files, introducing stupid syntax errors.
    String bad_config = min_config.replace("<requestHandler", "<reqsthalr");
    String bad_schema = min_schema.replace("<field", "<filed");

    // Create the cores with bad configs
    for (String coreName : badConfigCores) {
      writeCustomConfig(coreName, bad_config, min_schema, rand_snip);
    }

    // Create the cores with bad schemas.
    for (String coreName : badSchemaCores) {
      writeCustomConfig(coreName, min_config, bad_schema, rand_snip);
    }

    // Write the solr.xml file. Cute how minimal it can be now....
    File solrXml = new File(solrHomeDirectory, "solr.xml");
    FileUtils.write(solrXml, "<solr/>", Charsets.UTF_8.toString());

    SolrResourceLoader loader = new SolrResourceLoader(solrHomeDirectory.getAbsolutePath());
    ConfigSolrXml config = (ConfigSolrXml) ConfigSolr.fromFile(loader, solrXml);

    CoresLocator locator = new CorePropertiesLocator(solrHomeDirectory.getAbsolutePath());

    // OK this should succeed, but at the end we should have recorded a series of errors.
    final CoreContainer cores = new CoreContainer(loader, config, locator);
    cores.load();
    return cores;
  }
示例#10
0
  /**
   * Handle "SWAP" action
   *
   * @param req
   * @param rsp
   * @return true if a modification has resulted that requires persistance of the CoreContainer
   *     configuration.
   */
  protected boolean handleSwapAction(SolrQueryRequest req, SolrQueryResponse rsp) {
    final SolrParams params = req.getParams();
    final SolrParams required = params.required();

    final String cname = params.get(CoreAdminParams.CORE);
    boolean doPersist = params.getBool(CoreAdminParams.PERSISTENT, coreContainer.isPersistent());
    String other = required.get(CoreAdminParams.OTHER);
    coreContainer.swap(cname, other);
    return doPersist;
  }
 /** Make the zookeeper session on a particular jetty expire */
 public void expireZkSession(JettySolrRunner jetty) {
   CoreContainer cores = jetty.getCoreContainer();
   if (cores != null) {
     SolrZkClient zkClient = cores.getZkController().getZkClient();
     zkClient.getSolrZooKeeper().closeCnxn();
     long sessionId = zkClient.getSolrZooKeeper().getSessionId();
     zkServer.expire(sessionId);
     log.info("Expired zookeeper session {} from node {}", sessionId, jetty.getBaseUrl());
   }
 }
示例#12
0
 private boolean shouldAuthorize() {
   if (PKIAuthenticationPlugin.PATH.equals(path)) return false;
   // admin/info/key is the path where public key is exposed . it is always unsecured
   if (cores.getPkiAuthenticationPlugin() != null && req.getUserPrincipal() != null) {
     boolean b = cores.getPkiAuthenticationPlugin().needsAuthorization(req);
     log.debug("PkiAuthenticationPlugin says authorization required : {} ", b);
     return b;
   }
   return true;
 }
  // Make sure that creating a transient core from the admin handler correctly respects the
  // transient limits etc.
  @Test
  public void testCreateTransientFromAdmin() throws Exception {
    final CoreContainer cc = init();
    try {
      copyMinConf(new File(solrHomeDirectory, "core1"));
      copyMinConf(new File(solrHomeDirectory, "core2"));
      copyMinConf(new File(solrHomeDirectory, "core3"));
      copyMinConf(new File(solrHomeDirectory, "core4"));
      copyMinConf(new File(solrHomeDirectory, "core5"));

      createViaAdmin(cc, "core1", "./core1", true, true);
      createViaAdmin(cc, "core2", "./core2", true, false);
      createViaAdmin(cc, "core3", "./core3", true, true);
      createViaAdmin(cc, "core4", "./core4", true, false);
      createViaAdmin(cc, "core5", "./core5", true, false);

      SolrCore c1 = cc.getCore("core1");
      SolrCore c2 = cc.getCore("core2");
      SolrCore c3 = cc.getCore("core3");
      SolrCore c4 = cc.getCore("core4");
      SolrCore c5 = cc.getCore("core5");

      checkNotInCores(
          cc,
          "core1",
          "collectionLazy2",
          "collectionLazy3",
          "collectionLazy4",
          "collectionLazy6",
          "collectionLazy7",
          "collectionLazy8",
          "collectionLazy9");

      checkInCores(cc, "collection1", "collectionLazy5", "core2", "core3", "core4", "core5");

      // While we're at it, a test for SOLR-5366, unloading transient core that's been unloaded b/c
      // it's
      // transient generates a "too many closes" errorl

      unloadViaAdmin(cc, "core1");
      unloadViaAdmin(cc, "core2");
      unloadViaAdmin(cc, "core3");
      unloadViaAdmin(cc, "core4");
      unloadViaAdmin(cc, "core5");

      c1.close();
      c2.close();
      c3.close();
      c4.close();
      c5.close();

    } finally {
      cc.shutdown();
    }
  }
示例#14
0
 /**
  * Create a new CoreContainer and load its cores
  *
  * @param solrHome the solr home directory
  * @param configFile the file containing this container's configuration
  * @return a loaded CoreContainer
  */
 public static CoreContainer createAndLoad(Path solrHome, Path configFile) {
   SolrResourceLoader loader = new SolrResourceLoader(solrHome);
   CoreContainer cc = new CoreContainer(SolrXmlConfig.fromFile(loader, configFile));
   try {
     cc.load();
   } catch (Exception e) {
     cc.shutdown();
     throw e;
   }
   return cc;
 }
 /**
  * Sets the tracking queue for all nodes participating in this cluster. Once this method returns,
  * all search and core admin requests distributed to shards will be submitted to the given queue.
  *
  * @param runners a list of {@link org.apache.solr.client.solrj.embedded.JettySolrRunner} nodes
  * @param queue an implementation of {@link java.util.Queue} which accepts {@link
  *     org.apache.solr.handler.component.TrackingShardHandlerFactory.ShardRequestAndParams}
  *     instances
  */
 public static void setTrackingQueue(
     List<JettySolrRunner> runners, Queue<ShardRequestAndParams> queue) {
   for (JettySolrRunner runner : runners) {
     CoreContainer container = runner.getCoreContainer();
     ShardHandlerFactory factory = container.getShardHandlerFactory();
     assert factory instanceof TrackingShardHandlerFactory
         : "not a TrackingShardHandlerFactory: " + factory.getClass();
     TrackingShardHandlerFactory trackingShardHandlerFactory =
         (TrackingShardHandlerFactory) factory;
     trackingShardHandlerFactory.setTrackingQueue(queue);
   }
 }
 /**
  * Extract core names.
  *
  * @param cores All the available cores.
  * @return The core's name.
  */
 private static Iterable<String> coreNames(final CoreContainer cores) {
   List<String> names = new ArrayList<String>();
   for (SolrCore core : cores.getCores()) {
     String name = core.getName();
     if (isEmpty(name)) {
       // This is the default core.
       name = cores.getDefaultCoreName();
     }
     names.add(name);
   }
   return names;
 }
示例#17
0
  @Test
  public void testClose() throws Exception {
    final CoreContainer cores = h.getCoreContainer();
    SolrCore core = cores.getCore(SolrTestCaseJ4.DEFAULT_TEST_CORENAME);

    ClosingRequestHandler handler1 = new ClosingRequestHandler();
    handler1.inform(core);

    String path = "/this/is A path /that won't be registered 2!!!!!!!!!!!";
    SolrRequestHandler old = core.registerRequestHandler(path, handler1);
    assertNull(old); // should not be anything...
    assertEquals(core.getRequestHandlers().get(path), handler1);
    core.close();
    cores.shutdown();
    assertTrue("Handler not closed", handler1.closed == true);
  }
示例#18
0
  /**
   * Handler "PERSIST" action
   *
   * @param req
   * @param rsp
   * @return true if a modification has resulted that requires persistance of the CoreContainer
   *     configuration.
   * @throws SolrException
   */
  protected boolean handlePersistAction(SolrQueryRequest req, SolrQueryResponse rsp)
      throws SolrException {
    SolrParams params = req.getParams();
    boolean doPersist = false;
    String fileName = params.get(CoreAdminParams.FILE);
    if (fileName != null) {
      File file = new File(coreContainer.getConfigFile().getParentFile(), fileName);
      coreContainer.persistFile(file);
      rsp.add("saved", file.getAbsolutePath());
      doPersist = false;
    } else if (!coreContainer.isPersistent()) {
      throw new SolrException(SolrException.ErrorCode.FORBIDDEN, "Persistence is not enabled");
    } else doPersist = true;

    return doPersist;
  }
 /**
  * Returns an String with the name of a core.
  *
  * <p>This method searches the core with fromIndex name in the core's container. If fromIndex
  * isn't name of collection or alias it's returns fromIndex without changes. If fromIndex is name
  * of alias but if the alias points to multiple collections it's throw
  * SolrException.ErrorCode.BAD_REQUEST because multiple shards not yet supported.
  *
  * @param fromIndex name of the index
  * @param container the core container for searching the core with fromIndex name or alias
  * @return the string with name of core
  */
 public static String getCoreName(final String fromIndex, CoreContainer container) {
   if (container.isZooKeeperAware()) {
     ZkController zkController = container.getZkController();
     final String resolved =
         zkController.getClusterState().hasCollection(fromIndex)
             ? fromIndex
             : resolveAlias(fromIndex, zkController);
     if (resolved == null) {
       throw new SolrException(
           SolrException.ErrorCode.BAD_REQUEST,
           "SolrCloud join: Collection '" + fromIndex + "' not found!");
     }
     return findLocalReplicaForFromIndex(zkController, resolved);
   }
   return fromIndex;
 }
示例#20
0
  private String getRemotCoreUrl(String collectionName, String origCorename) {
    ClusterState clusterState = cores.getZkController().getClusterState();
    Collection<Slice> slices = clusterState.getActiveSlices(collectionName);
    boolean byCoreName = false;

    if (slices == null) {
      slices = new ArrayList<>();
      // look by core name
      byCoreName = true;
      getSlicesForCollections(clusterState, slices, true);
      if (slices.isEmpty()) {
        getSlicesForCollections(clusterState, slices, false);
      }
    }

    if (slices.isEmpty()) {
      return null;
    }

    if (collectionsList == null) collectionsList = new ArrayList<>();

    collectionsList.add(collectionName);
    String coreUrl =
        getCoreUrl(collectionName, origCorename, clusterState, slices, byCoreName, true);

    if (coreUrl == null) {
      coreUrl = getCoreUrl(collectionName, origCorename, clusterState, slices, byCoreName, false);
    }

    return coreUrl;
  }
示例#21
0
 private void extractRemotePath(String corename, String origCorename, int idx)
     throws UnsupportedEncodingException, KeeperException, InterruptedException {
   if (core == null && idx > 0) {
     coreUrl = getRemotCoreUrl(corename, origCorename);
     // don't proxy for internal update requests
     invalidStates = checkStateIsValid(queryParams.get(CloudSolrClient.STATE_VERSION));
     if (coreUrl != null
         && queryParams.get(DistributingUpdateProcessorFactory.DISTRIB_UPDATE_PARAM) == null) {
       path = path.substring(idx);
       if (invalidStates != null) {
         // it does not make sense to send the request to a remote node
         throw new SolrException(
             SolrException.ErrorCode.INVALID_STATE,
             new String(Utils.toJSON(invalidStates), org.apache.lucene.util.IOUtils.UTF_8));
       }
       action = REMOTEQUERY;
     } else {
       if (!retry) {
         // we couldn't find a core to work with, try reloading aliases
         // TODO: it would be nice if admin ui elements skipped this...
         ZkStateReader reader = cores.getZkController().getZkStateReader();
         reader.updateAliases();
         action = RETRY;
       }
     }
   }
 }
  private SolrServer createSolrServer(File indexPath)
      throws ParserConfigurationException, IOException, SAXException {
    SolrConfig config = new SolrConfig(null, null, getClass().getResourceAsStream(SOLR_CONFIG));
    IndexSchema schema = new IndexSchema(config, null, getClass().getResourceAsStream(SOLR_SCHEMA));

    CoreContainer coreContainer = new CoreContainer();

    SolrCore core =
        new SolrCore(
            "EMS",
            indexPath.getAbsolutePath(),
            config,
            schema,
            new CoreDescriptor(coreContainer, "EMS", SOLR_BASE));
    coreContainer.register("EMS", core, false);
    return new EmbeddedSolrServer(coreContainer, "EMS");
  }
 private final long getCoreStartTime(final CoreContainer cc, final String name) {
   SolrCore tmp = cc.getCore(name);
   try {
     return tmp.getStartTime();
   } finally {
     tmp.close();
   }
 }
示例#24
0
  /**
   * Handle "ALIAS" action
   *
   * @param req
   * @param rsp
   * @return true if a modification has resulted that requires persistance of the CoreContainer
   *     configuration.
   */
  @Deprecated
  protected boolean handleAliasAction(SolrQueryRequest req, SolrQueryResponse rsp) {
    SolrParams params = req.getParams();

    String name = params.get(CoreAdminParams.OTHER);
    String cname = params.get(CoreAdminParams.CORE);
    boolean doPersist = false;
    if (cname.equals(name)) return doPersist;

    SolrCore core = coreContainer.getCore(cname);
    if (core != null) {
      doPersist = coreContainer.isPersistent();
      coreContainer.register(name, core, false);
      // no core.close() since each entry in the cores map should increase the ref
    }
    return doPersist;
  }
  /**
   * Creates a {@link CoreContainer} object which has all the Solr cores.
   *
   * @param context The application's context. Required.
   * @return A {@link CoreContainer} object which has all the Solr cores.
   * @throws IOException If the Solr home cannot be created.
   * @throws ParserConfigurationException If the any of the Solr XML files are corrupted.
   * @throws SAXException If the any of the Solr XML files are corrupted.
   */
  @Bean
  public static CoreContainer solrCores(final ApplicationContext context)
      throws IOException, ParserConfigurationException, SAXException {
    notNull(context, "The application's context is required.");
    Environment env = context.getEnvironment();

    final File solrHome = findSolrHome(context);

    final File dataDir = findSolrDataDir(env);

    final Map<String, String> coreDefs = new LinkedHashMap<String, String>();
    CoreContainer cores =
        new CoreContainer(solrHome.getAbsolutePath()) {
          @Override
          public SolrCore create(final CoreDescriptor coreDescriptor) {
            String coreName = coreDescriptor.getName();
            if (coreName.length() == 0) {
              coreName = getDefaultCoreName();
            }

            Properties properties = new Properties();
            String coreDataDir = new File(dataDir, coreName).getAbsolutePath();
            coreDefs.put(coreName, coreDataDir);
            // default data dir
            properties.setProperty(CoreDescriptor.CORE_DATADIR, coreDataDir);

            return super.create(
                new CoreDescriptor(
                    coreDescriptor.getCoreContainer(),
                    coreDescriptor.getName(),
                    coreDescriptor.getInstanceDir(),
                    properties));
          }
        };
    // Initialize cores
    cores.load();

    logger.info("Solr home directory: {}", solrHome);
    for (Entry<String, String> core : coreDefs.entrySet()) {
      logger.info("  core: {}, dataDir: {}", core.getKey(), core.getValue());
    }
    return cores;
  }
示例#26
0
  /**
   * Handle "RENAME" Action
   *
   * @param req
   * @param rsp
   * @return true if a modification has resulted that requires persistance of the CoreContainer
   *     configuration.
   * @throws SolrException
   */
  protected boolean handleRenameAction(SolrQueryRequest req, SolrQueryResponse rsp)
      throws SolrException {
    SolrParams params = req.getParams();

    String name = params.get(CoreAdminParams.OTHER);
    String cname = params.get(CoreAdminParams.CORE);
    boolean doPersist = false;

    if (cname.equals(name)) return doPersist;

    SolrCore core = coreContainer.getCore(cname);
    if (core != null) {
      doPersist = coreContainer.isPersistent();
      coreContainer.register(name, core, false);
      coreContainer.remove(cname);
      core.close();
    }
    return doPersist;
  }
示例#27
0
  /**
   * Handle 'CREATE' action.
   *
   * @param req
   * @param rsp
   * @return true if a modification has resulted that requires persistance of the CoreContainer
   *     configuration.
   * @throws SolrException in case of a configuration error.
   */
  protected boolean handleCreateAction(SolrQueryRequest req, SolrQueryResponse rsp)
      throws SolrException {
    try {
      SolrParams params = req.getParams();
      String name = params.get(CoreAdminParams.NAME);
      CoreDescriptor dcore =
          new CoreDescriptor(coreContainer, name, params.get(CoreAdminParams.INSTANCE_DIR));

      //  fillup optional parameters
      String opts = params.get(CoreAdminParams.CONFIG);
      if (opts != null) dcore.setConfigName(opts);

      opts = params.get(CoreAdminParams.SCHEMA);
      if (opts != null) dcore.setSchemaName(opts);

      opts = params.get(CoreAdminParams.DATA_DIR);
      if (opts != null) dcore.setDataDir(opts);

      // Process all property.name=value parameters and set them as name=value core properties
      Properties coreProperties = new Properties();
      Iterator<String> parameterNamesIterator = params.getParameterNamesIterator();
      while (parameterNamesIterator.hasNext()) {
        String parameterName = parameterNamesIterator.next();
        if (parameterName.startsWith(CoreAdminParams.PROPERTY_PREFIX)) {
          String parameterValue = params.get(parameterName);
          String propertyName =
              parameterName.substring(CoreAdminParams.PROPERTY_PREFIX.length()); // skip prefix
          coreProperties.put(propertyName, parameterValue);
        }
      }
      dcore.setCoreProperties(coreProperties);

      SolrCore core = coreContainer.create(dcore);
      coreContainer.register(name, core, false);
      rsp.add("core", core.getName());
      return coreContainer.isPersistent();
    } catch (Exception ex) {
      throw new SolrException(
          SolrException.ErrorCode.BAD_REQUEST,
          "Error executing default implementation of CREATE",
          ex);
    }
  }
示例#28
0
 /**
  * Handler "RELOAD" action
  *
  * @param req
  * @param rsp
  * @return true if a modification has resulted that requires persistance of the CoreContainer
  *     configuration.
  */
 protected boolean handleReloadAction(SolrQueryRequest req, SolrQueryResponse rsp) {
   SolrParams params = req.getParams();
   String cname = params.get(CoreAdminParams.CORE);
   try {
     coreContainer.reload(cname);
     return false; // no change on reload
   } catch (Exception ex) {
     throw new SolrException(
         SolrException.ErrorCode.SERVER_ERROR, "Error handling 'reload' action", ex);
   }
 }
示例#29
0
 public void disable() {
   if (!enabled) {
     return;
   }
   nakamuraCore.close();
   coreContainer.shutdown();
   enabled = false;
   if (listener != null) {
     listener.disabled();
   }
 }
  /**
   *
   *
   * <h3>Fixtures</h3>
   *
   * You can add test or init data by creating a 'fixtures' directory under a Solr core. Test files
   * are described using the Solr XML format for documents.
   *
   * <h4>Fixtures properties</h4>
   *
   * <ul>
   *   solr.fixtures: enabled or disabled the loading of test files. Default is: true.
   *   solr.fixtures.async: if true, a new thread will be created for loading the fixtures. Default
   *   is: true.
   * </ul>
   */
  @PostConstruct
  public void runFixtures() {
    Environment env = applicationContext.getEnvironment();
    boolean runFixtures = env.getProperty(SOLR_FIXTURES, boolean.class, true);
    if (runFixtures) {
      Map<String, SolrServer> servers = applicationContext.getBeansOfType(SolrServer.class);
      CoreContainer cores = applicationContext.getBean(CoreContainer.class);
      String solrHome = cores.getSolrHome();

      boolean async = env.getProperty(SOLR_FIXTURES_ASYNC, boolean.class, true);

      for (Entry<String, SolrServer> server : servers.entrySet()) {
        String coreName = server.getKey();
        File coreHome = new File(solrHome, coreName);
        File fixtures = new File(coreHome, "fixtures");
        if (fixtures.exists()) {
          populate(server.getValue(), coreName, fixtures, async);
        }
      }
    }
  }