You are viewing a plain text version of this content. The canonical link for it is here.
Posted to commits@ozhera.apache.org by zh...@apache.org on 2025/07/08 02:45:02 UTC
(ozhera) branch master updated: refactor: refactor the custom metric monitoring SDK (#597)
This is an automated email from the ASF dual-hosted git repository.
zhangxiaowei pushed a commit to branch master
in repository https://gitbox.apache.org/repos/asf/ozhera.git
The following commit(s) were added to refs/heads/master by this push:
new 0767353d refactor: refactor the custom metric monitoring SDK (#597)
0767353d is described below
commit 0767353d5d81b3cfd56071d4991f1ea98c8ebd10
Author: EricDing <12...@users.noreply.github.com>
AuthorDate: Tue Jul 8 10:44:59 2025 +0800
refactor: refactor the custom metric monitoring SDK (#597)
* fix: add SNAPSHOT repository
* refactor: refactor the custom metric monitoring SDK
* refactor: update logger name
---
ozhera-intelligence/pom.xml | 15 ++
.../ozhera-metrics-sdk-config/pom.xml | 131 ++++++++++++
.../org/apache/ozhera/metrics/config}/Const.java | 8 +-
.../apache/ozhera/metrics/config/HeraConfig.java | 44 ++++
.../ozhera/metrics/config/LogFileNameUtil.java | 68 +++++++
.../apache/ozhera/metrics/config/PromEnvEnum.java | 6 +
.../metrics/config/SdkLoggerInitializer.java | 83 ++++++++
.../config/service/OzHeraPrometheusService.java | 224 +++++++++++++++++++++
.../metrics/config}/service/PrometheusService.java | 25 ++-
.../metrics/config/service}/ServiceFactory.java | 41 ++--
.../src/main/resources/META-INF/LICENSE.txt | 0
ozhera-metrics-all/ozhera-metrics-sdk/pom.xml | 166 +++++++++++++++
.../apache/ozhera/metrics/api/BusinessMetrics.java | 199 ++++++++++++++++++
.../org/apache/ozhera/metrics/api/Counter.java | 91 +++++++++
.../java/org/apache/ozhera/metrics/api/Gauge.java | 78 +++++++
.../org/apache/ozhera/metrics/api}/HTTPServer.java | 179 +++-------------
.../org/apache/ozhera/metrics/api/Histogram.java | 66 ++++++
.../java/org/apache/ozhera/metrics/api/Meter.java | 28 +--
.../org/apache/ozhera/metrics/api/Metrics.java | 129 ++++++++++++
.../apache/ozhera/metrics/api/MetricsContext.java | 58 +++---
.../apache/ozhera/metrics/api/MetricsFactory.java | 28 +--
.../ozhera/metrics/api/PrometheusExporter.java | 47 +++++
.../ozhera/metrics/api/PrometheusFactory.java | 181 +++++++++++++++++
.../java/org/apache/ozhera/metrics/api/Timer.java | 87 ++++++++
.../org/apache/ozhera/metrics/api/XmCounter.java | 62 ++++++
.../org/apache/ozhera/metrics/api/XmGauge.java | 61 ++++++
.../org/apache/ozhera/metrics/api/XmHistogram.java | 64 ++++++
.../org/apache/ozhera/metrics/api/XmMeter.java | 118 +++++++++++
.../org/apache/ozhera/metrics/api/XmMeterType.java | 38 ++--
.../apache/ozhera/metrics/api/XmMetricChild.java | 20 +-
.../org/apache/ozhera/metrics/api/XmTimer.java | 105 ++++++++++
.../api}/binder/ClassLoaderMetricsReduced.java | 2 +-
.../metrics/api}/binder/JvmGcMetricsReduced.java | 2 +-
.../api}/binder/JvmMemoryMetricsReduced.java | 2 +-
.../api}/binder/JvmThreadMetricsReduced.java | 2 +-
.../src/main/resources/META-INF/LICENSE.txt | 0
.../prometheus/all/client/OzHeraMetricsTest.java | 223 ++++++++++++++++++++
.../pom.xml | 6 +-
..._webhook_open_config_#_DEFAULT_GROUP.properties | 2 +-
pom.xml | 2 +-
.../prometheus-diy-client/pom.xml | 104 ----------
.../ozhera/prometheus/all/client/Metrics.java | 125 ------------
.../prometheus/all/client/MetricsManager.java | 55 -----
.../ozhera/prometheus/all/client/Prometheus.java | 201 ------------------
.../prometheus/all/client/PrometheusCounter.java | 79 --------
.../prometheus/all/client/PrometheusGauge.java | 91 ---------
.../prometheus/all/client/PrometheusHistogram.java | 74 -------
.../prometheus/all/client/PrometheusTest.java | 98 ---------
.../prometheus-diy-starter/pom.xml | 77 -------
.../starter/all/config/PrometheusConfigure.java | 102 ----------
.../all/service/MilinePrometheusService.java | 62 ------
51 files changed, 2412 insertions(+), 1347 deletions(-)
diff --git a/ozhera-intelligence/pom.xml b/ozhera-intelligence/pom.xml
index 02241488..65e75b04 100644
--- a/ozhera-intelligence/pom.xml
+++ b/ozhera-intelligence/pom.xml
@@ -181,4 +181,19 @@
</plugin>
</plugins>
</build>
+
+ <!-- SNAPSHOT repository, remove when hive deploy release version -->
+ <repositories>
+ <repository>
+ <name>Central Portal Snapshots</name>
+ <id>central-portal-snapshots</id>
+ <url>https://central.sonatype.com/repository/maven-snapshots/</url>
+ <releases>
+ <enabled>false</enabled>
+ </releases>
+ <snapshots>
+ <enabled>true</enabled>
+ </snapshots>
+ </repository>
+ </repositories>
</project>
\ No newline at end of file
diff --git a/ozhera-metrics-all/ozhera-metrics-sdk-config/pom.xml b/ozhera-metrics-all/ozhera-metrics-sdk-config/pom.xml
new file mode 100644
index 00000000..d4290204
--- /dev/null
+++ b/ozhera-metrics-all/ozhera-metrics-sdk-config/pom.xml
@@ -0,0 +1,131 @@
+<?xml version="1.0" encoding="UTF-8"?>
+<!--
+
+ 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.
+
+-->
+
+<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
+ <parent>
+ <groupId>org.apache.ozhera</groupId>
+ <artifactId>ozhera-metrics-all</artifactId>
+ <version>2.2.6-SNAPSHOT</version>
+ </parent>
+ <modelVersion>4.0.0</modelVersion>
+
+ <artifactId>ozhera-metrics-sdk-config</artifactId>
+ <version>2.2.6-SNAPSHOT</version>
+
+ <dependencies>
+
+ <dependency>
+ <groupId>io.prometheus</groupId>
+ <artifactId>simpleclient_common</artifactId>
+ </dependency>
+
+ <dependency>
+ <groupId>run.mone</groupId>
+ <artifactId>nacos-client</artifactId>
+ </dependency>
+
+ <dependency>
+ <groupId>junit</groupId>
+ <artifactId>junit</artifactId>
+ <scope>test</scope>
+ </dependency>
+
+ </dependencies>
+
+ <build>
+ <resources>
+ <resource>
+ <directory>src/main/resources</directory>
+ <filtering>true</filtering>
+ <excludes>
+ <exclude>META-INF/LICENSE.txt</exclude>
+ </excludes>
+ </resource>
+ <resource>
+ <directory>${project.basedir}/../../</directory>
+ <filtering>true</filtering>
+ <includes>
+ <include>DISCLAIMER</include>
+ <include>NOTICE</include>
+ <include>LICENSE</include>
+ </includes>
+ <targetPath>META-INF/</targetPath>
+ </resource>
+ </resources>
+ <plugins>
+ <plugin>
+ <artifactId>maven-shade-plugin</artifactId>
+ <version>3.5.0</version>
+ <executions>
+ <execution>
+ <phase>package</phase>
+ <goals>
+ <goal>shade</goal>
+ </goals>
+ <configuration>
+ <shadedArtifactAttached>false</shadedArtifactAttached>
+ <createDependencyReducedPom>true</createDependencyReducedPom>
+ <createSourcesJar>false</createSourcesJar>
+ <shadeSourcesContent>false</shadeSourcesContent>
+ <transformers>
+ <transformer implementation="org.apache.maven.plugins.shade.resource.ManifestResourceTransformer">
+ </transformer>
+ <transformer implementation="org.apache.maven.plugins.shade.resource.DontIncludeResourceTransformer">
+ <resources>
+ <resource>.txt</resource>
+ <resource>application.properties</resource>
+ <resource>nacos-log4j2.xml</resource>
+ <resource>nacos-logback.xml</resource>
+ </resources>
+ </transformer>
+ </transformers>
+ <artifactSet>
+ <includes>
+ <include>io.prometheus:simpleclient</include>
+ <include>io.prometheus:simpleclient_common</include>
+ <include>com.alibaba.nacos:*</include>
+ <include>com.alibaba:dubbo-registry-nacos</include>
+ </includes>
+ </artifactSet>
+ <relocations>
+ <relocation>
+ <pattern>io.prometheus</pattern>
+ <shadedPattern>shaded.ozhera.io.prometheus</shadedPattern>
+ </relocation>
+ <relocation>
+ <pattern>com.alibaba.nacos</pattern>
+ <shadedPattern>shaded.ozhera.com.alibaba.nacos</shadedPattern>
+ </relocation>
+ <relocation>
+ <pattern>com.alibaba.dubbo.registry.nacos</pattern>
+ <shadedPattern>shaded.ozhera.com.alibaba.dubbo.registry.nacos</shadedPattern>
+ </relocation>
+ </relocations>
+ </configuration>
+ </execution>
+ </executions>
+ </plugin>
+ </plugins>
+ </build>
+
+
+</project>
\ No newline at end of file
diff --git a/prometheus-starter-all/prometheus-diy-starter/src/main/java/org/apache/ozhera/prometheus/starter/all/domain/Const.java b/ozhera-metrics-all/ozhera-metrics-sdk-config/src/main/java/org/apache/ozhera/metrics/config/Const.java
similarity index 84%
rename from prometheus-starter-all/prometheus-diy-starter/src/main/java/org/apache/ozhera/prometheus/starter/all/domain/Const.java
rename to ozhera-metrics-all/ozhera-metrics-sdk-config/src/main/java/org/apache/ozhera/metrics/config/Const.java
index 82ffb291..27b59804 100644
--- a/prometheus-starter-all/prometheus-diy-starter/src/main/java/org/apache/ozhera/prometheus/starter/all/domain/Const.java
+++ b/ozhera-metrics-all/ozhera-metrics-sdk-config/src/main/java/org/apache/ozhera/metrics/config/Const.java
@@ -16,8 +16,7 @@
* specific language governing permissions and limitations
* under the License.
*/
-
-package org.apache.ozhera.prometheus.starter.all.domain;
+package org.apache.ozhera.metrics.config;
/**
* @Description
@@ -25,7 +24,6 @@ package org.apache.ozhera.prometheus.starter.all.domain;
*/
public class Const {
- public static final String MILINE = "miline";
+ public static final String OZHERA_PLATFORM = "ozhera";
- public static final String MATRIX = "matrix";
-}
\ No newline at end of file
+}
diff --git a/ozhera-metrics-all/ozhera-metrics-sdk-config/src/main/java/org/apache/ozhera/metrics/config/HeraConfig.java b/ozhera-metrics-all/ozhera-metrics-sdk-config/src/main/java/org/apache/ozhera/metrics/config/HeraConfig.java
new file mode 100644
index 00000000..ed779683
--- /dev/null
+++ b/ozhera-metrics-all/ozhera-metrics-sdk-config/src/main/java/org/apache/ozhera/metrics/config/HeraConfig.java
@@ -0,0 +1,44 @@
+/*
+ * 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.ozhera.metrics.config;
+
+import org.apache.ozhera.metrics.config.service.PrometheusService;
+import org.apache.ozhera.metrics.config.service.ServiceFactory;
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
+
+
+public class HeraConfig {
+ private static final Logger LOG = LoggerFactory.getLogger(HeraConfig.class);
+
+ public static PrometheusService registerNacos() {
+ try {
+ PrometheusService prometheusService = ServiceFactory.getPrometheusService();
+ String serviceName = prometheusService.getServiceName();
+ int port = prometheusService.getPort();
+ String serverIp = prometheusService.getServerIp();
+ prometheusService.registerNacos(prometheusService.getNacosAddr(), null, serviceName, serverIp, port);
+ return prometheusService;
+ } catch (Exception t) {
+ throw new IllegalStateException(t);
+ }
+ }
+
+}
diff --git a/ozhera-metrics-all/ozhera-metrics-sdk-config/src/main/java/org/apache/ozhera/metrics/config/LogFileNameUtil.java b/ozhera-metrics-all/ozhera-metrics-sdk-config/src/main/java/org/apache/ozhera/metrics/config/LogFileNameUtil.java
new file mode 100644
index 00000000..5fdb3944
--- /dev/null
+++ b/ozhera-metrics-all/ozhera-metrics-sdk-config/src/main/java/org/apache/ozhera/metrics/config/LogFileNameUtil.java
@@ -0,0 +1,68 @@
+package org.apache.ozhera.metrics.config;
+
+/**
+ * @author wtt
+ * @version 1.0
+ * @description
+ * @date 2025/5/12 16:16
+ */
+public class LogFileNameUtil {
+ public static final String LOG_PATH_PROPERTY_NAME = "otel.exporter.log.pathprefix";
+ private static final String LOG_PATH_SUFFIX = "/metrics/";
+ private static final String LOG_FILE_NAME = "custom-metrics.log";
+
+ public static String getLogPathFile() {
+ return getLogPath() + LOG_FILE_NAME;
+ }
+
+ public static String getLogPath() {
+ String logPathPrefixStr = System.getenv("MIONE_LOG_PATH");
+ if (logPathPrefixStr == null || logPathPrefixStr.isEmpty()) {
+ String logPathPrefix = System.getProperty(LOG_PATH_PROPERTY_NAME);
+ if (logPathPrefix == null || logPathPrefix.isEmpty()) {
+ logPathPrefix = "/home/work/log/";
+ }
+ String applicationName = getServiceName();
+ logPathPrefixStr = logPathPrefix + applicationName;
+ }
+ return logPathPrefixStr + LOG_PATH_SUFFIX;
+ }
+
+ /**
+ * get service name without project id
+ */
+ public static String getServiceName() {
+ String applicationName = System.getProperty("otel.resource.attributes") == null ?
+ (System.getenv("mione.app.name") == null ? "none" : System.getenv("mione.app.name")) :
+ System.getProperty("otel.resource.attributes").split("=")[1];
+
+ int i = applicationName.indexOf("-");
+ if (i >= 0) {
+ String id = applicationName.substring(0, i);
+ if (isNumeric(id)) {
+ return applicationName.substring(i + 1);
+ }
+ }
+ int j = applicationName.indexOf("_");
+ if (j >= 0) {
+ String id = applicationName.substring(0, j);
+ if (isNumeric(id)) {
+ return applicationName.substring(j + 1);
+ }
+ }
+ return applicationName;
+ }
+
+ public static boolean isNumeric(String cs) {
+ if (cs == null || cs.isEmpty()) {
+ return false;
+ }
+ int sz = cs.length();
+ for (int i = 0; i < sz; i++) {
+ if (!Character.isDigit(cs.charAt(i))) {
+ return false;
+ }
+ }
+ return true;
+ }
+}
diff --git a/ozhera-metrics-all/ozhera-metrics-sdk-config/src/main/java/org/apache/ozhera/metrics/config/PromEnvEnum.java b/ozhera-metrics-all/ozhera-metrics-sdk-config/src/main/java/org/apache/ozhera/metrics/config/PromEnvEnum.java
new file mode 100644
index 00000000..84feef3f
--- /dev/null
+++ b/ozhera-metrics-all/ozhera-metrics-sdk-config/src/main/java/org/apache/ozhera/metrics/config/PromEnvEnum.java
@@ -0,0 +1,6 @@
+package org.apache.ozhera.metrics.config;
+
+public enum PromEnvEnum {
+ STAGING,
+ ONLINE
+}
diff --git a/ozhera-metrics-all/ozhera-metrics-sdk-config/src/main/java/org/apache/ozhera/metrics/config/SdkLoggerInitializer.java b/ozhera-metrics-all/ozhera-metrics-sdk-config/src/main/java/org/apache/ozhera/metrics/config/SdkLoggerInitializer.java
new file mode 100644
index 00000000..df07d80f
--- /dev/null
+++ b/ozhera-metrics-all/ozhera-metrics-sdk-config/src/main/java/org/apache/ozhera/metrics/config/SdkLoggerInitializer.java
@@ -0,0 +1,83 @@
+package org.apache.ozhera.metrics.config;
+
+import ch.qos.logback.classic.AsyncAppender;
+import ch.qos.logback.classic.LoggerContext;
+import ch.qos.logback.classic.encoder.PatternLayoutEncoder;
+import ch.qos.logback.classic.spi.ILoggingEvent;
+import ch.qos.logback.core.rolling.FixedWindowRollingPolicy;
+import ch.qos.logback.core.rolling.RollingFileAppender;
+import ch.qos.logback.core.rolling.SizeBasedTriggeringPolicy;
+import ch.qos.logback.core.util.FileSize;
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
+
+/**
+ * @version 1.0
+ * @description
+ * @date 2025/5/12 16:01
+ */
+public class SdkLoggerInitializer {
+ private static final Logger SDK_LOGGER;
+
+ static {
+ LoggerContext loggerContext = (LoggerContext) LoggerFactory.getILoggerFactory();
+
+ // 编码器设置
+ PatternLayoutEncoder encoder = new PatternLayoutEncoder();
+ encoder.setContext(loggerContext);
+ encoder.setPattern("%d|%-4.5level|%thread|%logger|%L|%msg%n");
+ encoder.start();
+
+ // 文件 appender
+ RollingFileAppender<ILoggingEvent> rollingFileAppender = new RollingFileAppender<>();
+ rollingFileAppender.setContext(loggerContext);
+ rollingFileAppender.setName("SDK_ROLLING_FILE_APPENDER");
+ rollingFileAppender.setFile(LogFileNameUtil.getLogPathFile());
+ rollingFileAppender.setEncoder(encoder);
+
+ // 滚动策略
+ FixedWindowRollingPolicy rollingPolicy = new FixedWindowRollingPolicy();
+ rollingPolicy.setContext(loggerContext);
+ rollingPolicy.setParent(rollingFileAppender);
+ rollingPolicy.setFileNamePattern(LogFileNameUtil.getLogPathFile() + ".%i");
+ rollingPolicy.setMinIndex(1);
+ rollingPolicy.setMaxIndex(10);
+ rollingPolicy.start();
+
+ // 大小触发策略
+ SizeBasedTriggeringPolicy<ILoggingEvent> sizePolicy = new SizeBasedTriggeringPolicy<>();
+ sizePolicy.setContext(loggerContext);
+ sizePolicy.setMaxFileSize(FileSize.valueOf("10MB"));
+ sizePolicy.start();
+
+ rollingFileAppender.setRollingPolicy(rollingPolicy);
+ rollingFileAppender.setTriggeringPolicy(sizePolicy);
+ rollingFileAppender.start();
+
+ // 异步 appender 包装
+ AsyncAppender asyncAppender = new AsyncAppender();
+ asyncAppender.setContext(loggerContext);
+ asyncAppender.setName("ASYNC_SDK_APPENDER");
+ asyncAppender.addAppender(rollingFileAppender);
+ // 日志缓冲队列大小
+ asyncAppender.setQueueSize(5000);
+ // 当队列满时,丢弃低于 INFO 级别的日志
+ asyncAppender.setDiscardingThreshold(0);
+ // 是否记录调用链数据(可减少开销)
+ asyncAppender.setIncludeCallerData(false);
+ asyncAppender.start();
+
+ // 绑定到指定 logger
+ ch.qos.logback.classic.Logger logbackLogger =
+ loggerContext.getLogger("org.apache.ozhera.metrics.api.Metrics");
+ logbackLogger.addAppender(asyncAppender);
+ logbackLogger.setAdditive(false);
+
+ SDK_LOGGER = logbackLogger;
+ }
+
+ // 对外提供 org.slf4j.Logger 类型
+ public static Logger getLogger() {
+ return SDK_LOGGER;
+ }
+}
diff --git a/ozhera-metrics-all/ozhera-metrics-sdk-config/src/main/java/org/apache/ozhera/metrics/config/service/OzHeraPrometheusService.java b/ozhera-metrics-all/ozhera-metrics-sdk-config/src/main/java/org/apache/ozhera/metrics/config/service/OzHeraPrometheusService.java
new file mode 100644
index 00000000..f67e7fba
--- /dev/null
+++ b/ozhera-metrics-all/ozhera-metrics-sdk-config/src/main/java/org/apache/ozhera/metrics/config/service/OzHeraPrometheusService.java
@@ -0,0 +1,224 @@
+/*
+ * 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.ozhera.metrics.config.service;
+
+import java.util.HashMap;
+import java.util.Map;
+
+import org.apache.commons.lang3.StringUtils;
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
+
+import com.alibaba.nacos.api.exception.NacosException;
+import com.alibaba.nacos.api.naming.pojo.Instance;
+import com.alibaba.nacos.client.naming.NacosNamingService;
+
+/**
+ * OzHera Prometheus Service Singleton Class
+ * Uses double-checked locking pattern for thread-safe and lazy loading
+ *
+ * @Description OzHera implementation of Prometheus service, providing service registration and configuration management
+ * @Date 2023/3/5 3:41 PM
+ */
+class OzHeraPrometheusService extends PrometheusService {
+
+ private static final Logger LOG = LoggerFactory.getLogger(OzHeraPrometheusService.class);
+
+ private static final String NACOS_ADDRESS = System.getenv("nacos_addr");
+ private static final String DEFAULT_NACOS_ADDRESS = "nacos:80";
+
+ /**
+ * Server environment variable key
+ */
+ private static final String SERVER_ENV_KEY = "MIONE_PROJECT_ENV_NAME";
+
+ /**
+ * Singleton instance with volatile keyword to ensure visibility
+ */
+ private static volatile OzHeraPrometheusService instance;
+
+ // Static block: Turn off Nacos client logging
+ static {
+ ((ch.qos.logback.classic.Logger) LoggerFactory.getLogger("shaded.ozhera.com.alibaba.nacos.client.naming"))
+ .setLevel(ch.qos.logback.classic.Level.OFF);
+ }
+
+ /**
+ * Private constructor to prevent external instantiation
+ */
+ private OzHeraPrometheusService() {
+ // Private constructor
+ }
+
+ /**
+ * Get singleton instance
+ * Uses double-checked locking pattern to ensure thread safety and performance
+ *
+ * @return OzHeraPrometheusService singleton instance
+ */
+ public static OzHeraPrometheusService getInstance() {
+ if (instance == null) {
+ synchronized (OzHeraPrometheusService.class) {
+ if (instance == null) {
+ instance = new OzHeraPrometheusService();
+ }
+ }
+ }
+ return instance;
+ }
+
+ /**
+ * Get service name
+ * Priority: environment variable mione.app.name, then system property otel.resource.attributes
+ *
+ * @return service name in underscore format
+ */
+ @Override
+ public String getServiceName() {
+ String serviceName = System.getenv("mione.app.name");
+ if (StringUtils.isEmpty(serviceName)) {
+ String property = System.getProperty("otel.resource.attributes");
+ if (StringUtils.isEmpty(property)) {
+ serviceName = DEFAULT_SERVICE_NAME;
+ } else {
+ serviceName = property.split("=")[1];
+ }
+ }
+ // Replace hyphens with underscores to comply with service name standards
+ serviceName = serviceName.replace('-', '_');
+ return serviceName;
+ }
+
+ /**
+ * Get server IP address
+ * Priority: environment variable POD_IP, then system property otel.service.ip
+ *
+ * @return server IP address
+ */
+ @Override
+ public String getServerIp() {
+ String serverIp = System.getenv("POD_IP");
+ if (serverIp == null) {
+ serverIp = System.getProperty("otel.service.ip");
+ }
+ return serverIp;
+ }
+
+ /**
+ * Get server environment
+ *
+ * @return server environment name
+ */
+ @Override
+ public String getServerEnv() {
+ return System.getenv(SERVER_ENV_KEY);
+ }
+
+ /**
+ * Get Prometheus port
+ * From environment variable PROMETHEUS_PORT, defaults to DEFAULT_PORT
+ *
+ * @return Prometheus port number
+ */
+ @Override
+ public int getPort() {
+ String port = System.getenv("PROMETHEUS_PORT");
+ if (null == port) {
+ return DEFAULT_PORT;
+ }
+ return Integer.parseInt(port);
+ }
+
+ /**
+ * Get Nacos address
+ * Current implementation returns empty string
+ *
+ * @return Nacos address
+ */
+ @Override
+ public String getNacosAddr() {
+ if (NACOS_ADDRESS == null || NACOS_ADDRESS.isEmpty()) {
+ return DEFAULT_NACOS_ADDRESS;
+ } else {
+ return NACOS_ADDRESS;
+ }
+ }
+
+ /**
+ * Register service instance with Nacos
+ * Registers Prometheus custom service and automatically deregisters on JVM shutdown
+ *
+ * @param nacosAddr Nacos server address
+ * @param namespace namespace
+ * @param serviceName service name
+ * @param serverIp server IP
+ * @param port service port
+ * @throws NacosException when Nacos registration fails
+ */
+ @Override
+ public void registerNacos(String nacosAddr, String namespace, String serviceName, String serverIp, int port) throws NacosException {
+ String appName = PROMETHEUS_CUSTOM_SERVER_KEY + serviceName;
+ NacosNamingService nacosNamingService = new NacosNamingService(nacosAddr);
+ Instance instance = new Instance();
+ instance.setIp(serverIp);
+ instance.setPort(55257);
+
+ // Set port metadata
+ Map<String, String> map = new HashMap<>();
+ map.put(PROMETHEUS_CUSTOM_PORT_KEY, Integer.toString(port));
+ instance.setMetadata(map);
+
+ try {
+ // Register instance
+ nacosNamingService.registerInstance(appName, instance);
+
+ // Add JVM shutdown hook for automatic deregistration
+ Runtime.getRuntime().addShutdownHook(new Thread(() -> {
+ LOG.info("nacos shutdown hook deregister instance");
+ try {
+ nacosNamingService.deregisterInstance(appName, instance);
+ } catch (Exception e) {
+ LOG.warn("nacos shutdown hook error:{}", e.getMessage());
+ }
+ }));
+ } catch (NacosException e) {
+ LOG.error("ozhera metrics register nacos error:{}", e.getMessage());
+ throw e;
+ }
+ }
+
+ /**
+ * Get common tags
+ * Contains application name, server IP and server environment information
+ *
+ * @return common tags Map
+ */
+ @Override
+ public Map<String, String> getCommonTags() {
+ Map<String, String> commonTags = new HashMap<>();
+ commonTags.put("application", getServiceName());
+ commonTags.put("serverIp", getServerIp());
+
+ String serverEnv = getServerEnv();
+ if (serverEnv != null) {
+ commonTags.put("serverEnv", serverEnv);
+ }
+ return commonTags;
+ }
+}
diff --git a/prometheus-starter-all/prometheus-diy-starter/src/main/java/org/apache/ozhera/prometheus/starter/all/service/PrometheusService.java b/ozhera-metrics-all/ozhera-metrics-sdk-config/src/main/java/org/apache/ozhera/metrics/config/service/PrometheusService.java
similarity index 54%
copy from prometheus-starter-all/prometheus-diy-starter/src/main/java/org/apache/ozhera/prometheus/starter/all/service/PrometheusService.java
copy to ozhera-metrics-all/ozhera-metrics-sdk-config/src/main/java/org/apache/ozhera/metrics/config/service/PrometheusService.java
index e0514a78..db8c1fb8 100644
--- a/prometheus-starter-all/prometheus-diy-starter/src/main/java/org/apache/ozhera/prometheus/starter/all/service/PrometheusService.java
+++ b/ozhera-metrics-all/ozhera-metrics-sdk-config/src/main/java/org/apache/ozhera/metrics/config/service/PrometheusService.java
@@ -16,18 +16,33 @@
* specific language governing permissions and limitations
* under the License.
*/
+package org.apache.ozhera.metrics.config.service;
-package org.apache.ozhera.prometheus.starter.all.service;
+import com.alibaba.nacos.api.exception.NacosException;
+
+import java.util.Map;
public abstract class PrometheusService {
- protected static final String DEFAULT_SERVICE_NAME = "default_service_name";
+ public static final String DEFAULT_SERVICE_NAME = "default_service_name";
+
+ protected static final int DEFAULT_PORT = 5555;
- protected static final String DEFAULT_PORT = "5555";
+ protected static final String PROMETHEUS_CUSTOM_SERVER_KEY = "prometheus_custom_server_";
+ protected static final String PROMETHEUS_CUSTOM_PORT_KEY = "prometheus_port";
public abstract String getServiceName();
public abstract String getServerIp();
- public abstract String getPort();
-}
\ No newline at end of file
+ public abstract String getServerEnv();
+
+ public abstract int getPort();
+
+ public abstract String getNacosAddr();
+
+ public abstract void registerNacos(
+ String nacosAddr, String namespace, String serviceName, String serverIp, int port) throws NacosException;
+
+ public abstract Map<String, String> getCommonTags();
+}
diff --git a/prometheus-starter-all/prometheus-diy-starter/src/main/java/org/apache/ozhera/prometheus/starter/all/factory/ServiceFactory.java b/ozhera-metrics-all/ozhera-metrics-sdk-config/src/main/java/org/apache/ozhera/metrics/config/service/ServiceFactory.java
similarity index 53%
rename from prometheus-starter-all/prometheus-diy-starter/src/main/java/org/apache/ozhera/prometheus/starter/all/factory/ServiceFactory.java
rename to ozhera-metrics-all/ozhera-metrics-sdk-config/src/main/java/org/apache/ozhera/metrics/config/service/ServiceFactory.java
index d6cb2709..db9354c0 100644
--- a/prometheus-starter-all/prometheus-diy-starter/src/main/java/org/apache/ozhera/prometheus/starter/all/factory/ServiceFactory.java
+++ b/ozhera-metrics-all/ozhera-metrics-sdk-config/src/main/java/org/apache/ozhera/metrics/config/service/ServiceFactory.java
@@ -16,30 +16,33 @@
* specific language governing permissions and limitations
* under the License.
*/
+package org.apache.ozhera.metrics.config.service;
-package org.apache.ozhera.prometheus.starter.all.factory;
-
-import org.apache.ozhera.prometheus.starter.all.service.MilinePrometheusService;
-import org.apache.ozhera.prometheus.starter.all.service.PrometheusService;
-import org.apache.commons.lang3.StringUtils;
-
-import org.apache.ozhera.prometheus.starter.all.domain.Const;
+import org.apache.ozhera.metrics.config.Const;
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
/**
- * @Description
+ * Service Factory Class
+ * Provides methods to obtain PrometheusService instances
+ *
+ * @Description Service factory for creating and managing service instances
* @Date 2023/3/5 3:33 PM
*/
public class ServiceFactory {
- public static PrometheusService getPrometheusService(String platform){
- if(StringUtils.isEmpty(platform)){
- throw new IllegalArgumentException("platform is empty");
- }
- switch (platform) {
- case Const.MILINE:
- return new MilinePrometheusService();
- default:
- throw new IllegalArgumentException("platform is invalid");
- }
+ private static final Logger LOG = LoggerFactory.getLogger(ServiceFactory.class);
+
+ /**
+ * Get PrometheusService singleton instance
+ *
+ * @return singleton instance of OzHeraPrometheusService
+ */
+ public static PrometheusService getPrometheusService() {
+ return OzHeraPrometheusService.getInstance();
+ }
+
+ private static String getPlatForm() {
+ return Const.OZHERA_PLATFORM;
}
-}
\ No newline at end of file
+}
diff --git a/prometheus-starter-all/prometheus-diy-client/src/main/resources/META-INF/LICENSE.txt b/ozhera-metrics-all/ozhera-metrics-sdk-config/src/main/resources/META-INF/LICENSE.txt
similarity index 100%
rename from prometheus-starter-all/prometheus-diy-client/src/main/resources/META-INF/LICENSE.txt
rename to ozhera-metrics-all/ozhera-metrics-sdk-config/src/main/resources/META-INF/LICENSE.txt
diff --git a/ozhera-metrics-all/ozhera-metrics-sdk/pom.xml b/ozhera-metrics-all/ozhera-metrics-sdk/pom.xml
new file mode 100644
index 00000000..c87e184d
--- /dev/null
+++ b/ozhera-metrics-all/ozhera-metrics-sdk/pom.xml
@@ -0,0 +1,166 @@
+<?xml version="1.0" encoding="UTF-8"?>
+<!--
+
+ 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.
+
+-->
+
+<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
+ <parent>
+ <groupId>org.apache.ozhera</groupId>
+ <artifactId>ozhera-metrics-all</artifactId>
+ <version>2.2.6-SNAPSHOT</version>
+ </parent>
+ <modelVersion>4.0.0</modelVersion>
+
+ <artifactId>ozhera-metrics-sdk</artifactId>
+ <version>2.2.6-SNAPSHOT</version>
+
+ <dependencies>
+ <dependency>
+ <groupId>org.apache.ozhera</groupId>
+ <artifactId>ozhera-metrics-sdk-config</artifactId>
+ <version>${project.parent.version}</version>
+ </dependency>
+ <dependency>
+ <groupId>io.prometheus</groupId>
+ <artifactId>simpleclient</artifactId>
+ </dependency>
+ <dependency>
+ <groupId>io.micrometer</groupId>
+ <artifactId>micrometer-registry-prometheus</artifactId>
+ <exclusions>
+ <exclusion>
+ <groupId>io.prometheus</groupId>
+ <artifactId>simpleclient_common</artifactId>
+ </exclusion>
+ </exclusions>
+ </dependency>
+
+ <dependency>
+ <groupId>org.projectlombok</groupId>
+ <artifactId>lombok</artifactId>
+ </dependency>
+
+ <dependency>
+ <groupId>org.slf4j</groupId>
+ <artifactId>slf4j-api</artifactId>
+ </dependency>
+
+ <dependency>
+ <groupId>junit</groupId>
+ <artifactId>junit</artifactId>
+ <scope>test</scope>
+ </dependency>
+
+ <dependency>
+ <groupId>com.google.code.gson</groupId>
+ <artifactId>gson</artifactId>
+ </dependency>
+
+ </dependencies>
+
+ <build>
+
+ <resources>
+ <resource>
+ <directory>src/main/resources</directory>
+ <filtering>true</filtering>
+ <excludes>
+ <exclude>META-INF/LICENSE.txt</exclude>
+ </excludes>
+ </resource>
+ <resource>
+ <directory>${project.basedir}/../../</directory>
+ <filtering>true</filtering>
+ <includes>
+ <include>DISCLAIMER</include>
+ <include>NOTICE</include>
+ <include>LICENSE</include>
+ </includes>
+ <targetPath>META-INF/</targetPath>
+ </resource>
+ </resources>
+
+ <plugins>
+ <plugin>
+ <groupId>org.apache.maven.plugins</groupId>
+ <artifactId>maven-compiler-plugin</artifactId>
+ <version>3.11.0</version>
+ <configuration>
+ <compilerVersion>21</compilerVersion>
+ <source>21</source>
+ <target>21</target>
+ </configuration>
+ </plugin>
+ <plugin>
+ <artifactId>maven-shade-plugin</artifactId>
+ <version>3.5.0</version>
+ <executions>
+ <execution>
+ <phase>package</phase>
+ <goals>
+ <goal>shade</goal>
+ </goals>
+ <configuration>
+ <shadedArtifactAttached>false</shadedArtifactAttached>
+ <createDependencyReducedPom>true</createDependencyReducedPom>
+ <createSourcesJar>false</createSourcesJar>
+ <shadeSourcesContent>false</shadeSourcesContent>
+ <transformers>
+ <transformer implementation="org.apache.maven.plugins.shade.resource.ManifestResourceTransformer">
+ </transformer>
+ <transformer implementation="org.apache.maven.plugins.shade.resource.DontIncludeResourceTransformer">
+ <resources>
+ <resource>.txt</resource>
+ <resource>application.properties</resource>
+ <resource>nacos-log4j2.xml</resource>
+ <resource>nacos-logback.xml</resource>
+ </resources>
+ </transformer>
+ </transformers>
+ <artifactSet>
+ <includes>
+ <include>io.prometheus:simpleclient</include>
+ <include>io.prometheus:simpleclient_common</include>
+ <include>com.alibaba.nacos:*</include>
+ <include>com.alibaba:dubbo-registry-nacos</include>
+ </includes>
+ </artifactSet>
+ <relocations>
+ <relocation>
+ <pattern>io.prometheus</pattern>
+ <shadedPattern>shaded.ozhera.io.prometheus</shadedPattern>
+ </relocation>
+ <relocation>
+ <pattern>com.alibaba.nacos</pattern>
+ <shadedPattern>shaded.ozhera.com.alibaba.nacos</shadedPattern>
+ </relocation>
+ <relocation>
+ <pattern>com.alibaba.dubbo.registry.nacos</pattern>
+ <shadedPattern>shaded.ozhera.com.alibaba.dubbo.registry.nacos</shadedPattern>
+ </relocation>
+ </relocations>
+ </configuration>
+ </execution>
+ </executions>
+ </plugin>
+ </plugins>
+ </build>
+
+</project>
\ No newline at end of file
diff --git a/ozhera-metrics-all/ozhera-metrics-sdk/src/main/java/org/apache/ozhera/metrics/api/BusinessMetrics.java b/ozhera-metrics-all/ozhera-metrics-sdk/src/main/java/org/apache/ozhera/metrics/api/BusinessMetrics.java
new file mode 100644
index 00000000..108ee760
--- /dev/null
+++ b/ozhera-metrics-all/ozhera-metrics-sdk/src/main/java/org/apache/ozhera/metrics/api/BusinessMetrics.java
@@ -0,0 +1,199 @@
+/*
+ * 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.ozhera.metrics.api;
+
+import org.apache.ozhera.metrics.config.HeraConfig;
+import org.apache.ozhera.metrics.config.service.PrometheusService;
+import org.apache.ozhera.metrics.config.service.ServiceFactory;
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
+
+import java.util.Collections;
+import java.util.Map;
+import java.util.Map.Entry;
+
+/**
+ * Hera Business Metrics Reporting Utility
+ * Before using this utility to report metric data, you must create and associate [Scene] and [Metric]
+ * in the Hera Platform - Metric Monitoring section
+ */
+public class BusinessMetrics {
+ private static final Logger LOG = LoggerFactory.getLogger(BusinessMetrics.class);
+
+ // Fixed field constants
+ private static final String SERVICE_NAME_KEY = "serviceName";
+ private static final String SERVICE_IP_KEY = "serviceIp";
+ private static final String SERVICE_ENV_KEY = "env";
+ private static final String HERA_BIZ_METRIC_PREFIX = "hera_biz_metric_";
+ private static final String BIZ_COMMON_METRIC = "business_scence_metric";
+ private static final String SCENE_ID = "sceneId";
+ private static final String BUSINESS_METRIC = "businessMetric";
+ private static final String SYSTS_KEY = "systs";
+
+ // Default values
+ private static final String UNKNOWN_VALUE = "unknown";
+
+ private static final String SERVICE_NAME;
+ private static final String SERVICE_IP;
+ private static final String SERVICE_ENV;
+ static {
+ PrometheusService service = ServiceFactory.getPrometheusService();
+ SERVICE_NAME = service.getServiceName();
+ SERVICE_IP = service.getServerIp();
+ SERVICE_ENV = service.getServerEnv();
+ }
+
+ /**
+ * Metric Type: Counter
+ * Use Case: Cumulative counting
+ * Value Characteristics: Can only increase
+ * Dashboard Statistics: rate, calculates the change rate of metric data within 1 minute
+ *
+ * @param sceneId scene ID
+ * @param metricId metric ID
+ * @param delta delta value
+ */
+ public static void counter(String sceneId, String metricId, double delta) {
+ counter(sceneId, metricId, delta, Collections.emptyMap());
+ }
+
+ /**
+ * Report counter type business metric data with context information
+ *
+ * @param sceneId Scene ID created by user in Hera, can be obtained from platform [Scene] list, cannot be empty
+ * @param metricId Metric ID created by user in Hera, can be obtained from platform [Metric] list, cannot be empty
+ * @param delta Business calculated metric data, e.g., reconciliation amount difference
+ * @param context Business context information, can be null
+ * @throws IllegalArgumentException when required parameters are null
+ */
+ public static void counter(String sceneId, String metricId, double delta, Map<String, String> context) {
+ try {
+ // Parameter validation
+ if (sceneId == null) {
+ throw new NullPointerException("the sceneId cannot be empty");
+ }
+ if (metricId == null) {
+ throw new NullPointerException("the metricId cannot be empty");
+ }
+
+ // Basic metric reporting
+ Metrics.counter(BIZ_COMMON_METRIC)// Agreed metric item
+ .tag(SCENE_ID, sceneId)// Scene ID
+ .tag(BUSINESS_METRIC, metricId) // Metric ID
+ .inc(delta);// Metric data
+
+ // Build enhanced context information
+ MetricsContext metricsContext = buildEnhancedContext(context);
+
+ // Based on test results, direct string concatenation performs better
+ String metricKey = HERA_BIZ_METRIC_PREFIX + sceneId + "_" + metricId;
+ Metrics.counterWithLog(metricKey, metricsContext);
+
+ } catch (Exception e) {
+ LOG.error("Business metric reporting failed - sceneId: {}, metricId: {}", sceneId, metricId);
+ }
+ }
+
+ /**
+ * Metric Type: Gauge
+ * Use Case: Instantaneous value measurement
+ * Value Characteristics: Can increase or decrease arbitrarily
+ * Dashboard Statistics: Directly displays current value, e.g., current online users, queue length, memory usage
+ *
+ * @param sceneId scene ID
+ * @param metricId metric ID
+ * @param value current value
+ */
+ public static void gauge(String sceneId, String metricId, double value) {
+ gauge(sceneId, metricId, value, Collections.emptyMap());
+ }
+
+ /**
+ * Report gauge type business metric data with context information
+ *
+ * @param sceneId Scene ID created by user in Hera, can be obtained from platform [Scene] list, cannot be empty
+ * @param metricId Metric ID created by user in Hera, can be obtained from platform [Metric] list, cannot be empty
+ * @param value Business calculated metric data, e.g., current queue length, memory usage
+ * @param context Business context information, can be null
+ * @throws IllegalArgumentException when required parameters are null
+ */
+ public static void gauge(String sceneId, String metricId, double value, Map<String, String> context) {
+ try {
+ // Parameter validation
+ if (sceneId == null) {
+ throw new NullPointerException("the sceneId cannot be empty");
+ }
+ if (metricId == null) {
+ throw new NullPointerException("the metricId cannot be empty");
+ }
+
+ // Basic metric reporting
+ Metrics.gauge(BIZ_COMMON_METRIC)// Agreed metric item
+ .tag(SCENE_ID, sceneId)// Scene ID
+ .tag(BUSINESS_METRIC, metricId) // Metric ID
+ .set(value);// Metric data
+
+ // Build enhanced context information
+ MetricsContext MetricsContext = buildEnhancedContext(context);
+
+ // Based on test results, direct string concatenation performs better
+ String metricKey = HERA_BIZ_METRIC_PREFIX + sceneId + "_" + metricId;
+ Metrics.gaugeWithLog(metricKey, MetricsContext);
+
+ } catch (Exception e) {
+ LOG.error("Business metric reporting failed - sceneId: {}, metricId: {}", sceneId, metricId);
+ }
+ }
+
+ /**
+ * Build enhanced context information, including fixed fields and user-defined fields
+ *
+ * @param userContext user-defined context
+ * @return enhanced context object
+ */
+ private static MetricsContext buildEnhancedContext(Map<String, String> userContext) {
+ MetricsContext MetricsContext = new MetricsContext();
+
+ // Add system fixed fields
+ MetricsContext.addContext(SYSTS_KEY, Long.toString(System.currentTimeMillis()));
+ MetricsContext.addContext(SERVICE_NAME_KEY, getValueOrDefault(SERVICE_NAME, UNKNOWN_VALUE));
+ MetricsContext.addContext(SERVICE_IP_KEY, getValueOrDefault(SERVICE_IP, UNKNOWN_VALUE));
+ MetricsContext.addContext(SERVICE_ENV_KEY, getValueOrDefault(SERVICE_ENV, UNKNOWN_VALUE));
+
+ // Add user-defined context
+ if (userContext != null && !userContext.isEmpty()) {
+ for (Entry<String, String> entry : userContext.entrySet()) {
+ String key = entry.getKey();
+ String value = entry.getValue();
+ if (key != null && value != null && value.trim().length() > 0) {
+ MetricsContext.addContext(key, value.trim());
+ }
+ }
+ }
+
+ return MetricsContext;
+ }
+
+ /**
+ * Get value or default value
+ */
+ private static String getValueOrDefault(String value, String defaultValue) {
+ return (value != null && value.trim().length() > 0) ? value.trim() : defaultValue;
+ }
+}
diff --git a/ozhera-metrics-all/ozhera-metrics-sdk/src/main/java/org/apache/ozhera/metrics/api/Counter.java b/ozhera-metrics-all/ozhera-metrics-sdk/src/main/java/org/apache/ozhera/metrics/api/Counter.java
new file mode 100644
index 00000000..40aa6a70
--- /dev/null
+++ b/ozhera-metrics-all/ozhera-metrics-sdk/src/main/java/org/apache/ozhera/metrics/api/Counter.java
@@ -0,0 +1,91 @@
+/*
+ * 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.ozhera.metrics.api;
+
+/**
+ * Counter metric, to track counts of events or running totals.
+ * <p>
+ * Example of Counter include:
+ * <ul>
+ * <li>Number of requests processed</li>
+ * <li>Number of items that were inserted into a queue</li>
+ * <li>Total amount of data a system has processed</li>
+ * </ul>
+ *
+ * Counters can only go up (and be reset), if your use case can go down you should use a {@link Gauge} instead.
+ * Use the <code>rate()</code> function in Prometheus to calculate the rate of increase of a Counter.
+ * By convention, the names of Counter are suffixed by <code>_total</code>.
+ *
+ * <p>
+ * An example Counter:
+ * <pre>
+ * {@code
+ * class YourClass {
+ *
+ * void processRequest() {
+ * Metrics.counter("requests_total").inc();
+ * try {
+ * // Your code here.
+ * } catch (Exception e) {
+ * Metrics.counter("requests_failed_total").inc();
+ * throw e;
+ * }
+ * }
+ * }
+ * }
+ * </pre>
+ *
+ * <p>
+ * You can also use labels to track different types of metric:
+ * <pre>
+ * {@code
+ * class YourClass {
+ *
+ * void processGetRequest() {
+ * Metrics.count("requests_total").tag("method", "get").inc();
+ * // Your code here.
+ * }
+ * void processPostRequest() {
+ * Metrics.count("requests_total").tag("method", "post").inc();
+ * // Your code here.
+ * }
+ * }
+ * }
+ * </pre>
+ * These can be aggregated and processed together much more easily in the Prometheus
+ * server than individual metrics for each labelset.
+ *
+ * If there is a suffix of <code>_total</code> on the metric name, it will be
+ * removed. When exposing the time series for counter value, a
+ * <code>_total</code> suffix will be added. This is for compatibility between
+ * OpenMetrics and the Prometheus text format, as OpenMetrics requires the
+ * <code>_total</code> suffix.
+ */
+public interface Counter extends Meter<Counter> {
+ /**
+ * Increment the counter by 1.
+ */
+ void inc();
+
+ /**
+ * Increment the counter by the given amount.
+ * @throws IllegalArgumentException If amount is negative.
+ */
+ void inc(double amount);
+}
diff --git a/ozhera-metrics-all/ozhera-metrics-sdk/src/main/java/org/apache/ozhera/metrics/api/Gauge.java b/ozhera-metrics-all/ozhera-metrics-sdk/src/main/java/org/apache/ozhera/metrics/api/Gauge.java
new file mode 100644
index 00000000..3153031e
--- /dev/null
+++ b/ozhera-metrics-all/ozhera-metrics-sdk/src/main/java/org/apache/ozhera/metrics/api/Gauge.java
@@ -0,0 +1,78 @@
+/*
+ * 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.ozhera.metrics.api;
+
+/**
+ * Gauge metric, to report instantaneous values.
+ * <p>
+ * Examples of Gauge include:
+ * <ul>
+ * <li>Inprogress requests</li>
+ * <li>Number of items in a queue</li>
+ * <li>Free memory</li>
+ * <li>Total memory</li>
+ * <li>Temperature</li>
+ * </ul>
+ *
+ * Gauges can go both up and down.
+ * <p>
+ * An example Gauge:
+ * <pre>
+ * {@code
+ * class YourClass {
+ *
+ * void processRequest() {
+ * Metrics.gauge("inprogress_requests").inc();
+ * }
+ * }
+ * }
+ * </pre>
+ *
+ * <p>
+ * You can also use labels to track different types of metric:
+ * <pre>
+ * {@code
+ * class YourClass {
+ *
+ * void processGetRequest() {
+ * Metrics.gauge("inprogress_requests").tag("method", "get").inc();
+ * // Your code here.
+ * }
+ * void processPostRequest() {
+ * Metrics.gauge("inprogress_requests").tag("method", "post").inc();
+ * // Your code here.
+ * }
+ * }
+ * }
+ * </pre>
+ * <p>
+ * These can be aggregated and processed together much more easily in the Prometheus
+ * server than individual metrics for each labelset.
+ */
+public interface Gauge extends Meter<Gauge> {
+ /**
+ * Set the gauge to the given value.
+ */
+ void set(double value);
+
+ /**
+ * Increment the gauge by the given amount.
+ */
+ void inc(double amount);
+}
diff --git a/prometheus-starter-all/prometheus-diy-starter/src/main/java/org/apache/ozhera/prometheus/starter/all/exporter/HTTPServer.java b/ozhera-metrics-all/ozhera-metrics-sdk/src/main/java/org/apache/ozhera/metrics/api/HTTPServer.java
similarity index 50%
rename from prometheus-starter-all/prometheus-diy-starter/src/main/java/org/apache/ozhera/prometheus/starter/all/exporter/HTTPServer.java
rename to ozhera-metrics-all/ozhera-metrics-sdk/src/main/java/org/apache/ozhera/metrics/api/HTTPServer.java
index 8c8dfcf0..1f26e473 100644
--- a/prometheus-starter-all/prometheus-diy-starter/src/main/java/org/apache/ozhera/prometheus/starter/all/exporter/HTTPServer.java
+++ b/ozhera-metrics-all/ozhera-metrics-sdk/src/main/java/org/apache/ozhera/metrics/api/HTTPServer.java
@@ -16,28 +16,26 @@
* specific language governing permissions and limitations
* under the License.
*/
-
-package org.apache.ozhera.prometheus.starter.all.exporter;
+package org.apache.ozhera.metrics.api;
import com.sun.net.httpserver.HttpExchange;
import com.sun.net.httpserver.HttpHandler;
import com.sun.net.httpserver.HttpServer;
-import io.prometheus.client.Collector;
import io.prometheus.client.CollectorRegistry;
import io.prometheus.client.exporter.common.TextFormat;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.OutputStreamWriter;
-import java.lang.reflect.Field;
import java.net.HttpURLConnection;
-import java.net.InetSocketAddress;
-import java.net.URLDecoder;
-import java.nio.charset.Charset;
-import java.util.*;
-import java.util.concurrent.*;
+import java.nio.charset.StandardCharsets;
+import java.util.List;
+import java.util.concurrent.ExecutionException;
+import java.util.concurrent.ExecutorService;
+import java.util.concurrent.Executors;
+import java.util.concurrent.FutureTask;
+import java.util.concurrent.ThreadFactory;
import java.util.concurrent.atomic.AtomicInteger;
-import java.util.stream.Collectors;
import java.util.zip.GZIPOutputStream;
/**
@@ -50,7 +48,7 @@ import java.util.zip.GZIPOutputStream;
* }
* </pre>
*/
-public class HTTPServer {
+class HTTPServer {
private static class LocalByteArray extends ThreadLocal<ByteArrayOutputStream> {
@Override
protected ByteArrayOutputStream initialValue() {
@@ -62,65 +60,38 @@ public class HTTPServer {
* Handles Metrics collections from the given registry.
*/
static class HTTPMetricHandler implements HttpHandler {
- private final Map<String, CollectorRegistry> registryMap;
+ private final CollectorRegistry registry;
- private final LocalByteArray response = new LocalByteArray();
- private final static String HEALTHY_RESPONSE = "Exporter is Healthy.";
+ private final LocalByteArray buffer = new LocalByteArray();
+ private static final String HEALTHY_RESPONSE = "Exporter is Healthy.";
- HTTPMetricHandler(Map<String, CollectorRegistry> registryMap) {
- this.registryMap = registryMap;
+ HTTPMetricHandler(CollectorRegistry registry) {
+ this.registry = registry;
}
@Override
public void handle(HttpExchange t) throws IOException {
try {
- String query = t.getRequestURI().getRawQuery();
- String path = t.getRequestURI().getPath();
String contextPath = t.getHttpContext().getPath();
- ByteArrayOutputStream response = this.response.get();
+ ByteArrayOutputStream response = this.buffer.get();
response.reset();
- try (OutputStreamWriter osw = new OutputStreamWriter(response, Charset.forName("UTF-8"))) {
+ try (OutputStreamWriter osw = new OutputStreamWriter(response, StandardCharsets.UTF_8)) {
if ("/-/healthy".equals(contextPath)) {
osw.write(HEALTHY_RESPONSE);
} else {
String contentType = TextFormat.chooseContentType(t.getRequestHeaders().getFirst("Accept"));
t.getResponseHeaders().set("Content-Type", contentType);
- CollectorRegistry registry = this.registryMap.get("default");
-
- if ("/jvm".equals(path)) {
- registry = this.registryMap.get("jvm");
- }
-
- List<String> list = new ArrayList<>();
- try {
- Field field = registry.getClass().getDeclaredField("namesToCollectors");
- field.setAccessible(true);
- Map<String, Collector> namesToCollectors = (Map<String, Collector>) field.get(registry);
- list = namesToCollectors.keySet().stream()
- .filter(it -> !it.endsWith("created"))
- .filter(it -> !it.startsWith("nacos_"))
- .collect(Collectors.toList());
- } catch (NoSuchFieldException e) {
- e.printStackTrace();
- } catch (IllegalAccessException e) {
- e.printStackTrace();
- }
-
- TextFormat.writeFormat(contentType, osw,
- registry.filteredMetricFamilySamples(new HashSet<>(list)));
+ TextFormat.writeFormat(contentType, osw, registry.metricFamilySamples());
}
}
if (shouldUseCompression(t)) {
t.getResponseHeaders().set("Content-Encoding", "gzip");
t.sendResponseHeaders(HttpURLConnection.HTTP_OK, 0);
- final GZIPOutputStream os = new GZIPOutputStream(t.getResponseBody());
- try {
+ try (GZIPOutputStream os = new GZIPOutputStream(t.getResponseBody())) {
response.writeTo(os);
- } finally {
- os.close();
}
} else {
t.getResponseHeaders().set("Content-Length",
@@ -132,9 +103,7 @@ public class HTTPServer {
e.printStackTrace();
throw e;
} finally {
- if (null != t) {
- t.close();
- }
+ t.close();
}
}
@@ -155,20 +124,6 @@ public class HTTPServer {
return false;
}
- protected static Set<String> parseQuery(String query) throws IOException {
- Set<String> names = new HashSet<String>();
- if (query != null) {
- String[] pairs = query.split("&");
- for (String pair : pairs) {
- int idx = pair.indexOf("=");
- if (idx != -1 && URLDecoder.decode(pair.substring(0, idx), "UTF-8").equals("name[]")) {
- names.add(URLDecoder.decode(pair.substring(idx + 1), "UTF-8"));
- }
- }
- }
- return names;
- }
-
static class NamedDaemonThreadFactory implements ThreadFactory {
private static final AtomicInteger POOL_NUMBER = new AtomicInteger(1);
@@ -203,81 +158,20 @@ public class HTTPServer {
* Start a HTTP server serving Prometheus metrics from the given registry using the given {@link HttpServer}.
* The {@code httpServer} is expected to already be bound to an address
*/
- public HTTPServer(HttpServer httpServer, Map<String, CollectorRegistry> registryMap, boolean daemon) throws IOException {
- if (httpServer.getAddress() == null) {
- throw new IllegalArgumentException("HttpServer hasn't been bound to an address");
- }
- server = httpServer;
- HttpHandler mHandler = new HTTPMetricHandler(registryMap);
- server.createContext("/", mHandler);
- server.createContext("/metrics", mHandler);
- server.createContext("/-/healthy", mHandler);
- executorService = Executors.newFixedThreadPool(5, NamedDaemonThreadFactory.defaultThreadFactory(daemon));
- server.setExecutor(executorService);
- start(daemon);
- }
-
-
- public HTTPServer(HttpServer httpServer, final CollectorRegistry registry, boolean daemon) throws IOException {
+ HTTPServer(HttpServer httpServer, final CollectorRegistry registry, boolean daemon) {
if (httpServer.getAddress() == null) {
throw new IllegalArgumentException("HttpServer hasn't been bound to an address");
}
server = httpServer;
- HttpHandler mHandler = new HTTPMetricHandler(new HashMap<String, CollectorRegistry>(){{
- put("default",registry);
- }});
- server.createContext("/", mHandler);
- server.createContext("/metrics", mHandler);
- server.createContext("/-/healthy", mHandler);
+ HttpHandler handler = new HTTPMetricHandler(registry);
+ server.createContext("/", handler);
+ server.createContext("/metrics", handler);
+ server.createContext("/-/healthy", handler);
executorService = Executors.newFixedThreadPool(5, NamedDaemonThreadFactory.defaultThreadFactory(daemon));
server.setExecutor(executorService);
start(daemon);
}
- /**
- * Start a HTTP server serving Prometheus metrics from the given registry.
- */
- public HTTPServer(InetSocketAddress addr, final CollectorRegistry registry, boolean daemon) throws IOException {
- this(HttpServer.create(addr, 3), new HashMap<String, CollectorRegistry>() {{
- put("default", registry);
- }}, daemon);
- }
-
- /**
- * Start a HTTP server serving Prometheus metrics from the given registry using non-daemon threads.
- */
- public HTTPServer(InetSocketAddress addr, CollectorRegistry registry) throws IOException {
- this(addr, registry, false);
- }
-
- /**
- * Start a HTTP server serving the default Prometheus registry.
- */
- public HTTPServer(int port, boolean daemon) throws IOException {
- this(new InetSocketAddress(port), CollectorRegistry.defaultRegistry, daemon);
- }
-
- /**
- * Start a HTTP server serving the default Prometheus registry using non-daemon threads.
- */
- public HTTPServer(int port) throws IOException {
- this(port, false);
- }
-
- /**
- * Start a HTTP server serving the default Prometheus registry.
- */
- public HTTPServer(String host, int port, boolean daemon) throws IOException {
- this(new InetSocketAddress(host, port), CollectorRegistry.defaultRegistry, daemon);
- }
-
- /**
- * Start a HTTP server serving the default Prometheus registry using non-daemon threads.
- */
- public HTTPServer(String host, int port) throws IOException {
- this(new InetSocketAddress(host, port), CollectorRegistry.defaultRegistry, false);
- }
-
/**
* Start a HTTP server by making sure that its background thread inherit proper daemon flag.
*/
@@ -285,17 +179,12 @@ public class HTTPServer {
if (daemon == Thread.currentThread().isDaemon()) {
server.start();
} else {
- FutureTask<Void> startTask = new FutureTask<Void>(new Runnable() {
- @Override
- public void run() {
- server.start();
- }
- }, null);
+ FutureTask<Void> startTask = new FutureTask<>(server::start, null);
NamedDaemonThreadFactory.defaultThreadFactory(daemon).newThread(startTask).start();
try {
startTask.get();
} catch (ExecutionException e) {
- throw new RuntimeException("Unexpected exception on starting HTTPSever", e);
+ throw new IllegalStateException("Unexpected exception on starting HTTPSever", e);
} catch (InterruptedException e) {
// This is possible only if the current tread has been interrupted,
// but in real use cases this should not happen.
@@ -304,19 +193,5 @@ public class HTTPServer {
}
}
}
+}
- /**
- * Stop the HTTP server.
- */
- public void stop() {
- server.stop(0);
- executorService.shutdown(); // Free any (parked/idle) threads in pool
- }
-
- /**
- * Gets the port number.
- */
- public int getPort() {
- return server.getAddress().getPort();
- }
-}
\ No newline at end of file
diff --git a/ozhera-metrics-all/ozhera-metrics-sdk/src/main/java/org/apache/ozhera/metrics/api/Histogram.java b/ozhera-metrics-all/ozhera-metrics-sdk/src/main/java/org/apache/ozhera/metrics/api/Histogram.java
new file mode 100644
index 00000000..e228f5bd
--- /dev/null
+++ b/ozhera-metrics-all/ozhera-metrics-sdk/src/main/java/org/apache/ozhera/metrics/api/Histogram.java
@@ -0,0 +1,66 @@
+/*
+ * 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.ozhera.metrics.api;
+
+/**
+ * Histogram metric, to track distributions of events.
+ * <p>
+ * Example of uses for Histogram include:
+ * <ul>
+ * <li>Response latency</li>
+ * <li>Request size</li>
+ * </ul>
+ * <p>
+ * <em>Note:</em> Each bucket is one timeseries. Many buckets and/or many dimensions with labels
+ * can produce large amount of time series, that may cause performance problems.
+ *
+ * <p>
+ * The default buckets are intended to cover a typical web/rpc request from milliseconds to seconds.
+ * <p>
+ * Example Histogram:
+ * <pre>
+ * {@code
+ * class YourClass {
+ *
+ * void processRequest(Request req) {
+ * long startTime = System.currentTimeMillis();
+ * try {
+ * // Your code here.
+ * } finally {
+ * Metrics.histogram("requests_latency_seconds").observe(System.currentTimeMillis() - startTime);
+ * }
+ * }
+ * }
+ * }
+ * </pre>
+ * <p>
+ * You can choose your own buckets:
+ * <pre>
+ * {@code
+ * Metrics.histogram("requests_latency_seconds").buckets(new double[]{.01, .02, .03, .04});
+ * }
+ * </pre>
+ * offer easy ways to set common bucket patterns.
+ */
+public interface Histogram extends Meter<Histogram> {
+ /**
+ * Observe the given amount.
+ */
+ void observe(double amount);
+}
diff --git a/prometheus-starter-all/prometheus-diy-client/src/main/java/org/apache/ozhera/prometheus/all/client/XmHistogram.java b/ozhera-metrics-all/ozhera-metrics-sdk/src/main/java/org/apache/ozhera/metrics/api/Meter.java
similarity index 64%
copy from prometheus-starter-all/prometheus-diy-client/src/main/java/org/apache/ozhera/prometheus/all/client/XmHistogram.java
copy to ozhera-metrics-all/ozhera-metrics-sdk/src/main/java/org/apache/ozhera/metrics/api/Meter.java
index 0758dc09..48d0ffae 100644
--- a/prometheus-starter-all/prometheus-diy-client/src/main/java/org/apache/ozhera/prometheus/all/client/XmHistogram.java
+++ b/ozhera-metrics-all/ozhera-metrics-sdk/src/main/java/org/apache/ozhera/metrics/api/Meter.java
@@ -16,23 +16,23 @@
* specific language governing permissions and limitations
* under the License.
*/
+package org.apache.ozhera.metrics.api;
-package org.apache.ozhera.prometheus.all.client;
-/**
- * @author zhangxiaowei6
- */
-public interface XmHistogram {
+public interface Meter<T> {
/**
- * padding label value
- *
- * @param labelValues
- * @return XmHistogram
+ * tag the metrics
+ * @param name tag name
+ * @param value tag value
+ * @return the metrics
*/
- XmHistogram with(String... labelValues);
+ default T tag(String name, String value) {
+ return tags(name, value);
+ }
/**
- * Fill the data in the bucket
- * @param delta Increment
+ * tag the metrics
+ * @param tagNameValuePairs tag name and value pairs, Example: labels("method", "get", "path", "/user/info")
+ * @return the metrics
*/
- void observe(double delta,String... labelValue);
-}
\ No newline at end of file
+ T tags(String... tagNameValuePairs);
+}
diff --git a/ozhera-metrics-all/ozhera-metrics-sdk/src/main/java/org/apache/ozhera/metrics/api/Metrics.java b/ozhera-metrics-all/ozhera-metrics-sdk/src/main/java/org/apache/ozhera/metrics/api/Metrics.java
new file mode 100644
index 00000000..e4b15c3a
--- /dev/null
+++ b/ozhera-metrics-all/ozhera-metrics-sdk/src/main/java/org/apache/ozhera/metrics/api/Metrics.java
@@ -0,0 +1,129 @@
+/*
+ * 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.ozhera.metrics.api;
+
+import io.prometheus.client.CollectorRegistry;
+import lombok.extern.slf4j.Slf4j;
+import org.apache.commons.lang3.ArrayUtils;
+import org.apache.ozhera.metrics.config.HeraConfig;
+import org.apache.ozhera.metrics.config.SdkLoggerInitializer;
+import org.apache.ozhera.metrics.config.service.PrometheusService;
+
+import java.util.Arrays;
+import java.util.Map;
+
+import static org.apache.ozhera.metrics.api.MetricsContext.CUSTOM_DELIMITER;
+
+@Slf4j
+public class Metrics {
+
+ static final CollectorRegistry REGISTRY = new CollectorRegistry(true);
+ private static final MetricsFactory FACTORY = new PrometheusFactory(REGISTRY);
+
+ private static final org.slf4j.Logger LOGGER = SdkLoggerInitializer.getLogger();
+
+ private static final String[] COMMON_TAGS;
+
+ static final double[] DEFAULT_LATENCY_BUCKETS =
+ new double[]{.01, .05, 1, 5, 7.5, 10, 25, 50, 100, 200, 500, 1000, 1500, 2000, 3000, 4000, 5000};
+
+ static {
+ PrometheusService service = HeraConfig.registerNacos();
+ COMMON_TAGS = buildCommonTags(service.getCommonTags());
+ PrometheusExporter.startHttpServer(service.getPort(), REGISTRY);
+ }
+
+ private Metrics() {
+ }
+
+ private static String[] buildCommonTags(Map<String, String> tags) {
+ String[] ret = new String[tags.size() * 2];
+ int i = 0;
+ for (Map.Entry<String, String> kv : tags.entrySet()) {
+ ret[i] = kv.getKey();
+ ret[i + 1] = kv.getValue();
+ i += 2;
+ }
+ return ret;
+ }
+
+ public static CollectorRegistry getRegistry() {
+ return REGISTRY;
+ }
+
+ public static String[] getCommonTags() {
+ return COMMON_TAGS;
+ }
+
+ public static Counter counter(String name) {
+ return new XmCounter(FACTORY, name, COMMON_TAGS);
+ }
+
+ public static Counter counter(String name, String... tags) {
+ return new XmCounter(FACTORY, name, ArrayUtils.addAll(COMMON_TAGS, tags));
+ }
+
+ public static void counterWithLog(String name, MetricsContext context) {
+ LOGGER.info("{}" + CUSTOM_DELIMITER + "counter" + CUSTOM_DELIMITER + "{}", name, context.toJson());
+ }
+
+ public static Gauge gauge(String name) {
+ return new XmGauge(FACTORY, name, COMMON_TAGS);
+ }
+
+ public static Gauge gauge(String name, String... tags) {
+ return new XmGauge(FACTORY, name, ArrayUtils.addAll(COMMON_TAGS, tags));
+ }
+
+ public static void gaugeWithLog(String name, MetricsContext context) {
+ LOGGER.info("{}" + CUSTOM_DELIMITER + "gauge" + CUSTOM_DELIMITER + "{}", name, context.toJson());
+ }
+
+ public static Histogram histogram(String name) {
+ return histogram(name, DEFAULT_LATENCY_BUCKETS);
+ }
+
+ public static Histogram histogram(String name, double[] buckets) {
+ return new XmHistogram(FACTORY, name, buckets, COMMON_TAGS);
+ }
+
+ public static Histogram histogram(String name, double[] buckets, String... tags) {
+ return new XmHistogram(FACTORY, name, buckets, ArrayUtils.addAll(COMMON_TAGS, tags));
+ }
+
+ public static void histogramWithLog(String name, double[] buckets, MetricsContext context) {
+ String bucketStr = Arrays.toString(buckets == null ? new double[0] : buckets);
+ String ctxJson = context == null ? "{}" : context.toJson();
+ StringBuilder sb = new StringBuilder();
+ sb.append(name).append(CUSTOM_DELIMITER).append(bucketStr).append(CUSTOM_DELIMITER).append(ctxJson);
+ LOGGER.info(sb.toString());
+ }
+
+ public static Timer timer(String name) {
+ return timer(name, DEFAULT_LATENCY_BUCKETS);
+ }
+
+ public static Timer timer(String name, double[] buckets) {
+ return new XmTimer(FACTORY, name, buckets, COMMON_TAGS);
+ }
+
+ public static Timer timer(String name, double[] buckets, String... tags) {
+ return new XmTimer(FACTORY, name, buckets, ArrayUtils.addAll(COMMON_TAGS, tags));
+ }
+}
diff --git a/prometheus-starter-all/prometheus-diy-client/src/main/java/org/apache/ozhera/prometheus/all/client/XmGauge.java b/ozhera-metrics-all/ozhera-metrics-sdk/src/main/java/org/apache/ozhera/metrics/api/MetricsContext.java
similarity index 53%
rename from prometheus-starter-all/prometheus-diy-client/src/main/java/org/apache/ozhera/prometheus/all/client/XmGauge.java
rename to ozhera-metrics-all/ozhera-metrics-sdk/src/main/java/org/apache/ozhera/metrics/api/MetricsContext.java
index d6d40106..bc665db9 100644
--- a/prometheus-starter-all/prometheus-diy-client/src/main/java/org/apache/ozhera/prometheus/all/client/XmGauge.java
+++ b/ozhera-metrics-all/ozhera-metrics-sdk/src/main/java/org/apache/ozhera/metrics/api/MetricsContext.java
@@ -16,31 +16,39 @@
* specific language governing permissions and limitations
* under the License.
*/
+package org.apache.ozhera.metrics.api;
+
+import com.google.gson.Gson;
+import lombok.Getter;
+
+import java.util.HashMap;
+import java.util.Map;
-package org.apache.ozhera.prometheus.all.client;
/**
- * @author zhangxiaowei6
+ * @version 1.0
+ * @description
+ * @date 2025/5/13 16:56
*/
-public interface XmGauge {
- /**
- * padding label value
- *
- * @param labelValues
- * @return XMGauge
- */
- XmGauge with(String... labelValues);
-
- /**
- * Gauge
- *
- * @param delta Increment
- */
- void set(double delta,String... labelValue);
-
- /**
- * Gauge
- *
- * @param delta set Increment
- */
- void add(double delta,String... labelValue);
-}
\ No newline at end of file
+public class MetricsContext {
+
+ private Map<String, String> mapContent = new HashMap<>();
+ @Getter
+ private static final Gson gson = new Gson();
+
+ public static final String CUSTOM_DELIMITER = "#$@";
+
+ public MetricsContext() {
+ }
+
+ public void addContext(String key, String value) {
+ mapContent.put(key, value);
+ }
+
+ public String getContext(String key) {
+ return mapContent.get(key);
+ }
+
+ public String toJson() {
+ return gson.toJson(mapContent);
+ }
+}
diff --git a/prometheus-starter-all/prometheus-diy-client/src/main/java/org/apache/ozhera/prometheus/all/client/XmHistogram.java b/ozhera-metrics-all/ozhera-metrics-sdk/src/main/java/org/apache/ozhera/metrics/api/MetricsFactory.java
similarity index 64%
rename from prometheus-starter-all/prometheus-diy-client/src/main/java/org/apache/ozhera/prometheus/all/client/XmHistogram.java
rename to ozhera-metrics-all/ozhera-metrics-sdk/src/main/java/org/apache/ozhera/metrics/api/MetricsFactory.java
index 0758dc09..753c20e1 100644
--- a/prometheus-starter-all/prometheus-diy-client/src/main/java/org/apache/ozhera/prometheus/all/client/XmHistogram.java
+++ b/ozhera-metrics-all/ozhera-metrics-sdk/src/main/java/org/apache/ozhera/metrics/api/MetricsFactory.java
@@ -16,23 +16,15 @@
* specific language governing permissions and limitations
* under the License.
*/
+package org.apache.ozhera.metrics.api;
-package org.apache.ozhera.prometheus.all.client;
-/**
- * @author zhangxiaowei6
- */
-public interface XmHistogram {
- /**
- * padding label value
- *
- * @param labelValues
- * @return XmHistogram
- */
- XmHistogram with(String... labelValues);
+interface MetricsFactory {
+
+ XmCounter.Child counter(String name, String[] labelNames, String[] labelValues);
+
+ XmGauge.Child gauge(String name, String[] labelNames, String[] labelValues);
+
+ XmHistogram.Child histogram(String name, String[] labelNames, String[] labelValues, double[] buckets);
- /**
- * Fill the data in the bucket
- * @param delta Increment
- */
- void observe(double delta,String... labelValue);
-}
\ No newline at end of file
+ XmTimer.Child timer(String name, String[] labelNames, String[] labelValues, double[] buckets);
+}
diff --git a/ozhera-metrics-all/ozhera-metrics-sdk/src/main/java/org/apache/ozhera/metrics/api/PrometheusExporter.java b/ozhera-metrics-all/ozhera-metrics-sdk/src/main/java/org/apache/ozhera/metrics/api/PrometheusExporter.java
new file mode 100644
index 00000000..4c42cecb
--- /dev/null
+++ b/ozhera-metrics-all/ozhera-metrics-sdk/src/main/java/org/apache/ozhera/metrics/api/PrometheusExporter.java
@@ -0,0 +1,47 @@
+/*
+ * 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.ozhera.metrics.api;
+
+import com.sun.net.httpserver.HttpServer;
+import io.prometheus.client.CollectorRegistry;
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
+
+import java.io.IOException;
+import java.net.InetSocketAddress;
+
+class PrometheusExporter {
+ private static final Logger LOG = LoggerFactory.getLogger(PrometheusExporter.class);
+
+ private PrometheusExporter() {
+ }
+
+ static void startHttpServer(int port, CollectorRegistry registry) {
+ new Thread(() -> {
+ LOG.info("start prometheus exporter");
+ try {
+ LOG.info("prometheus port: {}", port);
+ InetSocketAddress addr = new InetSocketAddress(port);
+ new HTTPServer(HttpServer.create(addr, 3), registry, true);
+ } catch (IOException e) {
+ LOG.error("start prometheus exporter error", e);
+ }
+ }).start();
+ }
+}
diff --git a/ozhera-metrics-all/ozhera-metrics-sdk/src/main/java/org/apache/ozhera/metrics/api/PrometheusFactory.java b/ozhera-metrics-all/ozhera-metrics-sdk/src/main/java/org/apache/ozhera/metrics/api/PrometheusFactory.java
new file mode 100644
index 00000000..2cddef78
--- /dev/null
+++ b/ozhera-metrics-all/ozhera-metrics-sdk/src/main/java/org/apache/ozhera/metrics/api/PrometheusFactory.java
@@ -0,0 +1,181 @@
+/*
+ * 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.ozhera.metrics.api;
+
+import io.prometheus.client.Collector;
+import io.prometheus.client.CollectorRegistry;
+import io.prometheus.client.Counter;
+import io.prometheus.client.Gauge;
+import io.prometheus.client.Histogram;
+import io.prometheus.client.SimpleCollector;
+import io.prometheus.client.Summary;
+
+import java.util.Arrays;
+import java.util.Objects;
+import java.util.concurrent.ConcurrentHashMap;
+import java.util.concurrent.ConcurrentMap;
+
+class PrometheusFactory implements MetricsFactory {
+ private final ConcurrentMap<ParentKey, SimpleCollector<?>> parentMap = new ConcurrentHashMap<>();
+
+ private final ConcurrentMap<ChildKey, XmMetricChild<?>> childMap = new ConcurrentHashMap<>();
+
+ private final CollectorRegistry prometheus;
+
+ PrometheusFactory(CollectorRegistry prometheus) {
+ this.prometheus = prometheus;
+ }
+
+ public XmCounter.Child counter(String name, String[] labelNames, String[] labelValues) {
+ ChildKey key = new ChildKey(XmMeterType.COUNTER, name, labelNames, labelValues);
+ return (XmCounter.Child) childMap.computeIfAbsent(key, this::createChild);
+ }
+
+ public XmGauge.Child gauge(String name, String[] labelNames, String[] labelValues) {
+ ChildKey key = new ChildKey(XmMeterType.GAUGE, name, labelNames, labelValues);
+ return (XmGauge.Child) childMap.computeIfAbsent(key, this::createChild);
+ }
+
+ public XmHistogram.Child histogram(String name, String[] labelNames, String[] labelValues, double[] buckets) {
+ ChildKey key = new ChildKey(XmMeterType.HISTOGRAM, name, labelNames, labelValues, buckets);
+ return (XmHistogram.Child) childMap.computeIfAbsent(key, this::createChild);
+ }
+
+ public XmTimer.Child timer(String name, String[] labelNames, String[] labelValues, double[] buckets) {
+ ChildKey key = new ChildKey(XmMeterType.TIMER, name, labelNames, labelValues, buckets);
+ return (XmTimer.Child) childMap.computeIfAbsent(key, this::createChild);
+ }
+
+ @SuppressWarnings("unchecked")
+ private <C> SimpleCollector<C> getParent(Collector.Type type, String name, String[] labelNames, double[] buckets) {
+ ParentKey key = new ParentKey(type, name, labelNames, buckets);
+ return (SimpleCollector<C>) parentMap.computeIfAbsent(key, this::createParent);
+ }
+
+ private SimpleCollector<?> createParent(ParentKey key) {
+ switch (key.type) {
+ case COUNTER:
+ return Counter.build().help(key.name).name(key.name).labelNames(key.labelNames).register(prometheus);
+ case GAUGE:
+ return Gauge.build().help(key.name).name(key.name).labelNames(key.labelNames).register(prometheus);
+ case HISTOGRAM:
+ return Histogram.build().help(key.name).name(key.name).buckets(key.buckets).labelNames(key.labelNames).register(prometheus);
+ case SUMMARY:
+ return Summary.build().help(key.name).name(key.name).labelNames(key.labelNames).register(prometheus);
+ default:
+ throw new IllegalArgumentException("Unsupported parent type: " + key.type);
+ }
+ }
+
+ private XmMetricChild<?> createChild(ChildKey key) {
+ switch (key.type) {
+ case COUNTER:
+ Counter.Child counterChild = this.<Counter.Child>getParent(Collector.Type.COUNTER, key.name, key.labelNames, null).labels(key.labelValues);
+ return new XmCounter.Child(counterChild);
+ case GAUGE:
+ Gauge.Child gaugeChild = this.<Gauge.Child>getParent(Collector.Type.GAUGE, key.name, key.labelNames, null).labels(key.labelValues);
+ return new XmGauge.Child(gaugeChild);
+ case HISTOGRAM:
+ Histogram.Child histogramChild = this.<Histogram.Child>getParent(Collector.Type.HISTOGRAM, key.name, key.labelNames, key.buckets).labels(key.labelValues);
+ return new XmHistogram.Child(histogramChild);
+ case TIMER:
+ Histogram.Child timerChild = this.<Histogram.Child>getParent(Collector.Type.HISTOGRAM, key.name, key.labelNames, key.buckets).labels(key.labelValues);
+ return new XmTimer.Child(timerChild);
+ default:
+ throw new IllegalArgumentException("Unsupported child type: " + key.type);
+ }
+ }
+
+ private static class ParentKey {
+ private final Collector.Type type;
+ private final String name;
+ private final String[] labelNames;
+ private final double[] buckets;
+
+ ParentKey(Collector.Type type, String name, String[] labelNames, double[] buckets) {
+ this.type = type;
+ this.name = name;
+ this.labelNames = labelNames;
+ this.buckets = buckets;
+ }
+
+ @Override
+ public boolean equals(Object o) {
+ if (this == o) {
+ return true;
+ }
+ if (o == null || getClass() != o.getClass()) {
+ return false;
+ }
+ ParentKey mapKey = (ParentKey) o;
+ return type == mapKey.type && name.equals(mapKey.name) && Arrays.equals(labelNames, mapKey.labelNames);
+ }
+
+ @Override
+ public int hashCode() {
+ int result = Objects.hash(type, name);
+ result = 31 * result + Arrays.hashCode(labelNames);
+ return result;
+ }
+ }
+
+ private static class ChildKey {
+ private final XmMeterType type;
+ private final String name;
+ private final String[] labelNames;
+ private final String[] labelValues;
+ private final double[] buckets;
+
+ ChildKey(XmMeterType type, String name, String[] labelNames, String[] labelValues) {
+ this.type = type;
+ this.name = name;
+ this.labelNames = labelNames;
+ this.labelValues = labelValues;
+ this.buckets = Metrics.DEFAULT_LATENCY_BUCKETS;
+ }
+
+ ChildKey(XmMeterType type, String name, String[] labelNames, String[] labelValues, double[] buckets) {
+ this.type = type;
+ this.name = name;
+ this.labelNames = labelNames;
+ this.labelValues = labelValues;
+ this.buckets = buckets;
+ }
+
+ @Override
+ public boolean equals(Object o) {
+ if (this == o) {
+ return true;
+ }
+ if (o == null || getClass() != o.getClass()) {
+ return false;
+ }
+ ChildKey childKey = (ChildKey) o;
+ return type == childKey.type && name.equals(childKey.name) && Arrays.equals(labelNames, childKey.labelNames) && Arrays.equals(labelValues, childKey.labelValues);
+ }
+
+ @Override
+ public int hashCode() {
+ int result = Objects.hash(type, name);
+ result = 31 * result + Arrays.hashCode(labelNames);
+ result = 31 * result + Arrays.hashCode(labelValues);
+ return result;
+ }
+ }
+}
diff --git a/ozhera-metrics-all/ozhera-metrics-sdk/src/main/java/org/apache/ozhera/metrics/api/Timer.java b/ozhera-metrics-all/ozhera-metrics-sdk/src/main/java/org/apache/ozhera/metrics/api/Timer.java
new file mode 100644
index 00000000..92411976
--- /dev/null
+++ b/ozhera-metrics-all/ozhera-metrics-sdk/src/main/java/org/apache/ozhera/metrics/api/Timer.java
@@ -0,0 +1,87 @@
+/*
+ * 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.ozhera.metrics.api;
+
+import java.util.concurrent.Callable;
+
+/**
+ * Timer metric, to track distributions of events.
+ *
+ * <p>Example of uses for Timer include:
+ *
+ * <ul>
+ * <li>Request process duration
+ * </ul>
+ *
+ * <p><em>Note:</em> Each bucket is one timeseries. Many buckets and/or many dimensions with labels
+ * can produce large amount of time series, that may cause performance problems.
+ *
+ * <p>The default buckets are intended to cover a typical web/rpc request from milliseconds to
+ * seconds.
+ *
+ * <p>Example Timer:
+ *
+ * <pre>{@code
+ * class YourClass {
+ *
+ * void processRequest(Request req) {
+ * Timer.InnerTimer timer = Metrics.timer("requests_process_duration_seconds").startTimer();
+ * try {
+ * // Your code here.
+ * } finally {
+ * timer.endTimer();
+ * }
+ * }
+ *
+ * void recordDurationOfRunnable(Request req) {
+ * Metrics.timer("record_runnable_duration_seconds").record(() -> {
+ * // Your code here.
+ * });
+ * }
+ * }
+ * }</pre>
+ *
+ * <p>You can choose your own buckets:
+ *
+ * <pre>{@code
+ * Metrics.timer("requests_process_duration_seconds").buckets(new double[]{.01, .02, .03, .04});
+ * }</pre>
+ *
+ * offer easy ways to set common bucket patterns.
+ */
+public interface Timer extends Meter<Timer> {
+ /**
+ * Start timer
+ */
+ InnerTimer startTimer();
+
+ interface InnerTimer {
+ /**
+ * end timer
+ * @return duration
+ */
+ double endTimer();
+ }
+
+ void record(double duration);
+
+ double record(Runnable runnable);
+
+ <E> E record(Callable<E> callable);
+}
diff --git a/ozhera-metrics-all/ozhera-metrics-sdk/src/main/java/org/apache/ozhera/metrics/api/XmCounter.java b/ozhera-metrics-all/ozhera-metrics-sdk/src/main/java/org/apache/ozhera/metrics/api/XmCounter.java
new file mode 100644
index 00000000..196dde5e
--- /dev/null
+++ b/ozhera-metrics-all/ozhera-metrics-sdk/src/main/java/org/apache/ozhera/metrics/api/XmCounter.java
@@ -0,0 +1,62 @@
+/*
+ * 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.ozhera.metrics.api;
+
+class XmCounter extends XmMeter<XmCounter.Child> implements Counter {
+
+ XmCounter(MetricsFactory factory, String name, String... labels) {
+ super(factory, name, labels);
+ }
+
+ XmCounter(XmCounter base, String... labels) {
+ super(base, labels);
+ }
+
+ public XmCounter tags(String... labels) {
+ return new XmCounter(this, labels);
+ }
+
+ @Override
+ protected Child create() {
+ return factory().counter(name(), labelNames(), labelValues());
+ }
+
+ public void inc() {
+ child().inc(1);
+ }
+
+ public void inc(double amount) {
+ child().inc(amount);
+ }
+
+ static class Child extends XmMetricChild<io.prometheus.client.Counter.Child> {
+
+ Child(io.prometheus.client.Counter.Child child) {
+ super(child);
+ }
+
+ public void inc() {
+ innerChild.inc(1);
+ }
+
+ public void inc(double amount) {
+ innerChild.inc(amount);
+ }
+ }
+}
diff --git a/ozhera-metrics-all/ozhera-metrics-sdk/src/main/java/org/apache/ozhera/metrics/api/XmGauge.java b/ozhera-metrics-all/ozhera-metrics-sdk/src/main/java/org/apache/ozhera/metrics/api/XmGauge.java
new file mode 100644
index 00000000..ecd71d74
--- /dev/null
+++ b/ozhera-metrics-all/ozhera-metrics-sdk/src/main/java/org/apache/ozhera/metrics/api/XmGauge.java
@@ -0,0 +1,61 @@
+/*
+ * 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.ozhera.metrics.api;
+
+class XmGauge extends XmMeter<XmGauge.Child> implements Gauge {
+ XmGauge(MetricsFactory factory, String name, String[] labels) {
+ super(factory, name, labels);
+ }
+
+ XmGauge(XmGauge base, String... labels) {
+ super(base, labels);
+ }
+
+ public XmGauge tags(String... labels) {
+ return new XmGauge(this, labels);
+ }
+
+ @Override
+ protected Child create() {
+ return factory().gauge(name(), labelNames(), labelValues());
+ }
+
+ public void set(double value) {
+ child().set(value);
+ }
+
+ public void inc(double delta) {
+ child().inc(delta);
+ }
+
+ static class Child extends XmMetricChild<io.prometheus.client.Gauge.Child> {
+
+ Child(io.prometheus.client.Gauge.Child child) {
+ super(child);
+ }
+
+ public void set(double value) {
+ innerChild.set(value);
+ }
+
+ public void inc(double delta) {
+ innerChild.inc(delta);
+ }
+ }
+}
diff --git a/ozhera-metrics-all/ozhera-metrics-sdk/src/main/java/org/apache/ozhera/metrics/api/XmHistogram.java b/ozhera-metrics-all/ozhera-metrics-sdk/src/main/java/org/apache/ozhera/metrics/api/XmHistogram.java
new file mode 100644
index 00000000..c71f8e57
--- /dev/null
+++ b/ozhera-metrics-all/ozhera-metrics-sdk/src/main/java/org/apache/ozhera/metrics/api/XmHistogram.java
@@ -0,0 +1,64 @@
+/*
+ * 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.ozhera.metrics.api;
+
+class XmHistogram extends XmMeter<XmHistogram.Child> implements Histogram {
+ private final double[] buckets;
+
+ XmHistogram(MetricsFactory factory, String name, double[] buckets, String... labels) {
+ super(factory, name, labels);
+ this.buckets = buckets;
+ }
+
+ XmHistogram(XmHistogram base, String... labels) {
+ super(base, labels);
+ this.buckets = base.buckets;
+ }
+
+ XmHistogram(XmHistogram base, double[] buckets) {
+ this(base.factory(), base.name(), buckets);
+ }
+
+ public XmHistogram buckets(double[] buckets) {
+ return new XmHistogram(this, buckets);
+ }
+
+ public XmHistogram tags(String... labels) {
+ return new XmHistogram(this, labels);
+ }
+
+ protected Child create() {
+ return factory().histogram(name(), labelNames(), labelValues(), buckets);
+ }
+
+ public void observe(double value) {
+ child().observe(value);
+ }
+
+ static class Child extends XmMetricChild<io.prometheus.client.Histogram.Child> {
+
+ Child(io.prometheus.client.Histogram.Child child) {
+ super(child);
+ }
+
+ public void observe(double value) {
+ innerChild.observe(value);
+ }
+ }
+}
diff --git a/ozhera-metrics-all/ozhera-metrics-sdk/src/main/java/org/apache/ozhera/metrics/api/XmMeter.java b/ozhera-metrics-all/ozhera-metrics-sdk/src/main/java/org/apache/ozhera/metrics/api/XmMeter.java
new file mode 100644
index 00000000..3a128541
--- /dev/null
+++ b/ozhera-metrics-all/ozhera-metrics-sdk/src/main/java/org/apache/ozhera/metrics/api/XmMeter.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.ozhera.metrics.api;
+
+import org.apache.commons.lang3.Validate;
+
+abstract class XmMeter<CHILD> {
+ private final XmMeter<CHILD> base;
+ private final MetricsFactory factory;
+ private final String name;
+ private final String[] labels;
+ private volatile String[][] labelStore;
+
+ private volatile CHILD child;
+
+ protected XmMeter(MetricsFactory factory, String name, String[] labels) {
+ this(null, factory, name, labels);
+ }
+
+ private XmMeter(XmMeter<CHILD> base, MetricsFactory factory, String name, String... labels) {
+ this.base = base;
+ this.factory = factory;
+ this.name = name;
+ this.labels = labels;
+ Validate.isTrue((labels.length & 1) == 0);
+ }
+
+ protected XmMeter(XmMeter<CHILD> base, String... labels) {
+ this(base, base.factory, base.name, labels);
+ Validate.isTrue((labels.length & 1) == 0);
+ }
+
+ protected abstract CHILD create();
+
+ protected CHILD child() {
+ if (child == null) {
+ synchronized (this) {
+ if (child == null) {
+ child = create();
+ }
+ }
+ }
+ return child;
+ }
+
+ protected MetricsFactory factory() {
+ return factory;
+ }
+
+ protected String name() {
+ return name;
+ }
+
+ protected String[] labelNames() {
+ return labelStore()[0];
+ }
+
+ protected String[] labelValues() {
+ return labelStore()[1];
+ }
+
+ String[][] labelStore() {
+ if (labelStore == null) {
+ synchronized (this) {
+ if (labelStore == null) {
+ labelStore = buildLabelStore();
+ }
+ }
+ }
+ return labelStore;
+ }
+
+ String[][] buildLabelStore() {
+ int len = labels.length;
+ XmMeter<CHILD> node = base;
+ while (node != null) {
+ len += node.labels.length;
+ node = node.base;
+ }
+ len >>= 1;
+
+ String[][] ret = new String[2][len];
+ int half = (labels.length >> 1);
+ int pos = len - half;
+ shiftCopy(labels, ret, pos);
+ node = base;
+ while (pos > 0) {
+ half = (node.labels.length >> 1);
+ pos -= half;
+ shiftCopy(node.labels, ret, pos);
+ node = node.base;
+ }
+ return ret;
+ }
+
+ void shiftCopy(String[] src, String[][] dest, int destOffset) {
+ for (int in = 0, out = destOffset; in < src.length; in += 2, ++out) {
+ dest[0][out] = src[in];
+ dest[1][out] = src[in + 1];
+ }
+ }
+}
diff --git a/prometheus-starter-all/prometheus-diy-client/src/main/java/org/apache/ozhera/prometheus/all/client/XmCounter.java b/ozhera-metrics-all/ozhera-metrics-sdk/src/main/java/org/apache/ozhera/metrics/api/XmMeterType.java
similarity index 63%
rename from prometheus-starter-all/prometheus-diy-client/src/main/java/org/apache/ozhera/prometheus/all/client/XmCounter.java
rename to ozhera-metrics-all/ozhera-metrics-sdk/src/main/java/org/apache/ozhera/metrics/api/XmMeterType.java
index fc1bad16..9e4dc9e8 100644
--- a/prometheus-starter-all/prometheus-diy-client/src/main/java/org/apache/ozhera/prometheus/all/client/XmCounter.java
+++ b/ozhera-metrics-all/ozhera-metrics-sdk/src/main/java/org/apache/ozhera/metrics/api/XmMeterType.java
@@ -16,24 +16,24 @@
* specific language governing permissions and limitations
* under the License.
*/
+package org.apache.ozhera.metrics.api;
-package org.apache.ozhera.prometheus.all.client;
-/**
- * @author zhangxiaowei6
- */
-public interface XmCounter {
- /**
- * padding label value
- *
- * @param labelValues
- * @return XMCounter
- */
- XmCounter with(String... labelValues);
+import io.prometheus.client.Collector;
+
+enum XmMeterType {
+ UNKNOWN(Collector.Type.UNKNOWN),
+ COUNTER(Collector.Type.COUNTER),
+ GAUGE(Collector.Type.GAUGE),
+ HISTOGRAM(Collector.Type.HISTOGRAM),
+ TIMER(Collector.Type.HISTOGRAM);
+
+ private final Collector.Type type;
+
+ XmMeterType(Collector.Type type) {
+ this.type = type;
+ }
- /**
- * Counter Increment
- *
- * @param delta
- */
- void add(double delta,String... labelValues);
-}
\ No newline at end of file
+ public Collector.Type getType() {
+ return type;
+ }
+}
diff --git a/prometheus-starter-all/prometheus-diy-starter/src/main/java/org/apache/ozhera/prometheus/starter/all/service/PrometheusService.java b/ozhera-metrics-all/ozhera-metrics-sdk/src/main/java/org/apache/ozhera/metrics/api/XmMetricChild.java
similarity index 68%
rename from prometheus-starter-all/prometheus-diy-starter/src/main/java/org/apache/ozhera/prometheus/starter/all/service/PrometheusService.java
rename to ozhera-metrics-all/ozhera-metrics-sdk/src/main/java/org/apache/ozhera/metrics/api/XmMetricChild.java
index e0514a78..dbbe6b9e 100644
--- a/prometheus-starter-all/prometheus-diy-starter/src/main/java/org/apache/ozhera/prometheus/starter/all/service/PrometheusService.java
+++ b/ozhera-metrics-all/ozhera-metrics-sdk/src/main/java/org/apache/ozhera/metrics/api/XmMetricChild.java
@@ -16,18 +16,12 @@
* specific language governing permissions and limitations
* under the License.
*/
+package org.apache.ozhera.metrics.api;
-package org.apache.ozhera.prometheus.starter.all.service;
+abstract class XmMetricChild<INNER_CHILD> {
+ protected INNER_CHILD innerChild;
-public abstract class PrometheusService {
-
- protected static final String DEFAULT_SERVICE_NAME = "default_service_name";
-
- protected static final String DEFAULT_PORT = "5555";
-
- public abstract String getServiceName();
-
- public abstract String getServerIp();
-
- public abstract String getPort();
-}
\ No newline at end of file
+ protected XmMetricChild(INNER_CHILD innerChild) {
+ this.innerChild = innerChild;
+ }
+}
diff --git a/ozhera-metrics-all/ozhera-metrics-sdk/src/main/java/org/apache/ozhera/metrics/api/XmTimer.java b/ozhera-metrics-all/ozhera-metrics-sdk/src/main/java/org/apache/ozhera/metrics/api/XmTimer.java
new file mode 100644
index 00000000..56f09540
--- /dev/null
+++ b/ozhera-metrics-all/ozhera-metrics-sdk/src/main/java/org/apache/ozhera/metrics/api/XmTimer.java
@@ -0,0 +1,105 @@
+/*
+ * 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.ozhera.metrics.api;
+
+import io.prometheus.client.Histogram;
+
+import java.util.concurrent.Callable;
+
+class XmTimer extends XmMeter<XmTimer.Child> implements Timer {
+ private final double[] buckets;
+
+ XmTimer(MetricsFactory factory, String name, double[] buckets, String... labels) {
+ super(factory, name, labels);
+ this.buckets = buckets;
+ }
+
+ XmTimer(XmTimer base, String... labels) {
+ super(base, labels);
+ this.buckets = base.buckets;
+ }
+
+ XmTimer(XmTimer base, double[] buckets) {
+ this(base.factory(), base.name(), buckets);
+ }
+
+ public XmTimer buckets(double[] buckets) {
+ return new XmTimer(this, buckets);
+ }
+
+ public XmTimer tags(String... labels) {
+ return new XmTimer(this, labels);
+ }
+
+ protected Child create() {
+ return factory().timer(name(), labelNames(), labelValues(), buckets);
+ }
+
+ public InnerTimer startTimer() {
+ return child().startTimer();
+ }
+
+ public void record(double duration) {
+ child().record(duration);
+ }
+
+ public double record(Runnable runnable) {
+ return child().record(runnable);
+ }
+
+ public <E> E record(Callable<E> callable) {
+ return child().record(callable);
+ }
+
+ static class Child extends XmMetricChild<Histogram.Child> {
+
+ Child(Histogram.Child child) {
+ super(child);
+ }
+
+ public InnerTimer startTimer() {
+ return new Timer(innerChild.startTimer());
+ }
+
+ public void record(double duration) {
+ innerChild.observe(duration);
+ }
+
+ public double record(Runnable runnable) {
+ return innerChild.time(runnable);
+ }
+
+ public <E> E record(Callable<E> callable) {
+ return innerChild.time(callable);
+ }
+ }
+
+ static class Timer implements InnerTimer {
+
+ private final Histogram.Timer timer;
+
+ Timer(Histogram.Timer timer) {
+ this.timer = timer;
+ }
+
+ public double endTimer() {
+ return timer.observeDuration();
+ }
+ }
+}
diff --git a/prometheus-starter-all/prometheus-diy-client/src/main/java/org/apache/ozhera/prometheus/all/client/binder/ClassLoaderMetricsReduced.java b/ozhera-metrics-all/ozhera-metrics-sdk/src/main/java/org/apache/ozhera/metrics/api/binder/ClassLoaderMetricsReduced.java
similarity index 97%
rename from prometheus-starter-all/prometheus-diy-client/src/main/java/org/apache/ozhera/prometheus/all/client/binder/ClassLoaderMetricsReduced.java
rename to ozhera-metrics-all/ozhera-metrics-sdk/src/main/java/org/apache/ozhera/metrics/api/binder/ClassLoaderMetricsReduced.java
index c01b5c65..6f3f6c6d 100644
--- a/prometheus-starter-all/prometheus-diy-client/src/main/java/org/apache/ozhera/prometheus/all/client/binder/ClassLoaderMetricsReduced.java
+++ b/ozhera-metrics-all/ozhera-metrics-sdk/src/main/java/org/apache/ozhera/metrics/api/binder/ClassLoaderMetricsReduced.java
@@ -17,7 +17,7 @@
* under the License.
*/
-package org.apache.ozhera.prometheus.all.client.binder;
+package org.apache.ozhera.metrics.api.binder;
import io.micrometer.core.instrument.Gauge;
import io.micrometer.core.instrument.MeterRegistry;
diff --git a/prometheus-starter-all/prometheus-diy-client/src/main/java/org/apache/ozhera/prometheus/all/client/binder/JvmGcMetricsReduced.java b/ozhera-metrics-all/ozhera-metrics-sdk/src/main/java/org/apache/ozhera/metrics/api/binder/JvmGcMetricsReduced.java
similarity index 99%
rename from prometheus-starter-all/prometheus-diy-client/src/main/java/org/apache/ozhera/prometheus/all/client/binder/JvmGcMetricsReduced.java
rename to ozhera-metrics-all/ozhera-metrics-sdk/src/main/java/org/apache/ozhera/metrics/api/binder/JvmGcMetricsReduced.java
index 562f6d40..f6f246c0 100644
--- a/prometheus-starter-all/prometheus-diy-client/src/main/java/org/apache/ozhera/prometheus/all/client/binder/JvmGcMetricsReduced.java
+++ b/ozhera-metrics-all/ozhera-metrics-sdk/src/main/java/org/apache/ozhera/metrics/api/binder/JvmGcMetricsReduced.java
@@ -17,7 +17,7 @@
* under the License.
*/
-package org.apache.ozhera.prometheus.all.client.binder;
+package org.apache.ozhera.metrics.api.binder;
import com.sun.management.GarbageCollectionNotificationInfo;
import com.sun.management.GcInfo;
diff --git a/prometheus-starter-all/prometheus-diy-client/src/main/java/org/apache/ozhera/prometheus/all/client/binder/JvmMemoryMetricsReduced.java b/ozhera-metrics-all/ozhera-metrics-sdk/src/main/java/org/apache/ozhera/metrics/api/binder/JvmMemoryMetricsReduced.java
similarity index 98%
rename from prometheus-starter-all/prometheus-diy-client/src/main/java/org/apache/ozhera/prometheus/all/client/binder/JvmMemoryMetricsReduced.java
rename to ozhera-metrics-all/ozhera-metrics-sdk/src/main/java/org/apache/ozhera/metrics/api/binder/JvmMemoryMetricsReduced.java
index 60a49f85..822f00bb 100644
--- a/prometheus-starter-all/prometheus-diy-client/src/main/java/org/apache/ozhera/prometheus/all/client/binder/JvmMemoryMetricsReduced.java
+++ b/ozhera-metrics-all/ozhera-metrics-sdk/src/main/java/org/apache/ozhera/metrics/api/binder/JvmMemoryMetricsReduced.java
@@ -17,7 +17,7 @@
* under the License.
*/
-package org.apache.ozhera.prometheus.all.client.binder;
+package org.apache.ozhera.metrics.api.binder;
import io.micrometer.core.instrument.Gauge;
import io.micrometer.core.instrument.MeterRegistry;
diff --git a/prometheus-starter-all/prometheus-diy-client/src/main/java/org/apache/ozhera/prometheus/all/client/binder/JvmThreadMetricsReduced.java b/ozhera-metrics-all/ozhera-metrics-sdk/src/main/java/org/apache/ozhera/metrics/api/binder/JvmThreadMetricsReduced.java
similarity index 97%
rename from prometheus-starter-all/prometheus-diy-client/src/main/java/org/apache/ozhera/prometheus/all/client/binder/JvmThreadMetricsReduced.java
rename to ozhera-metrics-all/ozhera-metrics-sdk/src/main/java/org/apache/ozhera/metrics/api/binder/JvmThreadMetricsReduced.java
index 05543355..ddbda594 100644
--- a/prometheus-starter-all/prometheus-diy-client/src/main/java/org/apache/ozhera/prometheus/all/client/binder/JvmThreadMetricsReduced.java
+++ b/ozhera-metrics-all/ozhera-metrics-sdk/src/main/java/org/apache/ozhera/metrics/api/binder/JvmThreadMetricsReduced.java
@@ -17,7 +17,7 @@
* under the License.
*/
-package org.apache.ozhera.prometheus.all.client.binder;
+package org.apache.ozhera.metrics.api.binder;
import io.micrometer.core.instrument.Gauge;
import io.micrometer.core.instrument.MeterRegistry;
diff --git a/prometheus-starter-all/prometheus-diy-starter/src/main/resources/META-INF/LICENSE.txt b/ozhera-metrics-all/ozhera-metrics-sdk/src/main/resources/META-INF/LICENSE.txt
similarity index 100%
rename from prometheus-starter-all/prometheus-diy-starter/src/main/resources/META-INF/LICENSE.txt
rename to ozhera-metrics-all/ozhera-metrics-sdk/src/main/resources/META-INF/LICENSE.txt
diff --git a/ozhera-metrics-all/ozhera-metrics-sdk/src/test/java/org/apache/ozhera/prometheus/all/client/OzHeraMetricsTest.java b/ozhera-metrics-all/ozhera-metrics-sdk/src/test/java/org/apache/ozhera/prometheus/all/client/OzHeraMetricsTest.java
new file mode 100644
index 00000000..4f96ecdf
--- /dev/null
+++ b/ozhera-metrics-all/ozhera-metrics-sdk/src/test/java/org/apache/ozhera/prometheus/all/client/OzHeraMetricsTest.java
@@ -0,0 +1,223 @@
+/*
+ * 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.ozhera.prometheus.all.client;
+
+import org.apache.ozhera.metrics.api.BusinessMetrics;
+import org.apache.ozhera.metrics.api.Metrics;
+import org.junit.Before;
+import org.junit.Test;
+
+import java.util.HashMap;
+import java.util.Map;
+import java.util.stream.IntStream;
+
+/**
+ * Metrics unit test class
+ * Test functionality of the new Metrics API
+ */
+public class OzHeraMetricsTest {
+
+ @Before
+ public void setUp() throws Exception {
+ // New version Metrics uses static methods, no need to initialize singleton
+ // Metrics class has completed initialization work in static code block
+ System.out.println("Metrics test environment setup completed");
+ }
+
+ /**
+ * Test Counter metric
+ * Counter is used for cumulative counting, can only increase but not decrease
+ */
+ @Test
+ public void testCounter() {
+ IntStream.range(0, 100).forEach(i -> {
+ // Test basic Counter - with single tag
+ Metrics.counter("testCounter")
+ .tag("name", "zxw") // Use tag method to set label
+ .inc(1); // Increment count
+
+ // Test multi-tag Counter
+ Metrics.counter("testCounter2")
+ .tag("age", "18")
+ .tag("city", "beijing")
+ .inc(1);
+ });
+ }
+
+ /**
+ * Test Gauge metric
+ * Gauge is used to measure instantaneous values, can increase or decrease arbitrarily
+ */
+ @Test
+ public void testGauge() {
+ IntStream.range(0, 100).forEach(i -> {
+ // Test basic Gauge
+ Metrics.gauge("testGauge")
+ .tag("name", "zxw")
+ .set(128); // Set current value
+ });
+ }
+
+ /**
+ * Test Histogram metric
+ * Histogram is used to measure distributions, such as response time distribution
+ */
+ @Test
+ public void testHistogram() {
+ IntStream.range(0, 100).forEach(i -> {
+ // Histogram using default buckets
+ Metrics.histogram("testHistogramWithDefaultBucket")
+ .tag("name", "zxw")
+ .observe(12); // Record observation value
+
+ // Histogram using custom buckets
+ double[] customBuckets = {.01, .05, 0.7, 5, 10, 50, 100, 200};
+ Metrics.histogram("testHistogramWithDiyBucket", customBuckets)
+ .tag("name", "zxw")
+ .observe(12);
+ });
+ }
+
+ /**
+ * Test Timer metric
+ * Timer is used to measure duration
+ */
+ @Test
+ public void testTimer() {
+ IntStream.range(0, 10).forEach(i -> {
+ // Test timer functionality
+ var timer = Metrics.timer("testTimer")
+ .tag("operation", "test")
+ .startTimer();
+
+ try {
+ // Simulate some processing time
+ Thread.sleep(10);
+ } catch (InterruptedException e) {
+ Thread.currentThread().interrupt();
+ } finally {
+ // End timing
+ timer.endTimer();
+ }
+
+ // Test directly recording time
+ Metrics.timer("testTimerRecord")
+ .tag("operation", "direct")
+ .record(0.1); // Record 100ms
+
+ // Test using Runnable approach
+ Metrics.timer("testTimerRunnable")
+ .tag("operation", "runnable")
+ .record(() -> {
+ try {
+ Thread.sleep(5);
+ } catch (InterruptedException e) {
+ Thread.currentThread().interrupt();
+ }
+ });
+ });
+ }
+
+ /**
+ * Test chained operations and multiple tags
+ */
+ @Test
+ public void testChainedOperations() {
+ // Test chained tag setting
+ Metrics.counter("chainedCounter")
+ .tag("service", "order-service")
+ .tag("method", "POST")
+ .tag("endpoint", "/api/orders")
+ .inc(1);
+
+ // Test using tags method to set multiple tags in batch
+ Metrics.gauge("batchTagsGauge")
+ .tags("region", "beijing", "zone", "zone-a", "instance", "instance-1")
+ .set(99.9);
+ }
+
+ /**
+ * Test exception handling
+ * Verify validity of metric names and tags
+ */
+ @Test
+ public void testExceptionHandling() {
+ try {
+ // Test normal case
+ Metrics.counter("validCounter")
+ .tag("env", "test")
+ .inc(1);
+
+ System.out.println("Normal metric creation successful");
+ } catch (Exception e) {
+ System.err.println("Metric creation failed: " + e.getMessage());
+ }
+ }
+
+ /**
+ * Test business metrics
+ * BusinessMetrics provides higher-level business scenario metric encapsulation
+ */
+ @Test
+ public void testBusinessMetrics() {
+ // Test business Counter metric
+ BusinessMetrics.counter("order_scene", "order_count", 1.0);
+
+ // Test business Counter metric with context
+ Map<String, String> context = new HashMap<>();
+ context.put("region", "beijing");
+ context.put("channel", "mobile");
+ BusinessMetrics.counter("payment_scene", "payment_amount", 100.5, context);
+
+ // Test business Gauge metric
+ BusinessMetrics.gauge("inventory_scene", "stock_level", 500.0);
+
+ // Test business Gauge metric with context
+ Map<String, String> stockContext = new HashMap<>();
+ stockContext.put("warehouse", "beijing_warehouse");
+ stockContext.put("product_type", "electronics");
+ BusinessMetrics.gauge("warehouse_scene", "available_stock", 1000.0, stockContext);
+ }
+
+ /*
+ * Commented methods retain original logic for reference
+ * These are usage patterns of the old version API
+ */
+
+ /*
+ @Test
+ public void testNotMatchLabelNameAndLabelValueException() {
+ IntStream.range(0, 100).forEach(i -> {
+ // Old version label mismatch test
+ Metrics.getInstance().newCounter("testNotMatchLabelNameAndLabelValueExceptionCounter", "a", "b").with("1").add(1);
+ Metrics.getInstance().newGauge("testNotMatchLabelNameAndLabelValueExceptionGauge", "a", "b").with("1").add(1);
+ Metrics.getInstance().newHistogram("testNotMatchLabelNameAndLabelValueExceptionHistogram", null, "b", "c").with("1").observe(1);
+ });
+ }
+ */
+
+ /*
+ @Test
+ public void testJvm() throws InterruptedException {
+ // JVM metrics monitoring test
+ Thread.sleep(3000000);
+ }
+ */
+}
\ No newline at end of file
diff --git a/prometheus-starter-all/pom.xml b/ozhera-metrics-all/pom.xml
similarity index 97%
rename from prometheus-starter-all/pom.xml
rename to ozhera-metrics-all/pom.xml
index 3e194f93..1cca87fd 100644
--- a/prometheus-starter-all/pom.xml
+++ b/ozhera-metrics-all/pom.xml
@@ -30,13 +30,13 @@
<modelVersion>4.0.0</modelVersion>
- <artifactId>prometheus-starter-all</artifactId>
+ <artifactId>ozhera-metrics-all</artifactId>
<version>2.2.6-SNAPSHOT</version>
<packaging>pom</packaging>
<modules>
- <module>prometheus-diy-client</module>
- <module>prometheus-diy-starter</module>
+ <module>ozhera-metrics-sdk</module>
+ <module>ozhera-metrics-sdk-config</module>
</modules>
<dependencyManagement>
diff --git a/ozhera-operator/ozhera-operator-server/src/main/resources/ozhera_init/nacos/config/ozhera_webhook_open_config_#_DEFAULT_GROUP.properties b/ozhera-operator/ozhera-operator-server/src/main/resources/ozhera_init/nacos/config/ozhera_webhook_open_config_#_DEFAULT_GROUP.properties
index afaf2d56..664b22c4 100644
--- a/ozhera-operator/ozhera-operator-server/src/main/resources/ozhera_init/nacos/config/ozhera_webhook_open_config_#_DEFAULT_GROUP.properties
+++ b/ozhera-operator/ozhera-operator-server/src/main/resources/ozhera_init/nacos/config/ozhera_webhook_open_config_#_DEFAULT_GROUP.properties
@@ -35,6 +35,6 @@ log.agent.container.name=log-agent
log.agent.container.image=herahub/opensource-pub:log-agent-v1.2.8
log.agent.container.cpu.limit=1
log.agent.container.mem.limit=2Gi
-log.agent.nacos.addr=nacos:80
+log.agent.nacos.addr=${hera.nacos.address}
# Whether to enable automatic log-agent injection
log-agent.enabled=true
\ No newline at end of file
diff --git a/pom.xml b/pom.xml
index a470d26e..e0c65f6a 100644
--- a/pom.xml
+++ b/pom.xml
@@ -58,7 +58,7 @@
<module>ozhera-prometheus-agent</module>
<module>ozhera-tspandata</module>
<module>ozhera-webhook</module>
- <module>prometheus-starter-all</module>
+ <module>ozhera-metrics-all</module>
<module>trace-etl</module>
<module>ozhera-intelligence</module>
</modules>
diff --git a/prometheus-starter-all/prometheus-diy-client/pom.xml b/prometheus-starter-all/prometheus-diy-client/pom.xml
deleted file mode 100644
index 3cb0eea2..00000000
--- a/prometheus-starter-all/prometheus-diy-client/pom.xml
+++ /dev/null
@@ -1,104 +0,0 @@
-<?xml version="1.0" encoding="UTF-8"?>
-<!--
-
- 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.
-
--->
-
-<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
- <parent>
- <groupId>org.apache.ozhera</groupId>
- <artifactId>prometheus-starter-all</artifactId>
- <version>2.2.6-SNAPSHOT</version>
- </parent>
- <modelVersion>4.0.0</modelVersion>
-
- <artifactId>prometheus-diy-client</artifactId>
- <version>2.2.6-SNAPSHOT</version>
-
- <dependencies>
- <dependency>
- <groupId>io.prometheus</groupId>
- <artifactId>simpleclient</artifactId>
- </dependency>
- <dependency>
- <groupId>io.micrometer</groupId>
- <artifactId>micrometer-registry-prometheus</artifactId>
- <exclusions>
- <exclusion>
- <groupId>io.prometheus</groupId>
- <artifactId>simpleclient_common</artifactId>
- </exclusion>
- </exclusions>
- </dependency>
-
- <dependency>
- <groupId>org.projectlombok</groupId>
- <artifactId>lombok</artifactId>
- </dependency>
-
- <dependency>
- <groupId>org.slf4j</groupId>
- <artifactId>slf4j-api</artifactId>
- </dependency>
-
- <dependency>
- <groupId>junit</groupId>
- <artifactId>junit</artifactId>
- <scope>test</scope>
- </dependency>
-
- </dependencies>
-
- <build>
-
- <resources>
- <resource>
- <directory>src/main/resources</directory>
- <filtering>true</filtering>
- <excludes>
- <exclude>META-INF/LICENSE.txt</exclude>
- </excludes>
- </resource>
- <resource>
- <directory>${project.basedir}/../../</directory>
- <filtering>true</filtering>
- <includes>
- <include>DISCLAIMER</include>
- <include>NOTICE</include>
- <include>LICENSE</include>
- </includes>
- <targetPath>META-INF/</targetPath>
- </resource>
- </resources>
-
- <plugins>
- <plugin>
- <groupId>org.apache.maven.plugins</groupId>
- <artifactId>maven-compiler-plugin</artifactId>
- <version>3.11.0</version>
- <configuration>
- <compilerVersion>21</compilerVersion>
- <source>21</source>
- <target>21</target>
- </configuration>
- </plugin>
- </plugins>
- </build>
-
-</project>
\ No newline at end of file
diff --git a/prometheus-starter-all/prometheus-diy-client/src/main/java/org/apache/ozhera/prometheus/all/client/Metrics.java b/prometheus-starter-all/prometheus-diy-client/src/main/java/org/apache/ozhera/prometheus/all/client/Metrics.java
deleted file mode 100644
index 2e79a292..00000000
--- a/prometheus-starter-all/prometheus-diy-client/src/main/java/org/apache/ozhera/prometheus/all/client/Metrics.java
+++ /dev/null
@@ -1,125 +0,0 @@
-/*
- * 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.ozhera.prometheus.all.client;
-
-import org.apache.ozhera.prometheus.all.client.binder.ClassLoaderMetricsReduced;
-import org.apache.ozhera.prometheus.all.client.binder.JvmGcMetricsReduced;
-import org.apache.ozhera.prometheus.all.client.binder.JvmMemoryMetricsReduced;
-import org.apache.ozhera.prometheus.all.client.binder.JvmThreadMetricsReduced;
-import io.micrometer.core.instrument.binder.jvm.ClassLoaderMetrics;
-import io.micrometer.core.instrument.binder.jvm.JvmGcMetrics;
-import io.micrometer.core.instrument.binder.jvm.JvmMemoryMetrics;
-import io.micrometer.core.instrument.binder.jvm.JvmThreadMetrics;
-import io.micrometer.core.instrument.binder.system.FileDescriptorMetrics;
-import io.micrometer.core.instrument.binder.system.ProcessorMetrics;
-import io.micrometer.core.instrument.binder.system.UptimeMetrics;
-import lombok.extern.slf4j.Slf4j;
-
-import java.util.HashMap;
-
-/**
- * @author zhangxiaowei6
- */
-@Slf4j
-public class Metrics {
-
- public MetricsManager gMetricsMgr;
- /**
- * group+service become namespace
- */
- public static final String GROUP = "group";
- public static final String SERVICE = "service";
- public static final String APPLICATION = "application";
-
- private static class LazyHolder {
- private static final Metrics ins = new Metrics();
- }
-
-
- public void init(String group,String service) {
- this.init(group,service,false);
- }
-
- public void init(String group,String service, boolean jvmReduced){
- setGroup(group);
- setService(service);
- Prometheus.REGISTRY.config().commonTags(APPLICATION, Prometheus.constLabels.get(Metrics.SERVICE));
- if(jvmReduced){
- new ClassLoaderMetricsReduced().bindTo(Prometheus.REGISTRY);
- new JvmMemoryMetricsReduced().bindTo(Prometheus.REGISTRY);
- new JvmGcMetricsReduced().bindTo(Prometheus.REGISTRY);
- new ProcessorMetrics().bindTo(Prometheus.REGISTRY);
- new JvmThreadMetricsReduced().bindTo(Prometheus.REGISTRY);
- new UptimeMetrics().bindTo(Prometheus.REGISTRY);
- new FileDescriptorMetrics().bindTo(Prometheus.REGISTRY);
- }else{
- new ClassLoaderMetrics().bindTo(Prometheus.REGISTRY);
- new JvmMemoryMetrics().bindTo(Prometheus.REGISTRY);
- new JvmGcMetrics().bindTo(Prometheus.REGISTRY);
- new ProcessorMetrics().bindTo(Prometheus.REGISTRY);
- new JvmThreadMetrics().bindTo(Prometheus.REGISTRY);
- new UptimeMetrics().bindTo(Prometheus.REGISTRY);
- new FileDescriptorMetrics().bindTo(Prometheus.REGISTRY);
- }
- }
-
-
- //get singleton instance
- public static Metrics getInstance() {
- return LazyHolder.ins;
- }
-
- public void setGroup(String group) {
- Prometheus.constLabels.put(GROUP, group);
- }
-
- public void setService(String service) {
- Prometheus.constLabels.put(SERVICE, service);
- }
-
- public static double[] DEFAULT_LATENCY_BUCKETS =
- new double[]{.01, .05, 1, 5, 7.5, 10, 25, 50, 100, 200, 500, 1000,1500,2000,3000,4000,5000};
-
- private Metrics() {
- Prometheus.constLabels = new HashMap<>();
- gMetricsMgr = new Prometheus();
- }
-
- public XmCounter newCounter(String metricName, String... labelNames) {
- try {
- return gMetricsMgr.newCounter(metricName, labelNames);
- } catch (Throwable throwable) {
- log.warn(throwable.getMessage());
- return null;
- }
- }
-
- public XmGauge newGauge(String metricName, String... labelNames) {
- return gMetricsMgr.newGauge(metricName, labelNames);
- }
-
- public XmHistogram newHistogram(String metricName, double[] buckets, String... labelNames) {
- if (buckets != null && buckets.length > 0) {
- return gMetricsMgr.newHistogram(metricName, buckets, labelNames);
- }
- return gMetricsMgr.newHistogram(metricName, DEFAULT_LATENCY_BUCKETS, labelNames);
- }
-
-}
\ No newline at end of file
diff --git a/prometheus-starter-all/prometheus-diy-client/src/main/java/org/apache/ozhera/prometheus/all/client/MetricsManager.java b/prometheus-starter-all/prometheus-diy-client/src/main/java/org/apache/ozhera/prometheus/all/client/MetricsManager.java
deleted file mode 100644
index 9b02d89f..00000000
--- a/prometheus-starter-all/prometheus-diy-client/src/main/java/org/apache/ozhera/prometheus/all/client/MetricsManager.java
+++ /dev/null
@@ -1,55 +0,0 @@
-/*
- * 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.ozhera.prometheus.all.client;
-/**
- * @author zhangxiaowei6
- */
-public interface MetricsManager {
- /**
- * use Counter
- *
- * @param metricName
- * @param labelNames
- * @return XMCounter
- */
-
- XmCounter newCounter(String metricName, String... labelNames);
-
- /**
- * use Gauge
- *
- * @param metricName
- * @param labelNames
- * @return XMGauge
- */
-
- XmGauge newGauge(String metricName, String... labelNames);
-
- /**
- * use Histogram
- *
- * @param metricName
- * @param buckets
- * @param labelNames
- * @return XMHistogram
- */
-
- XmHistogram newHistogram(String metricName, double[] buckets, String... labelNames);
-}
\ No newline at end of file
diff --git a/prometheus-starter-all/prometheus-diy-client/src/main/java/org/apache/ozhera/prometheus/all/client/Prometheus.java b/prometheus-starter-all/prometheus-diy-client/src/main/java/org/apache/ozhera/prometheus/all/client/Prometheus.java
deleted file mode 100644
index d2443dc8..00000000
--- a/prometheus-starter-all/prometheus-diy-client/src/main/java/org/apache/ozhera/prometheus/all/client/Prometheus.java
+++ /dev/null
@@ -1,201 +0,0 @@
-/*
- * 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.ozhera.prometheus.all.client;
-
-import io.micrometer.prometheus.PrometheusConfig;
-import io.micrometer.prometheus.PrometheusMeterRegistry;
-import io.prometheus.client.*;
-import lombok.extern.slf4j.Slf4j;
-
-import java.util.*;
-import java.util.concurrent.ConcurrentHashMap;
-import java.util.concurrent.locks.ReentrantLock;
-
-/**
- * @author zhangxiaowei6
- */
-@Slf4j
-public class Prometheus implements MetricsManager {
-
- public static final int CONST_LABELS_NUM = 2;
- public static final PrometheusMeterRegistry REGISTRY = new PrometheusMeterRegistry(PrometheusConfig.DEFAULT);
- public static Map<String, String> constLabels;
- public Map<String, Object> prometheusMetrics;
- public Map<String, Object> prometheusTypeMetrics;
-
- private ReentrantLock lock = new ReentrantLock();
- private ReentrantLock typeLock = new ReentrantLock();
-
- public Prometheus() {
- this.prometheusMetrics = new ConcurrentHashMap<>();
- this.prometheusTypeMetrics = new ConcurrentHashMap<>();
- }
-
- @Override
- public XmCounter newCounter(String metricName, String... labelName) {
- if (prometheusTypeMetrics.containsKey(metricName)) {
- return (XmCounter) prometheusTypeMetrics.get(metricName);
- }
- typeLock.lock();
- try{
- PrometheusCounter prometheusCounter = new PrometheusCounter(getCounter(metricName, labelName), labelName, null);
- prometheusTypeMetrics.put(metricName, prometheusCounter);
- return prometheusCounter;
- }finally {
- typeLock.unlock();
- }
- }
-
- @Override
- public XmGauge newGauge(String metricName, String... labelName) {
- if (prometheusTypeMetrics.containsKey(metricName)) {
- return (XmGauge) prometheusTypeMetrics.get(metricName);
- }
- typeLock.lock();
- try{
- PrometheusGauge prometheusGauge = new PrometheusGauge(getGauge(metricName, labelName), labelName, null);
- prometheusTypeMetrics.put(metricName, prometheusGauge);
- return prometheusGauge;
- }finally {
- typeLock.unlock();
- }
-
- }
-
- @Override
- public XmHistogram newHistogram(String metricName, double[] bucket, String... labelNames) {
- if (prometheusTypeMetrics.containsKey(metricName)) {
- return (XmHistogram) prometheusTypeMetrics.get(metricName);
- }
- typeLock.lock();
- try{
- PrometheusHistogram prometheusHistogram = new PrometheusHistogram(getHistogram(metricName, bucket, labelNames), labelNames, null);
- prometheusTypeMetrics.put(metricName, prometheusHistogram);
- return prometheusHistogram;
- }finally {
- typeLock.unlock();
- }
- }
-
- public Counter getCounter(String metricName, String... labelName) {
- if (constLabels.size() != Prometheus.CONST_LABELS_NUM) {
- return null;
- }
- try {
- //If there is a direct return
- if (prometheusMetrics.containsKey(metricName)) {
- //log.debug("already have metric:" + metricName);
- return (Counter) prometheusMetrics.get(metricName);
- }
-
- lock.lock();
- try{
- //No need to register one first
- List<String> mylist = new ArrayList<>(Arrays.asList(labelName));
- mylist.add(Metrics.APPLICATION);
- String[] finalValue = mylist.toArray(new String[mylist.size()]);
- Counter newCounter = Counter.build()
- .name(metricName)
- .namespace(constLabels.get(Metrics.GROUP) + "_" + constLabels.get(Metrics.SERVICE))
- .labelNames(finalValue)
- .help(metricName)
- .register();
-
- prometheusMetrics.put(metricName, newCounter);
- return newCounter;
- }finally {
- lock.unlock();
- }
- } catch (Throwable throwable) {
- log.warn(throwable.getMessage());
- return null;
- }
- }
-
- public Gauge getGauge(String metricName, String... labelName) {
- if (constLabels.size() != Prometheus.CONST_LABELS_NUM) {
- return null;
- }
- try {
- //If there is a direct return
- if (prometheusMetrics.containsKey(metricName)) {
- // log.debug("already have metric:" + metricName);
- return (Gauge) prometheusMetrics.get(metricName);
- }
- lock.lock();
- try{
- //No need to register one first
- List<String> mylist = new ArrayList<>(Arrays.asList(labelName));
- mylist.add(Metrics.APPLICATION);
- String[] finalValue = mylist.toArray(new String[mylist.size()]);
- Gauge newGauge = Gauge.build()
- .name(metricName)
- .namespace(constLabels.get(Metrics.GROUP) + "_" + constLabels.get(Metrics.SERVICE))
- .labelNames(finalValue)
- .help(metricName)
- .register();
-
- prometheusMetrics.put(metricName, newGauge);
- return newGauge;
- }finally {
- lock.unlock();
- }
- } catch (Throwable throwable) {
- log.warn(throwable.getMessage());
- return null;
- }
-
- }
-
- public Histogram getHistogram(String metricName, double[] buckets, String... labelNames) {
- if (constLabels.size() != Prometheus.CONST_LABELS_NUM) {
- return null;
- }
- try {
- //If there is a direct return
- if (prometheusMetrics.containsKey(metricName)) {
- // log.debug("already have metric:" + metricName);
- return (Histogram) prometheusMetrics.get(metricName);
- }
-
- lock.lock();
- try{
- //No need to register one first
- List<String> mylist = new ArrayList<>(Arrays.asList(labelNames));
- mylist.add(Metrics.APPLICATION);
- String[] finalValue = mylist.toArray(new String[mylist.size()]);
- Histogram newHistogram = Histogram.build()
- .buckets(buckets)
- .name(metricName)
- .namespace(constLabels.get(Metrics.GROUP) + "_" + constLabels.get(Metrics.SERVICE))
- .labelNames(finalValue)
- .help(metricName)
- .register();
- prometheusMetrics.put(metricName, newHistogram);
- return newHistogram;
- }finally {
- lock.unlock();
- }
- } catch (Throwable throwable) {
- log.warn(throwable.getMessage());
- return null;
- }
- }
-}
\ No newline at end of file
diff --git a/prometheus-starter-all/prometheus-diy-client/src/main/java/org/apache/ozhera/prometheus/all/client/PrometheusCounter.java b/prometheus-starter-all/prometheus-diy-client/src/main/java/org/apache/ozhera/prometheus/all/client/PrometheusCounter.java
deleted file mode 100644
index e228c863..00000000
--- a/prometheus-starter-all/prometheus-diy-client/src/main/java/org/apache/ozhera/prometheus/all/client/PrometheusCounter.java
+++ /dev/null
@@ -1,79 +0,0 @@
-/*
- * 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.ozhera.prometheus.all.client;
-
-import io.prometheus.client.Counter;
-import lombok.extern.slf4j.Slf4j;
-
-import java.util.ArrayList;
-import java.util.Arrays;
-import java.util.List;
-
-/**
- * @author zhangxiaowei6
- */
-@Slf4j
-public class PrometheusCounter implements XmCounter {
-
- public String[] labelValues;
-
- public Counter myCounter;
-
- public String[] labelNames;
-
- public PrometheusCounter(Counter cb, String[] lns, String[] lvs) {
- this.myCounter = cb;
- this.labelNames = lns;
- this.labelValues = lvs;
- }
-
- public PrometheusCounter() {
-
- }
-
- @Override
- public XmCounter with(String... labelValues) {
- try {
- if (this.labelNames.length != labelValues.length) {
- log.warn("Incorrect numbers of labels : " + myCounter.describe().get(0).name + " labelName: " + this.labelNames.length + " labelValues: " + labelValues.length + "{} {}", Arrays.toString(this.labelNames), Arrays.toString(labelValues));
- return new PrometheusCounter();
- }
- return this;
- } catch (Throwable throwable) {
- log.warn(throwable.getMessage());
- return null;
- }
- }
-
- @Override
- public void add(double delta, String... labelValues) {
-
- List<String> mylist = new ArrayList<>(Arrays.asList(labelValues));
- mylist.add(Prometheus.constLabels.get(Metrics.SERVICE));
- // mylist.add(traceId);
- String[] finalValue = mylist.toArray(new String[mylist.size()]);
- try {
- this.myCounter.labels(finalValue).inc(delta);
- } catch (Throwable throwable) {
- log.warn(throwable.getMessage());
- }
-
- }
-}
\ No newline at end of file
diff --git a/prometheus-starter-all/prometheus-diy-client/src/main/java/org/apache/ozhera/prometheus/all/client/PrometheusGauge.java b/prometheus-starter-all/prometheus-diy-client/src/main/java/org/apache/ozhera/prometheus/all/client/PrometheusGauge.java
deleted file mode 100644
index 1db54f35..00000000
--- a/prometheus-starter-all/prometheus-diy-client/src/main/java/org/apache/ozhera/prometheus/all/client/PrometheusGauge.java
+++ /dev/null
@@ -1,91 +0,0 @@
-/*
- * 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.ozhera.prometheus.all.client;
-
-import io.prometheus.client.Gauge;
-import lombok.extern.slf4j.Slf4j;
-
-import java.util.ArrayList;
-import java.util.Arrays;
-import java.util.List;
-
-/**
- * @author zhangxiaowei6
- */
-@Slf4j
-public class PrometheusGauge implements XmGauge {
-
- public Gauge myGauge;
- public String[] labelNames;
- public String[] labelValues;
-
- public PrometheusGauge() {
-
- }
-
- @Override
- public void set(double delta,String ...labelValues) {
- try {
- List<String> mylist = new ArrayList<>(Arrays.asList(labelValues));
- mylist.add(Prometheus.constLabels.get(Metrics.SERVICE));
- String[] finalValue = mylist.toArray(new String[mylist.size()]);
- this.myGauge.labels(finalValue).set(delta);
- } catch (Throwable throwable) {
- log.warn(throwable.getMessage());
- }
- }
-
- public PrometheusGauge(Gauge cb, String[] lns, String[] lvs) {
- this.myGauge = cb;
- this.labelNames = lns;
- this.labelValues = lvs;
- }
-
- @Override
- public XmGauge with(String... labelValue) {
- /*String traceId = MDC.get("tid");
- if (StringUtils.isEmpty(traceId)) {
- traceId = "no traceId";
- }*/
- try {
- if (this.labelNames.length != labelValue.length) {
- log.warn("Incorrect numbers of labels : " + myGauge.describe().get(0).name);
- return new PrometheusGauge();
- }
- return this;
- } catch (Throwable throwable) {
- log.warn(throwable.getMessage());
- return null;
- }
- }
-
- @Override
- public void add(double delta,String... labelValue) {
-
- List<String> mylist = new ArrayList<>(Arrays.asList(labelValues));
- mylist.add(Prometheus.constLabels.get(Metrics.SERVICE));
- String[] finalValue = mylist.toArray(new String[mylist.size()]);
- try {
- this.myGauge.labels(finalValue).inc(delta);
- } catch (Throwable throwable) {
- log.warn(throwable.getMessage());
- }
- }
-}
\ No newline at end of file
diff --git a/prometheus-starter-all/prometheus-diy-client/src/main/java/org/apache/ozhera/prometheus/all/client/PrometheusHistogram.java b/prometheus-starter-all/prometheus-diy-client/src/main/java/org/apache/ozhera/prometheus/all/client/PrometheusHistogram.java
deleted file mode 100644
index 6b3e8d2c..00000000
--- a/prometheus-starter-all/prometheus-diy-client/src/main/java/org/apache/ozhera/prometheus/all/client/PrometheusHistogram.java
+++ /dev/null
@@ -1,74 +0,0 @@
-/*
- * 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.ozhera.prometheus.all.client;
-
-import io.prometheus.client.Histogram;
-import lombok.extern.slf4j.Slf4j;
-
-import java.util.ArrayList;
-import java.util.Arrays;
-import java.util.List;
-
-/**
- * @author zhangxiaowei6
- */
-@Slf4j
-public class PrometheusHistogram implements XmHistogram {
-
- public Histogram myHistogram;
- public String[] labelNames;
- public String[] labelValues;
-
- public PrometheusHistogram(Histogram cb, String[] lns, String[] lvs) {
- this.myHistogram = cb;
- this.labelNames = lns;
- this.labelValues = lvs;
- }
-
- public PrometheusHistogram() {
-
- }
-
- @Override
- public XmHistogram with(String... labelValues) {
- try {
- if (this.labelNames.length != labelValues.length) {
- log.warn("Incorrect numbers of labels : " + myHistogram.describe().get(0).name + " labelName: " + this.labelNames.length + " labelValues: " + this.labelValues.length);
- return new PrometheusHistogram();
- }
- return this;
- } catch (Throwable throwable) {
- log.warn(throwable.getMessage());
- return null;
- }
- }
-
- @Override
- public void observe(double delta,String... labelValue) {
- try {
- List<String> mylist = new ArrayList<>(Arrays.asList(labelValue));
- mylist.add(Prometheus.constLabels.get(Metrics.SERVICE));
- String[] finalValue = mylist.toArray(new String[mylist.size()]);
- this.myHistogram.labels(finalValue).observe(delta);
- } catch (Throwable throwable) {
- log.warn(throwable.getMessage());
- }
- }
-}
\ No newline at end of file
diff --git a/prometheus-starter-all/prometheus-diy-client/src/test/java/org/apache/ozhera/prometheus/all/client/PrometheusTest.java b/prometheus-starter-all/prometheus-diy-client/src/test/java/org/apache/ozhera/prometheus/all/client/PrometheusTest.java
deleted file mode 100644
index c9f5181f..00000000
--- a/prometheus-starter-all/prometheus-diy-client/src/test/java/org/apache/ozhera/prometheus/all/client/PrometheusTest.java
+++ /dev/null
@@ -1,98 +0,0 @@
-/*
- * 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.ozhera.prometheus.all.client;
-import org.junit.Before;
-import org.junit.Test;
-
-import java.util.stream.IntStream;
-
-public class PrometheusTest {
-
- @Before
- public void setUp() throws Exception {
-
- //HTTPServer newServer = new HTTPServer(8070);
- /*try {
- Enumeration<Collector.MetricFamilySamples> samples = CollectorRegistry.defaultRegistry.filteredMetricFamilySamples(Sets.newHashSet());
- StringWriter writer = new StringWriter();
- String str = "";
- try {
- TextFormat.write004(writer, samples);
- StringBuffer sb = writer.getBuffer();
- str = sb.toString();
- } catch (IOException e) {
- e.printStackTrace();
- }
- System.out.println(str);
- HttpServer server = HttpServer.create(new InetSocketAddress(8070), 0);
- server.createContext("/metrics", httpExchange -> {
- String response = Prometheus.registry.scrape();
- httpExchange.sendResponseHeaders(200, response.getBytes().length);
- try (OutputStream os = httpExchange.getResponseBody()) {
- os.write(response.getBytes());
- }
- });
- new Thread(server::start).start();
- } catch (IOException e) {
- throw new RuntimeException(e);
- }
- //m = new Metrics("systech", "zxw_test2");*/
- Metrics.getInstance().init("systch","zxw_test2");
- }
-
- @Test
- public void testCounter() {
- IntStream.range(0, 100).forEach(i -> {
-
- Metrics.getInstance().newCounter("testCounter", "name").
- with("zxw").
- add(1,"zxw");
- Metrics.getInstance().newCounter("testCounter2", "age", "city").with("99", "china").add(1,"18","beijing");
- });
- }
-
- @Test
- public void testGauge() {
- IntStream.range(0, 100).forEach(i -> {
- Metrics.getInstance().newGauge("testGauge", "name").with("zxw").set(128,"zxw");
- });
- }
-
- @Test
- public void testHistogram() {
- IntStream.range(0,100).forEach(i-> {
- Metrics.getInstance().newHistogram("testHistogramWithDefaultBucket",null,"name").with("zxw").observe(12,"zxw");
- Metrics.getInstance().newHistogram("testHistogramWithDiyBucket", new double[] {.01, .05, 0.7, 5 ,10, 50, 100, 200},"name").with("zxw").observe(12,"zxw");
- });
- }
-
-/* @Test
- public void testException() {
- IntStream.range(0, 100).forEach(i -> {
- Metrics.getInstance().newCounter("testNotMatchLabelNameAndLabelValueExceptionCounter", "a", "b").with("1").add(1);
- Metrics.getInstance().newGauge("testNotMatchLabelNameAndLabelValueExceptionGauge", "a", "b").with("1").add(1);
- Metrics.getInstance().newHistogram("testNotMatchLabelNameAndLabelValueExceptionHistogram", null, "b", "c").with("1").observe(1);
- });
- }*/
-/* @Test
- public void testJvm() throws InterruptedException {
- Thread.sleep(3000000);
- }*/
-}
\ No newline at end of file
diff --git a/prometheus-starter-all/prometheus-diy-starter/pom.xml b/prometheus-starter-all/prometheus-diy-starter/pom.xml
deleted file mode 100644
index e1a2ae31..00000000
--- a/prometheus-starter-all/prometheus-diy-starter/pom.xml
+++ /dev/null
@@ -1,77 +0,0 @@
-<?xml version="1.0" encoding="UTF-8"?>
-<!--
-
- 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.
-
--->
-
-<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
- <parent>
- <groupId>org.apache.ozhera</groupId>
- <artifactId>prometheus-starter-all</artifactId>
- <version>2.2.6-SNAPSHOT</version>
- </parent>
- <modelVersion>4.0.0</modelVersion>
-
- <artifactId>prometheus-diy-starter</artifactId>
- <version>2.2.6-SNAPSHOT</version>
-
- <dependencies>
-
- <dependency>
- <groupId>org.apache.ozhera</groupId>
- <artifactId>prometheus-diy-client</artifactId>
- <version>2.2.6-SNAPSHOT</version>
- </dependency>
-
- <dependency>
- <groupId>io.prometheus</groupId>
- <artifactId>simpleclient_common</artifactId>
- </dependency>
-
- <dependency>
- <groupId>run.mone</groupId>
- <artifactId>nacos-client</artifactId>
- </dependency>
-
- </dependencies>
-
- <build>
- <resources>
- <resource>
- <directory>src/main/resources</directory>
- <filtering>true</filtering>
- <excludes>
- <exclude>META-INF/LICENSE.txt</exclude>
- </excludes>
- </resource>
- <resource>
- <directory>${project.basedir}/../../</directory>
- <filtering>true</filtering>
- <includes>
- <include>DISCLAIMER</include>
- <include>NOTICE</include>
- <include>LICENSE</include>
- </includes>
- <targetPath>META-INF/</targetPath>
- </resource>
- </resources>
- </build>
-
-
-</project>
\ No newline at end of file
diff --git a/prometheus-starter-all/prometheus-diy-starter/src/main/java/org/apache/ozhera/prometheus/starter/all/config/PrometheusConfigure.java b/prometheus-starter-all/prometheus-diy-starter/src/main/java/org/apache/ozhera/prometheus/starter/all/config/PrometheusConfigure.java
deleted file mode 100644
index c92639a8..00000000
--- a/prometheus-starter-all/prometheus-diy-starter/src/main/java/org/apache/ozhera/prometheus/starter/all/config/PrometheusConfigure.java
+++ /dev/null
@@ -1,102 +0,0 @@
-/*
- * 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.ozhera.prometheus.starter.all.config;
-
-import com.alibaba.nacos.api.exception.NacosException;
-import com.alibaba.nacos.api.naming.pojo.Instance;
-import com.alibaba.nacos.client.naming.NacosNamingService;
-import com.sun.net.httpserver.HttpServer;
-import org.apache.ozhera.prometheus.starter.all.exporter.HTTPServer;
-import org.apache.ozhera.prometheus.starter.all.service.MilinePrometheusService;
-import org.apache.ozhera.prometheus.all.client.Metrics;
-import org.apache.ozhera.prometheus.all.client.Prometheus;
-import io.prometheus.client.CollectorRegistry;
-import lombok.extern.slf4j.Slf4j;
-
-import java.io.IOException;
-import java.net.InetSocketAddress;
-import java.util.HashMap;
-import java.util.Map;
-
-/**
- * @author goodjava@qq.com
- */
-@Slf4j
-public class PrometheusConfigure {
-
- private static final String PROMETHEUS_CUSTOM_SERVER_KEY = "prometheus_custom_server_";
- private static final String PROMETHEUS_CUSTOM_PORT_KEY = "ozhera_prometheus_port";
-
- public static void init(String nacosAddr, String serverEnv) {
- try {
- MilinePrometheusService prometheusService = new MilinePrometheusService();
- String serviceName = prometheusService.getServiceName();
- String port = prometheusService.getPort();
- String serverIp = prometheusService.getServerIp();
- log.info("prometheus init, serviceName is : "+serviceName+", port is : "+port+", serverIp is : "+serverIp);
- registNacos(nacosAddr, serviceName, serverIp, port);
- Metrics.getInstance().init(serverEnv, serviceName);
- startHttpServer(port);
- } catch (Throwable t) {
- log.error("customized prometheus SDK init error : ", t);
- }
- }
-
- private static void startHttpServer(String port) {
- new Thread(() -> {
- log.info("start prometheus server");
- try {
- log.info("prometheus port: {}", port);
- InetSocketAddress addr = new InetSocketAddress(Integer.valueOf(port));
- Map<String, CollectorRegistry> map = new HashMap<>(5);
- map.put("default", CollectorRegistry.defaultRegistry);
- map.put("jvm", Prometheus.REGISTRY.getPrometheusRegistry());
- new HTTPServer(HttpServer.create(addr, 3), map, false);
- } catch (IOException e) {
- log.error("start prometheus server error:{}", e.getMessage());
- }
- }).start();
- }
-
- private static void registNacos(String nacosAddr, String serviceName, String serverIp, String port) {
- String appName = PROMETHEUS_CUSTOM_SERVER_KEY + serviceName;
- NacosNamingService nacosNamingService = new NacosNamingService(nacosAddr);
- Instance instance = new Instance();
- instance.setIp(serverIp);
- instance.setPort(55257);
- Map<String, String> map = new HashMap<>();
- map.put(PROMETHEUS_CUSTOM_PORT_KEY, port);
- instance.setMetadata(map);
- try {
- nacosNamingService.registerInstance(appName, instance);
- // deregister
- Runtime.getRuntime().addShutdownHook(new Thread(() -> {
- log.info("nacos shutdown hook deregister instance");
- try {
- nacosNamingService.deregisterInstance(appName, instance);
- } catch (Exception e) {
- log.warn("nacos shutdown hook error : " + e.getMessage());
- }
- }));
- } catch (NacosException e) {
- log.error("prometheus diy register nacos error:{}", e.getMessage());
- }
- }
-}
\ No newline at end of file
diff --git a/prometheus-starter-all/prometheus-diy-starter/src/main/java/org/apache/ozhera/prometheus/starter/all/service/MilinePrometheusService.java b/prometheus-starter-all/prometheus-diy-starter/src/main/java/org/apache/ozhera/prometheus/starter/all/service/MilinePrometheusService.java
deleted file mode 100644
index 73dcee7d..00000000
--- a/prometheus-starter-all/prometheus-diy-starter/src/main/java/org/apache/ozhera/prometheus/starter/all/service/MilinePrometheusService.java
+++ /dev/null
@@ -1,62 +0,0 @@
-/*
- * 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.ozhera.prometheus.starter.all.service;
-
-import org.apache.commons.lang3.StringUtils;
-
-/**
- * @Description
- * @Date 2023/3/5 3:41 PM
- */
-public class MilinePrometheusService extends PrometheusService{
-
- @Override
- public String getServiceName() {
- String serviceName = System.getenv("MIONE_PROJECT_NAME");
- if (StringUtils.isEmpty(serviceName)) {
- String property = System.getProperty("otel.resource.attributes");
- if (StringUtils.isEmpty(property)) {
- serviceName = DEFAULT_SERVICE_NAME;
- } else {
- serviceName = property.split("=")[1];
- }
- }
- serviceName = serviceName.replaceAll("-", "_");
- return serviceName;
- }
-
- @Override
- public String getServerIp() {
- String serverIp = System.getenv("POD_IP");
- if(serverIp == null){
- serverIp = System.getProperty("otel.service.ip");
- }
- return serverIp;
- }
-
- @Override
- public String getPort() {
- String port = System.getenv("OZHERA_PROMETHEUS_PORT");
- if (null == port) {
- port = DEFAULT_PORT;
- }
- return port;
- }
-}
\ No newline at end of file
---------------------------------------------------------------------
To unsubscribe, e-mail: commits-unsubscribe@ozhera.apache.org
For additional commands, e-mail: commits-help@ozhera.apache.org