Apache Lucene open-source search software
SOLR-11779: Basic long-term collection of aggregated metrics.
Andrzej Bialecki6bbce38b77d5
diff --git a/lucene/ivy-versions.properties b/lucene/ivy-versions.propertiesindex 357972037b9..981bbe69fd6 100644--- a/lucene/ivy-versions.properties+++ b/lucene/ivy-versions.properties@@ -297,6 +297,8 @@ org.restlet.jee.version = 2.3.0/org.restlet.jee/org.restlet = ${org.restlet.jee.version}/org.restlet.jee/org.restlet.ext.servlet = ${org.restlet.jee.version}+/org.rrd4j/rrd4j = 3.2+/org.simpleframework/simple-xml = 2.7.1org.slf4j.version = 1.7.24diff --git a/solr/CHANGES.txt b/solr/CHANGES.txtindex d56bf03bc98..fcdcbaaa241 100644--- a/solr/CHANGES.txt+++ b/solr/CHANGES.txt@@ -143,6 +143,11 @@ New Features* SOLR-11453: Configuring slowQueryThresholdMillis logs slow requests to a separate file - solr_slow_requests.log .(Shawn Heisey, Remko Popma, Varun Thacker)+* SOLR-11779: Basic long-term collection of aggregated metrics. Historical data is+ maintained as multi-resolution time series using round-robin databases in the '.system'+ collection. New /admin/metrics/history API allows retrieval of this data in numeric+ or graph formats. (ab)+Bug Fixes----------------------diff --git a/solr/core/ivy.xml b/solr/core/ivy.xmlindex e47d5b8788d..ee6fe80db73 100644--- a/solr/core/ivy.xml+++ b/solr/core/ivy.xml@@ -155,6 +155,8 @@<dependency org="org.codehaus.janino" name="commons-compiler" rev="${/org.codehaus.janino/commons-compiler}" conf="compile"/><dependency org="com.google.protobuf" name="protobuf-java" rev="${/com.google.protobuf/protobuf-java}" conf="compile"/>+ <dependency org="org.rrd4j" name="rrd4j" rev="${/org.rrd4j/rrd4j}" conf="compile"/>+<exclude org="*" ext="*" matcher="regexp" type="${ivy.exclude.types}"/></dependencies></ivy-module>diff --git a/solr/core/src/java/org/apache/solr/cloud/api/collections/DeleteCollectionCmd.java b/solr/core/src/java/org/apache/solr/cloud/api/collections/DeleteCollectionCmd.javaindex c8143ba35cb..c676cf3a1d8 100644--- a/solr/core/src/java/org/apache/solr/cloud/api/collections/DeleteCollectionCmd.java+++ b/solr/core/src/java/org/apache/solr/cloud/api/collections/DeleteCollectionCmd.java@@ -40,7 +40,10 @@ import org.apache.solr.common.params.ModifiableSolrParams;import org.apache.solr.common.util.NamedList;import org.apache.solr.common.util.TimeSource;import org.apache.solr.common.util.Utils;+import org.apache.solr.core.SolrInfoBean;import org.apache.solr.core.snapshots.SolrSnapshotManager;+import org.apache.solr.handler.admin.MetricsHistoryHandler;+import org.apache.solr.metrics.SolrMetricManager;import org.apache.solr.util.TimeOut;import org.apache.zookeeper.KeeperException;import org.slf4j.Logger;@@ -67,6 +70,8 @@ public class DeleteCollectionCmd implements OverseerCollectionMessageHandler.CmdcheckNotReferencedByAlias(zkStateReader, collection);+ final boolean deleteHistory = message.getBool(CoreAdminParams.DELETE_METRICS_HISTORY, true);+boolean removeCounterNode = true;try {// Remove the snapshots meta-data for this collection in ZK. Deleting actual index files@@ -82,10 +87,19 @@ public class DeleteCollectionCmd implements OverseerCollectionMessageHandler.Cmdreturn;}}+ // remove collection-level metrics history+ if (deleteHistory) {+ MetricsHistoryHandler historyHandler = ocmh.overseer.getCoreContainer().getMetricsHistoryHandler();+ if (historyHandler != null) {+ String registry = SolrMetricManager.getRegistryName(SolrInfoBean.Group.collection, collection);+ historyHandler.removeHistory(registry);+ }+ }ModifiableSolrParams params = new ModifiableSolrParams();params.set(CoreAdminParams.ACTION, CoreAdminParams.CoreAdminAction.UNLOAD.toString());params.set(CoreAdminParams.DELETE_INSTANCE_DIR, true);params.set(CoreAdminParams.DELETE_DATA_DIR, true);+ params.set(CoreAdminParams.DELETE_METRICS_HISTORY, deleteHistory);String asyncId = message.getStr(ASYNC);Map<String, String> requestMap = null;@@ -126,7 +140,6 @@ public class DeleteCollectionCmd implements OverseerCollectionMessageHandler.Cmdthrow new SolrException(SolrException.ErrorCode.SERVER_ERROR,"Could not fully remove collection: " + collection);}-} finally {try {diff --git a/solr/core/src/java/org/apache/solr/cloud/api/collections/DeleteReplicaCmd.java b/solr/core/src/java/org/apache/solr/cloud/api/collections/DeleteReplicaCmd.javaindex eefe903fa6f..4dbc0599571 100644--- a/solr/core/src/java/org/apache/solr/cloud/api/collections/DeleteReplicaCmd.java+++ b/solr/core/src/java/org/apache/solr/cloud/api/collections/DeleteReplicaCmd.java@@ -233,6 +233,7 @@ public class DeleteReplicaCmd implements Cmd {params.set(CoreAdminParams.DELETE_INDEX, message.getBool(CoreAdminParams.DELETE_INDEX, true));params.set(CoreAdminParams.DELETE_INSTANCE_DIR, message.getBool(CoreAdminParams.DELETE_INSTANCE_DIR, true));params.set(CoreAdminParams.DELETE_DATA_DIR, message.getBool(CoreAdminParams.DELETE_DATA_DIR, true));+ params.set(CoreAdminParams.DELETE_METRICS_HISTORY, message.getBool(CoreAdminParams.DELETE_METRICS_HISTORY, true));boolean isLive = ocmh.zkStateReader.getClusterState().getLiveNodes().contains(replica.getNodeName());if (isLive) {diff --git a/solr/core/src/java/org/apache/solr/core/CoreContainer.java b/solr/core/src/java/org/apache/solr/core/CoreContainer.javaindex 74b718cdca5..cc546204b6b 100644--- a/solr/core/src/java/org/apache/solr/core/CoreContainer.java+++ b/solr/core/src/java/org/apache/solr/core/CoreContainer.java@@ -25,6 +25,7 @@ import static org.apache.solr.common.params.CommonParams.CONFIGSETS_HANDLER_PATHimport static org.apache.solr.common.params.CommonParams.CORES_HANDLER_PATH;import static org.apache.solr.common.params.CommonParams.HEALTH_CHECK_HANDLER_PATH;import static org.apache.solr.common.params.CommonParams.INFO_HANDLER_PATH;+import static org.apache.solr.common.params.CommonParams.METRICS_HISTORY_PATH;import static org.apache.solr.common.params.CommonParams.METRICS_PATH;import static org.apache.solr.common.params.CommonParams.ZK_PATH;import static org.apache.solr.security.AuthenticationPlugin.AUTHENTICATION_PLUGIN_PROP;@@ -56,6 +57,7 @@ import org.apache.http.client.CredentialsProvider;import org.apache.http.config.Lookup;import org.apache.lucene.index.CorruptIndexException;import org.apache.lucene.store.Directory;+import org.apache.solr.client.solrj.impl.CloudSolrClient;import org.apache.solr.client.solrj.impl.HttpClientUtil;import org.apache.solr.client.solrj.impl.SolrHttpClientBuilder;import org.apache.solr.client.solrj.impl.SolrHttpClientContextBuilder;@@ -87,6 +89,7 @@ import org.apache.solr.handler.admin.HealthCheckHandler;import org.apache.solr.handler.admin.InfoHandler;import org.apache.solr.handler.admin.MetricsCollectorHandler;import org.apache.solr.handler.admin.MetricsHandler;+import org.apache.solr.handler.admin.MetricsHistoryHandler;import org.apache.solr.handler.admin.SecurityConfHandler;import org.apache.solr.handler.admin.SecurityConfHandlerLocal;import org.apache.solr.handler.admin.SecurityConfHandlerZk;@@ -190,6 +193,8 @@ public class CoreContainer {protected MetricsHandler metricsHandler;+ protected MetricsHistoryHandler metricsHistoryHandler;+protected MetricsCollectorHandler metricsCollectorHandler;protected AutoscalingHistoryHandler autoscalingHistoryHandler;@@ -474,6 +479,14 @@ public class CoreContainer {return metricManager;}+ public MetricsHandler getMetricsHandler() {+ return metricsHandler;+ }++ public MetricsHistoryHandler getMetricsHistoryHandler() {+ return metricsHistoryHandler;+ }+//-------------------------------------------------------------------// Initialization / Cleanup//-------------------------------------------------------------------@@ -536,7 +549,28 @@ public class CoreContainer {infoHandler = createHandler(INFO_HANDLER_PATH, cfg.getInfoHandlerClass(), InfoHandler.class);coreAdminHandler = createHandler(CORES_HANDLER_PATH, cfg.getCoreAdminHandlerClass(), CoreAdminHandler.class);configSetsHandler = createHandler(CONFIGSETS_HANDLER_PATH, cfg.getConfigSetsHandlerClass(), ConfigSetsHandler.class);- metricsHandler = createHandler(METRICS_PATH, MetricsHandler.class.getName(), MetricsHandler.class);++ // metricsHistoryHandler uses metricsHandler, so create it first+ metricsHandler = new MetricsHandler(metricManager);+ containerHandlers.put(METRICS_PATH, metricsHandler);+ metricsHandler.initializeMetrics(metricManager, SolrInfoBean.Group.node.toString(), metricTag, METRICS_PATH);++ if (isZooKeeperAware()) {+ PluginInfo plugin = cfg.getMetricsConfig().getHistoryHandler();+ Map<String, Object> initArgs;+ if (plugin != null && plugin.initArgs != null) {+ initArgs = plugin.initArgs.asMap(5);+ initArgs.put(MetricsHistoryHandler.ENABLE_PROP, plugin.isEnabled());+ } else {+ initArgs = Collections.emptyMap();+ }+ metricsHistoryHandler = new MetricsHistoryHandler(getZkController().getNodeName(), metricsHandler,+ new CloudSolrClient.Builder(Collections.singletonList(getZkController().getZkServerAddress()), Optional.empty())+ .withHttpClient(updateShardHandler.getDefaultHttpClient()).build(), getZkController().getSolrCloudManager(), initArgs);+ containerHandlers.put(METRICS_HISTORY_PATH, metricsHistoryHandler);+ metricsHistoryHandler.initializeMetrics(metricManager, SolrInfoBean.Group.node.toString(), metricTag, METRICS_HISTORY_PATH);+ }+autoscalingHistoryHandler = createHandler(AUTOSCALING_HISTORY_PATH, AutoscalingHistoryHandler.class.getName(), AutoscalingHistoryHandler.class);metricsCollectorHandler = createHandler(MetricsCollectorHandler.HANDLER_PATH, MetricsCollectorHandler.class.getName(), MetricsCollectorHandler.class);// may want to add some configuration here in the future@@ -761,6 +795,10 @@ public class CoreContainer {} catch (Exception e) {log.warn("Error removing live node. Continuing to close CoreContainer", e);}+ if (metricsHistoryHandler != null) {+ IOUtils.closeQuietly(metricsHistoryHandler.getSolrClient());+ metricsHistoryHandler.close();+ }if (metricManager != null) {metricManager.closeReporters(SolrMetricManager.getRegistryName(SolrInfoBean.Group.cluster));}diff --git a/solr/core/src/java/org/apache/solr/core/MetricsConfig.java b/solr/core/src/java/org/apache/solr/core/MetricsConfig.javaindex 796483bd242..fab2553f970 100644--- a/solr/core/src/java/org/apache/solr/core/MetricsConfig.java+++ b/solr/core/src/java/org/apache/solr/core/MetricsConfig.java@@ -30,16 +30,19 @@ public class MetricsConfig {private final PluginInfo meterSupplier;private final PluginInfo timerSupplier;private final PluginInfo histogramSupplier;+ private final PluginInfo historyHandler;private MetricsConfig(PluginInfo[] metricReporters, Set<String> hiddenSysProps,PluginInfo counterSupplier, PluginInfo meterSupplier,- PluginInfo timerSupplier, PluginInfo histogramSupplier) {+ PluginInfo timerSupplier, PluginInfo histogramSupplier,+ PluginInfo historyHandler) {this.metricReporters = metricReporters;this.hiddenSysProps = hiddenSysProps;this.counterSupplier = counterSupplier;this.meterSupplier = meterSupplier;this.timerSupplier = timerSupplier;this.histogramSupplier = histogramSupplier;+ this.historyHandler = historyHandler;}public PluginInfo[] getMetricReporters() {@@ -66,6 +69,10 @@ public class MetricsConfig {return histogramSupplier;}+ public PluginInfo getHistoryHandler() {+ return historyHandler;+ }+public static class MetricsConfigBuilder {private PluginInfo[] metricReporterPlugins = new PluginInfo[0];private Set<String> hiddenSysProps = new HashSet<>();@@ -73,6 +80,7 @@ public class MetricsConfig {private PluginInfo meterSupplier;private PluginInfo timerSupplier;private PluginInfo histogramSupplier;+ private PluginInfo historyHandler;public MetricsConfigBuilder() {@@ -111,9 +119,14 @@ public class MetricsConfig {return this;}+ public MetricsConfigBuilder setHistoryHandler(PluginInfo info) {+ this.historyHandler = info;+ return this;+ }+public MetricsConfig build() {return new MetricsConfig(metricReporterPlugins, hiddenSysProps, counterSupplier, meterSupplier,- timerSupplier, histogramSupplier);+ timerSupplier, histogramSupplier, historyHandler);}}diff --git a/solr/core/src/java/org/apache/solr/core/SolrXmlConfig.java b/solr/core/src/java/org/apache/solr/core/SolrXmlConfig.javaindex 9737c09016a..64fe73189fb 100644--- a/solr/core/src/java/org/apache/solr/core/SolrXmlConfig.java+++ b/solr/core/src/java/org/apache/solr/core/SolrXmlConfig.java@@ -483,6 +483,10 @@ public class SolrXmlConfig {if (node != null) {builder = builder.setHistogramSupplier(new PluginInfo(node, "histogramSupplier", false, false));}+ node = config.getNode("solr/metrics/history", false);+ if (node != null) {+ builder = builder.setHistoryHandler(new PluginInfo(node, "history", false, false));+ }PluginInfo[] reporterPlugins = getMetricReporterPluginInfos(config);Set<String> hiddenSysProps = getHiddenSysProps(config);return builderdiff --git a/solr/core/src/java/org/apache/solr/handler/admin/CollectionsHandler.java b/solr/core/src/java/org/apache/solr/handler/admin/CollectionsHandler.javaindex e724167f870..f7f6172ef8a 100644--- a/solr/core/src/java/org/apache/solr/handler/admin/CollectionsHandler.java+++ b/solr/core/src/java/org/apache/solr/handler/admin/CollectionsHandler.java@@ -147,6 +147,7 @@ import static org.apache.solr.common.params.CoreAdminParams.DATA_DIR;import static org.apache.solr.common.params.CoreAdminParams.DELETE_DATA_DIR;import static org.apache.solr.common.params.CoreAdminParams.DELETE_INDEX;import static org.apache.solr.common.params.CoreAdminParams.DELETE_INSTANCE_DIR;+import static org.apache.solr.common.params.CoreAdminParams.DELETE_METRICS_HISTORY;import static org.apache.solr.common.params.CoreAdminParams.INSTANCE_DIR;import static org.apache.solr.common.params.CoreAdminParams.ULOG_DIR;import static org.apache.solr.common.params.ShardParams._ROUTE_;@@ -642,7 +643,8 @@ public class CollectionsHandler extends RequestHandlerBase implements Permissioncopy(req.getParams(), map,DELETE_INDEX,DELETE_DATA_DIR,- DELETE_INSTANCE_DIR);+ DELETE_INSTANCE_DIR,+ DELETE_METRICS_HISTORY);return map;}),FORCELEADER_OP(FORCELEADER, (req, rsp, h) -> {@@ -671,6 +673,7 @@ public class CollectionsHandler extends RequestHandlerBase implements PermissionDELETE_INDEX,DELETE_DATA_DIR,DELETE_INSTANCE_DIR,+ DELETE_METRICS_HISTORY,COUNT_PROP, REPLICA_PROP,SHARD_ID_PROP,ONLY_IF_DOWN);diff --git a/solr/core/src/java/org/apache/solr/handler/admin/CoreAdminOperation.java b/solr/core/src/java/org/apache/solr/handler/admin/CoreAdminOperation.javaindex 075fb8db964..8cf2bcb30f4 100644--- a/solr/core/src/java/org/apache/solr/handler/admin/CoreAdminOperation.java+++ b/solr/core/src/java/org/apache/solr/handler/admin/CoreAdminOperation.java@@ -25,6 +25,7 @@ import java.util.Optional;import org.apache.commons.lang.StringUtils;import org.apache.lucene.store.Directory;+import org.apache.solr.cloud.CloudDescriptor;import org.apache.solr.cloud.ZkController;import org.apache.solr.common.SolrException;import org.apache.solr.common.SolrException.ErrorCode;@@ -32,14 +33,17 @@ import org.apache.solr.common.params.CoreAdminParams;import org.apache.solr.common.params.SolrParams;import org.apache.solr.common.util.NamedList;import org.apache.solr.common.util.SimpleOrderedMap;+import org.apache.solr.common.util.Utils;import org.apache.solr.core.CoreContainer;import org.apache.solr.core.CoreDescriptor;import org.apache.solr.core.DirectoryFactory;import org.apache.solr.core.SolrCore;+import org.apache.solr.core.SolrInfoBean;import org.apache.solr.core.snapshots.SolrSnapshotManager;import org.apache.solr.core.snapshots.SolrSnapshotMetaDataManager;import org.apache.solr.core.snapshots.SolrSnapshotMetaDataManager.SnapshotMetaData;import org.apache.solr.handler.admin.CoreAdminHandler.CoreAdminOp;+import org.apache.solr.metrics.SolrMetricManager;import org.apache.solr.search.SolrIndexSearcher;import org.apache.solr.update.UpdateLog;import org.apache.solr.util.NumberUtils;@@ -98,7 +102,27 @@ enum CoreAdminOperation implements CoreAdminOp {boolean deleteIndexDir = params.getBool(CoreAdminParams.DELETE_INDEX, false);boolean deleteDataDir = params.getBool(CoreAdminParams.DELETE_DATA_DIR, false);boolean deleteInstanceDir = params.getBool(CoreAdminParams.DELETE_INSTANCE_DIR, false);+ boolean deleteMetricsHistory = params.getBool(CoreAdminParams.DELETE_METRICS_HISTORY, false);+ CoreDescriptor cdescr = it.handler.coreContainer.getCoreDescriptor(cname);it.handler.coreContainer.unload(cname, deleteIndexDir, deleteDataDir, deleteInstanceDir);+ if (deleteMetricsHistory) {+ MetricsHistoryHandler historyHandler = it.handler.coreContainer.getMetricsHistoryHandler();+ if (historyHandler != null) {+ CloudDescriptor cd = cdescr != null ? cdescr.getCloudDescriptor() : null;+ String registry;+ if (cd == null) {+ registry = SolrMetricManager.getRegistryName(SolrInfoBean.Group.core, cname);+ } else {+ String replicaName = Utils.parseMetricsReplicaName(cd.getCollectionName(), cname);+ registry = SolrMetricManager.getRegistryName(SolrInfoBean.Group.core,+ cd.getCollectionName(),+ cd.getShardId(),+ replicaName);+ }+ historyHandler.checkSystemCollection();+ historyHandler.removeHistory(registry);+ }+ }assert TestInjection.injectNonExistentCoreExceptionAfterUnload(cname);}),diff --git a/solr/core/src/java/org/apache/solr/handler/admin/MetricsHandler.java b/solr/core/src/java/org/apache/solr/handler/admin/MetricsHandler.javaindex ed1e4747e7f..ca291e8ed7b 100644--- a/solr/core/src/java/org/apache/solr/handler/admin/MetricsHandler.java+++ b/solr/core/src/java/org/apache/solr/handler/admin/MetricsHandler.java@@ -24,6 +24,7 @@ import java.util.HashSet;import java.util.List;import java.util.Map;import java.util.Set;+import java.util.function.BiConsumer;import java.util.regex.Pattern;import java.util.stream.Collectors;@@ -36,10 +37,10 @@ import com.codahale.metrics.MetricFilter;import com.codahale.metrics.MetricRegistry;import com.codahale.metrics.Timer;import org.apache.solr.common.SolrException;+import org.apache.solr.common.params.SolrParams;import org.apache.solr.common.util.NamedList;import org.apache.solr.common.util.SimpleOrderedMap;import org.apache.solr.common.util.StrUtils;-import org.apache.solr.core.CoreContainer;import org.apache.solr.handler.RequestHandlerBase;import org.apache.solr.metrics.SolrMetricManager;import org.apache.solr.request.SolrQueryRequest;@@ -52,7 +53,6 @@ import org.apache.solr.util.stats.MetricUtils;* Request handler to return metrics*/public class MetricsHandler extends RequestHandlerBase implements PermissionNameProvider {- final CoreContainer container;final SolrMetricManager metricManager;public static final String COMPACT_PARAM = "compact";@@ -69,13 +69,11 @@ public class MetricsHandler extends RequestHandlerBase implements PermissionNameprivate static final Pattern KEY_REGEX = Pattern.compile("(?<!" + Pattern.quote("\\") + ")" + Pattern.quote(":"));public MetricsHandler() {- this.container = null;this.metricManager = null;}- public MetricsHandler(CoreContainer container) {- this.container = container;- this.metricManager = this.container.getMetricManager();+ public MetricsHandler(SolrMetricManager metricManager) {+ this.metricManager = metricManager;}@Override@@ -85,21 +83,25 @@ public class MetricsHandler extends RequestHandlerBase implements PermissionName@Overridepublic void handleRequestBody(SolrQueryRequest req, SolrQueryResponse rsp) throws Exception {- if (container == null) {- throw new SolrException(SolrException.ErrorCode.INVALID_STATE, "Core container instance not initialized");+ if (metricManager == null) {+ throw new SolrException(SolrException.ErrorCode.INVALID_STATE, "SolrMetricManager instance not initialized");}- boolean compact = req.getParams().getBool(COMPACT_PARAM, true);- String[] keys = req.getParams().getParams(KEY_PARAM);+ handleRequest(req.getParams(), (k, v) -> rsp.add(k, v));+ }++ public void handleRequest(SolrParams params, BiConsumer<String, Object> consumer) throws Exception {+ boolean compact = params.getBool(COMPACT_PARAM, true);+ String[] keys = params.getParams(KEY_PARAM);if (keys != null && keys.length > 0) {- handleKeyRequest(keys, req, rsp);+ handleKeyRequest(keys, consumer);return;}- MetricFilter mustMatchFilter = parseMustMatchFilter(req);- MetricUtils.PropertyFilter propertyFilter = parsePropertyFilter(req);- List<MetricType> metricTypes = parseMetricTypes(req);+ MetricFilter mustMatchFilter = parseMustMatchFilter(params);+ MetricUtils.PropertyFilter propertyFilter = parsePropertyFilter(params);+ List<MetricType> metricTypes = parseMetricTypes(params);List<MetricFilter> metricFilters = metricTypes.stream().map(MetricType::asMetricFilter).collect(Collectors.toList());- Set<String> requestedRegistries = parseRegistries(req);+ Set<String> requestedRegistries = parseRegistries(params);NamedList response = new SimpleOrderedMap();for (String registryName : requestedRegistries) {@@ -111,10 +113,10 @@ public class MetricsHandler extends RequestHandlerBase implements PermissionNameresponse.add(registryName, result);}}- rsp.getValues().add("metrics", response);+ consumer.accept("metrics", response);}- private void handleKeyRequest(String[] keys, SolrQueryRequest req, SolrQueryResponse rsp) throws Exception {+ public void handleKeyRequest(String[] keys, BiConsumer<String, Object> consumer) throws Exception {SimpleOrderedMap result = new SimpleOrderedMap();SimpleOrderedMap errors = new SimpleOrderedMap();for (String key : keys) {@@ -153,9 +155,9 @@ public class MetricsHandler extends RequestHandlerBase implements PermissionName}});}- rsp.getValues().add("metrics", result);+ consumer.accept("metrics", result);if (errors.size() > 0) {- rsp.getValues().add("errors", errors);+ consumer.accept("errors", errors);}}@@ -174,8 +176,8 @@ public class MetricsHandler extends RequestHandlerBase implements PermissionNamereturn sb.toString();}- private MetricFilter parseMustMatchFilter(SolrQueryRequest req) {- String[] prefixes = req.getParams().getParams(PREFIX_PARAM);+ private MetricFilter parseMustMatchFilter(SolrParams params) {+ String[] prefixes = params.getParams(PREFIX_PARAM);MetricFilter prefixFilter = null;if (prefixes != null && prefixes.length > 0) {Set<String> prefixSet = new HashSet<>();@@ -184,7 +186,7 @@ public class MetricsHandler extends RequestHandlerBase implements PermissionName}prefixFilter = new SolrMetricManager.PrefixFilter(prefixSet);}- String[] regexes = req.getParams().getParams(REGEX_PARAM);+ String[] regexes = params.getParams(REGEX_PARAM);MetricFilter regexFilter = null;if (regexes != null && regexes.length > 0) {regexFilter = new SolrMetricManager.RegexFilter(regexes);@@ -204,8 +206,8 @@ public class MetricsHandler extends RequestHandlerBase implements PermissionNamereturn mustMatchFilter;}- private MetricUtils.PropertyFilter parsePropertyFilter(SolrQueryRequest req) {- String[] props = req.getParams().getParams(PROPERTY_PARAM);+ private MetricUtils.PropertyFilter parsePropertyFilter(SolrParams params) {+ String[] props = params.getParams(PROPERTY_PARAM);if (props == null || props.length == 0) {return MetricUtils.PropertyFilter.ALL;}@@ -222,12 +224,16 @@ public class MetricsHandler extends RequestHandlerBase implements PermissionName}}- private Set<String> parseRegistries(SolrQueryRequest req) {- String[] groupStr = req.getParams().getParams(GROUP_PARAM);- String[] registryStr = req.getParams().getParams(REGISTRY_PARAM);+ private Set<String> parseRegistries(SolrParams params) {+ String[] groupStr = params.getParams(GROUP_PARAM);+ String[] registryStr = params.getParams(REGISTRY_PARAM);+ return parseRegistries(groupStr, registryStr);+ }++ public Set<String> parseRegistries(String[] groupStr, String[] registryStr) {if ((groupStr == null || groupStr.length == 0) && (registryStr == null || registryStr.length == 0)) {// return all registries- return container.getMetricManager().registryNames();+ return metricManager.registryNames();}boolean allRegistries = false;Set<String> initialPrefixes = Collections.emptySet();@@ -243,7 +249,7 @@ public class MetricsHandler extends RequestHandlerBase implements PermissionNameinitialPrefixes.add(SolrMetricManager.overridableRegistryName(s.trim()));}if (allRegistries) {- return container.getMetricManager().registryNames();+ return metricManager.registryNames();}}}@@ -262,12 +268,12 @@ public class MetricsHandler extends RequestHandlerBase implements PermissionNameinitialPrefixes.add(SolrMetricManager.overridableRegistryName(s.trim()));}if (allRegistries) {- return container.getMetricManager().registryNames();+ return metricManager.registryNames();}}}Set<String> validRegistries = new HashSet<>();- for (String r : container.getMetricManager().registryNames()) {+ for (String r : metricManager.registryNames()) {for (String prefix : initialPrefixes) {if (r.startsWith(prefix)) {validRegistries.add(r);@@ -278,8 +284,8 @@ public class MetricsHandler extends RequestHandlerBase implements PermissionNamereturn validRegistries;}- private List<MetricType> parseMetricTypes(SolrQueryRequest req) {- String[] typeStr = req.getParams().getParams(TYPE_PARAM);+ private List<MetricType> parseMetricTypes(SolrParams params) {+ String[] typeStr = params.getParams(TYPE_PARAM);List<String> types = Collections.emptyList();if (typeStr != null && typeStr.length > 0) {types = new ArrayList<>();diff --git a/solr/core/src/java/org/apache/solr/handler/admin/MetricsHistoryHandler.java b/solr/core/src/java/org/apache/solr/handler/admin/MetricsHistoryHandler.javanew file mode 100644index 00000000000..f6abcdb2e8a--- /dev/null+++ b/solr/core/src/java/org/apache/solr/handler/admin/MetricsHistoryHandler.java@@ -0,0 +1,858 @@+/*+ * Licensed to the Apache Software Foundation (ASF) under one or more+ * contributor license agreements. See the NOTICE file distributed with+ * this work for additional information regarding copyright ownership.+ * The ASF licenses this file to You under the Apache License, Version 2.0+ * (the "License"); you may not use this file except in compliance with+ * the License. You may obtain a copy of the License at+ *+ * http://www.apache.org/licenses/LICENSE-2.0+ *+ * Unless required by applicable law or agreed to in writing, software+ * distributed under the License is distributed on an "AS IS" BASIS,+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.+ * See the License for the specific language governing permissions and+ * limitations under the License.+ */+package org.apache.solr.handler.admin;++import javax.imageio.ImageIO;+import java.awt.Color;+import java.awt.image.BufferedImage;+import java.io.ByteArrayOutputStream;+import java.io.Closeable;+import java.io.IOException;+import java.lang.invoke.MethodHandles;+import java.util.ArrayList;+import java.util.Arrays;+import java.util.Collection;+import java.util.Collections;+import java.util.HashMap;+import java.util.HashSet;+import java.util.Iterator;+import java.util.LinkedHashMap;+import java.util.List;+import java.util.Locale;+import java.util.Map;+import java.util.NoSuchElementException;+import java.util.Set;+import java.util.TimeZone;+import java.util.concurrent.ConcurrentHashMap;+import java.util.concurrent.Executors;+import java.util.concurrent.ScheduledThreadPoolExecutor;+import java.util.concurrent.TimeUnit;+import java.util.concurrent.atomic.AtomicBoolean;+import java.util.concurrent.atomic.AtomicReference;+import java.util.concurrent.atomic.DoubleAdder;+import java.util.function.Function;+import java.util.stream.Stream;++import com.google.common.annotations.VisibleForTesting;+import org.apache.solr.api.Api;+import org.apache.solr.api.ApiBag;+import org.apache.solr.client.solrj.SolrClient;+import org.apache.solr.client.solrj.cloud.NodeStateProvider;+import org.apache.solr.client.solrj.cloud.SolrCloudManager;+import org.apache.solr.client.solrj.cloud.autoscaling.ReplicaInfo;+import org.apache.solr.client.solrj.cloud.autoscaling.Suggestion;+import org.apache.solr.client.solrj.cloud.autoscaling.VersionedData;+import org.apache.solr.cloud.Overseer;+import org.apache.solr.common.SolrException;+import org.apache.solr.common.cloud.ClusterState;+import org.apache.solr.common.cloud.DocCollection;+import org.apache.solr.common.cloud.Replica;+import org.apache.solr.common.cloud.Slice;+import org.apache.solr.common.cloud.ZkNodeProps;+import org.apache.solr.common.params.CollectionAdminParams;+import org.apache.solr.common.params.CommonParams;+import org.apache.solr.common.params.ModifiableSolrParams;+import org.apache.solr.common.params.SolrParams;+import org.apache.solr.common.util.Base64;+import org.apache.solr.common.util.NamedList;+import org.apache.solr.common.util.SimpleOrderedMap;+import org.apache.solr.common.util.TimeSource;+import org.apache.solr.handler.RequestHandlerBase;+import org.apache.solr.metrics.SolrMetricManager;+import org.apache.solr.metrics.rrd.SolrRrdBackendFactory;+import org.apache.solr.request.SolrQueryRequest;+import org.apache.solr.response.SolrQueryResponse;+import org.apache.solr.security.AuthorizationContext;+import org.apache.solr.security.PermissionNameProvider;+import org.apache.solr.util.DefaultSolrThreadFactory;+import org.apache.zookeeper.KeeperException;+import org.rrd4j.ConsolFun;+import org.rrd4j.DsType;+import org.rrd4j.core.ArcDef;+import org.rrd4j.core.Archive;+import org.rrd4j.core.Datasource;+import org.rrd4j.core.DsDef;+import org.rrd4j.core.FetchData;+import org.rrd4j.core.FetchRequest;+import org.rrd4j.core.RrdDb;+import org.rrd4j.core.RrdDef;+import org.rrd4j.core.Sample;+import org.rrd4j.graph.RrdGraph;+import org.rrd4j.graph.RrdGraphDef;+import org.slf4j.Logger;+import org.slf4j.LoggerFactory;++import static java.util.stream.Collectors.toMap;+import static org.apache.solr.common.params.CommonParams.ID;++/**+ *+ */+public class MetricsHistoryHandler extends RequestHandlerBase implements PermissionNameProvider, Closeable {+ private static final Logger log = LoggerFactory.getLogger(MethodHandles.lookup().lookupClass());++ public static final List<String> DEFAULT_CORE_COUNTERS = new ArrayList<String>() {{+ add("QUERY./select.requests");+ add("UPDATE./update.requests");+ }};+ public static final List<String> DEFAULT_CORE_GAUGES = new ArrayList<String>() {{+ add("INDEX.sizeInBytes");+ }};+ public static final List<String> DEFAULT_NODE_GAUGES = new ArrayList<String>() {{+ add("CONTAINER.fs.coreRoot.usableSpace");+ }};+ public static final List<String> DEFAULT_JVM_GAUGES = new ArrayList<String>() {{+ add("memory.heap.used");+ add("os.processCpuLoad");+ add("os.systemLoadAverage");+ }};++ public static final String NUM_SHARDS_KEY = "numShards";+ public static final String NUM_REPLICAS_KEY = "numReplicas";+ public static final String NUM_NODES_KEY = "numNodes";++ public static final List<String> DEFAULT_COLLECTION_GAUGES = new ArrayList<String>() {{+ add(NUM_SHARDS_KEY);+ add(NUM_REPLICAS_KEY);+ }};++ public static final String COLLECT_PERIOD_PROP = "collectPeriod";+ public static final String SYNC_PERIOD_PROP = "syncPeriod";+ public static final String ENABLE_PROP = "enable";+ public static final String ENABLE_REPLICAS_PROP = "enableReplicas";+ public static final String ENABLE_NODES_PROP = "enableNodes";++ public static final int DEFAULT_COLLECT_PERIOD = 60;+ public static final String URI_PREFIX = "solr:";++ private final SolrRrdBackendFactory factory;+ private final String nodeName;+ private final SolrClient solrClient;+ private final MetricsHandler metricsHandler;+ private final SolrCloudManager cloudManager;+ private final TimeSource timeSource;+ private final int collectPeriod;+ private final Map<String, List<String>> counters = new HashMap<>();+ private final Map<String, List<String>> gauges = new HashMap<>();++ private final Map<String, RrdDb> knownDbs = new ConcurrentHashMap<>();++ private ScheduledThreadPoolExecutor collectService;+ private boolean logMissingCollection = true;+ private boolean enable;+ private boolean enableReplicas;+ private boolean enableNodes;+ private String versionString;++ public MetricsHistoryHandler(String nodeName, MetricsHandler metricsHandler,+ SolrClient solrClient, SolrCloudManager cloudManager, Map<String, Object> pluginArgs) {++ Map<String, Object> args = new HashMap<>();+ // init from optional solr.xml config+ if (pluginArgs != null) {+ args.putAll(pluginArgs);+ }+ // override from ZK+ Map<String, Object> props = (Map<String, Object>)cloudManager.getClusterStateProvider()+ .getClusterProperty("metrics", Collections.emptyMap())+ .getOrDefault("history", Collections.emptyMap());+ args.putAll(props);++ this.nodeName = nodeName;+ this.enable = Boolean.parseBoolean(String.valueOf(args.getOrDefault(ENABLE_PROP, "true")));+ // default to false - don't collect local per-replica metrics+ this.enableReplicas = Boolean.parseBoolean(String.valueOf(args.getOrDefault(ENABLE_REPLICAS_PROP, "false")));+ this.enableNodes = Boolean.parseBoolean(String.valueOf(args.getOrDefault(ENABLE_NODES_PROP, "false")));+ this.collectPeriod = Integer.parseInt(String.valueOf(args.getOrDefault(COLLECT_PERIOD_PROP, DEFAULT_COLLECT_PERIOD)));+ int syncPeriod = Integer.parseInt(String.valueOf(args.getOrDefault(SYNC_PERIOD_PROP, SolrRrdBackendFactory.DEFAULT_SYNC_PERIOD)));++ factory = new SolrRrdBackendFactory(solrClient, CollectionAdminParams.SYSTEM_COLL,+ syncPeriod, cloudManager.getTimeSource());+ this.solrClient = solrClient;+ this.metricsHandler = metricsHandler;+ this.cloudManager = cloudManager;+ this.timeSource = cloudManager.getTimeSource();++ counters.put(Group.core.toString(), DEFAULT_CORE_COUNTERS);+ counters.put(Group.node.toString(), Collections.emptyList());+ counters.put(Group.jvm.toString(), Collections.emptyList());+ counters.put(Group.collection.toString(), Collections.emptyList());+ gauges.put(Group.core.toString(), DEFAULT_CORE_GAUGES);+ gauges.put(Group.node.toString(), DEFAULT_NODE_GAUGES);+ gauges.put(Group.jvm.toString(), DEFAULT_JVM_GAUGES);+ gauges.put(Group.collection.toString(), DEFAULT_COLLECTION_GAUGES);++ versionString = this.getClass().getPackage().getImplementationVersion();+ if (versionString == null) {+ versionString = "?.?.?";+ }+ if (versionString.length() > 24) {+ versionString = versionString.substring(0, 24) + "...";+ }++ if (enable) {+ collectService = (ScheduledThreadPoolExecutor) Executors.newScheduledThreadPool(1,+ new DefaultSolrThreadFactory("MetricsHistoryHandler"));+ collectService.setRemoveOnCancelPolicy(true);+ collectService.setExecuteExistingDelayedTasksAfterShutdownPolicy(false);+ collectService.scheduleWithFixedDelay(() -> collectMetrics(),+ timeSource.convertDelay(TimeUnit.SECONDS, collectPeriod, TimeUnit.MILLISECONDS),+ timeSource.convertDelay(TimeUnit.SECONDS, collectPeriod, TimeUnit.MILLISECONDS),+ TimeUnit.MILLISECONDS);+ checkSystemCollection();+ }+ }++ public void checkSystemCollection() {+ // check that .system exists+ try {+ if (cloudManager.isClosed() || Thread.interrupted()) {+ factory.setPersistent(false);+ return;+ }+ ClusterState clusterState = cloudManager.getClusterStateProvider().getClusterState();+ DocCollection systemColl = clusterState.getCollectionOrNull(CollectionAdminParams.SYSTEM_COLL);+ if (systemColl == null) {+ if (logMissingCollection) {+ log.warn("Missing " + CollectionAdminParams.SYSTEM_COLL + ", keeping metrics history in memory");+ logMissingCollection = false;+ }+ factory.setPersistent(false);+ return;+ } else {+ boolean ready = false;+ for (Replica r : systemColl.getReplicas()) {+ if (r.isActive(clusterState.getLiveNodes())) {+ ready = true;+ break;+ }+ }+ if (!ready) {+ log.debug(CollectionAdminParams.SYSTEM_COLL + " not ready yet, keeping metrics history in memory");+ factory.setPersistent(false);+ return;+ }+ }+ } catch (Exception e) {+ log.warn("Error getting cluster state, keeping metrics history in memory", e);+ factory.setPersistent(false);+ return;+ }+ logMissingCollection = true;+ factory.setPersistent(true);+ }++ public SolrClient getSolrClient() {+ return solrClient;+ }++ public void removeHistory(String registry) throws IOException {+ registry = SolrMetricManager.overridableRegistryName(registry);+ knownDbs.remove(registry);+ factory.remove(registry);+ }++ @VisibleForTesting+ public SolrRrdBackendFactory getFactory() {+ return factory;+ }++ private boolean isOverseerLeader() {+ ZkNodeProps props = null;+ try {+ VersionedData data = cloudManager.getDistribStateManager().getData(+ Overseer.OVERSEER_ELECT + "/leader");+ if (data != null && data.getData() != null) {+ props = ZkNodeProps.load(data.getData());+ }+ } catch (KeeperException | IOException | NoSuchElementException e) {+ log.warn("Could not obtain overseer's address, skipping.", e);+ return false;+ } catch (InterruptedException e) {+ Thread.currentThread().interrupt();+ return false;+ }+ if (props == null) {+ return false;+ }+ String oid = props.getStr(ID);+ if (oid == null) {+ return false;+ }+ String[] ids = oid.split("-");+ if (ids.length != 3) { // unknown format+ log.warn("Unknown format of leader id, skipping: " + oid);+ return false;+ }+ return nodeName.equals(ids[1]);+ }++ private void collectMetrics() {+ log.debug("-- collectMetrics");+ try {+ checkSystemCollection();+ } catch (Exception e) {+ log.warn("Error checking for .system collection, keeping metrics history in memory", e);+ factory.setPersistent(false);+ }+ // get metrics+ collectLocalReplicaMetrics();+ collectGlobalMetrics();+ }++ private void collectLocalReplicaMetrics() {+ List<Group> groups = new ArrayList<>();+ if (enableNodes) {+ groups.add(Group.jvm);+ groups.add(Group.node);+ }+ if (enableReplicas) {+ groups.add(Group.core);+ }+ for (Group group : groups) {+ if (Thread.interrupted()) {+ return;+ }+ log.debug("-- collecting local " + group + "...");+ ModifiableSolrParams params = new ModifiableSolrParams();+ params.add(MetricsHandler.GROUP_PARAM, group.toString());+ params.add(MetricsHandler.COMPACT_PARAM, "true");+ counters.get(group.toString()).forEach(c -> params.add(MetricsHandler.PREFIX_PARAM, c));+ gauges.get(group.toString()).forEach(c -> params.add(MetricsHandler.PREFIX_PARAM, c));+ AtomicReference<Object> result = new AtomicReference<>();+ try {+ metricsHandler.handleRequest(params, (k, v) -> {+ if (k.equals("metrics")) {+ result.set(v);+ }+ });+ NamedList nl = (NamedList)result.get();+ if (nl != null) {+ for (Iterator<Map.Entry<String, Object>> it = nl.iterator(); it.hasNext(); ) {+ Map.Entry<String, Object> entry = it.next();+ String registry = entry.getKey();+ if (group != Group.core) { // add nodeName suffix+ registry = registry + "." + nodeName;+ }++ RrdDb db = getOrCreateDb(registry, group);+ if (db == null) {+ continue;+ }+ // set the timestamp+ Sample s = db.createSample(TimeUnit.SECONDS.convert(timeSource.getEpochTimeNs(), TimeUnit.NANOSECONDS));+ NamedList<Object> values = (NamedList<Object>)entry.getValue();+ AtomicBoolean dirty = new AtomicBoolean(false);+ counters.get(group.toString()).forEach(c -> {+ Number val = (Number)values.get(c);+ if (val != null) {+ dirty.set(true);+ s.setValue(c, val.doubleValue());+ }+ });+ gauges.get(group.toString()).forEach(c -> {+ Number val = (Number)values.get(c);+ if (val != null) {+ dirty.set(true);+ s.setValue(c, val.doubleValue());+ }+ });+ if (dirty.get()) {+ s.update();+ }+ }+ }+ } catch (Exception e) {+ e.printStackTrace();+ }+ }+ }++ private void collectGlobalMetrics() {+ if (!isOverseerLeader()) {+ return;+ }+ Set<String> nodes = new HashSet<>(cloudManager.getClusterStateProvider().getLiveNodes());+ NodeStateProvider nodeStateProvider = cloudManager.getNodeStateProvider();+ Set<String> collTags = new HashSet<>();+ collTags.addAll(counters.get(Group.core.toString()));+ collTags.addAll(gauges.get(Group.core.toString()));++ Set<String> nodeTags = new HashSet<>();+ String nodePrefix = "metrics:" + SolrMetricManager.getRegistryName(Group.node) + ":";+ counters.get(Group.node.toString()).forEach(name -> {+ nodeTags.add(nodePrefix + name);+ });+ gauges.get(Group.node.toString()).forEach(name -> {+ nodeTags.add(nodePrefix + name);+ });+ String jvmPrefix = "metrics:" + SolrMetricManager.getRegistryName(Group.jvm) + ":";+ counters.get(Group.jvm.toString()).forEach(name -> {+ nodeTags.add(jvmPrefix + name);+ });+ gauges.get(Group.jvm.toString()).forEach(name -> {+ nodeTags.add(jvmPrefix + name);+ });++ // per-registry totals+ // XXX at the moment the type of metrics that we collect allows+ // adding all partial values. At some point it may be necessary to implement+ // other aggregation functions.+ // group : registry : name : value+ Map<Group, Map<String, Map<String, Number>>> totals = new HashMap<>();++ // collect and aggregate per-collection totals+ for (String node : nodes) {+ if (cloudManager.isClosed() || Thread.interrupted()) {+ return;+ }+ // add core-level stats+ Map<String, Map<String, List<ReplicaInfo>>> infos = nodeStateProvider.getReplicaInfo(node, collTags);+ infos.forEach((coll, shards) -> {+ shards.forEach((sh, replicas) -> {+ String registry = SolrMetricManager.getRegistryName(Group.collection, coll);+ Map<String, Number> perReg = totals+ .computeIfAbsent(Group.collection, g -> new HashMap<>())+ .computeIfAbsent(registry, r -> new HashMap<>());+ replicas.forEach(ri -> {+ collTags.forEach(tag -> {+ double value = ((Number)ri.getVariable(tag, 0.0)).doubleValue();+ // TODO: fix this when Suggestion.Condition.DISK_IDX uses proper conversion+ if (tag.contains(Suggestion.coreidxsize)) {+ value = value * 1024.0 * 1024.0 * 1024.0;+ }+ DoubleAdder adder = (DoubleAdder)perReg.computeIfAbsent(tag, t -> new DoubleAdder());+ adder.add(value);+ });+ });+ });+ });+ // add node-level stats+ Map<String, Object> nodeValues = nodeStateProvider.getNodeValues(node, nodeTags);+ for (Group g : Arrays.asList(Group.node, Group.jvm)) {+ String registry = SolrMetricManager.getRegistryName(g);+ Map<String, Number> perReg = totals+ .computeIfAbsent(g, gr -> new HashMap<>())+ .computeIfAbsent(registry, r -> new HashMap<>());+ Set<String> names = new HashSet<>();+ names.addAll(counters.get(g.toString()));+ names.addAll(gauges.get(g.toString()));+ names.forEach(name -> {+ String tag = "metrics:" + registry + ":" + name;+ double value = ((Number)nodeValues.getOrDefault(tag, 0.0)).doubleValue();+ DoubleAdder adder = (DoubleAdder)perReg.computeIfAbsent(name, t -> new DoubleAdder());+ adder.add(value);+ });+ }+ }++ // add numNodes+ String nodeReg = SolrMetricManager.getRegistryName(Group.node);+ Map<String, Number> perNodeReg = totals+ .computeIfAbsent(Group.node, gr -> new HashMap<>())+ .computeIfAbsent(nodeReg, r -> new HashMap<>());+ perNodeReg.put(NUM_NODES_KEY, nodes.size());++ // add some global collection-level stats+ try {+ ClusterState state = cloudManager.getClusterStateProvider().getClusterState();+ state.forEachCollection(coll -> {+ String registry = SolrMetricManager.getRegistryName(Group.collection, coll.getName());+ Map<String, Number> perReg = totals+ .computeIfAbsent(Group.collection, g -> new HashMap<>())+ .computeIfAbsent(registry, r -> new HashMap<>());+ Collection<Slice> slices = coll.getActiveSlices();+ perReg.put(NUM_SHARDS_KEY, slices.size());+ DoubleAdder numActiveReplicas = new DoubleAdder();+ slices.forEach(s -> {+ s.forEach(r -> {+ if (r.isActive(state.getLiveNodes())) {+ numActiveReplicas.add(1.0);+ }+ });+ });+ perReg.put(NUM_REPLICAS_KEY, numActiveReplicas);+ });+ } catch (IOException e) {+ log.warn("Exception getting cluster state", e);+ }++ // now update the db-s+ totals.forEach((group, perGroup) -> {+ perGroup.forEach((reg, perReg) -> {+ RrdDb db = getOrCreateDb(reg, group);+ if (db == null) {+ return;+ }+ try {+ // set the timestamp+ Sample s = db.createSample(TimeUnit.SECONDS.convert(timeSource.getEpochTimeNs(), TimeUnit.NANOSECONDS));+ AtomicBoolean dirty = new AtomicBoolean(false);+ List<Group> groups = new ArrayList<>();+ groups.add(group);+ if (group == Group.collection) {+ groups.add(Group.core);+ }+ for (Group g : groups) {+ counters.get(g.toString()).forEach(c -> {+ Number val = perReg.get(c);+ if (val != null) {+ dirty.set(true);+ s.setValue(c, val.doubleValue());+ }+ });+ gauges.get(g.toString()).forEach(c -> {+ Number val = perReg.get(c);+ if (val != null) {+ dirty.set(true);+ s.setValue(c, val.doubleValue());+ }+ });+ }+ if (dirty.get()) {+ s.update();+ }+ } catch (Exception e) {+ }+ });+ });+ }++ private RrdDef createDef(String registry, Group group) {+ registry = SolrMetricManager.overridableRegistryName(registry);++ // base sampling period is collectPeriod - samples more frequent than+ // that will be dropped, samples less frequent will be interpolated+ RrdDef def = new RrdDef(URI_PREFIX + registry, collectPeriod);+ // set the start time early enough so that the first sample is always later+ // than the start of the archive+ def.setStartTime(TimeUnit.SECONDS.convert(timeSource.getEpochTimeNs(), TimeUnit.NANOSECONDS) - def.getStep());++ // add datasources+ List<Group> groups = new ArrayList<>();+ groups.add(group);+ if (group == Group.collection) {+ groups.add(Group.core);+ }+ for (Group g : groups) {+ // use NaN when more than 1 sample is missing+ counters.get(g.toString()).forEach(name ->+ def.addDatasource(name, DsType.COUNTER, collectPeriod * 2, Double.NaN, Double.NaN));+ gauges.get(g.toString()).forEach(name ->+ def.addDatasource(name, DsType.GAUGE, collectPeriod * 2, Double.NaN, Double.NaN));+ }+ if (groups.contains(Group.node)) {+ // add nomNodes gauge+ def.addDatasource(NUM_NODES_KEY, DsType.GAUGE, collectPeriod * 2, Double.NaN, Double.NaN);+ }++ // add archives++ // use AVERAGE consolidation,+ // use NaN when >50% samples are missing+ def.addArchive(ConsolFun.AVERAGE, 0.5, 1, 240); // 4 hours+ def.addArchive(ConsolFun.AVERAGE, 0.5, 10, 288); // 48 hours+ def.addArchive(ConsolFun.AVERAGE, 0.5, 60, 336); // 2 weeks+ def.addArchive(ConsolFun.AVERAGE, 0.5, 240, 180); // 2 months+ def.addArchive(ConsolFun.AVERAGE, 0.5, 1440, 365); // 1 year+ return def;+ }++ private RrdDb getOrCreateDb(String registry, Group group) {+ RrdDb db = knownDbs.computeIfAbsent(registry, r -> {+ RrdDef def = createDef(r, group);+ try {+ RrdDb newDb = new RrdDb(def, factory);+ return newDb;+ } catch (IOException e) {+ return null;+ }+ });+ return db;+ }++ @Override+ public void close() {+ log.debug("Closing " + hashCode());+ if (collectService != null) {+ collectService.shutdownNow();+ }+ if (factory != null) {+ factory.close();+ }+ knownDbs.clear();+ }++ public enum Cmd {+ LIST, STATUS, GET, DELETE;++ static final Map<String, Cmd> actions = Collections.unmodifiableMap(+ Stream.of(Cmd.values())+ .collect(toMap(Cmd::toLower, Function.identity())));++ public static Cmd get(String p) {+ return p == null ? null : actions.get(p.toLowerCase(Locale.ROOT));+ }++ public String toLower() {+ return toString().toLowerCase(Locale.ROOT);+ }+ }++ public enum Format {+ LIST, STRING, GRAPH;++ static final Map<String, Format> formats = Collections.unmodifiableMap(+ Stream.of(Format.values())+ .collect(toMap(Format::toLower, Function.identity())));++ public static Format get(String p) {+ return p == null ? null : formats.get(p.toLowerCase(Locale.ROOT));+ }++ public String toLower() {+ return toString().toLowerCase(Locale.ROOT);+ }+ }+++ @Override+ public void handleRequestBody(SolrQueryRequest req, SolrQueryResponse rsp) throws Exception {+ String actionStr = req.getParams().get(CommonParams.ACTION);+ if (actionStr == null) {+ throw new SolrException(SolrException.ErrorCode.BAD_REQUEST, "'action' is a required param");+ }+ Cmd cmd = Cmd.get(actionStr);+ if (cmd == null) {+ throw new SolrException(SolrException.ErrorCode.BAD_REQUEST, "unknown 'action' param '" + actionStr + "', supported actions: " + Cmd.actions);+ }+ Object res = null;+ switch (cmd) {+ case LIST:+ int rows = req.getParams().getInt(CommonParams.ROWS, SolrRrdBackendFactory.DEFAULT_MAX_DBS);+ res = factory.list(rows);+ break;+ case GET:+ String name = req.getParams().get(CommonParams.NAME);+ if (name == null) {+ throw new SolrException(SolrException.ErrorCode.BAD_REQUEST, "'name' is a required param");+ }+ String[] dsNames = req.getParams().getParams("ds");+ String formatStr = req.getParams().get("format", Format.LIST.toString());+ Format format = Format.get(formatStr);+ if (format == null) {+ throw new SolrException(SolrException.ErrorCode.BAD_REQUEST, "unknown 'format' param '" + formatStr + "', supported formats: " + Format.formats);+ }+ if (!factory.exists(name)) {+ rsp.add("error", "'" + name + "' doesn't exist");+ } else {+ // get a throwaway copy (safe to close and discard)+ RrdDb db = new RrdDb(URI_PREFIX + name, true, factory);+ res = new NamedList<>();+ NamedList<Object> data = new NamedList<>();+ data.add("data", getDbData(db, dsNames, format, req.getParams()));+ ((NamedList)res).add(name, data);+ db.close();+ }+ break;+ case STATUS:+ name = req.getParams().get(CommonParams.NAME);+ if (name == null) {+ throw new SolrException(SolrException.ErrorCode.BAD_REQUEST, "'name' is a required param");+ }+ if (!factory.exists(name)) {+ rsp.add("error", "'" + name + "' doesn't exist");+ } else {+ // get a throwaway copy (safe to close and discard)+ RrdDb db = new RrdDb(URI_PREFIX + name, true, factory);+ NamedList<Object> map = new NamedList<>();+ NamedList<Object> status = new NamedList<>();+ status.add("status", getDbStatus(db));+ map.add(name, status);+ db.close();+ res = map;+ }+ break;+ case DELETE:+ name = req.getParams().get(CommonParams.NAME);+ if (name == null) {+ throw new SolrException(SolrException.ErrorCode.BAD_REQUEST, "'name' is a required param");+ }+ if (name.equalsIgnoreCase("all") || name.equals("*")) {+ factory.removeAll();+ } else {+ factory.remove(name);+ }+ rsp.add("success", "ok");+ break;+ }+ if (res != null) {+ rsp.add("metrics", res);+ }+ }++ private NamedList<Object> getDbStatus(RrdDb db) throws IOException {+ NamedList<Object> res = new SimpleOrderedMap<>();+ res.add("lastModified", db.getLastUpdateTime());+ RrdDef def = db.getRrdDef();+ res.add("step", def.getStep());+ res.add("datasourceCount", db.getDsCount());+ res.add("archiveCount", db.getArcCount());+ res.add("datasourceNames", Arrays.asList(db.getDsNames()));+ List<Object> dss = new ArrayList<>(db.getDsCount());+ res.add("datasources", dss);+ for (DsDef dsDef : def.getDsDefs()) {+ Map<String, Object> map = new LinkedHashMap<>();+ map.put("datasource", dsDef.dump());+ Datasource ds = db.getDatasource(dsDef.getDsName());+ map.put("lastValue", ds.getLastValue());+ dss.add(map);+ }+ List<Object> archives = new ArrayList<>(db.getArcCount());+ res.add("archives", archives);+ ArcDef[] arcDefs = def.getArcDefs();+ for (int i = 0; i < db.getArcCount(); i++) {+ Archive a = db.getArchive(i);+ Map<String, Object> map = new LinkedHashMap<>();+ map.put("archive", arcDefs[i].dump());+ map.put("steps", a.getSteps());+ map.put("consolFun", a.getConsolFun().name());+ map.put("xff", a.getXff());+ map.put("startTime", a.getStartTime());+ map.put("endTime", a.getEndTime());+ map.put("rows", a.getRows());+ archives.add(map);+ }++ return res;+ }++ private NamedList<Object> getDbData(RrdDb db, String[] dsNames, Format format, SolrParams params) throws IOException {+ NamedList<Object> res = new SimpleOrderedMap<>();+ if (dsNames == null || dsNames.length == 0) {+ dsNames = db.getDsNames();+ }+ StringBuilder str = new StringBuilder();+ RrdDef def = db.getRrdDef();+ ArcDef[] arcDefs = def.getArcDefs();+ for (ArcDef arcDef : arcDefs) {+ SimpleOrderedMap map = new SimpleOrderedMap();+ res.add(arcDef.dump(), map);+ Archive a = db.getArchive(arcDef.getConsolFun(), arcDef.getSteps());+ // startTime / endTime, arcStep are in seconds+ FetchRequest fr = db.createFetchRequest(arcDef.getConsolFun(),+ a.getStartTime() - a.getArcStep(),+ a.getEndTime() + a.getArcStep());+ FetchData fd = fr.fetchData();+ if (format != Format.GRAPH) {+ // add timestamps separately from values+ long[] timestamps = fd.getTimestamps();+ str.setLength(0);+ for (int i = 0; i < timestamps.length; i++) {+ if (format == Format.LIST) {+ map.add("timestamps", timestamps[i]);+ } else {+ if (i > 0) {+ str.append('\n');+ }+ str.append(String.valueOf(timestamps[i]));+ }+ }+ if (format == Format.STRING) {+ map.add("timestamps", str.toString());+ }+ }+ SimpleOrderedMap values = new SimpleOrderedMap();+ map.add("values", values);+ for (String name : dsNames) {+ double[] vals = fd.getValues(name);+ switch (format) {+ case GRAPH:+ RrdGraphDef graphDef = new RrdGraphDef();+ graphDef.setTitle(name);+ graphDef.datasource(name, fd);+ graphDef.setStartTime(a.getStartTime() - a.getArcStep());+ graphDef.setEndTime(a.getEndTime() + a.getArcStep());+ graphDef.setPoolUsed(false);+ graphDef.setAltAutoscale(true);+ graphDef.setAltYGrid(true);+ graphDef.setAltYMrtg(true);+ graphDef.setSignature("Apache Solr " + versionString);+ graphDef.setNoLegend(true);+ graphDef.setAntiAliasing(true);+ graphDef.setTextAntiAliasing(true);+ graphDef.setWidth(500);+ graphDef.setHeight(175);+ graphDef.setTimeZone(TimeZone.getDefault());+ graphDef.setLocale(Locale.getDefault());+ // redraw immediately+ graphDef.setLazy(false);+ // area with a border+ graphDef.area(name, new Color(0xffb860), null);+ graphDef.line(name, Color.RED, null, 1.0f);+ RrdGraph graph = new RrdGraph(graphDef);+ BufferedImage bi = new BufferedImage(+ graph.getRrdGraphInfo().getWidth(),+ graph.getRrdGraphInfo().getHeight(),+ BufferedImage.TYPE_INT_RGB);+ graph.render(bi.getGraphics());+ ByteArrayOutputStream baos = new ByteArrayOutputStream();+ ImageIO.write(bi, "png", baos);+ values.add(name, Base64.byteArrayToBase64(baos.toByteArray()));+ break;+ case STRING:+ str.setLength(0);+ for (int i = 0; i < vals.length; i++) {+ if (i > 0) {+ str.append('\n');+ }+ str.append(String.valueOf(vals[i]));+ }+ values.add(name, str.toString());+ break;+ case LIST:+ for (int i = 0; i < vals.length; i++) {+ values.add(name, vals[i]);+ }+ break;+ }+ }+ }+ return res;+ }++ @Override+ public String getDescription() {+ return "A handler for metrics history";+ }++ @Override+ public Name getPermissionName(AuthorizationContext request) {+ return Name.METRICS_HISTORY_READ_PERM;+ }++ @Override+ public Boolean registerV2() {+ return Boolean.TRUE;+ }++ @Override+ public Collection<Api> getApis() {+ return ApiBag.wrapRequestHandlers(this, "metrics.history");+ }++}diff --git a/solr/core/src/java/org/apache/solr/metrics/SolrMetricManager.java b/solr/core/src/java/org/apache/solr/metrics/SolrMetricManager.javaindex d5b8864e7b9..5fa365943a5 100644--- a/solr/core/src/java/org/apache/solr/metrics/SolrMetricManager.java+++ b/solr/core/src/java/org/apache/solr/metrics/SolrMetricManager.java@@ -423,14 +423,14 @@ public class SolrMetricManager {} else {swapLock.lock();try {- return getOrCreate(registries, registry);+ return getOrCreateRegistry(registries, registry);} finally {swapLock.unlock();}}}- private static MetricRegistry getOrCreate(ConcurrentMap<String, MetricRegistry> map, String registry) {+ private static MetricRegistry getOrCreateRegistry(ConcurrentMap<String, MetricRegistry> map, String registry) {final MetricRegistry existing = map.get(registry);if (existing == null) {final MetricRegistry created = new MetricRegistry();diff --git a/solr/core/src/java/org/apache/solr/metrics/rrd/SolrRrdBackend.java b/solr/core/src/java/org/apache/solr/metrics/rrd/SolrRrdBackend.javanew file mode 100644index 00000000000..956aabba44c--- /dev/null+++ b/solr/core/src/java/org/apache/solr/metrics/rrd/SolrRrdBackend.java@@ -0,0 +1,118 @@+/*+ * Licensed to the Apache Software Foundation (ASF) under one or more+ * contributor license agreements. See the NOTICE file distributed with+ * this work for additional information regarding copyright ownership.+ * The ASF licenses this file to You under the Apache License, Version 2.0+ * (the "License"); you may not use this file except in compliance with+ * the License. You may obtain a copy of the License at+ *+ * http://www.apache.org/licenses/LICENSE-2.0+ *+ * Unless required by applicable law or agreed to in writing, software+ * distributed under the License is distributed on an "AS IS" BASIS,+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.+ * See the License for the specific language governing permissions and+ * limitations under the License.+ */+package org.apache.solr.metrics.rrd;++import java.io.Closeable;+import java.io.IOException;+import java.lang.invoke.MethodHandles;+import java.util.concurrent.locks.ReentrantLock;++import org.rrd4j.core.RrdByteArrayBackend;+import org.slf4j.Logger;+import org.slf4j.LoggerFactory;++/**+ *+ */+public class SolrRrdBackend extends RrdByteArrayBackend implements Closeable {+ private static final Logger log = LoggerFactory.getLogger(MethodHandles.lookup().lookupClass());++ private final SolrRrdBackendFactory factory;+ private final boolean readOnly;+ private final ReentrantLock lock = new ReentrantLock();+ private volatile boolean dirty = false;+ private volatile boolean closed = false;++ public SolrRrdBackend(String path, boolean readOnly, SolrRrdBackendFactory factory) {+ super(path);+ this.factory = factory;+ try {+ byte[] data = factory.getData(path);+ if (data != null) {+ this.buffer = data;+ }+ } catch (IOException e) {+ log.warn("Exception retrieving data from " + path + ", store will be readOnly", e);+ readOnly = true;+ }+ this.readOnly = readOnly;+ }++ /**+ * Open an unregistered (throwaway) read-only clone of another backend.+ * @param other other backend+ */+ public SolrRrdBackend(SolrRrdBackend other) {+ super(other.getPath());+ readOnly = true;+ factory = null;+ byte[] otherBuffer = other.buffer;+ buffer = new byte[otherBuffer.length];+ System.arraycopy(otherBuffer, 0, buffer, 0, otherBuffer.length);+ }++ public boolean isReadOnly() {+ return readOnly;+ }++ @Override+ protected void write(long offset, byte[] bytes) throws IOException {+ if (readOnly || closed) {+ return;+ }+ lock.lock();+ try {+ super.write(offset, bytes);+ dirty = true;+ } finally {+ lock.unlock();+ }+ }++ public byte[] getSyncData() {+ if (readOnly || closed) {+ return null;+ }+ if (!dirty) {+ return null;+ }+ // hold a lock to block writes so that we get consistent data+ lock.lock();+ try {+ byte[] bufferCopy = new byte[buffer.length];+ System.arraycopy(buffer, 0, bufferCopy, 0, buffer.length);+ return bufferCopy;+ } finally {+ lock.unlock();+ }+ }++ public void markClean() {+ dirty = false;+ }++ @Override+ public void close() throws IOException {+ super.close();+ closed = true;+ if (factory != null) {+ // unregister myself from the factory+ factory.unregisterBackend(getPath());+ }+ // close+ }+}diff --git a/solr/core/src/java/org/apache/solr/metrics/rrd/SolrRrdBackendFactory.java b/solr/core/src/java/org/apache/solr/metrics/rrd/SolrRrdBackendFactory.javanew file mode 100644index 00000000000..06ab5fe3888--- /dev/null+++ b/solr/core/src/java/org/apache/solr/metrics/rrd/SolrRrdBackendFactory.java@@ -0,0 +1,418 @@+/*+ * Licensed to the Apache Software Foundation (ASF) under one or more+ * contributor license agreements. See the NOTICE file distributed with+ * this work for additional information regarding copyright ownership.+ * The ASF licenses this file to You under the Apache License, Version 2.0+ * (the "License"); you may not use this file except in compliance with+ * the License. You may obtain a copy of the License at+ *+ * http://www.apache.org/licenses/LICENSE-2.0+ *+ * Unless required by applicable law or agreed to in writing, software+ * distributed under the License is distributed on an "AS IS" BASIS,+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.+ * See the License for the specific language governing permissions and+ * limitations under the License.+ */+package org.apache.solr.metrics.rrd;++import java.io.IOException;+import java.lang.invoke.MethodHandles;+import java.net.URI;+import java.net.URISyntaxException;+import java.util.ArrayList;+import java.util.Collections;+import java.util.Date;+import java.util.HashMap;+import java.util.HashSet;+import java.util.Iterator;+import java.util.List;+import java.util.Locale;+import java.util.Map;+import java.util.Set;+import java.util.concurrent.ConcurrentHashMap;+import java.util.concurrent.Executors;+import java.util.concurrent.ScheduledThreadPoolExecutor;+import java.util.concurrent.TimeUnit;++import org.apache.solr.client.solrj.SolrClient;+import org.apache.solr.client.solrj.SolrServerException;+import org.apache.solr.client.solrj.response.QueryResponse;+import org.apache.solr.common.SolrCloseable;+import org.apache.solr.common.SolrDocument;+import org.apache.solr.common.SolrDocumentList;+import org.apache.solr.common.SolrException;+import org.apache.solr.common.SolrInputDocument;+import org.apache.solr.common.params.CollectionAdminParams;+import org.apache.solr.common.params.CommonParams;+import org.apache.solr.common.params.ModifiableSolrParams;+import org.apache.solr.common.util.IOUtils;+import org.apache.solr.common.util.TimeSource;+import org.apache.solr.util.DefaultSolrThreadFactory;+import org.rrd4j.core.RrdBackend;+import org.rrd4j.core.RrdBackendFactory;+import org.slf4j.Logger;+import org.slf4j.LoggerFactory;++/**+ * RRD backend factory using Solr documents as underlying storage.+ * <p>RRD databases are identified by paths in the format <code>solr:dbName</code>.+ * Typically the path will correspond to the name of metric or a group of metrics, eg:+ * <code>solr:QUERY./select.requests</code></p>+ * <p>NOTE: Solr doesn't register instances of this factory in the static+ * registry {@link RrdBackendFactory#registerFactory(RrdBackendFactory)} because+ * it's then impossible to manage its life-cycle.</p>+ */+public class SolrRrdBackendFactory extends RrdBackendFactory implements SolrCloseable {+ private static final Logger log = LoggerFactory.getLogger(MethodHandles.lookup().lookupClass());++ public static final int DEFAULT_SYNC_PERIOD = 60;+ public static final int DEFAULT_MAX_DBS = 500;++ public static final String NAME = "SOLR";+ public static final String URI_PREFIX = "solr:";+ public static final String ID_SEP = "|";+ public static final String ID_PREFIX = "rrd";+ public static final String DOC_TYPE = "metrics_rrd";++ public static final String DATA_FIELD = "data_bin";++ private final SolrClient solrClient;+ private final TimeSource timeSource;+ private final String collection;+ private final int syncPeriod;+ private final int idPrefixLength;+ private ScheduledThreadPoolExecutor syncService;+ private volatile boolean closed = false;+ private volatile boolean persistent = true;++ private final Map<String, SolrRrdBackend> backends = new ConcurrentHashMap<>();++ /**+ * Create a factory.+ * @param solrClient SolrClient to use+ * @param collection collection name where documents are stored (typically this is+ * {@link CollectionAdminParams#SYSTEM_COLL})+ * @param syncPeriod synchronization period in seconds - how often modified+ * databases are stored as updated Solr documents+ * @param timeSource time source+ */+ public SolrRrdBackendFactory(SolrClient solrClient, String collection, int syncPeriod, TimeSource timeSource) {+ this.solrClient = solrClient;+ this.timeSource = timeSource;+ this.collection = collection;+ this.syncPeriod = syncPeriod;+ log.debug("Created " + hashCode());+ this.idPrefixLength = ID_PREFIX.length() + ID_SEP.length();+ syncService = (ScheduledThreadPoolExecutor) Executors.newScheduledThreadPool(2,+ new DefaultSolrThreadFactory("SolrRrdBackendFactory"));+ syncService.setRemoveOnCancelPolicy(true);+ syncService.setExecuteExistingDelayedTasksAfterShutdownPolicy(false);+ syncService.scheduleWithFixedDelay(() -> maybeSyncBackends(),+ timeSource.convertDelay(TimeUnit.SECONDS, syncPeriod, TimeUnit.MILLISECONDS),+ timeSource.convertDelay(TimeUnit.SECONDS, syncPeriod, TimeUnit.MILLISECONDS),+ TimeUnit.MILLISECONDS);+ }++ private void ensureOpen() throws IOException {+ if (closed) {+ throw new IOException("Factory already closed");+ }+ }++ @Override+ public boolean canStore(URI uri) {+ if (uri == null) {+ return false;+ }+ if (uri.getScheme().toUpperCase(Locale.ROOT).equals(getName())) {+ return true;+ } else {+ return false;+ }+ }++ @Override+ public String getPath(URI uri) {+ return uri.getSchemeSpecificPart();+ }++ @Override+ public URI getUri(String path) {+ if (!path.startsWith(URI_PREFIX)) {+ path = URI_PREFIX + path;+ }+ try {+ return new URI(path);+ } catch (URISyntaxException e) {+ throw new IllegalArgumentException("Invalid path: " + path);+ }+ }++ /**+ * Open (or get) a backend.+ * @param path backend path (without URI scheme)+ * @param readOnly if true then the backend will never be synchronized to Solr,+ * and updates will be silently ignored. Read-only backends can+ * be safely closed and discarded after use.+ * @return an instance of Solr backend.+ * @throws IOException on Solr error when retrieving existing data+ */+ @Override+ protected synchronized RrdBackend open(String path, boolean readOnly) throws IOException {+ ensureOpen();+ SolrRrdBackend backend = backends.computeIfAbsent(path, p -> new SolrRrdBackend(p, readOnly, this));+ if (backend.isReadOnly()) {+ if (readOnly) {+ return backend;+ } else {+ // replace it with a writable one+ backend = new SolrRrdBackend(path, readOnly, this);+ backends.put(path, backend);+ return backend;+ }+ } else {+ if (readOnly) {+ // return a throwaway unregistered read-only copy+ return new SolrRrdBackend(backend);+ } else {+ return backend;+ }+ }+ }++ byte[] getData(String path) throws IOException {+ if (!persistent) {+ return null;+ }+ try {+ ModifiableSolrParams params = new ModifiableSolrParams();+ params.add(CommonParams.Q, "{!term f=id}" + ID_PREFIX + ID_SEP + path);+ params.add(CommonParams.FQ, CommonParams.TYPE + ":" + DOC_TYPE);+ QueryResponse rsp = solrClient.query(collection, params);+ SolrDocumentList docs = rsp.getResults();+ if (docs == null || docs.isEmpty()) {+ return null;+ }+ if (docs.size() > 1) {+ throw new SolrServerException("Expected at most 1 doc with id '" + path + "' but got " + docs);+ }+ SolrDocument doc = docs.get(0);+ Object o = doc.getFieldValue(DATA_FIELD);+ if (o == null) {+ return null;+ }+ if (o instanceof byte[]) {+ return (byte[])o;+ } else {+ throw new SolrServerException("Unexpected value of '" + DATA_FIELD + "' field: " + o.getClass().getName() + ": " + o);+ }+ } catch (SolrServerException e) {+ throw new IOException(e);+ }+ }++ void unregisterBackend(String path) {+ backends.remove(path);+ }++ /**+ * List all available databases created by this node name+ * @param maxLength maximum number of results to return+ * @return list of database names, or empty+ * @throws IOException on server errors+ */+ public List<String> list(int maxLength) throws IOException {+ Set<String> names = new HashSet<>();+ if (persistent) {+ try {+ ModifiableSolrParams params = new ModifiableSolrParams();+ params.add(CommonParams.Q, "*:*");+ params.add(CommonParams.FQ, CommonParams.TYPE + ":" + DOC_TYPE);+ params.add(CommonParams.FL, "id");+ params.add(CommonParams.ROWS, String.valueOf(maxLength));+ QueryResponse rsp = solrClient.query(collection, params);+ SolrDocumentList docs = rsp.getResults();+ if (docs != null) {+ docs.forEach(d -> names.add(((String)d.getFieldValue("id")).substring(idPrefixLength)));+ }+ } catch (SolrServerException e) {+ log.warn("Error retrieving RRD list", e);+ }+ }+ // add in-memory backends not yet stored+ names.addAll(backends.keySet());+ ArrayList<String> list = new ArrayList<>(names);+ Collections.sort(list);+ return list;+ }++ /**+ * Remove all databases created by this node name.+ * @throws IOException on server error+ */+ public void removeAll() throws IOException {+ for (Iterator<SolrRrdBackend> it = backends.values().iterator(); it.hasNext(); ) {+ SolrRrdBackend backend = it.next();+ it.remove();+ IOUtils.closeQuietly(backend);+ }+ if (!persistent) {+ return;+ }+ // remove all Solr docs+ try {+ solrClient.deleteByQuery(collection,+ "{!term f=" + CommonParams.TYPE + "}:" + DOC_TYPE, syncPeriod * 1000);+ } catch (SolrServerException e) {+ log.warn("Error deleting RRDs", e);+ }+ }++ /**+ * Remove a database.+ * @param path database path.+ * @throws IOException on Solr exception+ */+ public void remove(String path) throws IOException {+ SolrRrdBackend backend = backends.remove(path);+ if (backend != null) {+ IOUtils.closeQuietly(backend);+ }+ if (!persistent) {+ return;+ }+ // remove Solr doc+ try {+ solrClient.deleteByQuery(collection, "{!term f=id}" + ID_PREFIX + ID_SEP + path);+ } catch (SolrServerException | SolrException e) {+ log.warn("Error deleting RRD for path " + path, e);+ }+ }++ synchronized void maybeSyncBackends() {+ if (closed) {+ return;+ }+ if (!persistent) {+ return;+ }+ if (Thread.interrupted()) {+ return;+ }+ log.debug("-- maybe sync backends: " + backends.keySet());+ Map<String, byte[]> syncData = new HashMap<>();+ backends.forEach((path, backend) -> {+ byte[] data = backend.getSyncData();+ if (data != null) {+ syncData.put(backend.getPath(), data);+ }+ });+ if (syncData.isEmpty()) {+ return;+ }+ log.debug("-- syncing " + syncData.keySet());+ // write updates+ try {+ syncData.forEach((path, data) -> {+ SolrInputDocument doc = new SolrInputDocument();+ doc.setField("id", ID_PREFIX + ID_SEP + path);+ doc.addField(CommonParams.TYPE, DOC_TYPE);+ doc.addField(DATA_FIELD, data);+ doc.setField("timestamp", new Date(TimeUnit.MILLISECONDS.convert(timeSource.getEpochTimeNs(), TimeUnit.NANOSECONDS)));+ try {+ solrClient.add(collection, doc);+ } catch (SolrServerException | IOException e) {+ log.warn("Error updating RRD data for " + path, e);+ }+ });+ if (Thread.interrupted()) {+ return;+ }+ try {+ solrClient.commit(collection);+ } catch (SolrServerException e) {+ log.warn("Error committing RRD data updates", e);+ }+ syncData.forEach((path, data) -> {+ SolrRrdBackend backend = backends.get(path);+ if (backend != null) {+ backend.markClean();+ }+ });+ } catch (IOException e) {+ log.warn("Error sending RRD data updates", e);+ }+ }++ /**+ * Check for existence of a backend.+ * @param path backend path, without the URI scheme+ * @return true when a backend exists. Note that a backend may exist only+ * in memory if it was created recently within {@link #syncPeriod}.+ * @throws IOException on Solr exception+ */+ @Override+ public boolean exists(String path) throws IOException {+ // check in-memory backends first+ if (backends.containsKey(path)) {+ return true;+ }+ if (!persistent) {+ return false;+ }+ try {+ ModifiableSolrParams params = new ModifiableSolrParams();+ params.add(CommonParams.Q, "{!term f=id}" + ID_PREFIX + ID_SEP + path);+ params.add(CommonParams.FQ, CommonParams.TYPE + ":" + DOC_TYPE);+ params.add(CommonParams.FL, "id");+ QueryResponse rsp = solrClient.query(collection, params);+ SolrDocumentList docs = rsp.getResults();+ if (docs == null || docs.isEmpty()) {+ return false;+ }+ if (docs.size() > 1) {+ throw new SolrServerException("Expected at most 1 doc with id '" + path + "' but got " + docs);+ }+ return true;+ } catch (SolrServerException e) {+ throw new IOException(e);+ }+ }++ public boolean isPersistent() {+ return persistent;+ }++ public void setPersistent(boolean persistent) {+ this.persistent = persistent;+ }++ @Override+ protected boolean shouldValidateHeader(String path) throws IOException {+ return false;+ }++ @Override+ public String getName() {+ return NAME;+ }++ @Override+ public boolean isClosed() {+ return closed;+ }++ @Override+ public void close() {+ if (closed) {+ return;+ }+ log.debug("Closing " + hashCode());+ closed = true;+ backends.forEach((p, b) -> IOUtils.closeQuietly(b));+ backends.clear();+ syncService.shutdownNow();+ syncService = null;+ }+}diff --git a/solr/core/src/java/org/apache/solr/metrics/rrd/package-info.java b/solr/core/src/java/org/apache/solr/metrics/rrd/package-info.javanew file mode 100644index 00000000000..2fd018c8d1e--- /dev/null+++ b/solr/core/src/java/org/apache/solr/metrics/rrd/package-info.java@@ -0,0 +1,22 @@+/*+ * Licensed to the Apache Software Foundation (ASF) under one or more+ * contributor license agreements. See the NOTICE file distributed with+ * this work for additional information regarding copyright ownership.+ * The ASF licenses this file to You under the Apache License, Version 2.0+ * (the "License"); you may not use this file except in compliance with+ * the License. You may obtain a copy of the License at+ *+ * http://www.apache.org/licenses/LICENSE-2.0+ *+ * Unless required by applicable law or agreed to in writing, software+ * distributed under the License is distributed on an "AS IS" BASIS,+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.+ * See the License for the specific language governing permissions and+ * limitations under the License.+ */++/**+ * This package contains {@link org.rrd4j.core.RrdBackendFactory} implementation+ * that supports storing metrics history in Solr.+ */+package org.apache.solr.metrics.rrd;diff --git a/solr/core/src/java/org/apache/solr/security/PermissionNameProvider.java b/solr/core/src/java/org/apache/solr/security/PermissionNameProvider.javaindex 407394794aa..79b4d29f9d4 100644--- a/solr/core/src/java/org/apache/solr/security/PermissionNameProvider.java+++ b/solr/core/src/java/org/apache/solr/security/PermissionNameProvider.java@@ -50,6 +50,7 @@ public interface PermissionNameProvider {AUTOSCALING_READ_PERM("autoscaling-read", null),AUTOSCALING_WRITE_PERM("autoscaling-write", null),AUTOSCALING_HISTORY_READ_PERM("autoscaling-history-read", null),+ METRICS_HISTORY_READ_PERM("metrics-history-read", null),ALL("all", unmodifiableSet(new HashSet<>(asList("*", null))));final String name;diff --git a/solr/core/src/test/org/apache/solr/cloud/MetricsHistoryIntegrationTest.java b/solr/core/src/test/org/apache/solr/cloud/MetricsHistoryIntegrationTest.javanew file mode 100644index 00000000000..2012a1ac8f4--- /dev/null+++ b/solr/core/src/test/org/apache/solr/cloud/MetricsHistoryIntegrationTest.java@@ -0,0 +1,193 @@+/*+ * Licensed to the Apache Software Foundation (ASF) under one or more+ * contributor license agreements. See the NOTICE file distributed with+ * this work for additional information regarding copyright ownership.+ * The ASF licenses this file to You under the Apache License, Version 2.0+ * (the "License"); you may not use this file except in compliance with+ * the License. You may obtain a copy of the License at+ *+ * http://www.apache.org/licenses/LICENSE-2.0+ *+ * Unless required by applicable law or agreed to in writing, software+ * distributed under the License is distributed on an "AS IS" BASIS,+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.+ * See the License for the specific language governing permissions and+ * limitations under the License.+ */+package org.apache.solr.cloud;++import javax.imageio.ImageIO;+import java.io.ByteArrayInputStream;+import java.io.IOException;+import java.lang.invoke.MethodHandles;+import java.util.List;+import java.util.concurrent.TimeUnit;++import org.apache.lucene.util.LuceneTestCase;+import org.apache.solr.client.solrj.SolrClient;+import org.apache.solr.client.solrj.SolrRequest;+import org.apache.solr.client.solrj.cloud.SolrCloudManager;+import org.apache.solr.client.solrj.request.CollectionAdminRequest;+import org.apache.solr.client.solrj.request.GenericSolrRequest;+import org.apache.solr.cloud.autoscaling.sim.SimCloudManager;+import org.apache.solr.common.params.CollectionAdminParams;+import org.apache.solr.common.params.CommonParams;+import org.apache.solr.common.params.SolrParams;+import org.apache.solr.common.util.Base64;+import org.apache.solr.common.util.NamedList;+import org.apache.solr.common.util.TimeSource;+import org.apache.solr.util.LogLevel;+import org.junit.AfterClass;+import org.junit.BeforeClass;+import org.junit.Test;+import org.slf4j.Logger;+import org.slf4j.LoggerFactory;++/**+ *+ */+@LogLevel("org.apache.solr.handler.admin=DEBUG")+public class MetricsHistoryIntegrationTest extends SolrCloudTestCase {+ private static final Logger log = LoggerFactory.getLogger(MethodHandles.lookup().lookupClass());++ private static SolrCloudManager cloudManager;+ private static SolrClient solrClient;+ private static TimeSource timeSource;++ @BeforeClass+ public static void setupCluster() throws Exception {+ boolean simulated = random().nextBoolean();+ if (simulated) {+ cloudManager = SimCloudManager.createCluster(1, TimeSource.get("simTime:50"));+ solrClient = ((SimCloudManager)cloudManager).simGetSolrClient();+ }+ configureCluster(1)+ .addConfig("conf", configset("cloud-minimal"))+ .configure();+ if (!simulated) {+ cloudManager = cluster.getJettySolrRunner(0).getCoreContainer().getZkController().getSolrCloudManager();+ solrClient = cluster.getSolrClient();+ }+ timeSource = cloudManager.getTimeSource();+ // create .system+ CollectionAdminRequest.createCollection(CollectionAdminParams.SYSTEM_COLL, null, 1, 1)+ .process(solrClient);+ CloudTestUtils.waitForState(cloudManager, CollectionAdminParams.SYSTEM_COLL,+ 30, TimeUnit.SECONDS, CloudTestUtils.clusterShape(1, 1));+ solrClient.query(CollectionAdminParams.SYSTEM_COLL, params(CommonParams.Q, "*:*"));+ // sleep a little to allow the handler to collect some metrics+ timeSource.sleep(90000);+ }++ @AfterClass+ public static void teardown() throws Exception {+ if (cloudManager instanceof SimCloudManager) {+ cloudManager.close();+ }+ solrClient = null;+ cloudManager = null;+ }++ @Test+ public void testList() throws Exception {+ NamedList<Object> rsp = solrClient.request(createHistoryRequest(params(CommonParams.ACTION, "list")));+ assertNotNull(rsp);+ // expected solr.jvm, solr.node and solr.collection..system+ List<String> lst = (List<String>)rsp.get("metrics");+ assertNotNull(lst);+ assertEquals(lst.toString(), 3, lst.size());+ assertTrue(lst.toString(), lst.contains("solr.jvm"));+ assertTrue(lst.toString(), lst.contains("solr.node"));+ assertTrue(lst.toString(), lst.contains("solr.collection..system"));+ }++ @Test+ public void testStatus() throws Exception {+ NamedList<Object> rsp = solrClient.request(createHistoryRequest(+ params(CommonParams.ACTION, "status", CommonParams.NAME, "solr.jvm")));+ assertNotNull(rsp);+ NamedList<Object> map = (NamedList<Object>)rsp.get("metrics");+ assertEquals(map.toString(), 1, map.size());+ map = (NamedList<Object>)map.get("solr.jvm");+ assertNotNull(map);+ NamedList<Object> status = (NamedList<Object>)map.get("status");+ assertNotNull(status);+ assertEquals(status.toString(), 7, status.size());+ List<Object> lst = (List<Object>)status.get("datasources");+ assertNotNull(lst);+ assertEquals(lst.toString(), 3, lst.size());+ lst = (List<Object>)status.get("archives");+ assertNotNull(lst);+ assertEquals(lst.toString(), 5, lst.size());+ }++ @Test+ public void testGet() throws Exception {+ NamedList<Object> rsp = solrClient.request(createHistoryRequest(params(+ CommonParams.ACTION, "get", CommonParams.NAME, "solr.jvm")));+ assertNotNull(rsp);+ // default format is LIST+ NamedList<Object> data = (NamedList<Object>)rsp.findRecursive("metrics", "solr.jvm", "data");+ assertNotNull(data);+ data.forEach((k, v) -> {+ NamedList<Object> entry = (NamedList<Object>)v;+ List<Object> lst = entry.getAll("timestamps");+ assertNotNull(lst);+ assertTrue("timestamps", lst.size() > 0);+ // 3 metrics, so the total size of values is 3 * the size of timestamps+ entry = (NamedList<Object>)entry.get("values");+ assertNotNull(entry);+ assertEquals(lst.size() * 3, entry.size());+ });++ // get STRING+ rsp = solrClient.request(createHistoryRequest(params(+ CommonParams.ACTION, "get", CommonParams.NAME, "solr.jvm", "format", "string")));+ data = (NamedList<Object>)rsp.findRecursive("metrics", "solr.jvm", "data");+ assertNotNull(data);+ data.forEach((k, v) -> {+ NamedList<Object> entry = (NamedList<Object>)v;+ List<Object> lst = entry.getAll("timestamps");+ assertNotNull(lst);+ assertEquals("timestamps", 1, lst.size());+ String timestampString = (String)lst.get(0);+ String[] timestamps = timestampString.split(("\n"));+ assertTrue(timestampString, timestamps.length > 1);+ entry = (NamedList<Object>)entry.get("values");+ assertNotNull(entry);+ assertEquals(3, entry.size());+ entry.forEach((vk, vv) -> {+ String valString = (String)vv;+ String[] values = valString.split("\n");+ assertEquals(valString, timestamps.length, values.length);+ });+ });++ // get GRAPH+ rsp = solrClient.request(createHistoryRequest(params(+ CommonParams.ACTION, "get", CommonParams.NAME, "solr.jvm", "format", "graph")));+ data = (NamedList<Object>)rsp.findRecursive("metrics", "solr.jvm", "data");+ assertNotNull(data);+ data.forEach((k, v) -> {+ NamedList<Object> entry = (NamedList<Object>) v;+ entry = (NamedList<Object>)entry.get("values");+ assertNotNull(entry);+ assertEquals(3, entry.size());+ entry.forEach((vk, vv) -> {+ String valString = (String)vv;+ byte[] img = Base64.base64ToByteArray(valString);+ try {+ ImageIO.read(new ByteArrayInputStream(img));+ } catch (IOException e) {+ fail("Error reading image data: " + e.toString());+ }+ });+ });+ }++ public static SolrRequest createHistoryRequest(SolrParams params) {+ return new GenericSolrRequest(SolrRequest.METHOD.GET, "/admin/metrics/history", params);+ }++}diff --git a/solr/core/src/test/org/apache/solr/cloud/autoscaling/sim/LiveNodesSet.java b/solr/core/src/test/org/apache/solr/cloud/autoscaling/sim/LiveNodesSet.javaindex ca4ed71ffed..3f5d5f4b3c8 100644--- a/solr/core/src/test/org/apache/solr/cloud/autoscaling/sim/LiveNodesSet.java+++ b/solr/core/src/test/org/apache/solr/cloud/autoscaling/sim/LiveNodesSet.java@@ -18,6 +18,7 @@ package org.apache.solr.cloud.autoscaling.sim;import java.util.Collection;import java.util.Collections;+import java.util.Iterator;import java.util.Set;import java.util.SortedSet;import java.util.TreeSet;@@ -28,7 +29,7 @@ import org.apache.solr.common.cloud.LiveNodesListener;/*** This class represents a set of live nodes and allows adding listeners to track their state.*/-public class LiveNodesSet {+public class LiveNodesSet implements Iterable<String> {private final Set<String> set = ConcurrentHashMap.newKeySet();private final Set<LiveNodesListener> listeners = ConcurrentHashMap.newKeySet();@@ -100,4 +101,9 @@ public class LiveNodesSet {set.clear();fireListeners(oldNodes, Collections.emptySortedSet());}++ @Override+ public Iterator<String> iterator() {+ return set.iterator();+ }}\ No newline at end of filediff --git a/solr/core/src/test/org/apache/solr/cloud/autoscaling/sim/SimCloudManager.java b/solr/core/src/test/org/apache/solr/cloud/autoscaling/sim/SimCloudManager.javaindex 9641552e1fa..c09d4a48c35 100644--- a/solr/core/src/test/org/apache/solr/cloud/autoscaling/sim/SimCloudManager.java+++ b/solr/core/src/test/org/apache/solr/cloud/autoscaling/sim/SimCloudManager.java@@ -18,6 +18,7 @@package org.apache.solr.cloud.autoscaling.sim;import java.io.ByteArrayOutputStream;+import java.io.File;import java.io.IOException;import java.lang.invoke.MethodHandles;import java.util.ArrayList;@@ -36,6 +37,10 @@ import java.util.concurrent.Future;import java.util.concurrent.atomic.AtomicInteger;import java.util.concurrent.atomic.AtomicLong;+import com.codahale.metrics.jvm.ClassLoadingGaugeSet;+import com.codahale.metrics.jvm.GarbageCollectorMetricSet;+import com.codahale.metrics.jvm.MemoryUsageGaugeSet;+import com.codahale.metrics.jvm.ThreadStatesGaugeSet;import org.apache.solr.client.solrj.SolrClient;import org.apache.solr.client.solrj.SolrRequest;import org.apache.solr.client.solrj.SolrResponse;@@ -79,10 +84,18 @@ import org.apache.solr.common.util.ObjectCache;import org.apache.solr.common.util.SimpleOrderedMap;import org.apache.solr.common.util.TimeSource;import org.apache.solr.core.CloudConfig;+import org.apache.solr.core.SolrInfoBean;import org.apache.solr.core.SolrResourceLoader;+import org.apache.solr.handler.admin.MetricsHandler;+import org.apache.solr.handler.admin.MetricsHistoryHandler;+import org.apache.solr.metrics.AltBufferPoolMetricSet;+import org.apache.solr.metrics.MetricsMap;+import org.apache.solr.metrics.OperatingSystemMetricSet;+import org.apache.solr.metrics.SolrMetricManager;import org.apache.solr.request.LocalSolrQueryRequest;import org.apache.solr.response.SolrQueryResponse;import org.apache.solr.util.DefaultSolrThreadFactory;+import org.apache.solr.util.MockSearchableSolrClient;import org.slf4j.Logger;import org.slf4j.LoggerFactory;@@ -101,9 +114,11 @@ public class SimCloudManager implements SolrCloudManager {private final LiveNodesSet liveNodesSet = new LiveNodesSet();private final DistributedQueueFactory queueFactory;private final ObjectCache objectCache = new ObjectCache();- private TimeSource timeSource;+ private final SolrMetricManager metricManager = new SolrMetricManager();+ private final String metricTag;private final List<SolrInputDocument> systemColl = Collections.synchronizedList(new ArrayList<>());+ private final MockSearchableSolrClient solrClient;private final Map<String, AtomicLong> opCounts = new ConcurrentSkipListMap<>();@@ -111,6 +126,8 @@ public class SimCloudManager implements SolrCloudManager {private Overseer.OverseerThread triggerThread;private ThreadGroup triggerThreadGroup;private SolrResourceLoader loader;+ private MetricsHistoryHandler historyHandler;+ private TimeSource timeSource;private static int nodeIdPort = 10000;public static int DEFAULT_DISK = 1000; // 1000 GB@@ -142,13 +159,72 @@ public class SimCloudManager implements SolrCloudManager {stateManager.makePath(ZkStateReader.SOLR_AUTOSCALING_TRIGGER_STATE_PATH);stateManager.makePath(ZkStateReader.SOLR_AUTOSCALING_NODE_LOST_PATH);stateManager.makePath(ZkStateReader.SOLR_AUTOSCALING_NODE_ADDED_PATH);+ stateManager.makePath(Overseer.OVERSEER_ELECT);++ // register common metrics+ metricTag = Integer.toHexString(hashCode());+ String registryName = SolrMetricManager.getRegistryName(SolrInfoBean.Group.jvm);+ metricManager.registerAll(registryName, new AltBufferPoolMetricSet(), true, "buffers");+ metricManager.registerAll(registryName, new ClassLoadingGaugeSet(), true, "classes");+ metricManager.registerAll(registryName, new OperatingSystemMetricSet(), true, "os");+ metricManager.registerAll(registryName, new GarbageCollectorMetricSet(), true, "gc");+ metricManager.registerAll(registryName, new MemoryUsageGaugeSet(), true, "memory");+ metricManager.registerAll(registryName, new ThreadStatesGaugeSet(), true, "threads"); // todo should we use CachedThreadStatesGaugeSet instead?+ MetricsMap sysprops = new MetricsMap((detailed, map) -> {+ System.getProperties().forEach((k, v) -> {+ map.put(String.valueOf(k), v);+ });+ });+ metricManager.registerGauge(null, registryName, sysprops, metricTag, true, "properties", "system");++ registryName = SolrMetricManager.getRegistryName(SolrInfoBean.Group.node);+ metricManager.registerGauge(null, registryName, () -> new File("/").getUsableSpace(),+ metricTag, true, "usableSpace", SolrInfoBean.Category.CONTAINER.toString(), "fs", "coreRoot");++ solrClient = new MockSearchableSolrClient() {+ @Override+ public NamedList<Object> request(SolrRequest request, String collection) throws SolrServerException, IOException {+ if (collection != null) {+ if (request instanceof AbstractUpdateRequest) {+ ((AbstractUpdateRequest)request).setParam("collection", collection);+ } else if (request instanceof QueryRequest) {+ if (request.getPath() != null && (+ request.getPath().startsWith("/admin/autoscaling") ||+ request.getPath().startsWith("/cluster/autoscaling") ||+ request.getPath().startsWith("/admin/metrics/history") ||+ request.getPath().startsWith("/cluster/metrics/history")+ )) {+ // forward it+ ModifiableSolrParams params = new ModifiableSolrParams(request.getParams());+ params.set("collection", collection);+ request = new QueryRequest(params);+ } else {+ // search request+ return super.request(request, collection);+ }+ } else {+ throw new SolrException(SolrException.ErrorCode.BAD_REQUEST, "when collection != null only UpdateRequest and QueryRequest are supported: request=" + request + ", collection=" + collection);+ }+ }+ try {+ SolrResponse rsp = SimCloudManager.this.request(request);+ return rsp.getResponse();+ } catch (UnsupportedOperationException e) {+ throw new SolrServerException(e);+ }+ }+ };+this.timeSource = timeSource != null ? timeSource : TimeSource.NANO_TIME;this.clusterStateProvider = new SimClusterStateProvider(liveNodesSet, this);this.nodeStateProvider = new SimNodeStateProvider(liveNodesSet, this.stateManager, this.clusterStateProvider, null);this.queueFactory = new GenericDistributedQueueFactory(stateManager);this.simCloudManagerPool = ExecutorUtil.newMDCAwareFixedThreadPool(200, new DefaultSolrThreadFactory("simCloudManagerPool"));+this.autoScalingHandler = new AutoScalingHandler(this, loader);++triggerThreadGroup = new ThreadGroup("Simulated Overseer autoscaling triggers");OverseerTriggerThread trigger = new OverseerTriggerThread(loader, this,new CloudConfig.CloudConfigBuilder("nonexistent", 0, "sim").build());@@ -167,13 +243,7 @@ public class SimCloudManager implements SolrCloudManager {public static SimCloudManager createCluster(int numNodes, TimeSource timeSource) throws Exception {SimCloudManager cloudManager = new SimCloudManager(timeSource);for (int i = 1; i <= numNodes; i++) {- Map<String, Object> values = createNodeValues(null);-// if (i == 1) { // designated Overseer ?- //values.put(ImplicitSnitch.NODEROLE, "overseer");-// }- String nodeId = (String)values.get(ImplicitSnitch.NODE);- cloudManager.getSimClusterStateProvider().simAddNode(nodeId);- cloudManager.getSimNodeStateProvider().simSetNodeValues(nodeId, values);+ cloudManager.simAddNode();}return cloudManager;}@@ -325,6 +395,12 @@ public class SimCloudManager implements SolrCloudManager {clusterStateProvider.simAddNode(nodeId);nodeStateProvider.simSetNodeValues(nodeId, values);LOG.trace("-- added node " + nodeId);+ // initialize history handler if this is the first node+ if (historyHandler == null && liveNodesSet.size() == 1) {+ MetricsHandler metricsHandler = new MetricsHandler(metricManager);+ historyHandler = new MetricsHistoryHandler(nodeId, metricsHandler, solrClient, this, Collections.emptyMap());+ historyHandler.initializeMetrics(metricManager, SolrMetricManager.getRegistryName(SolrInfoBean.Group.node), metricTag, CommonParams.METRICS_HISTORY_PATH);+ }return nodeId;}@@ -397,29 +473,30 @@ public class SimCloudManager implements SolrCloudManager {* @return simulated SolrClient.*/public SolrClient simGetSolrClient() {- return new SolrClient() {- @Override- public NamedList<Object> request(SolrRequest request, String collection) throws SolrServerException, IOException {- if (collection != null) {- if (request instanceof AbstractUpdateRequest) {- ((AbstractUpdateRequest)request).setParam("collection", collection);- } else if (request instanceof QueryRequest) {- ModifiableSolrParams params = new ModifiableSolrParams(request.getParams());- params.set("collection", collection);- request = new QueryRequest(params);- } else {- throw new SolrException(SolrException.ErrorCode.BAD_REQUEST, "when collection != null only UpdateRequest and QueryRequest are supported: request=" + request + ", collection=" + collection);- }- }- SolrResponse rsp = SimCloudManager.this.request(request);- return rsp.getResponse();- }-- @Override- public void close() throws IOException {-- }- };+ return solrClient;+// return new SolrClient() {+// @Override+// public NamedList<Object> request(SolrRequest request, String collection) throws SolrServerException, IOException {+// if (collection != null) {+// if (request instanceof AbstractUpdateRequest) {+// ((AbstractUpdateRequest)request).setParam("collection", collection);+// } else if (request instanceof QueryRequest) {+// ModifiableSolrParams params = new ModifiableSolrParams(request.getParams());+// params.set("collection", collection);+// request = new QueryRequest(params);+// } else {+// throw new SolrException(SolrException.ErrorCode.BAD_REQUEST, "when collection != null only UpdateRequest and QueryRequest are supported: request=" + request + ", collection=" + collection);+// }+// }+// SolrResponse rsp = SimCloudManager.this.request(request);+// return rsp.getResponse();+// }+//+// @Override+// public void close() throws IOException {+//+// }+// };}/**@@ -498,6 +575,10 @@ public class SimCloudManager implements SolrCloudManager {return count != null ? count.get() : 0L;}+ public SolrMetricManager getMetricManager() {+ return metricManager;+ }+// --------- interface methods -----------@@ -558,50 +639,71 @@ public class SimCloudManager implements SolrCloudManager {LOG.trace("--- got SolrRequest: " + req.getMethod() + " " + req.getPath() +(req.getParams() != null ? " " + req.getParams().toQueryString() : ""));- if (req.getPath() != null && req.getPath().startsWith("/admin/autoscaling") ||- req.getPath().startsWith("/cluster/autoscaling")) {- incrementCount("autoscaling");- ModifiableSolrParams params = new ModifiableSolrParams(req.getParams());- params.set(CommonParams.PATH, req.getPath());- LocalSolrQueryRequest queryRequest = new LocalSolrQueryRequest(null, params);- RequestWriter.ContentWriter cw = req.getContentWriter("application/json");- ByteArrayOutputStream baos = new ByteArrayOutputStream();- cw.write(baos);- String payload = baos.toString("UTF-8");- LOG.trace("-- payload: {}", payload);- queryRequest.setContentStreams(Collections.singletonList(new ContentStreamBase.StringStream(payload)));- queryRequest.getContext().put("httpMethod", req.getMethod().toString());- SolrQueryResponse queryResponse = new SolrQueryResponse();- autoScalingHandler.handleRequest(queryRequest, queryResponse);- if (queryResponse.getException() != null) {- LOG.debug("-- exception handling request", queryResponse.getException());- throw new IOException(queryResponse.getException());+ if (req.getPath() != null) {+ if (req.getPath().startsWith("/admin/autoscaling") ||+ req.getPath().startsWith("/cluster/autoscaling") ||+ req.getPath().startsWith("/admin/metrics/history") ||+ req.getPath().startsWith("/cluster/metrics/history")+ ) {+ metricManager.registry("solr.node").counter("ADMIN." + req.getPath() + ".requests").inc();+ boolean autoscaling = req.getPath().contains("autoscaling");+ if (autoscaling) {+ incrementCount("autoscaling");+ } else {+ incrementCount("metricsHistory");+ }+ ModifiableSolrParams params = new ModifiableSolrParams(req.getParams());+ params.set(CommonParams.PATH, req.getPath());+ LocalSolrQueryRequest queryRequest = new LocalSolrQueryRequest(null, params);+ if (autoscaling) {+ RequestWriter.ContentWriter cw = req.getContentWriter("application/json");+ ByteArrayOutputStream baos = new ByteArrayOutputStream();+ cw.write(baos);+ String payload = baos.toString("UTF-8");+ LOG.trace("-- payload: {}", payload);+ queryRequest.setContentStreams(Collections.singletonList(new ContentStreamBase.StringStream(payload)));+ }+ queryRequest.getContext().put("httpMethod", req.getMethod().toString());+ SolrQueryResponse queryResponse = new SolrQueryResponse();+ if (autoscaling) {+ autoScalingHandler.handleRequest(queryRequest, queryResponse);+ } else {+ if (historyHandler != null) {+ historyHandler.handleRequest(queryRequest, queryResponse);+ } else {+ throw new UnsupportedOperationException("must add at least 1 node first");+ }+ }+ if (queryResponse.getException() != null) {+ LOG.debug("-- exception handling request", queryResponse.getException());+ throw new IOException(queryResponse.getException());+ }+ SolrResponse rsp = new SolrResponseBase();+ rsp.setResponse(queryResponse.getValues());+ LOG.trace("-- response: {}", rsp);+ return rsp;}- SolrResponse rsp = new SolrResponseBase();- rsp.setResponse(queryResponse.getValues());- LOG.trace("-- response: {}", rsp);- return rsp;}if (req instanceof UpdateRequest) {incrementCount("update");- // support only updates to the system collectionUpdateRequest ureq = (UpdateRequest)req;String collection = ureq.getCollection();- if (collection != null && !collection.equals(CollectionAdminParams.SYSTEM_COLL)) {- // simulate an update- return clusterStateProvider.simUpdate(ureq);- } else {+ UpdateResponse rsp = clusterStateProvider.simUpdate(ureq);+ if (collection == null || collection.equals(CollectionAdminParams.SYSTEM_COLL)) {List<SolrInputDocument> docs = ureq.getDocuments();if (docs != null) {systemColl.addAll(docs);}return new UpdateResponse();+ } else {+ return rsp;}}// support only a specific subset of collection admin opsif (!(req instanceof CollectionAdminRequest)) {throw new UnsupportedOperationException("Only some CollectionAdminRequest-s are supported: " + req.getClass().getName());}+ metricManager.registry("solr.node").counter("ADMIN." + req.getPath() + ".requests").inc();SolrParams params = req.getParams();String a = params.get(CoreAdminParams.ACTION);SolrResponse rsp = new SolrResponseBase();@@ -721,6 +823,9 @@ public class SimCloudManager implements SolrCloudManager {@Overridepublic void close() throws IOException {+ if (historyHandler != null) {+ IOUtils.closeQuietly(historyHandler);+ }IOUtils.closeQuietly(clusterStateProvider);IOUtils.closeQuietly(nodeStateProvider);IOUtils.closeQuietly(stateManager);diff --git a/solr/core/src/test/org/apache/solr/cloud/autoscaling/sim/SimClusterStateProvider.java b/solr/core/src/test/org/apache/solr/cloud/autoscaling/sim/SimClusterStateProvider.javaindex f2feb8e634e..ca2dd48858d 100644--- a/solr/core/src/test/org/apache/solr/cloud/autoscaling/sim/SimClusterStateProvider.java+++ b/solr/core/src/test/org/apache/solr/cloud/autoscaling/sim/SimClusterStateProvider.java@@ -29,6 +29,7 @@ import java.util.Iterator;import java.util.List;import java.util.Locale;import java.util.Map;+import java.util.NoSuchElementException;import java.util.Random;import java.util.Set;import java.util.concurrent.ConcurrentHashMap;@@ -50,10 +51,12 @@ import org.apache.solr.client.solrj.impl.ClusterStateProvider;import org.apache.solr.client.solrj.request.UpdateRequest;import org.apache.solr.client.solrj.response.UpdateResponse;import org.apache.solr.cloud.ActionThrottle;+import org.apache.solr.cloud.Overseer;import org.apache.solr.cloud.api.collections.AddReplicaCmd;import org.apache.solr.cloud.api.collections.Assign;import org.apache.solr.cloud.api.collections.CreateCollectionCmd;import org.apache.solr.cloud.api.collections.CreateShardCmd;+import org.apache.solr.cloud.api.collections.OverseerCollectionMessageHandler;import org.apache.solr.cloud.api.collections.SplitShardCmd;import org.apache.solr.cloud.overseer.ClusterStateMutator;import org.apache.solr.cloud.overseer.CollectionMutator;@@ -69,11 +72,14 @@ import org.apache.solr.common.cloud.Slice;import org.apache.solr.common.cloud.ZkNodeProps;import org.apache.solr.common.cloud.ZkStateReader;import org.apache.solr.common.cloud.rule.ImplicitSnitch;+import org.apache.solr.common.params.CollectionAdminParams;import org.apache.solr.common.params.CollectionParams;import org.apache.solr.common.params.CommonAdminParams;import org.apache.solr.common.params.CoreAdminParams;import org.apache.solr.common.util.NamedList;import org.apache.solr.common.util.Utils;+import org.apache.solr.core.SolrInfoBean;+import org.apache.solr.metrics.SolrMetricManager;import org.apache.zookeeper.CreateMode;import org.junit.Assert;import org.slf4j.Logger;@@ -125,6 +131,8 @@ public class SimClusterStateProvider implements ClusterStateProvider {private volatile int clusterStateVersion = 0;+ private volatile String overseerLeader = null;+private Map<String, Object> lastSavedProperties = null;private AtomicReference<Map<String, DocCollection>> collectionsStatesRef = new AtomicReference<>();@@ -234,6 +242,7 @@ public class SimClusterStateProvider implements ClusterStateProvider {}liveNodes.add(nodeId);createEphemeralLiveNode(nodeId);+ updateOverseerLeader();nodeReplicaMap.putIfAbsent(nodeId, new ArrayList<>());}@@ -255,6 +264,7 @@ public class SimClusterStateProvider implements ClusterStateProvider {}// remove ephemeral nodesstateManager.getRoot().removeEphemeralChildren(nodeId);+ updateOverseerLeader();// create a nodeLost marker if neededAutoScalingConfig cfg = stateManager.getAutoScalingConfig(null);if (cfg.hasTriggerForEvents(TriggerEventType.NODELOST)) {@@ -269,6 +279,35 @@ public class SimClusterStateProvider implements ClusterStateProvider {}}+ private synchronized void updateOverseerLeader() throws Exception {+ if (overseerLeader != null && liveNodes.contains(overseerLeader)) {+ return;+ }+ String path = Overseer.OVERSEER_ELECT + "/leader";+ if (liveNodes.isEmpty()) {+ overseerLeader = null;+ // remove it from ZK+ try {+ cloudManager.getDistribStateManager().removeData(path, -1);+ } catch (NoSuchElementException e) {+ // ignore+ }+ return;+ }+ // pick first+ overseerLeader = liveNodes.iterator().next();+ LOG.debug("--- new Overseer leader: " + overseerLeader);+ // record it in ZK+ Map<String, Object> id = new HashMap<>();+ id.put("id", cloudManager.getTimeSource().getTimeNs() ++ "-" + overseerLeader + "-n_0000000000");+ try {+ cloudManager.getDistribStateManager().makePath(path, Utils.toJSON(id), CreateMode.EPHEMERAL, false);+ } catch (Exception e) {+ LOG.warn("Exception saving overseer leader id", e);+ }+ }+// this method needs to be called under a lockprivate void setReplicaStates(String nodeId, Replica.State state, Set<String> changedCollections) {List<ReplicaInfo> replicas = nodeReplicaMap.get(nodeId);@@ -423,6 +462,13 @@ public class SimClusterStateProvider implements ClusterStateProvider {disk = SimCloudManager.DEFAULT_DISK;}cloudManager.getSimNodeStateProvider().simSetNodeValue(nodeId, ImplicitSnitch.DISK, disk - 1);+ // fake metrics+ String registry = SolrMetricManager.getRegistryName(SolrInfoBean.Group.core, replicaInfo.getCollection(),+ replicaInfo.getShard(),+ Utils.parseMetricsReplicaName(replicaInfo.getCollection(), replicaInfo.getCore()));+ cloudManager.getMetricManager().registry(registry).counter("UPDATE./update.requests");+ cloudManager.getMetricManager().registry(registry).counter("QUERY./select.requests");+ cloudManager.getMetricManager().registerGauge(null, registry, () -> 1000, "", true, "INDEX.sizeInBytes");if (runLeaderElection) {simRunLeaderElection(Collections.singleton(replicaInfo.getCollection()), true);}@@ -1011,6 +1057,22 @@ public class SimClusterStateProvider implements ClusterStateProvider {}}+ public synchronized void createSystemCollection() throws IOException {+ try {+ if (simListCollections().contains(CollectionAdminParams.SYSTEM_COLL)) {+ return;+ }+ ZkNodeProps props = new ZkNodeProps(+ NAME, CollectionAdminParams.SYSTEM_COLL,+ REPLICATION_FACTOR, "1",+ OverseerCollectionMessageHandler.NUM_SLICES, "1"+ );+ simCreateCollection(props, new NamedList());+ } catch (Exception e) {+ throw new IOException(e);+ }+ }+/*** Simulate an update by modifying replica metrics.* The following core metrics are updated:@@ -1035,7 +1097,12 @@ public class SimClusterStateProvider implements ClusterStateProvider {throw new SolrException(SolrException.ErrorCode.BAD_REQUEST, "Collection not set");}if (!simListCollections().contains(collection)) {- throw new SolrException(SolrException.ErrorCode.BAD_REQUEST, "Collection '" + collection + "' doesn't exist");+ if (CollectionAdminParams.SYSTEM_COLL.equals(collection)) {+ // auto-create+ createSystemCollection();+ } else {+ throw new SolrException(SolrException.ErrorCode.BAD_REQUEST, "Collection '" + collection + "' doesn't exist");+ }}// always reset first to get the current metrics - it's easier than to keep matching// Replica with ReplicaInfo where the current real counts are stored@@ -1057,6 +1124,7 @@ public class SimClusterStateProvider implements ClusterStateProvider {LOG.debug("-- no leader in " + s);continue;}+ cloudManager.getMetricManager().registry(createRegistryName(collection, s.getName(), leader)).counter("UPDATE./update.requests").inc();String numDocsStr = leader.getStr("SEARCHER.searcher.numDocs");if (numDocsStr == null) {LOG.debug("-- no docs in " + leader);@@ -1085,7 +1153,14 @@ public class SimClusterStateProvider implements ClusterStateProvider {throw new UnsupportedOperationException("Only '*:*' query is supported in deleteByQuery");}for (Slice s : coll.getSlices()) {- String numDocsStr = s.getLeader().getStr("SEARCHER.searcher.numDocs");+ Replica leader = s.getLeader();+ if (leader == null) {+ LOG.debug("-- no leader in " + s);+ continue;+ }++ cloudManager.getMetricManager().registry(createRegistryName(collection, s.getName(), leader)).counter("UPDATE./update.requests").inc();+ String numDocsStr = leader.getStr("SEARCHER.searcher.numDocs");if (numDocsStr == null) {continue;}@@ -1111,6 +1186,10 @@ public class SimClusterStateProvider implements ClusterStateProvider {throw new SolrException(SolrException.ErrorCode.BAD_REQUEST, "Document without id: " + doc);}Slice s = router.getTargetSlice(id, null, null, req.getParams(), coll);+ Replica leader = s.getLeader();+ if (leader != null) {+ cloudManager.getMetricManager().registry(createRegistryName(collection, s.getName(), leader)).counter("UPDATE./update.requests").inc();+ }modified = true;try {simSetShardValue(collection, s.getName(), "SEARCHER.searcher.numDocs", 1, true, false);@@ -1132,6 +1211,11 @@ public class SimClusterStateProvider implements ClusterStateProvider {return new UpdateResponse();}+ private static String createRegistryName(String collection, String shard, Replica r) {+ return SolrMetricManager.getRegistryName(SolrInfoBean.Group.core, collection, shard,+ Utils.parseMetricsReplicaName(collection, r.getCoreName()));+ }+/*** Saves cluster properties to clusterprops.json.* @return current propertiesdiff --git a/solr/core/src/test/org/apache/solr/cloud/autoscaling/sim/TestComputePlanAction.java b/solr/core/src/test/org/apache/solr/cloud/autoscaling/sim/TestComputePlanAction.javaindex cdc4173cfa9..6f47b7f122e 100644--- a/solr/core/src/test/org/apache/solr/cloud/autoscaling/sim/TestComputePlanAction.java+++ b/solr/core/src/test/org/apache/solr/cloud/autoscaling/sim/TestComputePlanAction.java@@ -273,7 +273,7 @@ public class TestComputePlanAction extends SimSolrCloudTestCase {String setClusterPolicyCommand = "{" +" 'set-cluster-policy': [" +" {'cores':'<10', 'node':'#ANY'}," +- " {'replica':'<3', 'shard': '#EACH', 'node': '#ANY'}," ++ " {'replica':'<5', 'shard': '#EACH', 'node': '#ANY'}," +" {'nodeRole':'overseer', 'replica':0}" +" ]" +"}";@@ -282,7 +282,7 @@ public class TestComputePlanAction extends SimSolrCloudTestCase {assertEquals(response.get("result").toString(), "success");CollectionAdminRequest.Create create = CollectionAdminRequest.createCollection("testNodeAdded",- "conf",1, 2);+ "conf",1, 4);create.process(solrClient);CloudTestUtils.waitForState(cluster, "Timed out waiting for replicas of new collection to be active",@@ -292,7 +292,7 @@ public class TestComputePlanAction extends SimSolrCloudTestCase {setClusterPolicyCommand = "{" +" 'set-cluster-policy': [" +" {'cores':'<10', 'node':'#ANY'}," +- " {'replica':'<2', 'shard': '#EACH', 'node': '#ANY'}," ++ " {'replica':'<3', 'shard': '#EACH', 'node': '#ANY'}," +" {'nodeRole':'overseer', 'replica':0}" +" ]" +"}";diff --git a/solr/core/src/test/org/apache/solr/handler/admin/MetricsHandlerTest.java b/solr/core/src/test/org/apache/solr/handler/admin/MetricsHandlerTest.javaindex 0fe5ad75fc6..392bdfc8f1d 100644--- a/solr/core/src/test/org/apache/solr/handler/admin/MetricsHandlerTest.java+++ b/solr/core/src/test/org/apache/solr/handler/admin/MetricsHandlerTest.java@@ -48,7 +48,7 @@ public class MetricsHandlerTest extends SolrTestCaseJ4 {@Testpublic void test() throws Exception {- MetricsHandler handler = new MetricsHandler(h.getCoreContainer());+ MetricsHandler handler = new MetricsHandler(h.getCoreContainer().getMetricManager());SolrQueryResponse resp = new SolrQueryResponse();handler.handleRequestBody(req(CommonParams.QT, "/admin/metrics", MetricsHandler.COMPACT_PARAM, "false", CommonParams.WT, "json"), resp);@@ -179,7 +179,7 @@ public class MetricsHandlerTest extends SolrTestCaseJ4 {@Testpublic void testCompact() throws Exception {- MetricsHandler handler = new MetricsHandler(h.getCoreContainer());+ MetricsHandler handler = new MetricsHandler(h.getCoreContainer().getMetricManager());SolrQueryResponse resp = new SolrQueryResponse();handler.handleRequestBody(req(CommonParams.QT, "/admin/metrics", CommonParams.WT, "json", MetricsHandler.COMPACT_PARAM, "true"), resp);@@ -197,7 +197,7 @@ public class MetricsHandlerTest extends SolrTestCaseJ4 {public void testPropertyFilter() throws Exception {assertQ(req("*:*"), "//result[@numFound='0']");- MetricsHandler handler = new MetricsHandler(h.getCoreContainer());+ MetricsHandler handler = new MetricsHandler(h.getCoreContainer().getMetricManager());SolrQueryResponse resp = new SolrQueryResponse();handler.handleRequestBody(req(CommonParams.QT, "/admin/metrics", CommonParams.WT, "json",@@ -234,7 +234,7 @@ public class MetricsHandlerTest extends SolrTestCaseJ4 {@Testpublic void testKeyMetrics() throws Exception {- MetricsHandler handler = new MetricsHandler(h.getCoreContainer());+ MetricsHandler handler = new MetricsHandler(h.getCoreContainer().getMetricManager());String key1 = "solr.core.collection1:CACHE.core.fieldCache";SolrQueryResponse resp = new SolrQueryResponse();diff --git a/solr/core/src/test/org/apache/solr/handler/admin/MetricsHistoryHandlerTest.java b/solr/core/src/test/org/apache/solr/handler/admin/MetricsHistoryHandlerTest.javanew file mode 100644index 00000000000..e1e230fbb4f--- /dev/null+++ b/solr/core/src/test/org/apache/solr/handler/admin/MetricsHistoryHandlerTest.java@@ -0,0 +1,126 @@+/*+ * Licensed to the Apache Software Foundation (ASF) under one or more+ * contributor license agreements. See the NOTICE file distributed with+ * this work for additional information regarding copyright ownership.+ * The ASF licenses this file to You under the Apache License, Version 2.0+ * (the "License"); you may not use this file except in compliance with+ * the License. You may obtain a copy of the License at+ *+ * http://www.apache.org/licenses/LICENSE-2.0+ *+ * Unless required by applicable law or agreed to in writing, software+ * distributed under the License is distributed on an "AS IS" BASIS,+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.+ * See the License for the specific language governing permissions and+ * limitations under the License.+ */++package org.apache.solr.handler.admin;++import java.util.HashMap;+import java.util.List;+import java.util.Map;++import org.apache.solr.client.solrj.SolrClient;+import org.apache.solr.client.solrj.cloud.SolrCloudManager;+import org.apache.solr.client.solrj.cloud.autoscaling.AutoScalingConfig;+import org.apache.solr.client.solrj.request.CollectionAdminRequest;+import org.apache.solr.cloud.CloudTestUtils;+import org.apache.solr.cloud.SolrCloudTestCase;+import org.apache.solr.cloud.autoscaling.sim.SimCloudManager;+import org.apache.solr.common.params.CollectionAdminParams;+import org.apache.solr.common.params.CommonParams;+import org.apache.solr.common.util.TimeSource;+import org.apache.solr.core.SolrInfoBean;+import org.apache.solr.metrics.SolrMetricManager;+import org.apache.solr.util.LogLevel;+import org.junit.AfterClass;+import org.junit.BeforeClass;+import org.junit.Test;+import org.rrd4j.core.RrdDb;++/**+ *+ */+@LogLevel("org.apache.solr.cloud=DEBUG")+public class MetricsHistoryHandlerTest extends SolrCloudTestCase {++ private static SolrCloudManager cloudManager;+ private static SolrMetricManager metricManager;+ private static TimeSource timeSource;+ private static SolrClient solrClient;+ private static boolean simulated;+ private static int SPEED;++ private static MetricsHistoryHandler handler;+ private static MetricsHandler metricsHandler;++ @BeforeClass+ public static void beforeClass() throws Exception {+ simulated = random().nextBoolean();+ Map<String, Object> args = new HashMap<>();+ args.put(MetricsHistoryHandler.SYNC_PERIOD_PROP, 1);+ args.put(MetricsHistoryHandler.COLLECT_PERIOD_PROP, 1);+ if (simulated) {+ SPEED = 50;+ cloudManager = SimCloudManager.createCluster(1, TimeSource.get("simTime:" + SPEED));+ // wait for defaults to be applied - due to accelerated time sometimes we may miss this+ cloudManager.getTimeSource().sleep(10000);+ AutoScalingConfig cfg = cloudManager.getDistribStateManager().getAutoScalingConfig();+ assertFalse("autoscaling config is empty", cfg.isEmpty());+ metricManager = ((SimCloudManager)cloudManager).getMetricManager();+ solrClient = ((SimCloudManager)cloudManager).simGetSolrClient();+ // need to register the factory here, before we start the real cluster+ metricsHandler = new MetricsHandler(metricManager);+ handler = new MetricsHistoryHandler(cloudManager.getClusterStateProvider().getLiveNodes().iterator().next(),+ metricsHandler, solrClient, cloudManager, args);+ handler.initializeMetrics(metricManager, SolrInfoBean.Group.node.toString(), "", CommonParams.METRICS_HISTORY_PATH);+ }+ configureCluster(1)+ .addConfig("conf", configset("cloud-minimal"))+ .configure();+ if (!simulated) {+ cloudManager = cluster.getJettySolrRunner(0).getCoreContainer().getZkController().getSolrCloudManager();+ metricManager = cluster.getJettySolrRunner(0).getCoreContainer().getMetricManager();+ solrClient = cluster.getSolrClient();+ metricsHandler = new MetricsHandler(metricManager);+ handler = new MetricsHistoryHandler(cluster.getJettySolrRunner(0).getNodeName(), metricsHandler, solrClient, cloudManager, args);+ handler.initializeMetrics(metricManager, SolrInfoBean.Group.node.toString(), "", CommonParams.METRICS_HISTORY_PATH);+ SPEED = 1;+ }+ timeSource = cloudManager.getTimeSource();++ // create .system collection+ CollectionAdminRequest.Create create = CollectionAdminRequest.createCollection(CollectionAdminParams.SYSTEM_COLL,+ "conf", 1, 1);+ create.process(solrClient);+ CloudTestUtils.waitForState(cloudManager, "failed to create " + CollectionAdminParams.SYSTEM_COLL,+ CollectionAdminParams.SYSTEM_COLL, CloudTestUtils.clusterShape(1, 1));+ }++ @AfterClass+ public static void teardown() throws Exception {+ if (handler != null) {+ handler.close();+ }+ if (simulated) {+ cloudManager.close();+ }+ }++ @Test+ public void testBasic() throws Exception {+ timeSource.sleep(10000);+ List<String> list = handler.getFactory().list(100);+ // solr.jvm, solr.node, solr.collection..system+ assertEquals(list.toString(), 3, list.size());+ for (String path : list) {+ RrdDb db = new RrdDb(MetricsHistoryHandler.URI_PREFIX + path, true, handler.getFactory());+ int dsCount = db.getDsCount();+ int arcCount = db.getArcCount();+ assertTrue("dsCount should be > 0, was " + dsCount, dsCount > 0);+ assertEquals("arcCount", 5, arcCount);+ db.close();+ }+ }+}diff --git a/solr/core/src/test/org/apache/solr/metrics/rrd/SolrRrdBackendFactoryTest.java b/solr/core/src/test/org/apache/solr/metrics/rrd/SolrRrdBackendFactoryTest.javanew file mode 100644index 00000000000..2f5fa131318--- /dev/null+++ b/solr/core/src/test/org/apache/solr/metrics/rrd/SolrRrdBackendFactoryTest.java@@ -0,0 +1,182 @@+/*+ * Licensed to the Apache Software Foundation (ASF) under one or more+ * contributor license agreements. See the NOTICE file distributed with+ * this work for additional information regarding copyright ownership.+ * The ASF licenses this file to You under the Apache License, Version 2.0+ * (the "License"); you may not use this file except in compliance with+ * the License. You may obtain a copy of the License at+ *+ * http://www.apache.org/licenses/LICENSE-2.0+ *+ * Unless required by applicable law or agreed to in writing, software+ * distributed under the License is distributed on an "AS IS" BASIS,+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.+ * See the License for the specific language governing permissions and+ * limitations under the License.+ */++package org.apache.solr.metrics.rrd;++import java.util.Date;+import java.util.List;+import java.util.concurrent.TimeUnit;++import org.apache.solr.SolrTestCaseJ4;+import org.apache.solr.common.SolrInputDocument;+import org.apache.solr.common.params.CollectionAdminParams;+import org.apache.solr.common.util.TimeSource;+import org.apache.solr.util.MockSearchableSolrClient;+import org.junit.After;+import org.junit.Before;+import org.junit.Test;+import org.rrd4j.ConsolFun;+import org.rrd4j.DsType;+import org.rrd4j.core.FetchData;+import org.rrd4j.core.FetchRequest;+import org.rrd4j.core.RrdDb;+import org.rrd4j.core.RrdDef;+import org.rrd4j.core.Sample;++/**+ *+ */+public class SolrRrdBackendFactoryTest extends SolrTestCaseJ4 {++ private SolrRrdBackendFactory factory;+ private MockSearchableSolrClient solrClient;+ private TimeSource timeSource;++ @Before+ public void setup() {+ solrClient = new MockSearchableSolrClient();+ if (random().nextBoolean()) {+ timeSource = TimeSource.NANO_TIME;+ } else {+ timeSource = TimeSource.get("simTime:50");+ }+ factory = new SolrRrdBackendFactory(solrClient, CollectionAdminParams.SYSTEM_COLL, 1, timeSource);+ }++ @After+ public void teardown() throws Exception {+ if (factory != null) {+ factory.close();+ }+ }++ private RrdDef createDef() {+ RrdDef def = new RrdDef("solr:foo", 60);+ def.addDatasource("one", DsType.COUNTER, 120, Double.NaN, Double.NaN);+ def.addDatasource("two", DsType.GAUGE, 120, Double.NaN, Double.NaN);+ def.addArchive(ConsolFun.AVERAGE, 0.5, 1, 120); // 2 hours+ def.addArchive(ConsolFun.AVERAGE, 0.5, 10, 288); // 48 hours+ def.addArchive(ConsolFun.AVERAGE, 0.5, 60, 336); // 2 weeks+ def.addArchive(ConsolFun.AVERAGE, 0.5, 240, 180); // 2 months+ return def;+ }++ @Test+ public void testBasic() throws Exception {+ RrdDb db = new RrdDb(createDef(), factory);+ List<String> list = factory.list(100);+ assertEquals(list.toString(), 1, list.size());+ assertEquals(list.toString(), "foo", list.get(0));+ timeSource.sleep(2000);+ // there should be one sync data+ assertEquals(solrClient.docs.toString(), 1, solrClient.docs.size());+ String id = SolrRrdBackendFactory.ID_PREFIX + SolrRrdBackendFactory.ID_SEP + "foo";+ SolrInputDocument doc = solrClient.docs.get(CollectionAdminParams.SYSTEM_COLL).get(id);+ long timestamp = ((Date)doc.getFieldValue("timestamp")).getTime();+ timeSource.sleep(2000);+ SolrInputDocument newDoc = solrClient.docs.get(CollectionAdminParams.SYSTEM_COLL).get(id);+ assertEquals(newDoc.toString(), newDoc, doc);+ long firstTimestamp = TimeUnit.SECONDS.convert(timestamp, TimeUnit.MILLISECONDS);+ long lastTimestamp = firstTimestamp + 60;+ // update the db+ Sample s = db.createSample();+ for (int i = 0; i < 100; i++) {+ s.setTime(lastTimestamp);+ s.setValue("one", 1000 + i * 60);+ s.setValue("two", 100);+ s.update();+ lastTimestamp = lastTimestamp + 60;+ }+ timeSource.sleep(3000);+ newDoc = solrClient.docs.get(CollectionAdminParams.SYSTEM_COLL).get(id);+ assertFalse(newDoc.toString(), newDoc.equals(doc));+ long newTimestamp = ((Date)newDoc.getFieldValue("timestamp")).getTime();+ assertNotSame(newTimestamp, timestamp);+ FetchRequest fr = db.createFetchRequest(ConsolFun.AVERAGE, firstTimestamp + 60, lastTimestamp - 60, 60);+ FetchData fd = fr.fetchData();+ int rowCount = fd.getRowCount();+ double[] one = fd.getValues("one");+ assertEquals("one", 101, one.length);+ assertEquals(Double.NaN, one[0], 0.00001);+ assertEquals(Double.NaN, one[100], 0.00001);+ for (int i = 1; i < 100; i++) {+ assertEquals(1.0, one[i], 0.00001);+ }+ double[] two = fd.getValues("two");+ assertEquals(Double.NaN, two[100], 0.00001);+ for (int i = 1; i < 100; i++) {+ assertEquals("wrong value at pos " + i, 100.0, two[i], 0.00001);+ }+ db.close();++ // should still be listed+ list = factory.list(100);+ assertEquals(list.toString(), 1, list.size());+ assertEquals(list.toString(), "foo", list.get(0));++ // re-open read-write+ db = new RrdDb("solr:foo", factory);+ s = db.createSample();+ s.setTime(lastTimestamp);+ s.setValue("one", 7000);+ s.setValue("two", 100);+ s.update();+ timeSource.sleep(3000);+ // should update+ timestamp = newTimestamp;+ doc = newDoc;+ newDoc = solrClient.docs.get(CollectionAdminParams.SYSTEM_COLL).get(id);+ assertFalse(newDoc.toString(), newDoc.equals(doc));+ newTimestamp = ((Date)newDoc.getFieldValue("timestamp")).getTime();+ assertNotSame(newTimestamp, timestamp);+ fr = db.createFetchRequest(ConsolFun.AVERAGE, firstTimestamp + 60, lastTimestamp, 60);+ fd = fr.fetchData();+ rowCount = fd.getRowCount();+ one = fd.getValues("one");+ assertEquals("one", 102, one.length);+ assertEquals(Double.NaN, one[0], 0.00001);+ assertEquals(Double.NaN, one[101], 0.00001);+ for (int i = 1; i < 101; i++) {+ assertEquals(1.0, one[i], 0.00001);+ }+ two = fd.getValues("two");+ assertEquals(Double.NaN, two[101], 0.00001);+ for (int i = 1; i < 101; i++) {+ assertEquals(100.0, two[i], 0.00001);+ }++ db.close();++ // open a read-only version of the db+ RrdDb readOnly = new RrdDb("solr:foo", true, factory);+ s = readOnly.createSample();+ s.setTime(lastTimestamp + 120);+ s.setValue("one", 10000001);+ s.setValue("two", 100);+ s.update();+ // these updates should not be synced+ timeSource.sleep(3000);+ doc = newDoc;+ timestamp = newTimestamp;+ newDoc = solrClient.docs.get(CollectionAdminParams.SYSTEM_COLL).get(id);+ assertTrue(newDoc.toString(), newDoc.equals(doc));+ newTimestamp = ((Date)newDoc.getFieldValue("timestamp")).getTime();+ assertEquals(newTimestamp, timestamp);+ readOnly.close();+ }++}diff --git a/solr/core/src/test/org/apache/solr/util/MockSearchableSolrClient.java b/solr/core/src/test/org/apache/solr/util/MockSearchableSolrClient.javanew file mode 100644index 00000000000..6fce49844e4--- /dev/null+++ b/solr/core/src/test/org/apache/solr/util/MockSearchableSolrClient.java@@ -0,0 +1,117 @@+/*+ * Licensed to the Apache Software Foundation (ASF) under one or more+ * contributor license agreements. See the NOTICE file distributed with+ * this work for additional information regarding copyright ownership.+ * The ASF licenses this file to You under the Apache License, Version 2.0+ * (the "License"); you may not use this file except in compliance with+ * the License. You may obtain a copy of the License at+ *+ * http://www.apache.org/licenses/LICENSE-2.0+ *+ * Unless required by applicable law or agreed to in writing, software+ * distributed under the License is distributed on an "AS IS" BASIS,+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.+ * See the License for the specific language governing permissions and+ * limitations under the License.+ */+package org.apache.solr.util;++import java.io.IOException;+import java.util.LinkedHashMap;+import java.util.List;+import java.util.Map;+import java.util.concurrent.ConcurrentHashMap;++import org.apache.solr.client.solrj.SolrClient;+import org.apache.solr.client.solrj.SolrRequest;+import org.apache.solr.client.solrj.SolrServerException;+import org.apache.solr.client.solrj.request.QueryRequest;+import org.apache.solr.client.solrj.request.UpdateRequest;+import org.apache.solr.common.SolrDocument;+import org.apache.solr.common.SolrDocumentList;+import org.apache.solr.common.SolrInputDocument;+import org.apache.solr.common.params.SolrParams;+import org.apache.solr.common.util.NamedList;+import org.junit.Assert;++/**+ * Simple mock client that collects added documents and supports simple search by id+ * (both <code>{!term f=id}</code> and <code>id:</code> syntax is supported) or *:*.+ */+public class MockSearchableSolrClient extends SolrClient {+ public Map<String, Map<String, SolrInputDocument>> docs = new ConcurrentHashMap<>();++ public void clear() {+ docs.clear();+ }++ @Override+ public synchronized NamedList<Object> request(SolrRequest request, String coll) throws SolrServerException, IOException {+ if (coll == null) {+ if (request.getParams() != null) {+ coll = request.getParams().get("collection");+ }+ }+ if (coll == null) {+ coll = "";+ }+ final String collection = coll;+ NamedList<Object> res = new NamedList<>();+ if (request instanceof UpdateRequest) {+ List<SolrInputDocument> docList = ((UpdateRequest) request).getDocuments();+ if (docList != null) {+ docList.forEach(doc -> {+ String id = (String) doc.getFieldValue("id");+ Assert.assertNotNull(doc.toString(), id);+ docs.computeIfAbsent(collection, c -> new LinkedHashMap<>()).put(id, doc);+ });+ }+ } else if (request instanceof QueryRequest) {+ SolrParams params = request.getParams();+ if (params == null) {+ throw new UnsupportedOperationException("invalid request, no params: " + request);+ }+ String query = params.get("q");+ final SolrDocumentList lst = new SolrDocumentList();+ if (query != null) {+ if (query.startsWith("{!term f=id}") || query.startsWith("id:")) {+ String id;+ if (query.startsWith("{!")) {+ id = query.substring(12);+ } else {+ id = query.substring(3);+ }+ Map<String, SolrInputDocument> collDocs = docs.get(collection);+ if (collDocs != null) {+ SolrInputDocument doc = collDocs.get(id);+ if (doc != null) {+ SolrDocument d = new SolrDocument();+ doc.forEach((k, f) -> f.forEach(v -> d.addField(k, v)));+ lst.add(d);+ lst.setNumFound(1);+ }+ }+ } else if (query.equals("*:*")) {+ Map<String, SolrInputDocument> collDocs = docs.get(collection);+ if (collDocs != null) {+ lst.setNumFound(collDocs.size());+ collDocs.values().forEach(doc -> {+ SolrDocument d = new SolrDocument();+ doc.forEach((k, f) -> f.forEach(v -> d.addField(k, v)));+ lst.add(d);+ });+ }+ }+ }+ res.add("response", lst);+ } else {+ throw new UnsupportedOperationException("Unsupported request type: " + request.getClass() + ":" + request);+ }+ return res;+ }++ @Override+ public void close() throws IOException {++ }+}diff --git a/solr/licenses/rrd4j-3.2.jar.sha1 b/solr/licenses/rrd4j-3.2.jar.sha1new file mode 100644index 00000000000..5304919414c--- /dev/null+++ b/solr/licenses/rrd4j-3.2.jar.sha1@@ -0,0 +1 @@+8d480d5aa87b3d358862b78d6fa3660396220dc7diff --git a/solr/licenses/rrd4j-LICENSE-ASL.txt b/solr/licenses/rrd4j-LICENSE-ASL.txtnew file mode 100644index 00000000000..7a4a3ea2424--- /dev/null+++ b/solr/licenses/rrd4j-LICENSE-ASL.txt@@ -0,0 +1,202 @@++ Apache License+ Version 2.0, January 2004+ http://www.apache.org/licenses/++ TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION++ 1. Definitions.++ "License" shall mean the terms and conditions for use, reproduction,+ and distribution as defined by Sections 1 through 9 of this document.++ "Licensor" shall mean the copyright owner or entity authorized by+ the copyright owner that is granting the License.++ "Legal Entity" shall mean the union of the acting entity and all+ other entities that control, are controlled by, or are under common+ control with that entity. For the purposes of this definition,+ "control" means (i) the power, direct or indirect, to cause the+ direction or management of such entity, whether by contract or+ otherwise, or (ii) ownership of fifty percent (50%) or more of the+ outstanding shares, or (iii) beneficial ownership of such entity.++ "You" (or "Your") shall mean an individual or Legal Entity+ exercising permissions granted by this License.++ "Source" form shall mean the preferred form for making modifications,+ including but not limited to software source code, documentation+ source, and configuration files.++ "Object" form shall mean any form resulting from mechanical+ transformation or translation of a Source form, including but+ not limited to compiled object code, generated documentation,+ and conversions to other media types.++ "Work" shall mean the work of authorship, whether in Source or+ Object form, made available under the License, as indicated by a+ copyright notice that is included in or attached to the work+ (an example is provided in the Appendix below).++ "Derivative Works" shall mean any work, whether in Source or Object+ form, that is based on (or derived from) the Work and for which the+ editorial revisions, annotations, elaborations, or other modifications+ represent, as a whole, an original work of authorship. For the purposes+ of this License, Derivative Works shall not include works that remain+ separable from, or merely link (or bind by name) to the interfaces of,+ the Work and Derivative Works thereof.++ "Contribution" shall mean any work of authorship, including+ the original version of the Work and any modifications or additions+ to that Work or Derivative Works thereof, that is intentionally+ submitted to Licensor for inclusion in the Work by the copyright owner+ or by an individual or Legal Entity authorized to submit on behalf of+ the copyright owner. For the purposes of this definition, "submitted"+ means any form of electronic, verbal, or written communication sent+ to the Licensor or its representatives, including but not limited to+ communication on electronic mailing lists, source code control systems,+ and issue tracking systems that are managed by, or on behalf of, the+ Licensor for the purpose of discussing and improving the Work, but+ excluding communication that is conspicuously marked or otherwise+ designated in writing by the copyright owner as "Not a Contribution."++ "Contributor" shall mean Licensor and any individual or Legal Entity+ on behalf of whom a Contribution has been received by Licensor and+ subsequently incorporated within the Work.++ 2. Grant of Copyright License. Subject to the terms and conditions of+ this License, each Contributor hereby grants to You a perpetual,+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable+ copyright license to reproduce, prepare Derivative Works of,+ publicly display, publicly perform, sublicense, and distribute the+ Work and such Derivative Works in Source or Object form.++ 3. Grant of Patent License. Subject to the terms and conditions of+ this License, each Contributor hereby grants to You a perpetual,+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable+ (except as stated in this section) patent license to make, have made,+ use, offer to sell, sell, import, and otherwise transfer the Work,+ where such license applies only to those patent claims licensable+ by such Contributor that are necessarily infringed by their+ Contribution(s) alone or by combination of their Contribution(s)+ with the Work to which such Contribution(s) was submitted. If You+ institute patent litigation against any entity (including a+ cross-claim or counterclaim in a lawsuit) alleging that the Work+ or a Contribution incorporated within the Work constitutes direct+ or contributory patent infringement, then any patent licenses+ granted to You under this License for that Work shall terminate+ as of the date such litigation is filed.++ 4. Redistribution. You may reproduce and distribute copies of the+ Work or Derivative Works thereof in any medium, with or without+ modifications, and in Source or Object form, provided that You+ meet the following conditions:++ (a) You must give any other recipients of the Work or+ Derivative Works a copy of this License; and++ (b) You must cause any modified files to carry prominent notices+ stating that You changed the files; and++ (c) You must retain, in the Source form of any Derivative Works+ that You distribute, all copyright, patent, trademark, and+ attribution notices from the Source form of the Work,+ excluding those notices that do not pertain to any part of+ the Derivative Works; and++ (d) If the Work includes a "NOTICE" text file as part of its+ distribution, then any Derivative Works that You distribute must+ include a readable copy of the attribution notices contained+ within such NOTICE file, excluding those notices that do not+ pertain to any part of the Derivative Works, in at least one+ of the following places: within a NOTICE text file distributed+ as part of the Derivative Works; within the Source form or+ documentation, if provided along with the Derivative Works; or,+ within a display generated by the Derivative Works, if and+ wherever such third-party notices normally appear. The contents+ of the NOTICE file are for informational purposes only and+ do not modify the License. You may add Your own attribution+ notices within Derivative Works that You distribute, alongside+ or as an addendum to the NOTICE text from the Work, provided+ that such additional attribution notices cannot be construed+ as modifying the License.++ You may add Your own copyright statement to Your modifications and+ may provide additional or different license terms and conditions+ for use, reproduction, or distribution of Your modifications, or+ for any such Derivative Works as a whole, provided Your use,+ reproduction, and distribution of the Work otherwise complies with+ the conditions stated in this License.++ 5. Submission of Contributions. Unless You explicitly state otherwise,+ any Contribution intentionally submitted for inclusion in the Work+ by You to the Licensor shall be under the terms and conditions of+ this License, without any additional terms or conditions.+ Notwithstanding the above, nothing herein shall supersede or modify+ the terms of any separate license agreement you may have executed+ with Licensor regarding such Contributions.++ 6. Trademarks. This License does not grant permission to use the trade+ names, trademarks, service marks, or product names of the Licensor,+ except as required for reasonable and customary use in describing the+ origin of the Work and reproducing the content of the NOTICE file.++ 7. Disclaimer of Warranty. Unless required by applicable law or+ agreed to in writing, Licensor provides the Work (and each+ Contributor provides its Contributions) on an "AS IS" BASIS,+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or+ implied, including, without limitation, any warranties or conditions+ of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A+ PARTICULAR PURPOSE. You are solely responsible for determining the+ appropriateness of using or redistributing the Work and assume any+ risks associated with Your exercise of permissions under this License.++ 8. Limitation of Liability. In no event and under no legal theory,+ whether in tort (including negligence), contract, or otherwise,+ unless required by applicable law (such as deliberate and grossly+ negligent acts) or agreed to in writing, shall any Contributor be+ liable to You for damages, including any direct, indirect, special,+ incidental, or consequential damages of any character arising as a+ result of this License or out of the use or inability to use the+ Work (including but not limited to damages for loss of goodwill,+ work stoppage, computer failure or malfunction, or any and all+ other commercial damages or losses), even if such Contributor+ has been advised of the possibility of such damages.++ 9. Accepting Warranty or Additional Liability. While redistributing+ the Work or Derivative Works thereof, You may choose to offer,+ and charge a fee for, acceptance of support, warranty, indemnity,+ or other liability obligations and/or rights consistent with this+ License. However, in accepting such obligations, You may act only+ on Your own behalf and on Your sole responsibility, not on behalf+ of any other Contributor, and only if You agree to indemnify,+ defend, and hold each Contributor harmless for any liability+ incurred by, or claims asserted against, such Contributor by reason+ of your accepting any such warranty or additional liability.++ END OF TERMS AND CONDITIONS++ APPENDIX: How to apply the Apache License to your work.++ To apply the Apache License to your work, attach the following+ boilerplate notice, with the fields enclosed by brackets "[]"+ replaced with your own identifying information. (Don't include+ the brackets!) The text should be enclosed in the appropriate+ comment syntax for the file format. We also recommend that a+ file or class name and description of purpose be included on the+ same "printed page" as the copyright notice for easier+ identification within third-party archives.++ Copyright [yyyy] [name of copyright owner]++ Licensed under the Apache License, Version 2.0 (the "License");+ you may not use this file except in compliance with the License.+ You may obtain a copy of the License at++ http://www.apache.org/licenses/LICENSE-2.0++ Unless required by applicable law or agreed to in writing, software+ distributed under the License is distributed on an "AS IS" BASIS,+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.+ See the License for the specific language governing permissions and+ limitations under the License.\ No newline at end of filediff --git a/solr/licenses/rrd4j-NOTICE.txt b/solr/licenses/rrd4j-NOTICE.txtnew file mode 100644index 00000000000..841dd309998--- /dev/null+++ b/solr/licenses/rrd4j-NOTICE.txt@@ -0,0 +1,2 @@+GitHub: https://github.com/rrd4j/rrd4j/+Maven-generated site: http://rrd4j.org/site/diff --git a/solr/solr-ref-guide/src/images/metrics-history/loadAvg-60s.png b/solr/solr-ref-guide/src/images/metrics-history/loadAvg-60s.pngnew file mode 100644index 00000000000..4812edea936Binary files /dev/null and b/solr/solr-ref-guide/src/images/metrics-history/loadAvg-60s.png differdiff --git a/solr/solr-ref-guide/src/images/metrics-history/memHeap-60s.png b/solr/solr-ref-guide/src/images/metrics-history/memHeap-60s.pngnew file mode 100644index 00000000000..cbf1a2ee5c2Binary files /dev/null and b/solr/solr-ref-guide/src/images/metrics-history/memHeap-60s.png differdiff --git a/solr/solr-ref-guide/src/images/metrics-history/query-graph-10min.png b/solr/solr-ref-guide/src/images/metrics-history/query-graph-10min.pngnew file mode 100644index 00000000000..81aa1b4302eBinary files /dev/null and b/solr/solr-ref-guide/src/images/metrics-history/query-graph-10min.png differdiff --git a/solr/solr-ref-guide/src/images/metrics-history/query-graph-60s.png b/solr/solr-ref-guide/src/images/metrics-history/query-graph-60s.pngnew file mode 100644index 00000000000..31d230e11cfBinary files /dev/null and b/solr/solr-ref-guide/src/images/metrics-history/query-graph-60s.png differdiff --git a/solr/solr-ref-guide/src/images/metrics-history/update-graph-60s.png b/solr/solr-ref-guide/src/images/metrics-history/update-graph-60s.pngnew file mode 100644index 00000000000..594f02de2a3Binary files /dev/null and b/solr/solr-ref-guide/src/images/metrics-history/update-graph-60s.png differdiff --git a/solr/solr-ref-guide/src/metrics-history.adoc b/solr/solr-ref-guide/src/metrics-history.adocnew file mode 100644index 00000000000..5dc1c3cb18c--- /dev/null+++ b/solr/solr-ref-guide/src/metrics-history.adoc@@ -0,0 +1,411 @@+= Metrics History+// Licensed to the Apache Software Foundation (ASF) under one+// or more contributor license agreements. See the NOTICE file+// distributed with this work for additional information+// regarding copyright ownership. The ASF licenses this file+// to you under the Apache License, Version 2.0 (the+// "License"); you may not use this file except in compliance+// with the License. You may obtain a copy of the License at+//+// http://www.apache.org/licenses/LICENSE-2.0+//+// Unless required by applicable law or agreed to in writing,+// software distributed under the License is distributed on an+// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY+// KIND, either express or implied. See the License for the+// specific language governing permissions and limitations+// under the License.++== Design+=== Round-robin databases+When Solr runs in "cloud" mode it collects long-term history of certain key metrics. This information+can be used for very simple monitoring and troubleshooting, but also some Solr Cloud components+(eg. autoscaling) can use this data for making informed decisions based on long-term+trends of selected metrics.++[IMPORTANT]+====+Metrics history is available ONLY in SolrCloud mode, it's not supported in standalone Solr. Also,+the `.system` collection must exist if metrics history should be persisted.+====++This data is maintained as multi-resolution time series, with a fixed total number of data points+per metric history (a fixed size window). Multi-resolution refers to the fact that data from the most detailed+time series is periodically resampled to create coarser-grained time series, which in turn+are periodically resampled again to build even coarser-grained series.++In the default configuration selected metrics are sampled every 60 seconds, and the following+time series are built:++* 240 samples, every 60 sec (4 hours)+* 288 samples, every 600 sec (48 hours)+* 336 samples, every 1h (2 weeks)+* 180 samples, every 4h (2 months)+* 365 samples, every 1 day (1 year)++This means that the total number of samples in all data series is constant, and consequently+the size of this data structure is also constant (because the size of the moving window is fixed, and+older samples are replaced by newer ones). This arrangement is referred to as a+round-robin database, and Solr uses implementation of this concept provided by RRD4j library.++=== Storage+Databases created with RRD4j are compact - for the time series specified above the total size+of data is ca. 11kB for each of the primary time series, including its resampled data. Each database may contain+several primary time series ("datasources" in RRD4j parlance) and their re-sampled versions (called+"archives").++This data is updated in memory and then periodically stored in the `.system`+collection in the form of Solr documents with a binary `data_bin` field, each document+containing data of one full database. This method of storage is much more compact and generates less+update operations than storing each data point in a separate Solr document. Metrics history API allows retrieving+detailed data from each database, including retrieval of all individual datapoints.++Databases are identified primarily by their corresponding metric registry name, so for databases that+keep track of aggregated metrics this will be eg. `solr.jvm`, `solr.node`, `solr.collection.gettingstarted`,+and for databases with non-aggregated metrics this will be eg. `solr.jvm.localhost:8983_solr`,+`solr.node.localhost:7574_solr`, `solr.core.gettingstarted.shard1.replica_n1`.++=== Collected metrics+Currently the following selected metrics are tracked:++* `solr.core` and `solr.collection` metrics:+** `QUERY./select.requests`+** `UPDATE./update.requests`+** `INDEX.sizeInBytes`+** `numShards` (aggregated, active shards)+** `numReplicas` (aggregated, active replicas)++* `solr.node` metrics:+** `CONTAINER.fs.coreRoot.usableSpace`+** `numNodes` (aggregated, number of live nodes)+* `solr.jvm` metrics:+** `memory.heap.used`+** `os.processCpuLoad`+** `os.systemLoadAverage`++Separate databases are created for each of these groups, and each database keeps data for+all metrics listed in that group.++=== SolrRrdBackendFactory+This component is responsible for managing in-memory databases and periodically saving them+to the `.system` collection. If the `.system` collection is not available the updates to the+databases will be kept in memory, until the time when `.system` collection becomes available.++If the `.system` collection is permanently unavailable then data will not be saved and it will+be lost when the Solr node is shut down.++=== MetricsHistoryHandler+This component provides a REST API for accessing the metrics history. It is also responsible for+collecting and periodically updating the in-memory databases.++This handler also performs aggregation of metrics on per-collection level, and on a cluster level.+By default only these aggregated metrics are tracked - historic data from each node and each replica+in each collection is not collected separately. Aggregated databases are managed on the Overseer leader+node.++The handler assumes that a simple aggregation (sum of partial metric values from each resource) is+sufficient. This happens to make sense for the default built-in sets of metrics. Future extensions will+provide other aggregation strategies (average, max, min, ...).++== Metrics History Configuration+There are two mechanisms for configuring this subsystem:++* `/clusterprops.json` - this is the primary mechanism. It uses the cluster properties JSON+file in ZooKeeper. Configuration is stored in the `/metrics/history` element in a JSON map.++* `solr.xml` - this is the secondary mechanism, which is not recommended but provided for consistency+with the existing metrics configuration section in this file. Configuration is stored in the+`/solr/metrics/history` element of this file.++Currently the following configuration options are supported:++`enable`:: boolean, default is true. If this if false then metrics history is not collected+but can still be retrieved from existing databases. When this is true then metrics are+periodically collected, aggregated and saved.++`enableReplicas`:: boolean, default is false. When this is true non-aggregated history will be+collected for each replica in each collection. When this is false then only aggregated history+is collected for each collection.++`enableNodes`:: boolean, default is false. When this is true then non-aggregated history will be+collected separately for each node (for node and JVM metrics), with database names consisting of+base registry name with appended node name, eg. `solr.jvm.localhost:8983_solr`. When this is false+then only aggregated history will be collected in a single `solr.jvm` and `solr.node` cluster-wide+databases.++`collectPeriod`:: integer, in seconds, default is 60. Metrics values will be collected and respective+databases updated every `collectPeriod` seconds.+[IMPORTANT]+====+Value of `collectPeriod` must be at least 1, and if it's changed then all previously existing databases+with their historic data must be manually removed (new databases will be created automatically).+====++`syncPeriod`:: integer, in seconds, default is 60. Data from modified databases will be saved to Solr+every `syncPeriod` seconds. When accessing the databases via REST API the visibility of most recent+data depends on this period, because requests accessing the data from other nodes see only the+version of the data that is stored in the `.system` collection.++=== Example configuration+Example `/clusterprops.json` file with metrics history configuration that turns on the collection of+per-node metrics history for node and JVM metrics. Note: typically this file will also contain other+properties unrelated to metrics history API.++[source,json]+----+{+ "metrics" : {+ "history" : {+ "enable" : true,+ "enableNodes" : true,+ "syncPeriod" : 300+ }+ }+}+----++== Metrics History API+Main entry point for accessing metrics history is `/admin/metrics/history` (or `/api/cluster/metrics/history` for+v2 API).++The following sections describe actions available in this API. All calls have at least one+required parameter `action`.++=== List databases (`action=list`)+This call produces a list of available databases. It supports the following parameters:++`rows`:: optional integer, default is 500. Maximum number of results to return++Example:+[source,bash]+----+curl http://localhost:8983/solr/admin/metrics/history?action=list&rows=10+----+[source,json]+----+{+ "responseHeader": {+ "status": 0,+ "QTime": 16+ },+ "metrics": [+ "solr.collection..system",+ "solr.collection.gettingstarted",+ "solr.jvm",+ "solr.node"+ ]+}+----++=== Database status (`action=status`)+This call provides detailed status of the selected database.++The following parameters are supported:++`name`:: string, required: database name++Example:+[source,bash]+----+curl http://localhost:8983/solr/admin/metrics/history?action=status&name=solr.collection.gettingstarted+----+[source,json]+----+{+ "responseHeader": {+ "status": 0,+ "QTime": 38+ },+ "metrics": [+ "solr.collection.gettingstarted",+ [+ "status",+ {+ "lastModified": 1527268438,+ "step": 60,+ "datasourceCount": 5,+ "archiveCount": 5,+ "datasourceNames": [+ "numShards",+ "numReplicas",+ "QUERY./select.requests",+ "UPDATE./update.requests",+ "INDEX.sizeInBytes"+ ],+ "datasources": [+ {+ "datasource": "DS:numShards:GAUGE:120:U:U",+ "lastValue": 2+ },+ {+ "datasource": "DS:QUERY./select.requests:COUNTER:120:U:U",+ "lastValue": 8786+ },+ ...+ ],+ "archives": [+ {+ "archive": "RRA:AVERAGE:0.5:1:240",+ "steps": 1,+ "consolFun": "AVERAGE",+ "xff": 0.5,+ "startTime": 1527254040,+ "endTime": 1527268380,+ "rows": 240+ },+ {+ "archive": "RRA:AVERAGE:0.5:10:288",+ "steps": 10,+ "consolFun": "AVERAGE",+ "xff": 0.5,+ "startTime": 1527096000,+ "endTime": 1527268200,+ "rows": 288+ },+ ...+ ]+ }+ ]+ ]+}+----++=== Get database data (`action=get`)+This call retrieves all data collected in the specified database.++The following parameters are supported:++`name`:: string, required: database name+`format`:: string, optional, default is `list`. Format of the data. Currently the+following formats are supported:++* `list` - each datapoint is returned as separate JSON element. For efficiency, for each+datasource in a database for each time series the timestamps are provided separately from+values (because points from all datasources in a given time series share the same timestamps).+* `string` - all datapoint values and timestamps are returned as strings, with values separated by new line character.+* `graph` - data is returned as PNG images, Base64-encoded, containing graphs of each time series values over time.++In each case the response is structured in a similar way: archive identifiers are keys in a JSON map,+and timestamps / datapoints / graphs are values.++==== Examples+This is the output using the default `list` format:+[source,bash]+----+curl http://localhost:8983/solr/admin/metrics/history?action=get&name=solr.collection.gettingstarted+----+[source,json]+----+{+ "responseHeader": {+ "status": 0,+ "QTime": 36+ },+ "metrics": [+ "solr.collection.gettingstarted",+ [+ "data",+ {+ "RRA:AVERAGE:0.5:1:240": {+ "timestamps":1527254460,+ "timestamps":1527254520,+ "timestamps":1527254580,+ ...+ "values": {+ "numShards": "NaN",+ "numShards": 2.0,+ "numShards": 2.0,+ ...+ "numReplicas": "NaN",+ "numReplicas": 4.0,+ "numReplicas": 4.0,+ ...+ "QUERY./select.requests": "NaN",+ "QUERY./select.requests": 123,+ "QUERY./select.requests": 456,+ ...+ }+ },+ "RRA:AVERAGE:0.5:10:288": {+...+----++This is the output when using the `string` format:+[source,bash]+----+curl http://localhost:8983/solr/admin/metrics/history?action=get&name=solr.collection.gettingstarted&format=string+----+[source,json]+----+{+ "responseHeader": {+ "status": 0,+ "QTime": 11+ },+ "metrics": [+ "solr.collection.gettingstarted",+ [+ "data",+ {+ "RRA:AVERAGE:0.5:1:240": {+ "timestamps": "1527254820\n1527254880\n1527254940\n...",+ "values": {+ "numShards": "NaN\n2.0\n2.0\n2.0\n2.0\n2.0\n2.0\n...",+ "numReplicas": "NaN\n4.0\n4.0\n4.0\n4.0\n4.0\n4.0\n...",+ "QUERY./select.requests": "NaN\n123\n456\n789\n...",+ ...+ }+ },+ "RRA:AVERAGE:0.5:10:288": {+ ...+----++This is the output when using the `graph` format:+[source,bash]+----+curl http://localhost:8983/solr/admin/metrics/history?action=get&name=solr.collection.gettingstarted&format=graph+----+[source,json]+----+{+ "responseHeader": {+ "status": 0,+ "QTime": 2275+ },+ "metrics": [+ "solr.collection.gettingstarted",+ [+ "data",+ {+ "RRA:AVERAGE:0.5:1:240": {+ "values": {+ "numShards": "iVBORw0KGgoAAAANSUhEUgAAAkQAAA...",+ "numReplicas": "iVBORw0KGgoAAAANSUhEUgAAAkQA...",+ "QUERY./select.requests": "iVBORw0KGgoAAAANS...",+ ...+ }+ },+ "RRA:AVERAGE:0.5:10:288": {+ "values": {+ "numShards": "iVBORw0KGgoAAAANSUhEUgAAAkQAAA...",+ ...+ },+ ...+----++.Example 60 sec resolution history graph for `QUERY./select.requests` metric+image::images/metrics-history/query-graph-60s.png[image]+++.Example 10 min resolution history graph for `QUERY./select.requests` metric+image::images/metrics-history/query-graph-10min.png[image]+++.Example 60 sec resolution history graph for `UPDATE./update.requests` metric+image::images/metrics-history/update-graph-60s.png[image]++.Example 60 sec resolution history graph for `memory.heap.used` metric+image::images/metrics-history/memHeap-60s.png[image]++.Example 60 sec resolution history graph for `os.systemLoadAverage` metric+image::images/metrics-history/loadAvg-60s.png[image]\ No newline at end of filediff --git a/solr/solr-ref-guide/src/monitoring-solr.adoc b/solr/solr-ref-guide/src/monitoring-solr.adocindex 2fb70775968..2a8e1e87022 100644--- a/solr/solr-ref-guide/src/monitoring-solr.adoc+++ b/solr/solr-ref-guide/src/monitoring-solr.adoc@@ -1,5 +1,5 @@= Monitoring Solr-:page-children: metrics-reporting, mbean-request-handler, configuring-logging, using-jmx-with-solr, monitoring-solr-with-prometheus-and-grafana, performance-statistics-reference+:page-children: metrics-reporting, metrics-history, mbean-request-handler, configuring-logging, using-jmx-with-solr, monitoring-solr-with-prometheus-and-grafana, performance-statistics-reference// Licensed to the Apache Software Foundation (ASF) under one// or more contributor license agreements. See the NOTICE file// distributed with this work for additional information@@ -24,6 +24,8 @@ Common administrative tasks include:<<metrics-reporting.adoc#metrics-reporting,Metrics Reporting>>: Details of Solr's metrics registries and Metrics API.+<<metrics-history.adoc#metrics-history,Metrics History>>: Metrics history collection, configuration and API.+<<mbean-request-handler.adoc#mbean-request-handler,MBean Request Handler>>: How to use Solr's MBeans for programmatic access to the system plugins and stats.<<configuring-logging.adoc#configuring-logging,Configuring Logging>>: Describes how to configure logging for Solr.diff --git a/solr/solrj/src/java/org/apache/solr/common/params/CommonParams.java b/solr/solrj/src/java/org/apache/solr/common/params/CommonParams.javaindex a67f43324bf..21879ba174c 100644--- a/solr/solrj/src/java/org/apache/solr/common/params/CommonParams.java+++ b/solr/solrj/src/java/org/apache/solr/common/params/CommonParams.java@@ -183,6 +183,7 @@ public interface CommonParams {String AUTHC_PATH = "/admin/authentication";String ZK_PATH = "/admin/zookeeper";String METRICS_PATH = "/admin/metrics";+ String METRICS_HISTORY_PATH = "/admin/metrics/history";String AUTOSCALING_PATH = "/admin/autoscaling";String AUTOSCALING_HISTORY_PATH = "/admin/autoscaling/history";String AUTOSCALING_DIAGNOSTICS_PATH = "/admin/autoscaling/diagnostics";@@ -201,6 +202,7 @@ public interface CommonParams {AUTHC_PATH,AUTHZ_PATH,METRICS_PATH,+ METRICS_HISTORY_PATH,AUTOSCALING_PATH,AUTOSCALING_HISTORY_PATH,AUTOSCALING_DIAGNOSTICS_PATH,diff --git a/solr/solrj/src/java/org/apache/solr/common/params/CoreAdminParams.java b/solr/solrj/src/java/org/apache/solr/common/params/CoreAdminParams.javaindex 3fc6157c595..58c39a34399 100644--- a/solr/solrj/src/java/org/apache/solr/common/params/CoreAdminParams.java+++ b/solr/solrj/src/java/org/apache/solr/common/params/CoreAdminParams.java@@ -101,6 +101,8 @@ public abstract class CoreAdminParamspublic static final String DELETE_INSTANCE_DIR = "deleteInstanceDir";+ public static final String DELETE_METRICS_HISTORY = "deleteMetricsHistory";+public static final String LOAD_ON_STARTUP = "loadOnStartup";public static final String TRANSIENT = "transient";diff --git a/solr/solrj/src/resources/apispec/metrics.history.json b/solr/solrj/src/resources/apispec/metrics.history.jsonnew file mode 100644index 00000000000..975d77528ae--- /dev/null+++ b/solr/solrj/src/resources/apispec/metrics.history.json@@ -0,0 +1,23 @@+{+ "documentation": "https://lucene.apache.org/solr/guide/metrics-reporting.html",+ "description": "Metrics history handler allows retrieving samples of past metrics recorded in the .system collection.",+ "methods": [+ "GET"+ ],+ "url": {+ "paths": [+ "/cluster/metrics/history"+ ],+ "params": {+ "action": {+ "type": "string",+ "description": "one of supported actions",+ "default": "list"+ },+ "name": {+ "type": "string",+ "description": "registry name"+ }+ }+ }+}