You are viewing a plain text version of this content. The canonical link for it is here.
Posted to notifications@skywalking.apache.org by wu...@apache.org on 2026/04/30 08:42:26 UTC
(skywalking) branch feature/layer-extension created (now 49d38daace)
This is an automated email from the ASF dual-hosted git repository.
wu-sheng pushed a change to branch feature/layer-extension
in repository https://gitbox.apache.org/repos/asf/skywalking.git
at 49d38daace Layer extension: register custom layers without modifying OAP source
This branch includes the following new commits:
new 49d38daace Layer extension: register custom layers without modifying OAP source
The 1 revisions listed above as "new" are entirely new to this
repository and will be described in separate emails. The revisions
listed as "add" were already present in the repository and have only
been added to this reference.
(skywalking) 01/01: Layer extension: register custom layers without modifying OAP source
Posted by wu...@apache.org.
This is an automated email from the ASF dual-hosted git repository.
wu-sheng pushed a commit to branch feature/layer-extension
in repository https://gitbox.apache.org/repos/asf/skywalking.git
commit 49d38daaceb829b763144f7afd7c0fb1a8044cc4
Author: Wu Sheng <wu...@foxmail.com>
AuthorDate: Thu Apr 30 16:42:14 2026 +0800
Layer extension: register custom layers without modifying OAP source
`Layer` becomes a registry-backed value type with the same public API as
the prior enum (`Layer.SERVICE`, `value()`, `name()`, `valueOf(int)`,
`valueOf(String)`, `nameOf(String)`, `values()`). Built-in layers stay as
`public static final Layer` constants with frozen ordinals 0–49.
External layers can be registered through any of three new paths, all
funneling through `Layer.register(name, ordinal, normal)`:
- `layer-extensions.yml` on the OAP classpath / config dir — operator
config; one line per layer, no code change required.
- `LayerExtension` Java SPI under `META-INF/services/` — for plugin jars.
- Inline `layerDefinitions:` block at the top of any MAL or LAL rule
file — the cleanest path when a layer ships together with the rules
that produce its telemetry.
Storage encoding is unchanged: layers persist by ordinal int in BanyanDB,
Elasticsearch, and JDBC. Built-in ordinals 0–49 stay frozen; 50–999 are
reserved by convention for future built-ins; external layers are
recommended to start at >= 1000. The recommendation is informational —
collisions are reported loudly at boot via the ordinal-uniqueness check.
The registry is sealed at the start of `Core.notifyAfterCompleted()` after
every module's prepare/start has run. Subsequent `Layer.register` calls
throw, so runtime-rule MAL/LAL `/addOrUpdate` requests now reject inline
`layerDefinitions:` with a clear error pointing operators at the boot-time
registration paths.
`UITemplateInitializer` no longer iterates `Layer.values()` for folder
discovery; it walks `ui-initialized-templates/**/*.json` recursively and
trusts each template's own `configuration.layer` field, so dashboards for
external layers are auto-discovered without code changes.
`Layer.values()` now throws before seal — pre-seal the registry may still
grow, and a partial snapshot would silently mislead callers. The cached
sorted snapshot is computed once at seal so post-seal calls are O(1) plus
an array clone.
BanyanDB `MetadataRegistry.parseTagSpec` previously relied on
`Class.isEnum()` to map Layer columns to TAG_TYPE_INT; with `Layer` no
longer an enum, that path now treats `Layer.class` explicitly, matching
the existing ES / JDBC handling.
---
.claude/skills/new-monitoring-feature/SKILL.md | 28 +-
docs/en/changes/changes.md | 1 +
docs/en/concepts-and-designs/lal.md | 45 +++
docs/en/concepts-and-designs/mal.md | 38 ++
.../oap/log/analyzer/v2/provider/LALConfigs.java | 30 ++
.../meter/analyzer/v2/prometheus/rule/Rule.java | 7 +
.../meter/analyzer/v2/prometheus/rule/Rules.java | 23 ++
.../oap/server/core/CoreModuleProvider.java | 14 +
.../skywalking/oap/server/core/analysis/Layer.java | 423 ++++++++++++---------
.../oap/server/core/analysis/LayerDefinition.java} | 28 +-
.../oap/server/core/analysis/LayerExtension.java | 57 +++
.../server/core/analysis/LayerExtensionLoader.java | 109 ++++++
.../ui/template/UITemplateInitializer.java | 55 +--
.../receiver/runtimerule/apply/LalFileApplier.java | 9 +
.../receiver/runtimerule/apply/MalFileApplier.java | 9 +
.../src/main/resources/layer-extensions.yml | 63 +++
.../oap/server/starter/UITemplateCheckerTest.java | 67 ++--
.../storage/plugin/banyandb/MetadataRegistry.java | 3 +-
.../elasticsearch/query/MetadataQueryEsDAO.java | 3 -
19 files changed, 753 insertions(+), 259 deletions(-)
diff --git a/.claude/skills/new-monitoring-feature/SKILL.md b/.claude/skills/new-monitoring-feature/SKILL.md
index cb0a12d2a2..c524a8374d 100644
--- a/.claude/skills/new-monitoring-feature/SKILL.md
+++ b/.claude/skills/new-monitoring-feature/SKILL.md
@@ -21,11 +21,22 @@ There is one skill per narrow concern. This one is the wiring map.
## 0. Register the `Layer` — the feature's entry point
-A `Layer` is how OAP slices services / instances / endpoints by data source. **Every new feature needs a new `Layer` enum value.** The UI, storage partitioning, menu navigation, and OAL aggregation all key off it.
+A `Layer` is how OAP slices services / instances / endpoints by data source. The UI, storage partitioning, menu navigation, and OAL aggregation all key off it.
-**Only one place to edit** — `oap-server/server-core/src/main/java/org/apache/skywalking/oap/server/core/analysis/Layer.java`. Add a new enum constant with a unique id and `normal` flag. Ids are never reused; pick the next integer. Examples: `IOS(47, true)`, `APISIX(27, true)`, `VIRTUAL_DATABASE(11, false)` for inferred/non-real services.
+`Layer` is a registry-backed value type (no longer a closed enum). Built-in layers are declared as `public static final Layer` constants in `oap-server/server-core/src/main/java/org/apache/skywalking/oap/server/core/analysis/Layer.java`; external layers are registered through the `Layer.register(name, ordinal, normal)` API at boot. **Pick the registration path that matches the scope of your feature:**
-UI template folders are auto-discovered: `UITemplateInitializer.UI_TEMPLATE_FOLDER` is computed from `Layer.values()` + `"custom"` at class-init time. Drop a `ui-initialized-templates/<layer-name-lowercased>/` folder on disk and the initializer picks it up on the next boot. Missing folders are silently skipped. There is no allowlist to append to.
+| Your feature ships as | Registration path |
+|---|---|
+| Part of the OAP distribution (in-tree, the common case for new SkyWalking-supported targets) | Add a `public static final Layer` constant to `Layer.java` with the next sequential ordinal in `0–49`. Examples: `IOS = register("IOS", 47, true)`, `APISIX = register("APISIX", 21, true)`, `VIRTUAL_DATABASE = register("VIRTUAL_DATABASE", 14, false)` for inferred/non-real services. |
+| An out-of-tree MAL or LAL rule file | Add a top-level `layerDefinitions:` block to the rule file. The DSL loader funnels each entry through `Layer.register` before compiling the rule. One file ships the layer + the rules that produce its telemetry. |
+| An out-of-tree plugin module (jar) | Implement `org.apache.skywalking.oap.server.core.analysis.LayerExtension` and register via `META-INF/services/`. Discovered by `LayerExtensionLoader` during `CoreModuleProvider.prepare()`. |
+| Operator-deployed config (no code, no DSL) | Add an entry to `oap-server/server-starter/src/main/resources/layer-extensions.yml` (or override on the OAP node's classpath). |
+
+**Ordinal conventions:** `0–49` is in active use by built-ins. `50–999` is reserved by convention for future built-in layers. External layers are recommended (not required) to start at `>= 1000` to avoid colliding with future built-ins on OAP upgrade. Collisions in either direction are detected at boot via the ordinal-uniqueness check, which fails OAP startup loudly.
+
+**Storage encoding is the ordinal int**, persisted in BanyanDB / Elasticsearch / JDBC. Every OAP node that reads or writes a given layer must agree on its `(name, ordinal)` mapping — deploy `layer-extensions.yml` and any `layerDefinitions:` rule files identically across all nodes. The registry is sealed at the start of `Core.notifyAfterCompleted()`; later registration attempts throw.
+
+**UI template folders are auto-discovered by file scan, not by `Layer.values()`.** `UITemplateInitializer` walks `ui-initialized-templates/**/*.json` recursively (depth 2) and trusts each template's own `configuration.layer` field. Drop a folder of dashboard JSONs on disk and the initializer picks them up on the next boot — folder name is purely organizational.
**Component ID lookup in Java code**: IDs declared in `component-libraries.yml` are loaded at runtime into `ComponentLibraryCatalogService`'s `componentName2Id` map — they are **not** exposed as Java enum constants. To look up by name in listener code, inject the catalog service and resolve once at construction:
```java
@@ -35,11 +46,14 @@ int myComponentId = catalog.getComponentId("My-Component-Name");
```
Cache as an `int` field; runtime comparisons are then plain `componentId == myComponentId`. **Trap:** there is a `ComponentsDefine` class under `skywalking-trace-receiver-plugin/src/test/java/.../mock/ComponentsDefine.java` — it is a test-only mock holding five hand-picked constants (Tomcat, Dubbo, RocketMQ, MongoDB). Do not import or extend it from production code.
-Emit the layer from every source object your feature produces:
+Emit the layer from every source object your feature produces. Built-in layers have a static-field accessor; external layers are looked up by name through the registry:
+
```java
-service.setLayer(Layer.<YOUR_LAYER>);
-serviceInstance.setServiceLayer(Layer.<YOUR_LAYER>);
-endpoint.setServiceLayer(Layer.<YOUR_LAYER>);
+// Built-in layer (constant)
+service.setLayer(Layer.IOS);
+
+// External layer (registered via yaml / SPI / layerDefinitions:)
+service.setLayer(Layer.nameOf("IOT_FLEET"));
```
Downstream (the core OAL, `service ly <LAYER>` swctl query, topology filters, UI root dashboard's layer selector) all work off this single enum value.
diff --git a/docs/en/changes/changes.md b/docs/en/changes/changes.md
index 8a146805ab..4f6108a2ca 100644
--- a/docs/en/changes/changes.md
+++ b/docs/en/changes/changes.md
@@ -59,6 +59,7 @@
validation code requires the `protobuf-java 4.x` runtime.
#### OAP Server
+* Custom `Layer`s can be declared without modifying the OAP source — via an operator-managed `layer-extensions.yml`, inline `layerDefinitions:` block in a MAL or LAL rule file, or a plugin extension. UI dashboard templates for new layers are auto-discovered from the `ui-initialized-templates/` directory. Recommended ordinal range for external layers is `>= 1000`; conflicting names or ordinals are reported at boot.
* Add Zipkin Virtual GenAI e2e test. Use `zipkin_json` exporter to avoid protobuf dependency conflict
between `opentelemetry-exporter-zipkin-proto-http` (protobuf~=3.12) and `opentelemetry-proto` (protobuf>=5.0).
* Fix missing `taskId` filter and incorrect `IN` clause parameter binding in `JDBCJFRDataQueryDAO` and `JDBCPprofDataQueryDAO`.
diff --git a/docs/en/concepts-and-designs/lal.md b/docs/en/concepts-and-designs/lal.md
index 3a8e39e810..5a44925177 100644
--- a/docs/en/concepts-and-designs/lal.md
+++ b/docs/en/concepts-and-designs/lal.md
@@ -30,6 +30,51 @@ Use `tag 'key': sourceAttribute("attr")` in the extractor to selectively persist
Layer should be declared in the LAL script to represent the analysis scope of the logs.
LAL rules are routed by layer — only rules matching the incoming log's layer are evaluated.
+### Inline layer declarations (`layerDefinitions:`)
+
+A LAL file may declare its own custom layers with a top-level `layerDefinitions:` block.
+Each entry is funneled through `Layer.register(name, ordinal, normal)` **before**
+the rules in the same file compile, so a LAL file is fully self-describing — a new
+monitoring target can land as a single LAL file without an enum edit elsewhere in the OAP
+source.
+
+```yaml
+layerDefinitions:
+ - name: IOT_FLEET # upper-snake-case, must match [A-Z][A-Z0-9_]*
+ ordinal: 1000 # unique across all layers; >= 1000 recommended
+ normal: true # true = agent-installed (default), false = conjectured/virtual
+
+rules:
+ - name: iot-fleet-access
+ layer: IOT_FLEET
+ dsl: |
+ filter {
+ text { regexp $/(?<status>\d+)\s+(?<path>\S+)/$ }
+ sink { sampler { rateLimit { rpm 1800 } } }
+ }
+```
+
+Notes:
+- **Storage encoding is the ordinal int**, persisted in BanyanDB / Elasticsearch / JDBC.
+ Every OAP node that reads or writes a given layer must agree on its `(name, ordinal)`
+ mapping — deploy a LAL file with `layerDefinitions:` identically across all nodes.
+- **Identical re-registration is a no-op**, so the same `IOT_FLEET` entry can appear in
+ multiple LAL files (and additionally in a MAL file, in `layer-extensions.yml`, or via the
+ `LayerExtension` SPI). Conflicting registrations cause OAP boot to fail loudly with the
+ offending file in the stack trace.
+- **Ordinals 0–49** are in active use by the OAP distribution's built-in layers; **50–999**
+ are reserved by convention for future built-ins. External layers should start at `>= 1000`
+ — enforcement is not strict, but staying above the reserved band avoids upgrade-time
+ collisions.
+- `layer: auto` works with extension layers too — the extractor body can call
+ `layer "IOT_FLEET"` and the runtime resolves it through the registry.
+
+Three other registration paths exist for layers that are **not** specific to a LAL file: an
+operator-managed `layer-extensions.yml`, a `LayerExtension` Java SPI for plugin jars, and
+the built-in static fields in `Layer.java` for distribution layers. See
+[`Layer.java`](../../../oap-server/server-core/src/main/java/org/apache/skywalking/oap/server/core/analysis/Layer.java)
+javadoc for the full picture.
+
When `layer: auto` is declared, the rule matches logs where `service.layer` is absent (common for OTLP
sources that don't set this attribute). The script is expected to set the layer in the extractor:
diff --git a/docs/en/concepts-and-designs/mal.md b/docs/en/concepts-and-designs/mal.md
index 19e5e1bddd..f050c3aee7 100644
--- a/docs/en/concepts-and-designs/mal.md
+++ b/docs/en/concepts-and-designs/mal.md
@@ -377,6 +377,44 @@ name: <string>
exp: <string>
```
+### <layer_definitions>
+
+Optional top-level block for declaring custom layers inline alongside the rules that produce
+their telemetry. Each entry is funneled through `Layer.register(name, ordinal, normal)`
+**before** the rules in the same file compile, so a MAL file is fully self-describing — a new
+monitoring target can land as a single MAL file without an enum edit elsewhere in the OAP source.
+
+```yaml
+layerDefinitions:
+ - name: IOT_FLEET # upper-snake-case, must match [A-Z][A-Z0-9_]*
+ ordinal: 1000 # unique across all layers; >= 1000 recommended
+ normal: true # true = agent-installed (default), false = conjectured/virtual
+
+metricsRules:
+ - name: device_battery_percentage
+ exp: iot_device_battery_level.tagAverage(['service'], ['host'])
+expSuffix: instance(['host'], ['service'], Layer.nameOf('IOT_FLEET'))
+```
+
+Notes:
+- **Storage encoding is the ordinal int**, persisted in BanyanDB / Elasticsearch / JDBC. Every
+ OAP node that reads or writes a given layer must agree on its `(name, ordinal)` mapping —
+ deploy a MAL file with `layerDefinitions:` identically across all nodes.
+- **Identical re-registration is a no-op**, so the same `IOT_FLEET` entry can appear in multiple
+ MAL files (and additionally in a LAL file, in `layer-extensions.yml`, or via the
+ `LayerExtension` SPI). Conflicting registrations (same name with different ordinal, or same
+ ordinal with different name) cause OAP boot to fail loudly with the offending file in the
+ stack trace.
+- **Ordinals 0–49** are in active use by the OAP distribution's built-in layers; **50–999** are
+ reserved by convention for future built-ins. External layers should start at `>= 1000` —
+ enforcement is not strict, but staying above the reserved band avoids upgrade-time collisions.
+
+Three other registration paths exist for layers that are **not** specific to a MAL file: an
+operator-managed `layer-extensions.yml`, a `LayerExtension` Java SPI for plugin jars, and the
+built-in static fields in `Layer.java` for distribution layers. See
+[`Layer.java`](../../../oap-server/server-core/src/main/java/org/apache/skywalking/oap/server/core/analysis/Layer.java)
+javadoc for the full picture.
+
## More Examples
Please refer to [OAP Self-Observability](../../../oap-server/server-starter/src/main/resources/otel-rules/oap.yaml).
diff --git a/oap-server/analyzer/log-analyzer/src/main/java/org/apache/skywalking/oap/log/analyzer/v2/provider/LALConfigs.java b/oap-server/analyzer/log-analyzer/src/main/java/org/apache/skywalking/oap/log/analyzer/v2/provider/LALConfigs.java
index 0e22b883c2..f0dea01585 100644
--- a/oap-server/analyzer/log-analyzer/src/main/java/org/apache/skywalking/oap/log/analyzer/v2/provider/LALConfigs.java
+++ b/oap-server/analyzer/log-analyzer/src/main/java/org/apache/skywalking/oap/log/analyzer/v2/provider/LALConfigs.java
@@ -33,6 +33,8 @@ import java.util.List;
import java.util.Map;
import lombok.Data;
import lombok.extern.slf4j.Slf4j;
+import org.apache.skywalking.oap.server.core.UnexpectedException;
+import org.apache.skywalking.oap.server.core.analysis.LayerDefinition;
import org.apache.skywalking.oap.server.core.rule.ext.RuleSetMerger;
import org.apache.skywalking.oap.server.library.module.ModuleManager;
import org.apache.skywalking.oap.server.library.module.ModuleStartException;
@@ -48,6 +50,12 @@ import static org.apache.skywalking.oap.server.library.util.CollectionUtils.isEm
@Slf4j
public class LALConfigs {
private List<LALConfig> rules;
+ /**
+ * Optional inline layer registrations. When present, each entry is registered through
+ * {@code Layer.register(...)} before the rules in this file are compiled, so a
+ * LAL file is self-describing for any custom layers it references.
+ */
+ private List<LayerDefinition> layerDefinitions;
public static List<LALConfigs> load(final String path, final List<String> files) throws Exception {
return loadInternal(path, files, null, /* useInstalledManager= */ true);
@@ -127,6 +135,7 @@ public class LALConfigs {
if (configs == null || configs.getRules() == null) {
continue;
}
+ registerInlineLayers(ruleName, configs);
// sourceFileName is only present for entries that came from disk; resolver-
// only rules synthesise a name so diagnostics still print something.
final String src = sourceFileName.getOrDefault(ruleName, ruleName + ".yaml");
@@ -141,4 +150,25 @@ public class LALConfigs {
throw new ModuleStartException("Failed to load LAL config rules", e);
}
}
+
+ /**
+ * Funnel any inline {@code layerDefinitions:} entries through {@code Layer.register}.
+ * Conflict checks (reserved-range, name uniqueness, ordinal uniqueness, sealed-state) live
+ * in {@code Layer.register}; failures here surface with the offending rule name in
+ * the stack trace, which is enough for an operator to find the bad file.
+ */
+ private static void registerInlineLayers(final String ruleName, final LALConfigs configs) {
+ final List<LayerDefinition> defs = configs.getLayerDefinitions();
+ if (defs == null || defs.isEmpty()) {
+ return;
+ }
+ for (final LayerDefinition def : defs) {
+ try {
+ def.register();
+ } catch (RuntimeException e) {
+ throw new UnexpectedException(
+ "LAL rule " + ruleName + " layerDefinitions entry rejected: " + def, e);
+ }
+ }
+ }
}
diff --git a/oap-server/analyzer/meter-analyzer/src/main/java/org/apache/skywalking/oap/meter/analyzer/v2/prometheus/rule/Rule.java b/oap-server/analyzer/meter-analyzer/src/main/java/org/apache/skywalking/oap/meter/analyzer/v2/prometheus/rule/Rule.java
index 930b2e7718..47497a964f 100644
--- a/oap-server/analyzer/meter-analyzer/src/main/java/org/apache/skywalking/oap/meter/analyzer/v2/prometheus/rule/Rule.java
+++ b/oap-server/analyzer/meter-analyzer/src/main/java/org/apache/skywalking/oap/meter/analyzer/v2/prometheus/rule/Rule.java
@@ -21,6 +21,7 @@ package org.apache.skywalking.oap.meter.analyzer.v2.prometheus.rule;
import lombok.Data;
import lombok.NoArgsConstructor;
import org.apache.skywalking.oap.meter.analyzer.v2.MetricRuleConfig;
+import org.apache.skywalking.oap.server.core.analysis.LayerDefinition;
import java.util.List;
@@ -36,6 +37,12 @@ public class Rule implements MetricRuleConfig {
private String expPrefix;
private String filter;
private List<MetricsRule> metricsRules;
+ /**
+ * Optional inline layer registrations. When present, each entry is registered through
+ * {@code Layer.register(...)} before the rule's expressions compile, so the
+ * rule file is self-describing for any custom layers it references.
+ */
+ private List<LayerDefinition> layerDefinitions;
@Override
public String getSourceName() {
diff --git a/oap-server/analyzer/meter-analyzer/src/main/java/org/apache/skywalking/oap/meter/analyzer/v2/prometheus/rule/Rules.java b/oap-server/analyzer/meter-analyzer/src/main/java/org/apache/skywalking/oap/meter/analyzer/v2/prometheus/rule/Rules.java
index 9596f03e02..5be3b570a9 100644
--- a/oap-server/analyzer/meter-analyzer/src/main/java/org/apache/skywalking/oap/meter/analyzer/v2/prometheus/rule/Rules.java
+++ b/oap-server/analyzer/meter-analyzer/src/main/java/org/apache/skywalking/oap/meter/analyzer/v2/prometheus/rule/Rules.java
@@ -37,6 +37,7 @@ import java.util.stream.Collectors;
import java.util.stream.Stream;
import org.apache.skywalking.oap.server.core.UnexpectedException;
+import org.apache.skywalking.oap.server.core.analysis.LayerDefinition;
import org.apache.skywalking.oap.server.core.rule.ext.RuleSetMerger;
import org.apache.skywalking.oap.server.library.module.ModuleManager;
import org.apache.skywalking.oap.server.library.util.ResourceUtils;
@@ -149,9 +150,31 @@ public class Rules {
return null;
}
rule.setName(ruleName);
+ registerInlineLayers(ruleName, rule);
return rule;
} catch (IOException e) {
throw new UnexpectedException("Load rule " + ruleName + " failed", e);
}
}
+
+ /**
+ * Funnel any inline {@code layerDefinitions:} entries through {@code Layer.register}.
+ * Conflict checks (reserved-range, name uniqueness, ordinal uniqueness, sealed-state) live
+ * in {@code Layer.register}; failures here surface with the offending rule name in
+ * the stack trace, which is enough for an operator to find the bad file.
+ */
+ private static void registerInlineLayers(final String ruleName, final Rule rule) {
+ final List<LayerDefinition> defs = rule.getLayerDefinitions();
+ if (defs == null || defs.isEmpty()) {
+ return;
+ }
+ for (final LayerDefinition def : defs) {
+ try {
+ def.register();
+ } catch (RuntimeException e) {
+ throw new UnexpectedException(
+ "MAL rule " + ruleName + " layerDefinitions entry rejected: " + def, e);
+ }
+ }
+ }
}
diff --git a/oap-server/server-core/src/main/java/org/apache/skywalking/oap/server/core/CoreModuleProvider.java b/oap-server/server-core/src/main/java/org/apache/skywalking/oap/server/core/CoreModuleProvider.java
index 273b4bfbb6..17752a4321 100755
--- a/oap-server/server-core/src/main/java/org/apache/skywalking/oap/server/core/CoreModuleProvider.java
+++ b/oap-server/server-core/src/main/java/org/apache/skywalking/oap/server/core/CoreModuleProvider.java
@@ -25,6 +25,8 @@ import org.apache.skywalking.oap.server.configuration.api.DynamicConfigurationSe
import org.apache.skywalking.oap.server.core.analysis.ApdexThresholdConfig;
import org.apache.skywalking.oap.server.core.rule.ext.RuleSetMerger;
import org.apache.skywalking.oap.server.core.analysis.DisableRegister;
+import org.apache.skywalking.oap.server.core.analysis.Layer;
+import org.apache.skywalking.oap.server.core.analysis.LayerExtensionLoader;
import org.apache.skywalking.oap.server.core.analysis.StreamAnnotationListener;
import org.apache.skywalking.oap.server.core.analysis.meter.MeterEntity;
import org.apache.skywalking.oap.server.core.analysis.meter.MeterSystem;
@@ -184,6 +186,12 @@ public class CoreModuleProvider extends ModuleProvider {
@Override
public void prepare() throws ServiceNotProvidedException, ModuleStartException {
+ // Load external Layer registrations (yaml + SPI) before anything else in Core
+ // wires up. Downstream modules' prepare()/start() — including MAL/LAL DSL loaders
+ // that may declare inline `layerDefinitions:` blocks — register on top of this
+ // baseline. The registry is sealed at the start of notifyAfterCompleted().
+ LayerExtensionLoader.load();
+
if (moduleConfig.isActiveExtraModelColumns()) {
DefaultScopeDefine.activeExtraModelColumns();
}
@@ -473,6 +481,12 @@ public class CoreModuleProvider extends ModuleProvider {
@Override
public void notifyAfterCompleted() throws ModuleStartException {
+ // Seal the Layer registry: every module's prepare() and start() has now run, so
+ // MAL/LAL/SPI/yaml all had their full window to register external layers. After
+ // this point, Layer.register() throws — UI templates and downstream
+ // queries see a stable layer set.
+ Layer.seal();
+
try {
if (!RunningMode.isInitMode()) {
grpcServer.start();
diff --git a/oap-server/server-core/src/main/java/org/apache/skywalking/oap/server/core/analysis/Layer.java b/oap-server/server-core/src/main/java/org/apache/skywalking/oap/server/core/analysis/Layer.java
index 207698a413..0d7e1a8354 100644
--- a/oap-server/server-core/src/main/java/org/apache/skywalking/oap/server/core/analysis/Layer.java
+++ b/oap-server/server-core/src/main/java/org/apache/skywalking/oap/server/core/analysis/Layer.java
@@ -18,325 +18,398 @@
package org.apache.skywalking.oap.server.core.analysis;
-import org.apache.skywalking.oap.server.core.UnexpectedException;
-
-import java.util.Arrays;
-import java.util.HashMap;
+import java.util.Comparator;
import java.util.Map;
+import java.util.concurrent.ConcurrentHashMap;
+import java.util.regex.Pattern;
+import java.util.stream.Collectors;
+import org.apache.skywalking.oap.server.core.UnexpectedException;
/**
* Layer represents an abstract framework in computer science, such as Operating System(OS_LINUX layer), Kubernetes(k8s
* layer). This kind of layer would be owners of different services detected from different technology.
+ *
+ * <p>A registry-backed value type. Built-in layers are declared as {@code public static final}
+ * constants below; external layers are contributed at boot through
+ * {@link #register(String, int, boolean)}. Lookups are by name ({@link #nameOf(String)},
+ * {@link #valueOf(String)}) or by ordinal ({@link #valueOf(int)}); {@link #values()} returns
+ * every registered layer sorted by ordinal.
+ *
+ * <p>Layers are persisted by ordinal (int). Built-in ordinals 0–49 are frozen forever and
+ * must never be reused. Ordinals 50–999 are reserved by convention for future built-ins;
+ * external extensions are <strong>recommended</strong> to start at {@code 1000} to avoid
+ * colliding with future built-ins on OAP upgrade. The recommendation is informational and
+ * not enforced — any non-colliding ordinal is accepted — but a future built-in landing on
+ * the same ordinal as an extension layer will cause OAP boot to fail loudly via the
+ * ordinal uniqueness check, which is the upgrade-time detection mechanism.
+ *
+ * <p>Registration paths (all funnel through {@link #register}):
+ * <ol>
+ * <li>Operator yaml — {@code layer-extensions.yml} on the OAP classpath/config dir.</li>
+ * <li>Java SPI — {@code LayerExtension} discovered via {@code ServiceLoader}.</li>
+ * <li>DSL inline — MAL/LAL rule files declaring a top-level {@code layerDefinitions:}
+ * block; the DSL loader funnels each entry through this method before compiling.</li>
+ * </ol>
+ * The registry is sealed at the start of {@code CoreModuleProvider.notifyAfterCompleted()};
+ * any registration attempt after that throws.
*/
-public enum Layer {
- /**
- * Default Layer if the layer is not defined
- */
- UNDEFINED(0, false),
+public final class Layer {
- /**
- * Envoy Access Log Service
- */
- MESH(1, true),
+ private static final Pattern NAME_PATTERN = Pattern.compile("[A-Z][A-Z0-9_]*");
+ private static final Map<Integer, Layer> BY_VALUE = new ConcurrentHashMap<>();
+ private static final Map<String, Layer> BY_NAME = new ConcurrentHashMap<>();
+ private static volatile boolean SEALED = false;
/**
- * Agent-installed Service
+ * Snapshot of all registered layers sorted by ordinal, frozen at {@link #seal()}.
+ * Before seal, {@link #values()} computes on the fly so newly registered layers are
+ * visible; after seal, {@link #values()} returns a clone of this cached array.
*/
- GENERAL(2, true),
+ private static volatile Layer[] CACHED_VALUES = null;
- /**
- * Linux Machine
- */
- OS_LINUX(3, true),
+ /** Default Layer if the layer is not defined */
+ public static final Layer UNDEFINED = register("UNDEFINED", 0, false);
- /**
- * Kubernetes cluster
- */
- K8S(4, true),
+ /** Envoy Access Log Service */
+ public static final Layer MESH = register("MESH", 1, true);
+
+ /** Agent-installed Service */
+ public static final Layer GENERAL = register("GENERAL", 2, true);
+
+ /** Linux Machine */
+ public static final Layer OS_LINUX = register("OS_LINUX", 3, true);
+
+ /** Kubernetes cluster */
+ public static final Layer K8S = register("K8S", 4, true);
/**
- * Function as a Service
- *
- * Deprecated since 9.7.0. OpenFunction relative features are not maintained anymore.
+ * Function as a Service. Deprecated since 9.7.0. OpenFunction relative features are not maintained anymore.
*/
@Deprecated
- FAAS(5, true),
+ public static final Layer FAAS = register("FAAS", 5, true);
- /**
- * Mesh control plane, eg. Istio control plane
- */
- MESH_CP(6, true),
+ /** Mesh control plane, eg. Istio control plane */
+ public static final Layer MESH_CP = register("MESH_CP", 6, true);
- /**
- * Mesh data plane, eg. Envoy
- */
- MESH_DP(7, true),
+ /** Mesh data plane, eg. Envoy */
+ public static final Layer MESH_DP = register("MESH_DP", 7, true);
- /**
- * Telemetry from real database
- */
- DATABASE(8, true),
+ /** Telemetry from real database */
+ public static final Layer DATABASE = register("DATABASE", 8, true);
- /**
- * Cache service eg. ehcache, guava-cache, memcache
- */
- CACHE(9, true),
+ /** Cache service eg. ehcache, guava-cache, memcache */
+ public static final Layer CACHE = register("CACHE", 9, true);
- /**
- * Telemetry from the Browser eg. Apache SkyWalking Client JS
- */
- BROWSER(10, true),
+ /** Telemetry from the Browser eg. Apache SkyWalking Client JS */
+ public static final Layer BROWSER = register("BROWSER", 10, true);
- /**
- * Self Observability of OAP
- */
- SO11Y_OAP(11, true),
+ /** Self Observability of OAP */
+ public static final Layer SO11Y_OAP = register("SO11Y_OAP", 11, true);
- /**
- * Self Observability of Satellite
- */
- SO11Y_SATELLITE(12, true),
+ /** Self Observability of Satellite */
+ public static final Layer SO11Y_SATELLITE = register("SO11Y_SATELLITE", 12, true);
- /**
- * Telemetry from the real MQ
- */
- MQ(13, true),
+ /** Telemetry from the real MQ */
+ public static final Layer MQ = register("MQ", 13, true);
- /**
- * Database conjectured by client side plugin
- */
- VIRTUAL_DATABASE(14, false),
+ /** Database conjectured by client side plugin */
+ public static final Layer VIRTUAL_DATABASE = register("VIRTUAL_DATABASE", 14, false);
- /**
- * MQ conjectured by client side plugin
- */
- VIRTUAL_MQ(15, false),
+ /** MQ conjectured by client side plugin */
+ public static final Layer VIRTUAL_MQ = register("VIRTUAL_MQ", 15, false);
- /**
- * The uninstrumented gateways configured in OAP
- */
- VIRTUAL_GATEWAY(16, false),
+ /** The uninstrumented gateways configured in OAP */
+ public static final Layer VIRTUAL_GATEWAY = register("VIRTUAL_GATEWAY", 16, false);
- /**
- * Kubernetes service
- */
- K8S_SERVICE(17, true),
+ /** Kubernetes service */
+ public static final Layer K8S_SERVICE = register("K8S_SERVICE", 17, true);
/**
* MySQL Server, also known as mysqld, is a single multithreaded program that does most of the work in a MySQL
* installation.
*/
- MYSQL(18, true),
+ public static final Layer MYSQL = register("MYSQL", 18, true);
- /**
- * Cache conjectured by client side plugin(eg. skywalking-java -> JedisPlugin LettucePlugin)
- */
- VIRTUAL_CACHE(19, false),
+ /** Cache conjectured by client side plugin(eg. skywalking-java -> JedisPlugin LettucePlugin) */
+ public static final Layer VIRTUAL_CACHE = register("VIRTUAL_CACHE", 19, false);
- /**
- * PostgreSQL is an advanced, enterprise-class, and open-source relational database system.
- */
- POSTGRESQL(20, true),
+ /** PostgreSQL is an advanced, enterprise-class, and open-source relational database system. */
+ public static final Layer POSTGRESQL = register("POSTGRESQL", 20, true);
- /**
- * Apache APISIX is an open source, dynamic, scalable, and high-performance cloud native API gateway.
- */
- APISIX(21, true),
+ /** Apache APISIX is an open source, dynamic, scalable, and high-performance cloud native API gateway. */
+ public static final Layer APISIX = register("APISIX", 21, true);
- /**
- * EKS (Amazon Elastic Kubernetes Service) is k8s service provided by AWS Cloud
- */
- AWS_EKS(22, true),
+ /** EKS (Amazon Elastic Kubernetes Service) is k8s service provided by AWS Cloud */
+ public static final Layer AWS_EKS = register("AWS_EKS", 22, true);
- /**
- * Windows Machine
- */
- OS_WINDOWS(23, true),
+ /** Windows Machine */
+ public static final Layer OS_WINDOWS = register("OS_WINDOWS", 23, true);
- /**
- * Amazon Simple Storage Service (Amazon S3) is an object storage service provided by AWS Cloud
- */
- AWS_S3(24, true),
+ /** Amazon Simple Storage Service (Amazon S3) is an object storage service provided by AWS Cloud */
+ public static final Layer AWS_S3 = register("AWS_S3", 24, true);
/**
* Amazon DynamoDB is a fully managed NoSQL database service that provides
* fast and predictable performance with seamless scalability.
*/
- AWS_DYNAMODB(25, true),
+ public static final Layer AWS_DYNAMODB = register("AWS_DYNAMODB", 25, true);
/**
* Amazon API Gateway is an AWS service for creating, publishing, maintaining, monitoring, and securing REST, HTTP,
* and WebSocket APIs at any scale.
*/
- AWS_GATEWAY(26, true),
+ public static final Layer AWS_GATEWAY = register("AWS_GATEWAY", 26, true);
/**
* Redis is an open source (BSD licensed), in-memory data structure store,
* used as a database, cache, and message broker.
*/
- REDIS(27, true),
+ public static final Layer REDIS = register("REDIS", 27, true);
/**
* Elasticsearch is a distributed, open source search and analytics engine for all types of data,
* including textual, numerical, geospatial, structured, and unstructured.
*/
- ELASTICSEARCH(28, true),
+ public static final Layer ELASTICSEARCH = register("ELASTICSEARCH", 28, true);
/**
* RabbitMQ is one of the most popular open source message brokers. RabbitMQ is lightweight and easy to deploy
* on premises and in the cloud. It supports multiple messaging protocols.
*/
- RABBITMQ(29, true),
+ public static final Layer RABBITMQ = register("RABBITMQ", 29, true);
- /**
- * MongoDB is a document database. It stores data in a type of JSON format called BSON.
- */
- MONGODB(30, true),
+ /** MongoDB is a document database. It stores data in a type of JSON format called BSON. */
+ public static final Layer MONGODB = register("MONGODB", 30, true);
- /**
- * Kafka is a distributed streaming platform that is used publish and subscribe to streams of records.
- */
- KAFKA(31, true),
+ /** Kafka is a distributed streaming platform that is used publish and subscribe to streams of records. */
+ public static final Layer KAFKA = register("KAFKA", 31, true);
/**
* Pulsar is a distributed pub-sub messaging platform that provides high-performance, durable messaging.
* It is used to publish and subscribe to streams of records.
* Pulsar supports scalable and fault-tolerant messaging, making it suitable for use in distributed systems.
*/
- PULSAR(32, true),
+ public static final Layer PULSAR = register("PULSAR", 32, true);
- /**
- * A scalable, fault-tolerant, and low-latency storage service optimized for real-time workloads.
- */
- BOOKKEEPER(33, true),
+ /** A scalable, fault-tolerant, and low-latency storage service optimized for real-time workloads. */
+ public static final Layer BOOKKEEPER = register("BOOKKEEPER", 33, true);
- /**
- * Nginx is an HTTP and reverse proxy server, a mail proxy server, and a generic TCP/UDP proxy server.
- */
- NGINX(34, true),
+ /** Nginx is an HTTP and reverse proxy server, a mail proxy server, and a generic TCP/UDP proxy server. */
+ public static final Layer NGINX = register("NGINX", 34, true);
- /**
- * A cloud native messaging and streaming platform, making it simple to build event-driven applications.
- */
- ROCKETMQ(35, true),
+ /** A cloud native messaging and streaming platform, making it simple to build event-driven applications. */
+ public static final Layer ROCKETMQ = register("ROCKETMQ", 35, true);
/**
* A high-performance, column-oriented SQL database management system (DBMS) for online analytical processing (OLAP).
*/
- CLICKHOUSE(36, true),
+ public static final Layer CLICKHOUSE = register("CLICKHOUSE", 36, true);
- /**
- * ActiveMQ is a popular open source, multi-protocol, Java-based message broker.
- */
- ACTIVEMQ(37, true),
+ /** ActiveMQ is a popular open source, multi-protocol, Java-based message broker. */
+ public static final Layer ACTIVEMQ = register("ACTIVEMQ", 37, true);
/**
* Cilium is open source software for providing and transparently securing network connectivity and load balancing
* between application workloads such as application containers or processes.
*/
- CILIUM_SERVICE(38, true),
+ public static final Layer CILIUM_SERVICE = register("CILIUM_SERVICE", 38, true);
/**
* The self observability of SkyWalking Java Agent,
* which provides the abilities to measure the tracing performance and error statistics of plugins.
*/
- SO11Y_JAVA_AGENT(39, true),
+ public static final Layer SO11Y_JAVA_AGENT = register("SO11Y_JAVA_AGENT", 39, true);
- /**
- * Kong is Cloud-Native API Gateway and AI Gateway.
- */
- KONG(40, true),
+ /** Kong is Cloud-Native API Gateway and AI Gateway. */
+ public static final Layer KONG = register("KONG", 40, true);
/**
* The self observability of SkyWalking Go Agent,
* which provides the abilities to measure the tracing performance and error statistics of plugins.
*/
- SO11Y_GO_AGENT(41, true),
+ public static final Layer SO11Y_GO_AGENT = register("SO11Y_GO_AGENT", 41, true);
/**
* Apache Flink is a framework and distributed processing engine for stateful computations over unbounded and bounded data streams
*/
- FLINK(42, true),
+ public static final Layer FLINK = register("FLINK", 42, true);
/**
* BanyanDB is a distributed time-series database with built-in self-monitoring for real-time tracking of system health, performance, and resource utilization.
*/
- BANYANDB(43, true),
+ public static final Layer BANYANDB = register("BANYANDB", 43, true);
- /**
- * GenAI represents an instrumented Generative AI service or application.
- */
- GENAI(44, true),
+ /** GenAI represents an instrumented Generative AI service or application. */
+ public static final Layer GENAI = register("GENAI", 44, true);
/**
* Virtual GenAI is a virtual layer used to represent and monitor remote, uninstrumented
* Generative AI providers.
*/
- VIRTUAL_GENAI(45, false),
+ public static final Layer VIRTUAL_GENAI = register("VIRTUAL_GENAI", 45, false);
/**
* Envoy AI Gateway is an AI/LLM traffic gateway built on Envoy Proxy,
* providing observability for GenAI API traffic.
*/
- ENVOY_AI_GATEWAY(46, true),
+ public static final Layer ENVOY_AI_GATEWAY = register("ENVOY_AI_GATEWAY", 46, true);
- /**
- * iOS/iPadOS app monitoring via OpenTelemetry Swift SDK
- */
- IOS(47, true),
+ /** iOS/iPadOS app monitoring via OpenTelemetry Swift SDK */
+ public static final Layer IOS = register("IOS", 47, true);
- /**
- * WeChat Mini Program monitoring via mini-program-monitor SDK
- */
- WECHAT_MINI_PROGRAM(48, true),
+ /** WeChat Mini Program monitoring via mini-program-monitor SDK */
+ public static final Layer WECHAT_MINI_PROGRAM = register("WECHAT_MINI_PROGRAM", 48, true);
- /**
- * Alipay Mini Program monitoring via mini-program-monitor SDK
- */
- ALIPAY_MINI_PROGRAM(49, true);
+ /** Alipay Mini Program monitoring via mini-program-monitor SDK */
+ public static final Layer ALIPAY_MINI_PROGRAM = register("ALIPAY_MINI_PROGRAM", 49, true);
+ private final String name;
private final int value;
/**
* The `normal` status represents this service is detected by an agent. The `un-normal` service is conjectured by
* telemetry data collected from agents on/in the `normal` service.
*/
private final boolean isNormal;
- private static final Map<Integer, Layer> DICTIONARY = new HashMap<>();
- private static final Map<String, Layer> DICTIONARY_NAME = new HashMap<>();
-
- static {
- Arrays.stream(Layer.values()).forEach(l -> {
- DICTIONARY.put(l.value, l);
- DICTIONARY_NAME.put(l.name(), l);
- });
- }
- Layer(int value, boolean isNormal) {
+ private Layer(final String name, final int value, final boolean isNormal) {
+ this.name = name;
this.value = value;
this.isNormal = isNormal;
}
+ public String name() {
+ return name;
+ }
+
public int value() {
return value;
}
- public static Layer valueOf(int value) {
- Layer layer = DICTIONARY.get(value);
+ public boolean isNormal() {
+ return isNormal;
+ }
+
+ @Override
+ public String toString() {
+ return name;
+ }
+
+ /**
+ * Single registration path used by both the built-in static initializer above and by every
+ * external source ({@code LayerExtensionLoader} for operator yaml + SPI, and the MAL/LAL DSL
+ * loaders parsing inline {@code layerDefinitions:} blocks). Idempotent on identical
+ * re-registration so the same extension loaded by multiple paths is harmless.
+ *
+ * @param name upper-snake-case identifier; must match {@code [A-Z][A-Z0-9_]*}
+ * @param value ordinal unique across all layers (see class javadoc for the ordinal
+ * conventions and the {@code >= 1000} recommendation for extensions)
+ * @param isNormal whether services in this layer are agent-installed (true) or conjectured (false)
+ * @return the registered layer
+ * @throws IllegalStateException if the registry is sealed, or on a name/ordinal conflict
+ * @throws IllegalArgumentException if name shape is invalid
+ */
+ public static synchronized Layer register(final String name, final int value, final boolean isNormal) {
+ if (SEALED) {
+ throw new IllegalStateException(
+ "Layer registry is sealed; cannot register " + name + "=" + value
+ + ". External layers must register before CoreModule.notifyAfterCompleted().");
+ }
+ if (name == null || !NAME_PATTERN.matcher(name).matches()) {
+ throw new IllegalArgumentException(
+ "Layer name must match [A-Z][A-Z0-9_]*: " + name);
+ }
+ final Layer existingByName = BY_NAME.get(name);
+ if (existingByName != null) {
+ if (existingByName.value == value && existingByName.isNormal == isNormal) {
+ return existingByName;
+ }
+ throw new IllegalStateException(
+ "Layer name conflict: " + name + " already registered as ordinal=" + existingByName.value
+ + ", normal=" + existingByName.isNormal
+ + "; refused re-registration as ordinal=" + value + ", normal=" + isNormal);
+ }
+ final Layer existingByValue = BY_VALUE.get(value);
+ if (existingByValue != null) {
+ throw new IllegalStateException(
+ "Layer ordinal conflict at " + value
+ + ": existing=" + existingByValue.name + ", new=" + name);
+ }
+ final Layer layer = new Layer(name, value, isNormal);
+ BY_VALUE.put(value, layer);
+ BY_NAME.put(name, layer);
+ return layer;
+ }
+
+ /**
+ * Closes the registry. Subsequent {@link #register} calls throw. Called by
+ * {@code CoreModuleProvider.notifyAfterCompleted()} after every module's prepare/start
+ * has run, so MAL/LAL/SPI/yaml all had their full window. Idempotent.
+ */
+ public static synchronized void seal() {
+ CACHED_VALUES = BY_VALUE.values()
+ .stream()
+ .sorted(Comparator.comparingInt(Layer::value))
+ .toArray(Layer[]::new);
+ SEALED = true;
+ }
+
+ public static Layer valueOf(final int value) {
+ final Layer layer = BY_VALUE.get(value);
if (layer == null) {
- throw new UnexpectedException("Unknown Layer value");
+ throw new UnexpectedException("Unknown Layer value: " + value);
}
return layer;
}
- public static Layer nameOf(String name) {
- Layer layer = DICTIONARY_NAME.get(name);
+ /**
+ * Look up a layer by name, throwing on miss. Matches the prior enum-generated
+ * {@code valueOf(String)} contract. Use {@link #nameOf(String)} for the lenient
+ * variant that returns {@link #UNDEFINED} on miss.
+ */
+ public static Layer valueOf(final String name) {
+ final Layer layer = BY_NAME.get(name);
+ if (layer == null) {
+ throw new IllegalArgumentException("No layer constant with name: " + name);
+ }
+ return layer;
+ }
+
+ public static Layer nameOf(final String name) {
+ final Layer layer = BY_NAME.get(name);
if (layer == null) {
return UNDEFINED;
}
return layer;
}
- public boolean isNormal() {
- return isNormal;
+ /**
+ * Snapshot of all registered layers, sorted by ordinal value. Returns a fresh array each
+ * call to preserve enum-style mutation safety; the underlying snapshot is computed once
+ * at {@link #seal()} so calls only pay the array-clone cost.
+ *
+ * <p>Throws if called before {@link #seal()} — pre-seal the registry may still grow as
+ * MAL/LAL/SPI/yaml extensions register, so any caller iterating {@code values()} during
+ * boot would silently snapshot a partial view. Callers that need a layer set during boot
+ * are almost always wrong; either look up specific layers by name via {@link #nameOf},
+ * or defer the iteration to a post-boot phase.
+ */
+ public static Layer[] values() {
+ if (CACHED_VALUES == null) {
+ throw new IllegalStateException(
+ "Layer.values() called before the registry was sealed. "
+ + "External layers may still register during module prepare()/start(); "
+ + "iterating now would snapshot a partial view. "
+ + "Defer the iteration until after CoreModule.notifyAfterCompleted().");
+ }
+ return CACHED_VALUES.clone();
+ }
+
+ /** Renders the registry as {@code "NAME=ordinal,NAME=ordinal,..."} sorted by ordinal. */
+ public static String describeRegistry() {
+ return BY_VALUE.values()
+ .stream()
+ .sorted(Comparator.comparingInt(Layer::value))
+ .map(l -> l.name + "=" + l.value)
+ .collect(Collectors.joining(","));
}
}
diff --git a/oap-server/analyzer/meter-analyzer/src/main/java/org/apache/skywalking/oap/meter/analyzer/v2/prometheus/rule/Rule.java b/oap-server/server-core/src/main/java/org/apache/skywalking/oap/server/core/analysis/LayerDefinition.java
similarity index 53%
copy from oap-server/analyzer/meter-analyzer/src/main/java/org/apache/skywalking/oap/meter/analyzer/v2/prometheus/rule/Rule.java
copy to oap-server/server-core/src/main/java/org/apache/skywalking/oap/server/core/analysis/LayerDefinition.java
index 930b2e7718..6cfa8ec3d0 100644
--- a/oap-server/analyzer/meter-analyzer/src/main/java/org/apache/skywalking/oap/meter/analyzer/v2/prometheus/rule/Rule.java
+++ b/oap-server/server-core/src/main/java/org/apache/skywalking/oap/server/core/analysis/LayerDefinition.java
@@ -16,29 +16,29 @@
*
*/
-package org.apache.skywalking.oap.meter.analyzer.v2.prometheus.rule;
+package org.apache.skywalking.oap.server.core.analysis;
import lombok.Data;
import lombok.NoArgsConstructor;
-import org.apache.skywalking.oap.meter.analyzer.v2.MetricRuleConfig;
-
-import java.util.List;
/**
- * Rule contains the global configuration of prometheus fetcher.
+ * Wire format for a single external {@link Layer} declaration. Used by every yaml-driven
+ * registration path: the operator-managed {@code layer-extensions.yml}, MAL rule files'
+ * {@code layerDefinitions:} block, and LAL rule files' {@code layerDefinitions:} block. All
+ * paths funnel through {@link Layer#register(String, int, boolean)}, which enforces
+ * name-shape, name-uniqueness, ordinal-uniqueness, and seal-state checks.
+ *
+ * <p>Defaults to {@code normal=true}.
*/
@Data
@NoArgsConstructor
-public class Rule implements MetricRuleConfig {
+public class LayerDefinition {
private String name;
- private String metricPrefix;
- private String expSuffix;
- private String expPrefix;
- private String filter;
- private List<MetricsRule> metricsRules;
+ private int ordinal;
+ private boolean normal = true;
- @Override
- public String getSourceName() {
- return name;
+ /** Funnels this declaration through the registry; idempotent on identical re-registration. */
+ public Layer register() {
+ return Layer.register(name, ordinal, normal);
}
}
diff --git a/oap-server/server-core/src/main/java/org/apache/skywalking/oap/server/core/analysis/LayerExtension.java b/oap-server/server-core/src/main/java/org/apache/skywalking/oap/server/core/analysis/LayerExtension.java
new file mode 100644
index 0000000000..c65161dd2e
--- /dev/null
+++ b/oap-server/server-core/src/main/java/org/apache/skywalking/oap/server/core/analysis/LayerExtension.java
@@ -0,0 +1,57 @@
+/*
+ * 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.skywalking.oap.server.core.analysis;
+
+/**
+ * SPI for out-of-tree extensions to register custom {@link Layer} values without
+ * modifying the OAP source. Implementations are discovered by {@code LayerExtensionLoader}
+ * via {@code ServiceLoader} during {@code CoreModuleProvider.prepare()}, before any
+ * downstream module wires up.
+ *
+ * <p>Implementations call {@link Layer#register(String, int, boolean)} for each
+ * layer they want to contribute. Name-shape, name-uniqueness, ordinal-uniqueness, and
+ * seal-state checks are enforced by that method, so an implementation cannot bypass them
+ * by going through this SPI.
+ *
+ * <p>Register on the classpath via
+ * {@code META-INF/services/org.apache.skywalking.oap.server.core.analysis.LayerExtension}.
+ *
+ * <p>Example:
+ * <pre>{@code
+ * public final class IotFleetLayers implements LayerExtension {
+ * @Override
+ * public void contribute() {
+ * Layer.register("IOT_FLEET", 1000, true);
+ * Layer.register("IOT_GATEWAY", 1001, true);
+ * }
+ * }
+ * }</pre>
+ *
+ * <p>SPI is preferred over registering from a downstream module's {@code prepare()} because
+ * Core's {@code prepare()} runs before every other module's {@code prepare()} — there is no
+ * way for a downstream module to register layers earlier than Core, and the registry is
+ * sealed at the start of {@code Core.notifyAfterCompleted()}.
+ */
+public interface LayerExtension {
+ /**
+ * Called once during Core boot. Implementations should call
+ * {@link Layer#register(String, int, boolean)} one or more times.
+ */
+ void contribute();
+}
diff --git a/oap-server/server-core/src/main/java/org/apache/skywalking/oap/server/core/analysis/LayerExtensionLoader.java b/oap-server/server-core/src/main/java/org/apache/skywalking/oap/server/core/analysis/LayerExtensionLoader.java
new file mode 100644
index 0000000000..be4742e970
--- /dev/null
+++ b/oap-server/server-core/src/main/java/org/apache/skywalking/oap/server/core/analysis/LayerExtensionLoader.java
@@ -0,0 +1,109 @@
+/*
+ * 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.skywalking.oap.server.core.analysis;
+
+import java.io.FileNotFoundException;
+import java.io.Reader;
+import java.util.List;
+import java.util.ServiceLoader;
+import lombok.Data;
+import lombok.extern.slf4j.Slf4j;
+import org.apache.skywalking.oap.server.library.util.ResourceUtils;
+import org.yaml.snakeyaml.Yaml;
+
+/**
+ * Loads external {@link Layer} registrations from two sources during
+ * {@code CoreModuleProvider.prepare()}:
+ *
+ * <ol>
+ * <li>{@code layer-extensions.yml} on the OAP classpath — operator-deployed config.
+ * Optional file; absence is not an error.</li>
+ * <li>{@link LayerExtension} implementations discovered via {@code ServiceLoader} —
+ * out-of-tree plugin jars on the OAP classpath.</li>
+ * </ol>
+ *
+ * <p>Both sources funnel through {@link Layer#register(String, int, boolean)};
+ * conflict checks (reserved-range, name-uniqueness, ordinal-uniqueness, name-shape,
+ * sealed-state) live there.
+ *
+ * <p>MAL/LAL DSL files declaring inline {@code layerDefinitions:} blocks are
+ * <strong>not</strong> handled here — they're processed by their respective DSL loaders
+ * during the meter-receiver / log-analyzer modules' {@code prepare()}, which runs after
+ * Core's {@code prepare()} but before the registry is sealed in
+ * {@code Core.notifyAfterCompleted()}.
+ *
+ * <p>Expected yaml schema (all entries optional, file may be empty):
+ * <pre>{@code
+ * layers:
+ * - name: IOT_FLEET # upper-snake-case, must match [A-Z][A-Z0-9_]*
+ * ordinal: 1000 # >= 1000 (0-999 reserved for OAP distribution)
+ * normal: true # true = agent-installed, false = conjectured/virtual
+ * }</pre>
+ */
+@Slf4j
+public final class LayerExtensionLoader {
+
+ private static final String LAYER_EXTENSIONS_FILE = "layer-extensions.yml";
+
+ private LayerExtensionLoader() {
+ }
+
+ /**
+ * Loads yaml first, then SPI. Each entry is registered immediately so collisions
+ * are reported with their actual source (yaml line or SPI class) in the stack trace.
+ * Logs the (name, ordinal) table contributed by these two sources at INFO; later
+ * additions from MAL/LAL inline {@code layerDefinitions:} blocks are not yet present
+ * at this point and will appear in subsequent boot logs as those rule files load.
+ */
+ public static void load() {
+ loadFromYaml();
+ loadFromSpi();
+ log.info("Layer registry after yaml + SPI extension loading: {}", Layer.describeRegistry());
+ }
+
+ private static void loadFromYaml() {
+ final Reader reader;
+ try {
+ reader = ResourceUtils.read(LAYER_EXTENSIONS_FILE);
+ } catch (FileNotFoundException e) {
+ log.debug("{} not found on classpath; no operator-defined layer extensions.", LAYER_EXTENSIONS_FILE);
+ return;
+ }
+ final LayerExtensionsFile root = new Yaml().loadAs(reader, LayerExtensionsFile.class);
+ if (root == null || root.getLayers() == null) {
+ return;
+ }
+ for (final LayerDefinition def : root.getLayers()) {
+ def.register();
+ }
+ }
+
+ /** SnakeYAML target for {@code layer-extensions.yml}'s root document. */
+ @Data
+ public static class LayerExtensionsFile {
+ private List<LayerDefinition> layers;
+ }
+
+ private static void loadFromSpi() {
+ for (final LayerExtension extension : ServiceLoader.load(LayerExtension.class)) {
+ log.info("Applying LayerExtension SPI: {}", extension.getClass().getName());
+ extension.contribute();
+ }
+ }
+}
diff --git a/oap-server/server-core/src/main/java/org/apache/skywalking/oap/server/core/management/ui/template/UITemplateInitializer.java b/oap-server/server-core/src/main/java/org/apache/skywalking/oap/server/core/management/ui/template/UITemplateInitializer.java
index 42c5f2f1fb..561cb86186 100644
--- a/oap-server/server-core/src/main/java/org/apache/skywalking/oap/server/core/management/ui/template/UITemplateInitializer.java
+++ b/oap-server/server-core/src/main/java/org/apache/skywalking/oap/server/core/management/ui/template/UITemplateInitializer.java
@@ -25,12 +25,9 @@ import lombok.extern.slf4j.Slf4j;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.IOException;
-import java.util.Arrays;
import java.util.List;
import java.util.Objects;
-import java.util.stream.Stream;
import org.apache.skywalking.oap.server.core.CoreModule;
-import org.apache.skywalking.oap.server.core.analysis.Layer;
import org.apache.skywalking.oap.server.core.query.input.DashboardSetting;
import org.apache.skywalking.oap.server.core.query.type.DashboardConfiguration;
import org.apache.skywalking.oap.server.library.module.ModuleManager;
@@ -41,13 +38,14 @@ import org.apache.skywalking.oap.server.library.util.StringUtil;
* UITemplateInitializer load the template from the config file in json format. It depends on the UI implementation only.
* Each config file should be only one dashboard setting json object.
* The dashboard names should be different in the same Layer and entity.
- * <p>
- * Folder discovery is automatic: every {@link Layer} enum value is probed as a folder
- * (via {@code Layer.name().toLowerCase()}) plus the {@code "custom"} slot. Folders that
- * don't exist are silently skipped. Extensions adding a new {@code Layer} do not need to
- * touch this class.
- * <p>
- * Dev/extension reload: when environment variable {@code SW_UI_TEMPLATE_FORCE_RELOAD}
+ *
+ * <p>Folder discovery is automatic: the {@code ui-initialized-templates/} root is walked
+ * recursively and every {@code *.json} file is loaded as a template. The template's owning
+ * layer comes from the {@code configuration.layer} field inside the JSON itself, so the
+ * folder name is purely organizational. Out-of-tree extensions can drop a folder of their
+ * own (named after their custom Layer or anything else) and the initializer picks it up.
+ *
+ * <p>Dev/extension reload: when environment variable {@code SW_UI_TEMPLATE_FORCE_RELOAD}
* is {@code true}, each template on disk is written via {@code addOrReplace} rather
* than {@code addIfNotExist}, so edits to shipped JSON take effect on the next OAP
* restart without needing to wipe the storage container.
@@ -55,14 +53,18 @@ import org.apache.skywalking.oap.server.library.util.StringUtil;
@Slf4j
public class UITemplateInitializer {
/**
- * Every {@link Layer} enum value, lower-cased, plus the {@code "custom"} folder.
- * Computed once from {@link Layer#values()} so adding a new {@code Layer} automatically
- * causes its {@code ui-initialized-templates/<layer>/} folder to be scanned.
+ * Root directory holding all UI dashboard templates. Subdirectory names are hints
+ * (typically the layer name lowercased, plus {@code custom/}); the actual layer the
+ * template applies to is read from {@code configuration.layer} inside each JSON file.
*/
- public static final String[] UI_TEMPLATE_FOLDER = Stream.concat(
- Arrays.stream(Layer.values()).map(Layer::name),
- Stream.of("custom")
- ).toArray(String[]::new);
+ public static final String UI_TEMPLATE_ROOT = "ui-initialized-templates";
+
+ /**
+ * Walk depth: {@code ui-initialized-templates/<folder>/<file>.json}. Depth 2 covers
+ * the canonical layout; files nested deeper are silently ignored to keep template
+ * discovery predictable. If a deeper layout is ever needed, raise this constant.
+ */
+ private static final int WALK_MAX_DEPTH = 2;
/**
* Environment variable: when {@code true}, templates on disk overwrite any previously
@@ -87,15 +89,18 @@ public class UITemplateInitializer {
if (FORCE_RELOAD) {
log.info("SW_UI_TEMPLATE_FORCE_RELOAD=true — shipped UI templates will overwrite any previously seeded copy on this boot.");
}
- for (String folder : UITemplateInitializer.UI_TEMPLATE_FOLDER) {
- try {
- File[] templateFiles = ResourceUtils.getPathFiles("ui-initialized-templates/" + folder.toLowerCase());
- for (File file : templateFiles) {
- initTemplate(file);
- }
- } catch (FileNotFoundException e) {
- log.debug("No such folder of path: {}, skipping loading UI templates", folder);
+ final List<File> templateFiles;
+ try {
+ templateFiles = ResourceUtils.getDirectoryFilesRecursive(UI_TEMPLATE_ROOT, WALK_MAX_DEPTH);
+ } catch (FileNotFoundException e) {
+ log.debug("No {} folder on classpath, skipping UI template initialization.", UI_TEMPLATE_ROOT);
+ return;
+ }
+ for (File file : templateFiles) {
+ if (!file.getName().endsWith(".json")) {
+ continue;
}
+ initTemplate(file);
}
}
diff --git a/oap-server/server-receiver-plugin/skywalking-runtime-rule-receiver-plugin/src/main/java/org/apache/skywalking/oap/server/receiver/runtimerule/apply/LalFileApplier.java b/oap-server/server-receiver-plugin/skywalking-runtime-rule-receiver-plugin/src/main/java/org/apache/skywalking/oap/server/receiver/runtimerule/apply/LalFileApplier.java
index 8ba89cb2bf..cdca5ca236 100644
--- a/oap-server/server-receiver-plugin/skywalking-runtime-rule-receiver-plugin/src/main/java/org/apache/skywalking/oap/server/receiver/runtimerule/apply/LalFileApplier.java
+++ b/oap-server/server-receiver-plugin/skywalking-runtime-rule-receiver-plugin/src/main/java/org/apache/skywalking/oap/server/receiver/runtimerule/apply/LalFileApplier.java
@@ -257,6 +257,15 @@ public class LalFileApplier {
"LAL YAML parsed to empty/malformed — no rules list in " + sourceName,
null, Collections.emptyList());
}
+ if (configs.getLayerDefinitions() != null && !configs.getLayerDefinitions().isEmpty()) {
+ throw new ApplyException(
+ "LAL rule " + sourceName + " declares `layerDefinitions:`, which is only "
+ + "permitted in bundled rule files loaded at OAP boot. Layer extensions "
+ + "cannot be added at runtime — the registry is sealed once OAP startup "
+ + "completes. Declare the layer in `layer-extensions.yml` or a bundled "
+ + "MAL/LAL file, restart OAP, then retry this update.",
+ null, Collections.emptyList());
+ }
return configs.getRules();
} catch (final ApplyException e) {
throw e;
diff --git a/oap-server/server-receiver-plugin/skywalking-runtime-rule-receiver-plugin/src/main/java/org/apache/skywalking/oap/server/receiver/runtimerule/apply/MalFileApplier.java b/oap-server/server-receiver-plugin/skywalking-runtime-rule-receiver-plugin/src/main/java/org/apache/skywalking/oap/server/receiver/runtimerule/apply/MalFileApplier.java
index b9560aaa26..fb015f6f45 100644
--- a/oap-server/server-receiver-plugin/skywalking-runtime-rule-receiver-plugin/src/main/java/org/apache/skywalking/oap/server/receiver/runtimerule/apply/MalFileApplier.java
+++ b/oap-server/server-receiver-plugin/skywalking-runtime-rule-receiver-plugin/src/main/java/org/apache/skywalking/oap/server/receiver/runtimerule/apply/MalFileApplier.java
@@ -217,6 +217,15 @@ public class MalFileApplier {
if (rule.getName() == null || rule.getName().isEmpty()) {
rule.setName(sourceName);
}
+ if (rule.getLayerDefinitions() != null && !rule.getLayerDefinitions().isEmpty()) {
+ throw new ApplyException(
+ "MAL rule " + sourceName + " declares `layerDefinitions:`, which is only "
+ + "permitted in bundled rule files loaded at OAP boot. Layer extensions "
+ + "cannot be added at runtime — the registry is sealed once OAP startup "
+ + "completes. Declare the layer in `layer-extensions.yml` or a bundled "
+ + "MAL/LAL file, restart OAP, then retry this update.",
+ null, Collections.emptySet());
+ }
return rule;
} catch (final ApplyException e) {
throw e;
diff --git a/oap-server/server-starter/src/main/resources/layer-extensions.yml b/oap-server/server-starter/src/main/resources/layer-extensions.yml
new file mode 100644
index 0000000000..b6ade772a9
--- /dev/null
+++ b/oap-server/server-starter/src/main/resources/layer-extensions.yml
@@ -0,0 +1,63 @@
+# 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.
+
+# ----------------------------------------------------------------------------
+# Layer Extensions
+# ----------------------------------------------------------------------------
+# Declare custom layers that the OAP distribution does not ship out of the box.
+# Each layer becomes a first-class identifier that MAL rules, LAL rules, UI dashboard
+# templates, and query APIs can reference by name.
+#
+# A layer is persisted alongside every service / instance / endpoint it owns. Because
+# every OAP node in a cluster reads and writes the same data, every node MUST agree on
+# the (name, ordinal) mapping. Deploy this file identically to every node.
+#
+# Recommended ordinal range:
+# 0-999 reserved by convention for the OAP distribution's built-in layers.
+# >= 1000 strongly recommended for external layers. Staying above 1000 avoids
+# colliding with future built-in layers added by the OAP distribution.
+# Conflicting ordinals or names cause OAP boot to fail with a clear error.
+#
+# Name shape: must match the regex `[A-Z][A-Z0-9_]*` (upper-snake-case, leading letter).
+#
+# Field reference:
+# name: upper-snake-case identifier. MAL/LAL rules and UI templates reference
+# the layer by this name.
+# ordinal: stable integer. Once assigned and used to write data, this value is
+# permanent — changing it orphans every previously stored row tagged with
+# the old ordinal.
+# normal: true = services in this layer are agent-installed
+# false = services are conjectured/virtual (e.g. inferred from upstream
+# calls). Defaults to true if omitted.
+#
+# Example (uncomment and edit):
+#
+# layers:
+# - name: IOT_FLEET
+# ordinal: 1000
+# normal: true
+# - name: IOT_GATEWAY
+# ordinal: 1001
+# normal: true
+# - name: VIRTUAL_IOT_DEVICE
+# ordinal: 1002
+# normal: false
+#
+# Other places a custom layer can be declared:
+# - At the top of a MAL or LAL rule file via a `layerDefinitions:` block —
+# recommended when a layer ships together with the rules that produce its telemetry.
+# - As an in-process extension contributed by a plugin jar on the OAP classpath.
+
+layers: []
diff --git a/oap-server/server-starter/src/test/java/org/apache/skywalking/oap/server/starter/UITemplateCheckerTest.java b/oap-server/server-starter/src/test/java/org/apache/skywalking/oap/server/starter/UITemplateCheckerTest.java
index 56965ec879..a99840eee2 100644
--- a/oap-server/server-starter/src/test/java/org/apache/skywalking/oap/server/starter/UITemplateCheckerTest.java
+++ b/oap-server/server-starter/src/test/java/org/apache/skywalking/oap/server/starter/UITemplateCheckerTest.java
@@ -31,7 +31,7 @@ import java.io.File;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.util.HashSet;
-import java.util.Locale;
+import java.util.List;
import java.util.Set;
/**
@@ -45,44 +45,43 @@ public class UITemplateCheckerTest {
mapper.enable(JsonParser.Feature.ALLOW_COMMENTS);
Set<String> dashboardIds = new HashSet<>();
Set<String> dashboardNames = new HashSet<>();
- for (String folder : UITemplateInitializer.UI_TEMPLATE_FOLDER) {
- File[] templateFiles;
+ final List<File> templateFiles;
+ try {
+ templateFiles = ResourceUtils.getDirectoryFilesRecursive(UITemplateInitializer.UI_TEMPLATE_ROOT, 2);
+ } catch (FileNotFoundException e) {
+ // No template root on classpath — mirrors UITemplateInitializer.initAll() behavior.
+ return;
+ }
+ for (File template : templateFiles) {
+ if (!template.getName().endsWith(".json")) {
+ continue;
+ }
+ JsonNode jsonNode;
try {
- templateFiles = ResourceUtils.getPathFiles("ui-initialized-templates/" + folder.toLowerCase(
- Locale.ROOT));
- } catch (FileNotFoundException e) {
- // Layer enum values without an on-disk template folder are skipped —
- // mirrors UITemplateInitializer.initAll() behavior post-auto-discovery.
+ jsonNode = mapper.readTree(template);
+ } catch (Exception e) {
+ throw new IllegalArgumentException("File: " + template.getName() + " is not a legal json file.", e);
+ }
+ if (jsonNode == null || jsonNode.isEmpty()) {
continue;
}
- for (File template : templateFiles) {
- JsonNode jsonNode;
- try {
- jsonNode = mapper.readTree(template);
- } catch (Exception e) {
- throw new IllegalArgumentException("File: " + template.getName() + " is not a legal json file.", e);
- }
- if (jsonNode == null || jsonNode.isEmpty()) {
- continue;
- }
- if (jsonNode.size() > 1) {
- throw new IllegalArgumentException(
- "File: " + template.getName() + " should be only one dashboard setting json object.");
- }
+ if (jsonNode.size() > 1) {
+ throw new IllegalArgumentException(
+ "File: " + template.getName() + " should be only one dashboard setting json object.");
+ }
- JsonNode configNode = jsonNode.get(0).get("configuration");
- String inId = jsonNode.get(0).get("id").textValue();
- String inName = configNode.get("name").textValue();
- String inLayer = configNode.get("layer").textValue();
- String inEntity = configNode.get("entity").textValue();
- Assertions.assertFalse(dashboardIds.contains(inId), "File: " + template + " has duplicate id: " + inId);
- dashboardIds.add(inId);
- String nameKey = StringUtil.join('_', inLayer, inEntity, inName);
- Assertions.assertFalse(dashboardNames.contains(nameKey), "File:" + template + " has duplicate name: " + inName);
- dashboardNames.add(nameKey);
+ JsonNode configNode = jsonNode.get(0).get("configuration");
+ String inId = jsonNode.get(0).get("id").textValue();
+ String inName = configNode.get("name").textValue();
+ String inLayer = configNode.get("layer").textValue();
+ String inEntity = configNode.get("entity").textValue();
+ Assertions.assertFalse(dashboardIds.contains(inId), "File: " + template + " has duplicate id: " + inId);
+ dashboardIds.add(inId);
+ String nameKey = StringUtil.join('_', inLayer, inEntity, inName);
+ Assertions.assertFalse(dashboardNames.contains(nameKey), "File:" + template + " has duplicate name: " + inName);
+ dashboardNames.add(nameKey);
- //Todo: implement more validation.
- }
+ //Todo: implement more validation.
}
}
}
diff --git a/oap-server/server-storage-plugin/storage-banyandb-plugin/src/main/java/org/apache/skywalking/oap/server/storage/plugin/banyandb/MetadataRegistry.java b/oap-server/server-storage-plugin/storage-banyandb-plugin/src/main/java/org/apache/skywalking/oap/server/storage/plugin/banyandb/MetadataRegistry.java
index ad6c2911b4..09e4affc5a 100644
--- a/oap-server/server-storage-plugin/storage-banyandb-plugin/src/main/java/org/apache/skywalking/oap/server/storage/plugin/banyandb/MetadataRegistry.java
+++ b/oap-server/server-storage-plugin/storage-banyandb-plugin/src/main/java/org/apache/skywalking/oap/server/storage/plugin/banyandb/MetadataRegistry.java
@@ -51,6 +51,7 @@ import org.apache.skywalking.library.banyandb.v1.client.And;
import org.apache.skywalking.library.banyandb.v1.client.PairQueryCondition;
import org.apache.skywalking.library.banyandb.v1.client.metadata.Duration;
import org.apache.skywalking.oap.server.core.analysis.DownSampling;
+import org.apache.skywalking.oap.server.core.analysis.Layer;
import org.apache.skywalking.oap.server.core.analysis.metrics.IntList;
import org.apache.skywalking.oap.server.core.analysis.metrics.Metrics;
import org.apache.skywalking.oap.server.core.storage.model.BanyanDBTrace;
@@ -631,7 +632,7 @@ public enum MetadataRegistry {
TagSpec.Builder tagSpec = TagSpec.newBuilder().setName(colName);
if (String.class.equals(clazz) || StorageDataComplexObject.class.isAssignableFrom(clazz) || JsonObject.class.equals(clazz)) {
tagSpec = tagSpec.setType(TagType.TAG_TYPE_STRING);
- } else if (int.class.equals(clazz) || long.class.equals(clazz) || Integer.class.equals(clazz) || Long.class.equals(clazz)) {
+ } else if (int.class.equals(clazz) || long.class.equals(clazz) || Integer.class.equals(clazz) || Long.class.equals(clazz) || Layer.class.equals(clazz)) {
tagSpec = tagSpec.setType(TagType.TAG_TYPE_INT);
} else if (byte[].class.equals(clazz)) {
tagSpec = tagSpec.setType(TagType.TAG_TYPE_DATA_BINARY);
diff --git a/oap-server/server-storage-plugin/storage-elasticsearch-plugin/src/main/java/org/apache/skywalking/oap/server/storage/plugin/elasticsearch/query/MetadataQueryEsDAO.java b/oap-server/server-storage-plugin/storage-elasticsearch-plugin/src/main/java/org/apache/skywalking/oap/server/storage/plugin/elasticsearch/query/MetadataQueryEsDAO.java
index 0220b9f9c2..5633350f0e 100644
--- a/oap-server/server-storage-plugin/storage-elasticsearch-plugin/src/main/java/org/apache/skywalking/oap/server/storage/plugin/elasticsearch/query/MetadataQueryEsDAO.java
+++ b/oap-server/server-storage-plugin/storage-elasticsearch-plugin/src/main/java/org/apache/skywalking/oap/server/storage/plugin/elasticsearch/query/MetadataQueryEsDAO.java
@@ -37,7 +37,6 @@ import org.apache.skywalking.library.elasticsearch.requests.search.Sort;
import org.apache.skywalking.library.elasticsearch.response.search.SearchHit;
import org.apache.skywalking.library.elasticsearch.response.search.SearchResponse;
import org.apache.skywalking.oap.server.core.analysis.IDManager;
-import org.apache.skywalking.oap.server.core.analysis.Layer;
import org.apache.skywalking.oap.server.core.analysis.TimeBucket;
import org.apache.skywalking.oap.server.core.analysis.manual.endpoint.EndpointTraffic;
import org.apache.skywalking.oap.server.core.analysis.manual.instance.InstanceTraffic;
@@ -71,7 +70,6 @@ public class MetadataQueryEsDAO extends EsDAO implements IMetadataQueryDAO {
private final int scrollingBatchSize;
private String endpointTrafficNameAlias;
private boolean aliasNameInit = false;
- private final int layerSize;
protected final Function<SearchHit, Service> searchHitServiceFunction = hit -> {
final var sourceAsMap = hit.getSource();
@@ -121,7 +119,6 @@ public class MetadataQueryEsDAO extends EsDAO implements IMetadataQueryDAO {
super(client);
this.queryMaxSize = config.getMetadataQueryMaxSize();
this.scrollingBatchSize = config.getScrollingBatchSize();
- this.layerSize = Layer.values().length;
}
@Override