Compare commits

9 Commits
master ... dev

Author SHA1 Message Date
shizhendong
1154baae0d build: 更新log4j版本为,2.17.0 2021-12-20 12:59:22 +08:00
fangshunjian
e1b9773187 build: 更新log4j版本为,2.16.0 2021-12-16 17:47:49 +08:00
fangshunjian
cc175a6537 build: 更新log4j 版本 2021-12-10 18:47:20 +08:00
方顺健
8ffd8fe438 fix: 修改默认端口为 10096 ,防止和 loki 端口冲突 2021-09-30 07:03:12 +00:00
fangshunjian
b45142da9c feat: 新增打包脚本
打包方式:
1、mvn clean package
2、将编译好的 jar 删除.jar 文件后缀后 和 build 中文件 放到同一目录
3、使用tar 命令打包,tar -zcvf olp_exporter.tar.gz ./*

安装:
1、执行 install.sh ,安装成功后会自动启动运行,并设置开机启动
2021-08-31 16:15:23 +08:00
hyx
5b43c802ba NEZ-762 增加对target格式为IP:PORT的情况的处理 2021-07-05 17:10:13 +08:00
hyx
38819cbb94 将包名com.nis修改为net.geedge 2021-07-05 12:42:38 +08:00
hyx
866811f7fc NEZ-762 OLP_exporter程序开发:去掉多余的metrics信息 2021-06-29 10:20:36 +08:00
hyx
991a81e068 NEZ-762 OLP_exporter程序开发:olp_exporter 首次提交 2021-06-25 18:32:58 +08:00
23 changed files with 1031 additions and 0 deletions

32
.classpath Normal file
View File

@@ -0,0 +1,32 @@
<?xml version="1.0" encoding="UTF-8"?>
<classpath>
<classpathentry kind="src" output="target/classes" path="src/main/java">
<attributes>
<attribute name="optional" value="true"/>
<attribute name="maven.pomderived" value="true"/>
</attributes>
</classpathentry>
<classpathentry kind="src" output="target/test-classes" path="src/test/java">
<attributes>
<attribute name="optional" value="true"/>
<attribute name="maven.pomderived" value="true"/>
<attribute name="test" value="true"/>
</attributes>
</classpathentry>
<classpathentry kind="con" path="org.eclipse.jdt.launching.JRE_CONTAINER/org.eclipse.jdt.internal.debug.ui.launcher.StandardVMType/JavaSE-1.8">
<attributes>
<attribute name="maven.pomderived" value="true"/>
</attributes>
</classpathentry>
<classpathentry kind="con" path="org.eclipse.m2e.MAVEN2_CLASSPATH_CONTAINER">
<attributes>
<attribute name="maven.pomderived" value="true"/>
</attributes>
</classpathentry>
<classpathentry excluding="**" kind="src" output="target/classes" path="src/main/resources">
<attributes>
<attribute name="maven.pomderived" value="true"/>
</attributes>
</classpathentry>
<classpathentry kind="output" path="target/classes"/>
</classpath>

1
.gitignore vendored Normal file
View File

@@ -0,0 +1 @@
/target/

23
.project Normal file
View File

@@ -0,0 +1,23 @@
<?xml version="1.0" encoding="UTF-8"?>
<projectDescription>
<name>olp_exporter</name>
<comment></comment>
<projects>
</projects>
<buildSpec>
<buildCommand>
<name>org.eclipse.jdt.core.javabuilder</name>
<arguments>
</arguments>
</buildCommand>
<buildCommand>
<name>org.eclipse.m2e.core.maven2Builder</name>
<arguments>
</arguments>
</buildCommand>
</buildSpec>
<natures>
<nature>org.eclipse.jdt.core.javanature</nature>
<nature>org.eclipse.m2e.core.maven2Nature</nature>
</natures>
</projectDescription>

View File

@@ -0,0 +1,5 @@
eclipse.preferences.version=1
encoding//src/main/java=UTF-8
encoding//src/main/resources=UTF-8
encoding//src/test/java=UTF-8
encoding/<project>=UTF-8

View File

@@ -0,0 +1,7 @@
eclipse.preferences.version=1
org.eclipse.jdt.core.compiler.codegen.methodParameters=generate
org.eclipse.jdt.core.compiler.codegen.targetPlatform=1.8
org.eclipse.jdt.core.compiler.compliance=1.8
org.eclipse.jdt.core.compiler.problem.forbiddenReference=warning
org.eclipse.jdt.core.compiler.release=disabled
org.eclipse.jdt.core.compiler.source=1.8

View File

@@ -0,0 +1,4 @@
activeProfiles=
eclipse.preferences.version=1
resolveWorkspaceProjects=true
version=1

105
pom.xml Normal file
View File

@@ -0,0 +1,105 @@
<?xml version="1.0" encoding="UTF-8"?>
<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">
<modelVersion>4.0.0</modelVersion>
<parent>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-parent</artifactId>
<version>2.3.3.RELEASE</version>
<relativePath />
</parent>
<groupId>net.geedge</groupId>
<artifactId>olp_exporter</artifactId>
<version>1.0</version>
<packaging>jar</packaging>
<name>olp_exporter</name>
<description>olp_exporter</description>
<properties>
<java.version>8</java.version>
<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
<java_source_version>1.8</java_source_version>
<java_target_version>1.8</java_target_version>
<file_encoding>UTF-8</file_encoding>
<project.reporting.outputEncoding>UTF-8</project.reporting.outputEncoding>
<log4j2.version>2.17.0</log4j2.version>
</properties>
<repositories>
<repository>
<id>aliyun</id>
<name>Aliyun Central Repository</name>
<layout>default</layout>
<url>http://maven.aliyun.com/nexus/content/groups/public</url>
</repository>
<repository>
<id>unidal-nexus-repo</id>
<name>dianping</name>
<url>http://unidal.org/nexus/content/repositories/releases</url>
<releases>
<enabled>true</enabled>
</releases>
<snapshots>
<enabled>false</enabled>
</snapshots>
</repository>
</repositories>
<dependencies>
<!--prometheus依赖 -->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-actuator</artifactId>
</dependency>
<dependency>
<groupId>io.micrometer</groupId>
<artifactId>micrometer-registry-prometheus</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
<dependency>
<groupId>com.google.guava</groupId>
<artifactId>guava</artifactId>
<version>23.6-jre</version>
</dependency>
</dependencies>
<build>
<finalName>${project.artifactId}</finalName>
<resources>
<resource>
<directory>src/main/resources</directory>
<excludes>
<exclude>**/application-*</exclude>
<exclude>/build/**</exclude>
</excludes>
</resource>
</resources>
<plugins>
<plugin>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-maven-plugin</artifactId>
<configuration>
<executable>true</executable>
<excludes>
<exclude>
<groupId>org.projectlombok</groupId>
<artifactId>lombok</artifactId>
</exclude>
</excludes>
</configuration>
</plugin>
</plugins>
</build>
</project>

View File

@@ -0,0 +1,25 @@
package net.geedge;
import com.google.common.util.concurrent.AtomicDouble;
import io.micrometer.prometheus.PrometheusMeterRegistry;
import org.springframework.stereotype.Service;
import javax.annotation.Resource;
/**
* created by bailong001 on 2019/07/16 14:49
*/
@Service
public class CounterService {
@Resource
private PrometheusMeterRegistry appleMeterRegistry;
public Object incrCount(String type, String value) {
String name = "user.counter." + type;
if ("Olp".equals(type)) {
return appleMeterRegistry.gauge(name, new AtomicDouble(Double.parseDouble(value))).get();
}
return "null";
}
}

View File

@@ -0,0 +1,18 @@
package net.geedge;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.actuate.autoconfigure.metrics.JvmMetricsAutoConfiguration;
import org.springframework.boot.actuate.autoconfigure.metrics.LogbackMetricsAutoConfiguration;
import org.springframework.boot.actuate.autoconfigure.metrics.SystemMetricsAutoConfiguration;
import org.springframework.boot.actuate.autoconfigure.metrics.web.servlet.WebMvcMetricsAutoConfiguration;
import org.springframework.boot.actuate.autoconfigure.metrics.web.tomcat.TomcatMetricsAutoConfiguration;
import org.springframework.boot.autoconfigure.SpringBootApplication;
@SpringBootApplication(exclude = {JvmMetricsAutoConfiguration.class,SystemMetricsAutoConfiguration.class,TomcatMetricsAutoConfiguration.class,LogbackMetricsAutoConfiguration.class,WebMvcMetricsAutoConfiguration.class})
public class OlpExporterApplication {
public static void main(String[] args) throws Exception {
SpringApplication.run(OlpExporterApplication.class, args);
}
}

View File

@@ -0,0 +1,23 @@
package net.geedge.config;
//package net.geedge.config;
//
//import io.prometheus.client.CollectorRegistry;
//import io.prometheus.client.Gauge;
//import org.springframework.beans.factory.annotation.Autowired;
//import org.springframework.context.annotation.Bean;
//import org.springframework.context.annotation.Configuration;
//
//@Configuration
//public class MetricConfig {
//// @Autowired
// public CollectorRegistry collectorRegistry = new CollectorRegistry();
//
// @Bean
// Gauge processorNatGatewayMonitorSnat(){
// return Gauge.build().name("processorNatGatewayMonitor_snat")
// .labelNames("natgatewayid")
// .help("processorNatGatewayMonitorSnatrecord by gatewayid and nodeip")
// .register(collectorRegistry);
// }
//
//}

View File

@@ -0,0 +1,115 @@
package net.geedge.controller;
import io.prometheus.client.CollectorRegistry;
import io.prometheus.client.Gauge;
import net.geedge.util.UdpUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import java.io.IOException;
import java.util.Arrays;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
@RestController
public class OlpDataCollectController {
private static final Logger logger = LoggerFactory.getLogger(OlpDataCollectController.class);
@Autowired
private CollectorRegistry olpCollectorRegistry;
@GetMapping("/probe")
public void endpointOlp(HttpServletRequest request,HttpServletResponse response,@RequestParam(required = true) String target,@RequestParam(required = true) Integer[] slot,@RequestParam(required = false) Integer timeout) throws IOException {
if(timeout==null) {
timeout = 5000;//默认5秒
}
logger.info(target);
logger.info(Arrays.deepToString(slot));
logger.info(timeout+"");
olpCollectorRegistry.clear();
Gauge labeledDurationSecondsGauge = Gauge.build().name("probe_duration_seconds")
.labelNames("slot")
.help("Check device status response time")
.register(olpCollectorRegistry);
Gauge labeledBypassGauge = Gauge.build().name("probe_bypass")
.labelNames("slot")
.help("Return bypass status")
.register(olpCollectorRegistry);
Gauge labeledSuccessGauge = Gauge.build().name("probe_success")
.labelNames("slot")
.help("Displays whether or not the probe was a success")
.register(olpCollectorRegistry);
for(Integer oneSlot:slot) {
double start = System.currentTimeMillis();
String rlt = UdpUtils.send(target, oneSlot,timeout);
double end = System.currentTimeMillis();
double durationSeconds = (end-start)/1000;
String slotStr = oneSlot+"";
long bypass = rlt.endsWith("03")?0:(rlt.endsWith("0c")?1:-1);
long success = (rlt.endsWith("03")||rlt.endsWith("0c"))?1:0;
labeledDurationSecondsGauge.labels(slotStr).set(durationSeconds);
labeledBypassGauge.labels(slotStr).set(bypass);
labeledSuccessGauge.labels(slotStr).set(success);
}
response.sendRedirect("/probePrometheus");
}
// @GetMapping("/probe2")
// public Object endpointOlp2(@RequestParam(required = true) String target,@RequestParam(required = true) Integer[] slot,@RequestParam(required = false) Integer timeout) {
// if(timeout==null) {
// timeout = 5000;//默认5秒
// }
// logger.info(target);
// logger.info(Arrays.deepToString(slot));
// logger.info(timeout+"");
//
// List<MetricFamilySamples> mfs = new ArrayList<MetricFamilySamples>();
//
// GaugeMetricFamily labeledDurationSecondsGauge = new GaugeMetricFamily("probe_duration_seconds", "Check device status response time", Arrays.asList("slot"));
// mfs.add(labeledDurationSecondsGauge);
//
// GaugeMetricFamily labeledBypassGauge = new GaugeMetricFamily("probe_bypass", "Return bypass status", Arrays.asList("slot"));
// mfs.add(labeledBypassGauge);
//
// GaugeMetricFamily labeledSuccessGauge = new GaugeMetricFamily("probe_success", "Displays whether or not the probe was a success", Arrays.asList("slot"));
// mfs.add(labeledSuccessGauge);
//
// for(Integer oneSlot:slot) {
// double start = System.currentTimeMillis();
// String rlt = UdpUtils.send(target, oneSlot,timeout);
// double end = System.currentTimeMillis();
// double durationSeconds = (end-start)/1000;
// String slotStr = oneSlot+"";
// long bypass = rlt.endsWith("03")?0:(rlt.endsWith("0c")?1:-1);
// long success = (rlt.endsWith("03")||rlt.endsWith("0c"))?1:0;
//
// labeledDurationSecondsGauge.addMetric(Arrays.asList(slotStr), durationSeconds);
// labeledBypassGauge.addMetric(Arrays.asList(slotStr), bypass);
// labeledSuccessGauge.addMetric(Arrays.asList(slotStr),success);
// }
//
// Writer writer = new StringWriter();
// TextFormatUtils.write004(writer, mfs);
//
//// return "<pre style=\"word-wrap: break-word; white-space: pre-wrap;\">"+writer.toString()+"</pre>";
// return writer.toString();
// }
}

View File

@@ -0,0 +1,45 @@
package net.geedge.endpoint;
import io.prometheus.client.CollectorRegistry;
import io.prometheus.client.Gauge;
import io.prometheus.client.exporter.common.TextFormat;
import org.springframework.boot.actuate.endpoint.annotation.ReadOperation;
import org.springframework.boot.actuate.endpoint.web.annotation.WebEndpoint;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import java.io.IOException;
import java.io.StringWriter;
import java.io.Writer;
/**
* created by bailong001 on 2019/08/12 16:47
*/
@WebEndpoint(id = "probePrometheus")
public class OlpEndPoint {
private final CollectorRegistry collectorRegistry;
public OlpEndPoint(CollectorRegistry collectorRegistry) {
this.collectorRegistry = collectorRegistry;
// Gauge g = Gauge.build().name("gauge").help("blah").register();
// g.set(1);
// Gauge processorNatGatewayMonitorSnat =
// processorNatGatewayMonitorSnat.labels("id-123145","192.168.1.1").set(123);
// this.collectorRegistry.clear();
}
@ReadOperation(produces = TextFormat.CONTENT_TYPE_004)
public String scrape() {
try {
Writer writer = new StringWriter();
TextFormat.write004(writer, this.collectorRegistry.metricFamilySamples());
return writer.toString();
} catch (IOException ex) {
// This actually never happens since StringWriter::write() doesn't throw any
// IOException
throw new RuntimeException("Writing metrics failed", ex);
}
}
}

View File

@@ -0,0 +1,94 @@
package net.geedge.endpoint;
import io.micrometer.core.instrument.Clock;
import io.micrometer.prometheus.PrometheusConfig;
import io.micrometer.prometheus.PrometheusMeterRegistry;
import io.prometheus.client.CollectorRegistry;
import io.prometheus.client.Gauge;
//import org.springframework.boot.actuate.autoconfigure.endpoint.condition.ConditionalOnEnabledEndpoint;
import org.springframework.boot.actuate.autoconfigure.metrics.export.prometheus.PrometheusMetricsExportAutoConfiguration;
import org.springframework.boot.actuate.autoconfigure.metrics.export.prometheus.PrometheusProperties;
import org.springframework.boot.autoconfigure.AutoConfigureAfter;
import org.springframework.boot.autoconfigure.condition.ConditionalOnClass;
import org.springframework.boot.autoconfigure.condition.ConditionalOnMissingBean;
import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import javax.annotation.Resource;
/**
* created by bailong001 on 2019/08/12 16:30
*/
@Configuration
@AutoConfigureAfter(value = {PrometheusMetricsExportAutoConfiguration.class})
@ConditionalOnClass(value = {PrometheusMeterRegistry.class})
@ConditionalOnProperty(prefix = "management.metrics.export.olp", name = "enabled", havingValue = "true",
matchIfMissing = true)
public class OlpPrometheusAutoConfiguration {
CollectorRegistry collectorRegistry = new CollectorRegistry();
@Bean(name = "olpPrometheusProperties")
@ConfigurationProperties(prefix = "management.metrics.export.olp")
public PrometheusProperties olpPrometheusProperties() {
return new PrometheusProperties();
}
@Bean(name = "olpPrometheusConfig")
public PrometheusConfig olpPrometheusConfig() {
return new OlpPropertiesConfigAdapter(olpPrometheusProperties());
}
@Bean(name = "olpMeterRegistry")
public PrometheusMeterRegistry olpMeterRegistry(Clock clock) {
return new PrometheusMeterRegistry(olpPrometheusConfig(), olpCollectorRegistry(), clock);
}
// @Bean(name = "labeledDurationSecondsGauge")
// public Gauge labeledDurationSecondsGauge() {
// return Gauge.build().name("probe_duration_seconds")
// .labelNames("slot")
// .help("Check device status response time")
// .register(collectorRegistry);
// }
// @Bean(name = "labeledBypassGauge")
// public Gauge labeledBypassGauge() {
// return Gauge.build().name("probe_bypass")
// .labelNames("slot")
// .help("Return bypass status")
// .register(collectorRegistry);
// }
// @Bean(name = "labeledSuccessGauge")
// public Gauge labeledSuccessGauge() {
// return Gauge.build().name("probe_success")
// .labelNames("slot")
// .help("Displays whether or not the probe was a success")
// .register(collectorRegistry);
// }
@Bean(name = "olpCollectorRegistry")
public CollectorRegistry olpCollectorRegistry() {
// CollectorRegistry collectorRegistry = new CollectorRegistry(true);
// CollectorRegistry collectorRegistry = new CollectorRegistry();
// collectorRegistry.clear();
return collectorRegistry;
}
@Configuration
public static class TicketScrapeEndpointConfiguration {
@Resource
private CollectorRegistry olpCollectorRegistry;
@Bean(name = "olpEndpoint")
@ConditionalOnMissingBean
public OlpEndPoint olpEndpoint() {
return new OlpEndPoint(olpCollectorRegistry);
}
}
}

View File

@@ -0,0 +1,34 @@
package net.geedge.endpoint;
import io.micrometer.prometheus.PrometheusConfig;
import org.springframework.boot.actuate.autoconfigure.metrics.export.prometheus.PrometheusProperties;
import org.springframework.boot.actuate.autoconfigure.metrics.export.properties.PropertiesConfigAdapter;
import java.time.Duration;
/**
* created by bailong001 on 2019/08/12 17:56
*/
public class OlpPropertiesConfigAdapter extends PropertiesConfigAdapter<PrometheusProperties>
implements PrometheusConfig {
OlpPropertiesConfigAdapter(PrometheusProperties properties) {
super(properties);
}
@Override
public String get(String key) {
return null;
}
@Override
public boolean descriptions() {
return get(PrometheusProperties::isDescriptions, PrometheusConfig.super::descriptions);
}
@Override
public Duration step() {
return get(PrometheusProperties::getStep, PrometheusConfig.super::step);
}
}

View File

@@ -0,0 +1,207 @@
package net.geedge.util;
public class HexUtils {
/**
* 16进制表示的字符串转换为字节数组
*
* @param hexString 16进制表示的字符串
* @return byte[] 字节数组
*/
public static byte[] hexStringToByteArray(String hexString) {
hexString = hexString.replaceAll(" ", "");
int len = hexString.length();
byte[] bytes = new byte[len / 2];
for (int i = 0; i < len; i += 2) {
// 两位一组,表示一个字节,把这样表示的16进制字符串还原成一个字节
bytes[i / 2] = (byte) ((Character.digit(hexString.charAt(i), 16) << 4) + Character
.digit(hexString.charAt(i + 1), 16));
}
return bytes;
}
/**
* 字节转十六进制字符串
* @param b 需要进行转换的byte字节
* @return 转换后的Hex字符串
*/
public static String byteToHex(byte b){
String hex = Integer.toHexString(b & 0xFF);
if(hex.length() < 2){
hex = "0" + hex;
}
return hex;
}
/**
* byte[]数组转换为16进制的字符串
*
* @param bytes 要转换的字节数组
* @return 转换后的结果
*/
public static String bytesToHexString(byte[] bytes) {
StringBuilder sb = new StringBuilder();
for (int i = 0; i < bytes.length; i++) {
String hex = Integer.toHexString(0xFF & bytes[i]);
if (hex.length() == 1) {
sb.append('0');
}
sb.append(hex);
}
return sb.toString();
}
/**
* 合并字节数组System.arraycopy()方法
* @param bt1
* @param bt2
* @return
*/
public static byte[] byteMerger(byte[] bt1, byte[] bt2){
byte[] bt3 = new byte[bt1.length+bt2.length];
System.arraycopy(bt1, 0, bt3, 0, bt1.length);
System.arraycopy(bt2, 0, bt3, bt1.length, bt2.length);
return bt3;
}
/**
* 从一个byte[]数组中截取一部分
* @param src
* @param begin
* @param count
* @return
*/
public static byte[] subBytes(byte[] src, int begin, int count) {
byte[] bs = new byte[count];
for (int i=begin;i<begin+count; i++) {
bs[i-begin] = src[i];
}
return bs;
}
/**
* Hex字符串转byte :需注意的是Hex的字符串必须为十六进制的字符否则会抛出异常。Hex的范围为0x00到0xFF。
* @param inHex 待转换的Hex字符串 "55"
* @return 转换后的byte 85
*/
public static byte hexToByte(String inHex){
return (byte)Integer.parseInt(inHex,16);
}
/**
* 将16进制字符串转换为10进制数
* @param inHex
* @return
*/
public static int hexToInt(String inHex){
return Integer.parseInt(inHex, 16);
}
/**
* 将10进制数转换为4个字节的16进制字符串
* @param inHex
* @return
*/
public static String intToHex(int inNum){
return String.format("%08x", inNum);
}
public static String intToHex(long inNum){
return String.format("%08x", inNum);
}
public static void main(String[] args) {
// String s = " ";
// System.out.print(HexUtils.stringToHexString(s));
byte[] pzlxByte = new byte[2];
String pzlx = new String(pzlxByte);//2byte
// System.out.println(pzlx);
// System.out.println(pzlx.getBytes().length);
// System.out.println(HexUtils.stringToHexString(pzlx));
byte[] pzidByte = new byte[17];
String pzid = new String(pzidByte);//17byte
// System.out.println(pzid);
// System.out.println(pzid.getBytes().length);
// System.out.println(HexUtils.stringToHexString(pzid));
String rltHex = HexUtils.bytesToHexString(pzlx.getBytes());
String rltHex2 = HexUtils.bytesToHexString(pzid.getBytes());
System.out.println(rltHex);
System.out.println(rltHex2);
}
/**
* 16进制字符串转换为字符串
*
* @param s
* @return
*/
// public static String hexStringToString(String s) {
// if (s == null || s.equals("")) {
// return null;
// }
// s = s.replace(" ", "");
// byte[] baKeyword = new byte[s.length() / 2];
// for (int i = 0; i < baKeyword.length; i++) {
// try {
// baKeyword[i] = (byte) (0xff & Integer.parseInt(
// s.substring(i * 2, i * 2 + 2), 16));
// } catch (Exception e) {
// e.printStackTrace();
// }
// }
// try {
// s = new String(baKeyword, "gbk");
// new String();
// } catch (Exception e1) {
// e1.printStackTrace();
// }
// return s;
// }
/**
* hex字符串转byte数组:如果Hex超过0xFF显然转换后结果不是一个byte而是一个byte数组
* @param inHex 待转换的Hex字符串
* @return 转换后的byte数组结果
*/
public static byte[] hexToByteArray(String inHex){
int hexlen = inHex.length();
byte[] result;
if (hexlen % 2 == 1){
//奇数
hexlen++;
result = new byte[(hexlen/2)];
inHex="0"+inHex;
}else {
//偶数
result = new byte[(hexlen/2)];
}
int j=0;
for (int i = 0; i < hexlen; i+=2){
result[j]=hexToByte(inHex.substring(i,i+2));
j++;
}
return result;
}
/**
* 一个十六进制数Hex正好为4个二进制位。一个字节byte为8个二进制位。因此一个字节可表示为两个十六进制数字。
* 字节数组转16进制
* @param bytes 需要转换的byte数组
* @return 转换后的Hex字符串
*/
public static String bytesToHex(byte[] bytes) {
StringBuffer sb = new StringBuffer();
for(int i = 0; i < bytes.length; i++) {
String hex = Integer.toHexString(bytes[i] & 0xFF);
if(hex.length() < 2){
sb.append(0);
}
sb.append(hex);
}
return sb.toString();
}
}

View File

@@ -0,0 +1,110 @@
package net.geedge.util;
import java.io.IOException;
import java.io.Writer;
import java.util.List;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import io.prometheus.client.Collector;
import io.prometheus.client.Collector.MetricFamilySamples;
public class TextFormatUtils {
private static final Logger logger = LoggerFactory.getLogger(TextFormatUtils.class);
public static void write004(Writer writer, List<MetricFamilySamples> mfs) {
try {
String enter = "\n";
for(MetricFamilySamples mfSample:mfs) {
Collector.MetricFamilySamples metricFamilySamples = mfSample;
writer.write("# HELP ");
writer.write(metricFamilySamples.name);
writer.write(' ');
writeEscapedHelp(writer, metricFamilySamples.help);
writer.write(enter);
writer.write("# TYPE ");
writer.write(metricFamilySamples.name);
writer.write(' ');
writer.write(typeString(metricFamilySamples.type));
writer.write(enter);
for (Collector.MetricFamilySamples.Sample sample: metricFamilySamples.samples) {
writer.write(sample.name);
if (sample.labelNames.size() > 0) {
writer.write('{');
for (int i = 0; i < sample.labelNames.size(); ++i) {
writer.write(sample.labelNames.get(i));
writer.write("=\"");
writeEscapedLabelValue(writer, sample.labelValues.get(i));
writer.write("\",");
}
writer.write('}');
}
writer.write(' ');
writer.write(Collector.doubleToGoString(sample.value));
if (sample.timestampMs != null){
writer.write(' ');
writer.write(sample.timestampMs.toString());
}
writer.write(enter);
}
}
}catch (Exception e) {
logger.error(e.getMessage());
}
}
private static void writeEscapedHelp(Writer writer, String s) throws IOException {
for (int i = 0; i < s.length(); i++) {
char c = s.charAt(i);
switch (c) {
case '\\':
writer.append("\\\\");
break;
case '\n':
writer.append("\\n");
break;
default:
writer.append(c);
}
}
}
private static String typeString(Collector.Type t) {
switch (t) {
case GAUGE:
return "gauge";
case COUNTER:
return "counter";
case SUMMARY:
return "summary";
case HISTOGRAM:
return "histogram";
default:
return "untyped";
}
}
private static void writeEscapedLabelValue(Writer writer, String s) throws IOException {
for (int i = 0; i < s.length(); i++) {
char c = s.charAt(i);
switch (c) {
case '\\':
writer.append("\\\\");
break;
case '\"':
writer.append("\\\"");
break;
case '\n':
writer.append("\\n");
break;
default:
writer.append(c);
}
}
}
}

View File

@@ -0,0 +1,55 @@
package net.geedge.util;
import java.net.DatagramPacket;
import java.net.DatagramSocket;
import java.net.InetAddress;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
public class UdpUtils {
private static final Logger logger = LoggerFactory.getLogger(TextFormatUtils.class);
public static String send(String target,Integer slot,int timeout) {
String sendIp = target;
int port = 6800;
String rlt = "";
DatagramSocket ds = null;
try {
if(target.contains(":")) {
int splitIndex = target.indexOf(":");
sendIp = target.substring(0, splitIndex);
port = Integer.parseInt(target.substring(splitIndex+1, target.length()));
}
ds = new DatagramSocket();//通过DatagramSocket对象创建udp服务
ds.setSoTimeout(timeout);
// String line = "00 06 0502 00 00 68c2"; //发送的16进制字符串
String slotStr = slot+"";
if(slot<10) {
slotStr = "0"+slotStr;
}
String line = "00 "+slotStr+" 0502 00 00"; //发送的16进制字符串
byte[] buf = HexUtils.hexStringToByteArray(line);
DatagramPacket dp = new DatagramPacket(buf,buf.length,InetAddress.getByName(sendIp),port);//发送至指定IP指定端口
ds.send(dp);//通过send方法将数据包发送出去
//定义数据包,用于存储数据
byte[] buf2 = new byte[8];
DatagramPacket dp2 = new DatagramPacket(buf2,buf2.length);
ds.receive(dp2);//通过服务的receive方法将收到数据存入数据包中,receive()为阻塞式方法
//通过数据包的方法获取其中的数据
String ip = dp2.getAddress().getHostAddress();
System.out.println(ip+"::"+HexUtils.bytesToHexString(buf2));
rlt = HexUtils.bytesToHexString(buf2);
}catch (Exception e) {
logger.error(sendIp+"::"+slot+">>"+e.getMessage());
}finally {
if(ds!=null) {
ds.close();//关闭资源
}
}
return rlt;
}
}

View File

@@ -0,0 +1,28 @@
server:
port: 9100
servlet:
context-path: /
spring:
application:
name: olp_exporter
management:
metrics:
binders:
jvm:
enabled: false
files:
enabled: false
integration:
enabled: false
logback:
enabled: false
processor:
enabled: false
uptime:
enabled: false
endpoints:
web:
base-path: /
exposure:
include: ['probePrometheus']

View File

@@ -0,0 +1,28 @@
server:
port: 9100
servlet:
context-path: /
spring:
application:
name: olp_exporter
management:
metrics:
binders:
jvm:
enabled: false
files:
enabled: false
integration:
enabled: false
logback:
enabled: false
processor:
enabled: false
uptime:
enabled: false
endpoints:
web:
base-path: /
exposure:
include: ['probePrometheus']

View File

@@ -0,0 +1,28 @@
server:
port: 10096
servlet:
context-path: /
spring:
application:
name: olp_exporter
management:
metrics:
binders:
jvm:
enabled: false
files:
enabled: false
integration:
enabled: false
logback:
enabled: false
processor:
enabled: false
uptime:
enabled: false
endpoints:
web:
base-path: /
exposure:
include: [info,health,heapdump,threaddump,env,mappings,probePrometheus]

View File

@@ -0,0 +1,8 @@
_______ _ _______ _______ _______ _______ _______ _________ _______ _______
( ___ )( \ ( ____ ) ( ____ \|\ /|( ____ )( ___ )( ____ )\__ __/( ____ \( ____ )
| ( ) || ( | ( )| | ( \/( \ / )| ( )|| ( ) || ( )| ) ( | ( \/| ( )|
| | | || | | (____)| | (__ \ (_) / | (____)|| | | || (____)| | | | (__ | (____)|
| | | || | | _____) | __) ) _ ( | _____)| | | || __) | | | __) | __)
| | | || | | ( | ( / ( ) \ | ( | | | || (\ ( | | | ( | (\ (
| (___) || (____/\| ) | (____/\( / \ )| ) | (___) || ) \ \__ | | | (____/\| ) \ \__
(_______)(_______/|/ (_______/|/ \||/ (_______)|/ \__/ )_( (_______/|/ \__/

View File

@@ -0,0 +1,10 @@
################################## 1.INSTALL #######################################
#
# Execute install.sh script
# ./install.sh
#
################################## 2、CHECK ########################################
#
# Browser or CURL visit http://[IP]:10095/health ,response {"status":"UP"} is OK
#

View File

@@ -0,0 +1,26 @@
#!/bin/bash
CUR_PATH=`pwd`
echo "install path: $CUR_PATH"
echo "install olp_exporter as a systemd service"
chmod +x $CUR_PATH/olp_exporter
cat > /etc/systemd/system/olp_exporter.service <<EOF
[Unit]
Description=olp_exporter
After=syslog.target
[Service]
ExecStart=$CUR_PATH/olp_exporter
SuccessExitStatus=143
RestartSec=10s
Restart=always
[Install]
WantedBy=multi-user.target
EOF
systemctl daemon-reload
echo "systemctl start olp_exporter.service"
systemctl start olp_exporter.service
echo "Set the power-on start-up"
systemctl enable olp_exporter.service
echo "install done"