Search code examples
solr

Is there any Solr API that can tell when all cores on that particular Solr node are loaded and can serve queries (legacy mode)?


I tried /solr/api/cores and I think that is what I want, although, if Solr has just rebooted then it returns with the statuses of however many cores are loaded so far. It does not halt for all cores. Is there a way to make it halt till all the cores are loaded and queryable?


Solution

  • What I ended up doing was writing a custom Solr plugin. Here is the code:

    public class CustomHealthCheckHandler extends RequestHandlerBase {
    private static final Logger LOG = LoggerFactory.getLogger(CustomHealthCheckHandler.class);
    
    @Override
    public String getDescription() {
        return "A Simple healthcheck handler that checks if all cores are loaded and queriable";
    }
    
    @Override
    public void handleRequestBody(SolrQueryRequest req, SolrQueryResponse resp) {
        CoreContainer coreContainer = req.getCore().getCoreContainer();
    
    
        // Get list of core names regardless of whether they are loaded or not
        // Notice that we are intenetionally not using coreContainer.getLoadedCoreNames()
        // or coreContainer.geAllCoreNames() here because they might not return all the cores
        // in the case Solr is just restarted and all the cores are not loaded yet.
        Path solrHome = Paths.get(coreContainer.getSolrHome());
        CorePropertiesLocator locator = new CorePropertiesLocator(solrHome);
        List<CoreDescriptor> coreDescriptors = locator.discover(coreContainer);
        Collection<String> cores = coreDescriptors.stream().map(cd -> cd.getName()).collect(java.util.stream.Collectors.toList());
    
        for (String core : cores) {
            // get the /admin/ping handler for each core
            SolrRequestHandler handler = coreContainer.getCore(core).getRequestHandler("/admin/ping");
            // if handler is null, then return with UNHEALTHY status
            if (handler == null) {
                resp.add("status", "UNHEALTHY");
                return;
            }
    
            SolrQueryResponse response = new SolrQueryResponse();
            SolrQuery query = new SolrQuery();
            query.set("wt", "json");
            query.set("indent", true);
    
            // execute the query
            handler.handleRequest(new SolrQueryRequestBase(coreContainer.getCore(core), query) {}, response);
            String status = ((String) response.getValues().get("status"));
            // if status is null or not OK, then return
            if (status == null || !status.equals("OK")) {
                resp.add("status", "UNHEALTHY");
                return;
            }
        }
        resp.add("status", "HEALTHY");
    }
    

    }