code
stringlengths
1
1.05M
repo_name
stringlengths
6
83
path
stringlengths
3
242
language
stringclasses
222 values
license
stringclasses
20 values
size
int64
1
1.05M
package com.zmops.zeus.iot.server.receiver; public class Const { public static final String CAMEL_ZABBIX_COMPONENT_NAME = "Zabbix"; public static final String CAMEL_ARK_COMPONENT_NAME = "ArkBiz"; }
2301_81045437/zeus-iot
iot-server/server-camel-receiver/src/main/java/com/zmops/zeus/iot/server/receiver/Const.java
Java
gpl-3.0
209
package com.zmops.zeus.iot.server.receiver; /** * 协议服务启停 */ public enum ProtocolAction { stop, start }
2301_81045437/zeus-iot
iot-server/server-camel-receiver/src/main/java/com/zmops/zeus/iot/server/receiver/ProtocolAction.java
Java
gpl-3.0
123
package com.zmops.zeus.iot.server.receiver; /** * @author nantian created at 2021/10/24 13:47 */ public enum ProtocolEnum { HttpServer, MqttClient, TcpServer, UdpServer, CoapServer, WebSocketServer }
2301_81045437/zeus-iot
iot-server/server-camel-receiver/src/main/java/com/zmops/zeus/iot/server/receiver/ProtocolEnum.java
Java
gpl-3.0
208
package com.zmops.zeus.iot.server.receiver; import lombok.Setter; import org.apache.camel.builder.RouteBuilder; import java.util.Map; /** * @author nantian created at 2021/10/24 14:38 */ public abstract class ReceiverServerRoute extends RouteBuilder { @Setter protected String routeId; @Setter protected Map<String, Object> options; public ReceiverServerRoute(String routeId, Map<String, Object> options) { this.routeId = routeId; this.options = options; } }
2301_81045437/zeus-iot
iot-server/server-camel-receiver/src/main/java/com/zmops/zeus/iot/server/receiver/ReceiverServerRoute.java
Java
gpl-3.0
507
package com.zmops.zeus.iot.server.receiver.handler.ark; import com.zmops.zeus.server.library.module.ModuleManager; import org.apache.camel.Endpoint; import org.apache.camel.support.DefaultComponent; import java.util.Map; /** * @author nantian created at 2021/12/2 22:35 */ public class ArkBizComponent extends DefaultComponent { private final ModuleManager moduleManager; public ArkBizComponent(ModuleManager moduleManager) { this.moduleManager = moduleManager; } @Override protected Endpoint createEndpoint(String uri, String remaining, Map<String, Object> parameters) throws Exception { String uniqueId = getAndRemoveParameter(parameters, "uniqueId", String.class); String methodName = getAndRemoveParameter(parameters, "methodName", String.class); return new ArkBizEndpoint(uri, this, moduleManager, uniqueId, methodName); } }
2301_81045437/zeus-iot
iot-server/server-camel-receiver/src/main/java/com/zmops/zeus/iot/server/receiver/handler/ark/ArkBizComponent.java
Java
gpl-3.0
896
package com.zmops.zeus.iot.server.receiver.handler.ark; import org.apache.camel.Endpoint; import org.apache.camel.Processor; import org.apache.camel.support.DefaultConsumer; /** * @author nantian created at 2021/12/2 22:35 */ public class ArkBizConsumer extends DefaultConsumer { public ArkBizConsumer(Endpoint endpoint, Processor processor) { super(endpoint, processor); } }
2301_81045437/zeus-iot
iot-server/server-camel-receiver/src/main/java/com/zmops/zeus/iot/server/receiver/handler/ark/ArkBizConsumer.java
Java
gpl-3.0
397
package com.zmops.zeus.iot.server.receiver.handler.ark; import com.zmops.zeus.server.library.module.ModuleManager; import org.apache.camel.Component; import org.apache.camel.Consumer; import org.apache.camel.Processor; import org.apache.camel.Producer; import org.apache.camel.support.DefaultEndpoint; /** * @author nantian created at 2021/12/2 22:34 */ @SuppressWarnings("all") public class ArkBizEndpoint extends DefaultEndpoint { private final ModuleManager moduleManager; private final ArkBizProducer producer; public ArkBizEndpoint(String endpointUri, Component component, ModuleManager moduleManager, String uniqueId, String methodName) { super(endpointUri, component); this.moduleManager = moduleManager; this.producer = new ArkBizProducer(this, moduleManager, uniqueId, methodName); } @Override public Producer createProducer() throws Exception { return this.producer; } @Override public Consumer createConsumer(Processor processor) throws Exception { return new ArkBizConsumer(this, processor); } @Override public boolean isSingleton() { return false; } }
2301_81045437/zeus-iot
iot-server/server-camel-receiver/src/main/java/com/zmops/zeus/iot/server/receiver/handler/ark/ArkBizEndpoint.java
Java
gpl-3.0
1,203
package com.zmops.zeus.iot.server.receiver.handler.ark; import com.zmops.zeus.dto.DataMessage; import com.zmops.zeus.dto.ItemValue; import com.zmops.zeus.facade.DynamicProcotol; import com.zmops.zeus.iot.server.receiver.module.CamelReceiverModule; import com.zmops.zeus.iot.server.receiver.service.ReferenceClientService; import com.zmops.zeus.server.library.module.ModuleManager; import org.apache.camel.Endpoint; import org.apache.camel.Exchange; import org.apache.camel.support.DefaultProducer; import java.util.Collections; import java.util.List; /** * @author nantian created at 2021/12/2 22:35 */ @SuppressWarnings("all") public class ArkBizProducer extends DefaultProducer { private final ModuleManager moduleManager; private final DynamicProcotol dynamicProcotol; public ArkBizProducer(Endpoint endpoint, ModuleManager moduleManager, String uniqueId, String methodName) { super(endpoint); this.moduleManager = moduleManager; ReferenceClientService referenceClientService = moduleManager.find(CamelReceiverModule.NAME) .provider().getService(ReferenceClientService.class); dynamicProcotol = referenceClientService.getDynamicProtocolClient(uniqueId); } @Override public void process(Exchange exchange) throws Exception { DataMessage message = new DataMessage(); message.setBody(exchange.getMessage().getBody()); message.setHeaders(exchange.getMessage().getHeaders()); List<ItemValue> itemValueList = dynamicProcotol.protocolHandler(message); if (itemValueList == null) { itemValueList = Collections.emptyList(); } exchange.getIn().setBody(itemValueList); } }
2301_81045437/zeus-iot
iot-server/server-camel-receiver/src/main/java/com/zmops/zeus/iot/server/receiver/handler/ark/ArkBizProducer.java
Java
gpl-3.0
1,723
package com.zmops.zeus.iot.server.receiver.handler.zabbix; import lombok.Getter; import lombok.Setter; import java.util.Map; /** * @author nantian created at 2021/8/23 18:01 * <p> * 方便大家理解,转换一下 命名 */ @Getter @Setter public class IoTDeviceValue { private String deviceId; // 设备ID private Map<String, String> attributes; // key : value private Long clock; // 毫秒,70年到现在时间戳 }
2301_81045437/zeus-iot
iot-server/server-camel-receiver/src/main/java/com/zmops/zeus/iot/server/receiver/handler/zabbix/IoTDeviceValue.java
Java
gpl-3.0
445
package com.zmops.zeus.iot.server.receiver.handler.zabbix; import com.zmops.zeus.server.library.module.ModuleManager; import org.apache.camel.Endpoint; import org.apache.camel.support.DefaultComponent; import java.util.Map; /** * @author nantian created at 2021/8/16 22:38 */ public class ZabbixSenderComponent extends DefaultComponent { private final ModuleManager moduleManager; public ZabbixSenderComponent(ModuleManager moduleManager) { this.moduleManager = moduleManager; } @Override protected Endpoint createEndpoint(String uri, String remaining, Map<String, Object> parameters) throws Exception { // parameters 里面的参数 必须要清空 String value = getAndRemoveParameter(parameters, "method", String.class); return new ZabbixSenderEndpoint(uri, this, moduleManager); } }
2301_81045437/zeus-iot
iot-server/server-camel-receiver/src/main/java/com/zmops/zeus/iot/server/receiver/handler/zabbix/ZabbixSenderComponent.java
Java
gpl-3.0
853
package com.zmops.zeus.iot.server.receiver.handler.zabbix; import org.apache.camel.Endpoint; import org.apache.camel.Processor; import org.apache.camel.support.DefaultConsumer; /** * @author nantian created at 2021/8/16 22:47 */ public class ZabbixSenderConsumer extends DefaultConsumer { public ZabbixSenderConsumer(Endpoint endpoint, Processor processor) { super(endpoint, processor); } }
2301_81045437/zeus-iot
iot-server/server-camel-receiver/src/main/java/com/zmops/zeus/iot/server/receiver/handler/zabbix/ZabbixSenderConsumer.java
Java
gpl-3.0
412
package com.zmops.zeus.iot.server.receiver.handler.zabbix; import com.zmops.zeus.server.library.module.ModuleManager; import org.apache.camel.Component; import org.apache.camel.Consumer; import org.apache.camel.Processor; import org.apache.camel.Producer; import org.apache.camel.support.DefaultEndpoint; /** * @author nantian created at 2021/8/16 22:45 */ public class ZabbixSenderEndpoint extends DefaultEndpoint { private final ModuleManager moduleManager; private final ZabbixTrapperProducer producer; public ZabbixSenderEndpoint(String endpointUri, Component component, ModuleManager moduleManager) { super(endpointUri, component); this.moduleManager = moduleManager; this.producer = new ZabbixTrapperProducer(this, moduleManager); } @Override public Producer createProducer() throws Exception { return producer; // 每次 process 都会创建一个对象, 单例返回 } @Override public Consumer createConsumer(Processor processor) throws Exception { return new ZabbixSenderConsumer(this, processor); //TODO } @Override public boolean isSingleton() { return false; } }
2301_81045437/zeus-iot
iot-server/server-camel-receiver/src/main/java/com/zmops/zeus/iot/server/receiver/handler/zabbix/ZabbixSenderEndpoint.java
Java
gpl-3.0
1,185
package com.zmops.zeus.iot.server.receiver.handler.zabbix; import com.zmops.zeus.dto.ItemValue; import lombok.Getter; import lombok.Setter; import java.util.ArrayList; import java.util.List; /** * @author nantian created at 2021/8/23 16:49 */ public class ZabbixTrapper { @Getter private final String request = "sender data"; @Setter @Getter private List<ItemValue> data; public ZabbixTrapper(List<ItemValue> itemValues) { data = new ArrayList<>(); data.addAll(itemValues); } }
2301_81045437/zeus-iot
iot-server/server-camel-receiver/src/main/java/com/zmops/zeus/iot/server/receiver/handler/zabbix/ZabbixTrapper.java
Java
gpl-3.0
531
package com.zmops.zeus.iot.server.receiver.handler.zabbix; import com.google.gson.Gson; import com.zmops.zeus.dto.ItemValue; import com.zmops.zeus.iot.server.receiver.handler.zabbix.worker.ItemDataTransferWorker; import com.zmops.zeus.server.library.module.ModuleManager; import com.zmops.zeus.server.library.util.StringUtil; import lombok.extern.slf4j.Slf4j; import org.apache.camel.Endpoint; import org.apache.camel.Exchange; import org.apache.camel.Message; import org.apache.camel.support.DefaultProducer; import java.util.List; import java.util.concurrent.ExecutorService; import java.util.concurrent.Executors; /** * @author nantian created at 2021/8/16 22:48 * <p> * to("Zabbix") */ @Slf4j public class ZabbixTrapperProducer extends DefaultProducer { private final ModuleManager moduleManager; private final ItemDataTransferWorker itemDataTransferWorker; private final ExecutorService itemValueThread = Executors.newFixedThreadPool(20); public ZabbixTrapperProducer(Endpoint endpoint, ModuleManager moduleManager) { super(endpoint); this.moduleManager = moduleManager; this.itemDataTransferWorker = new ItemDataTransferWorker(moduleManager); } /** * Body 必须是 ItemValue * * @param exchange Exchange */ @Override public void process(Exchange exchange) { Message message = exchange.getIn(); if (message.getBody() == null && !(message.getBody() instanceof List)) { return; } List<ItemValue> values = (List<ItemValue>) message.getBody(); for (ItemValue itemValue : values) { if (StringUtil.isEmpty(itemValue.getHost()) || StringUtil.isEmpty(itemValue.getKey()) || StringUtil.isEmpty(itemValue.getValue())) { log.error(" process item data error,{}", new Gson().toJson(itemValue)); continue; } itemValueThread.submit(() -> { itemDataTransferWorker.in(itemValue); }); } exchange.getMessage().setBody("{\"success\":\"true\"}"); } }
2301_81045437/zeus-iot
iot-server/server-camel-receiver/src/main/java/com/zmops/zeus/iot/server/receiver/handler/zabbix/ZabbixTrapperProducer.java
Java
gpl-3.0
2,138
package com.zmops.zeus.iot.server.receiver.handler.zabbix.process; import com.google.gson.Gson; import com.zmops.zeus.dto.ItemValue; import com.zmops.zeus.iot.server.receiver.handler.zabbix.IoTDeviceValue; import org.apache.camel.Exchange; import org.apache.camel.Message; import org.apache.camel.Processor; import java.io.ByteArrayOutputStream; import java.io.IOException; import java.io.InputStream; import java.util.ArrayList; import java.util.List; /** * @author nantian created at 2021/8/23 17:16 * <p> * Json 转 对象,进队列,一定要转成 ItemValue 对象,{@link ItemValue} */ public class JsonToItemValueProcess implements Processor { private final Gson gson = new Gson(); @Override public void process(Exchange exchange) throws Exception { Message message = exchange.getIn(); InputStream bodyStream = (InputStream) message.getBody(); String inputContext = this.analysisMessage(bodyStream); IoTDeviceValue iotValue = gson.fromJson(inputContext, IoTDeviceValue.class); List<ItemValue> itemValueList = new ArrayList<>(); iotValue.getAttributes().forEach((key, value) -> { ItemValue item = new ItemValue(iotValue.getDeviceId(), iotValue.getClock()); item.setKey(key); item.setValue(value); itemValueList.add(item); }); exchange.getMessage().setBody(itemValueList); } private String analysisMessage(InputStream bodyStream) throws IOException { ByteArrayOutputStream outStream = new ByteArrayOutputStream(); byte[] contextBytes = new byte[4096]; int realLen; while ((realLen = bodyStream.read(contextBytes, 0, 4096)) != -1) { outStream.write(contextBytes, 0, realLen); } // 返回从Stream中读取的字串 try { return outStream.toString("UTF-8"); } finally { outStream.close(); } } }
2301_81045437/zeus-iot
iot-server/server-camel-receiver/src/main/java/com/zmops/zeus/iot/server/receiver/handler/zabbix/process/JsonToItemValueProcess.java
Java
gpl-3.0
1,964
/* * 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 com.zmops.zeus.iot.server.receiver.handler.zabbix.worker; import com.zmops.zeus.server.library.module.ModuleDefineHolder; import lombok.Getter; /** * Abstract worker definition. Provide the {@link ModuleDefineHolder} to make sure the worker could find and access * services in different modules. Also, {@link #in(Object)} is provided as the primary entrance of every worker. * <p> * * @param <INPUT> the datatype this worker implementation processes. * @editor nantian * 数据从协议入口 发送到 zabbix 过程中的队列,to("zabbix") */ public abstract class AbstractWorker<INPUT> { @Getter private final ModuleDefineHolder moduleDefineHolder; public AbstractWorker(ModuleDefineHolder moduleDefineHolder) { this.moduleDefineHolder = moduleDefineHolder; } /** * Main entrance of this worker. */ public abstract void in(INPUT input); }
2301_81045437/zeus-iot
iot-server/server-camel-receiver/src/main/java/com/zmops/zeus/iot/server/receiver/handler/zabbix/worker/AbstractWorker.java
Java
gpl-3.0
1,714
package com.zmops.zeus.iot.server.receiver.handler.zabbix.worker; import com.google.gson.Gson; import com.zmops.zeus.dto.ItemValue; import com.zmops.zeus.iot.server.receiver.handler.zabbix.ZabbixTrapper; import com.zmops.zeus.iot.server.sender.module.ZabbixSenderModule; import com.zmops.zeus.iot.server.sender.service.ZabbixSenderService; import com.zmops.zeus.iot.server.telemetry.TelemetryModule; import com.zmops.zeus.iot.server.telemetry.api.CounterMetrics; import com.zmops.zeus.iot.server.telemetry.api.MetricsCreator; import com.zmops.zeus.iot.server.telemetry.api.MetricsTag; import com.zmops.zeus.server.datacarrier.DataCarrier; import com.zmops.zeus.server.datacarrier.consumer.BulkConsumePool; import com.zmops.zeus.server.datacarrier.consumer.ConsumerPoolFactory; import com.zmops.zeus.server.datacarrier.consumer.IConsumer; import com.zmops.zeus.server.library.module.ModuleManager; import lombok.extern.slf4j.Slf4j; import java.io.IOException; import java.util.ArrayList; import java.util.Collection; import java.util.List; /** * @author nantian created at 2021/8/23 15:11 * <p> * 数据发送队列 */ @Slf4j public class ItemDataTransferWorker extends TransferWorker<ItemValue> { private final DataCarrier<ItemValue> dataCarrier; private final CounterMetrics iotDataTransferCounter; private final Gson gson = new Gson(); public ItemDataTransferWorker(ModuleManager moduleManager) { super(moduleManager); String name = "ITEMVALUE_TRANSFER_TUNNEL"; int size = BulkConsumePool.Creator.recommendMaxSize() / 8; if (size == 0) { size = 1; } BulkConsumePool.Creator creator = new BulkConsumePool.Creator(name, size, 20); try { ConsumerPoolFactory.INSTANCE.createIfAbsent(name, creator); } catch (Exception e) { e.printStackTrace(); } this.dataCarrier = new DataCarrier<>("ZABBIX_SENDER", name, 4, 2000); this.dataCarrier.consume(ConsumerPoolFactory.INSTANCE.get(name), new SenderConsumer()); // #### 发送数量 指标采集 MetricsCreator metricsCreator = moduleManager.find(TelemetryModule.NAME) .provider() .getService(MetricsCreator.class); iotDataTransferCounter = metricsCreator.createCounter( "transfer_data_count", "The count number of iot device data in transfer", new MetricsTag.Keys("name"), new MetricsTag.Values("transfer_data_count") ); } @Override public void in(ItemValue itemValue) { iotDataTransferCounter.inc(); dataCarrier.produce(itemValue); } @Override public void prepareBatch(Collection<ItemValue> lastCollection) { long start = System.currentTimeMillis(); if (lastCollection.size() == 0) { return; } int maxBatchGetSize = 500; final int batchSize = Math.min(maxBatchGetSize, lastCollection.size()); List<ItemValue> valueList = new ArrayList<>(); for (ItemValue data : lastCollection) { valueList.add(data); if (valueList.size() == batchSize) { batchSenderDataToZabbix(valueList); } } if (valueList.size() > 0) { batchSenderDataToZabbix(valueList); } log.debug("batch sender data size:{}, took time: {}", lastCollection.size(), System.currentTimeMillis() - start); } private void batchSenderDataToZabbix(List<ItemValue> valueList) { ZabbixTrapper zabbixTrapper = new ZabbixTrapper(valueList); ZabbixSenderService senderService = getModuleDefineHolder() .find(ZabbixSenderModule.NAME).provider().getService(ZabbixSenderService.class); try { String sendResult = senderService.sendData(gson.toJson(zabbixTrapper)); log.debug(sendResult); } catch (IOException e) { log.error(" itemvalue data sender error,msg :{}", e.getMessage()); e.printStackTrace(); } finally { valueList.clear(); } } private class SenderConsumer implements IConsumer<ItemValue> { @Override public void init() { } @Override public void consume(List<ItemValue> data) { ItemDataTransferWorker.this.onWork(data); } @Override public void onError(List<ItemValue> data, Throwable t) { log.error(t.getMessage(), t); } @Override public void onExit() { } } }
2301_81045437/zeus-iot
iot-server/server-camel-receiver/src/main/java/com/zmops/zeus/iot/server/receiver/handler/zabbix/worker/ItemDataTransferWorker.java
Java
gpl-3.0
4,611
/* * 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 com.zmops.zeus.iot.server.receiver.handler.zabbix.worker; import com.zmops.zeus.dto.Item; import com.zmops.zeus.server.library.module.ModuleDefineHolder; import lombok.extern.slf4j.Slf4j; import java.util.Collection; import java.util.List; /** * 1. 协议入口 -> zabbix trapper item * * @param <INPUT> The type of worker input. */ @Slf4j public abstract class TransferWorker<INPUT extends Item> extends AbstractWorker<INPUT> { TransferWorker(ModuleDefineHolder moduleDefineHolder) { super(moduleDefineHolder); } void onWork(List<INPUT> input) { prepareBatch(input); } public abstract void prepareBatch(Collection<INPUT> lastCollection); }
2301_81045437/zeus-iot
iot-server/server-camel-receiver/src/main/java/com/zmops/zeus/iot/server/receiver/handler/zabbix/worker/TransferWorker.java
Java
gpl-3.0
1,503
package com.zmops.zeus.iot.server.receiver.module; import com.zmops.zeus.iot.server.receiver.service.CamelContextHolderService; import com.zmops.zeus.iot.server.receiver.service.ReferenceClientService; import com.zmops.zeus.server.library.module.ModuleDefine; import java.util.ArrayList; import java.util.List; /** * @author nantian created at 2021/10/23 20:59 * <p> * 通信服务模块,Apache Camel 统一接入 */ public class CamelReceiverModule extends ModuleDefine { public static final String NAME = "camel-receiver"; public CamelReceiverModule() { super(NAME); } @Override public Class<?>[] services() { List<Class<?>> classes = new ArrayList<>(); classes.add(CamelContextHolderService.class); classes.add(ReferenceClientService.class); return classes.toArray(new Class[]{}); } }
2301_81045437/zeus-iot
iot-server/server-camel-receiver/src/main/java/com/zmops/zeus/iot/server/receiver/module/CamelReceiverModule.java
Java
gpl-3.0
864
package com.zmops.zeus.iot.server.receiver.provider; import com.zmops.zeus.server.library.module.ModuleConfig; import lombok.Getter; import lombok.Setter; /** * @author nantian created at 2021/10/23 21:25 */ @Getter @Setter public class CamelReceiverConfig extends ModuleConfig { private String version; }
2301_81045437/zeus-iot
iot-server/server-camel-receiver/src/main/java/com/zmops/zeus/iot/server/receiver/provider/CamelReceiverConfig.java
Java
gpl-3.0
316
package com.zmops.zeus.iot.server.receiver.provider; import com.zmops.zeus.iot.server.receiver.Const; import com.zmops.zeus.iot.server.receiver.handler.ark.ArkBizComponent; import com.zmops.zeus.iot.server.receiver.handler.zabbix.ZabbixSenderComponent; import com.zmops.zeus.iot.server.receiver.module.CamelReceiverModule; import com.zmops.zeus.iot.server.receiver.service.CamelContextHolderService; import com.zmops.zeus.iot.server.receiver.service.ReferenceClientService; import com.zmops.zeus.iot.server.sender.module.ZabbixSenderModule; import com.zmops.zeus.server.library.module.*; import com.zmops.zeus.server.runtime.SofaStarter; import com.zmops.zeus.server.runtime.api.client.ReferenceClient; import org.apache.camel.ExtendedCamelContext; import org.apache.camel.impl.DefaultCamelContext; import org.apache.camel.impl.engine.PooledExchangeFactory; import org.apache.camel.model.ModelCamelContext; /** * @author nantian created at 2021/10/23 21:24 */ public class CamelReceiverProvider extends ModuleProvider { private final CamelReceiverConfig camelReceiverConfig; private ModelCamelContext camelContext; private ReferenceClient referenceClient; public CamelReceiverProvider() { this.camelReceiverConfig = new CamelReceiverConfig(); } @Override public String name() { return "default"; } @Override public Class<? extends ModuleDefine> module() { return CamelReceiverModule.class; } @Override public ModuleConfig createConfigBeanIfAbsent() { return camelReceiverConfig; } @Override public void prepare() throws ServiceNotProvidedException, ModuleStartException { camelContext = new DefaultCamelContext(); // master 只有一个 CamelContext camelContext.disableJMX(); camelContext.setTracing(true); camelContext.adapt(ExtendedCamelContext.class).setExchangeFactory(new PooledExchangeFactory()); // biz-ark JVM 通信客户端 SofaStarter sofaStarter = new SofaStarter(); this.referenceClient = sofaStarter.getSofaRuntimeContext().getClientFactory().getClient(ReferenceClient.class); this.registerServiceImplementation(CamelContextHolderService.class, new CamelContextHolderService(camelContext, getManager())); this.registerServiceImplementation(ReferenceClientService.class, new ReferenceClientService(referenceClient, getManager())); } @Override public void start() throws ServiceNotProvidedException, ModuleStartException { camelContext.addComponent(Const.CAMEL_ZABBIX_COMPONENT_NAME, new ZabbixSenderComponent(getManager())); camelContext.addComponent(Const.CAMEL_ARK_COMPONENT_NAME, new ArkBizComponent(getManager())); } @Override public void notifyAfterCompleted() throws ServiceNotProvidedException, ModuleStartException { try { camelContext.start(); } catch (Exception e) { e.printStackTrace(); } } @Override public String[] requiredModules() { return new String[]{ ZabbixSenderModule.NAME }; } }
2301_81045437/zeus-iot
iot-server/server-camel-receiver/src/main/java/com/zmops/zeus/iot/server/receiver/provider/CamelReceiverProvider.java
Java
gpl-3.0
3,135
package com.zmops.zeus.iot.server.receiver.routes; import com.zmops.zeus.iot.server.receiver.ReceiverServerRoute; import java.util.Map; /** * @author nantian created at 2021/10/24 14:23 */ public class CoapServerRouteBuilder extends ReceiverServerRoute { public CoapServerRouteBuilder(String routeId, Map<String, Object> options) { super(routeId, options); } @Override public void configure() throws Exception { } }
2301_81045437/zeus-iot
iot-server/server-camel-receiver/src/main/java/com/zmops/zeus/iot/server/receiver/routes/CoapServerRouteBuilder.java
Java
gpl-3.0
452
package com.zmops.zeus.iot.server.receiver.routes; import com.zmops.zeus.iot.server.receiver.ReceiverServerRoute; import lombok.extern.slf4j.Slf4j; import org.apache.camel.LoggingLevel; import java.util.Map; /** * @author nantian created at 2021/10/23 23:25 */ @Slf4j public class HttpRouteBuilder extends ReceiverServerRoute { public HttpRouteBuilder(String routeId, Map<String, Object> option) { super(routeId, option); log.info("Http Route Created ====> ip : {},port : {}", option.get("hostIp"), option.get("port")); } @Override public void configure() throws Exception { fromF("netty4-http:http://0.0.0.0:%s/data?sync=true", options.get("port")) .routeId(routeId) .log(LoggingLevel.DEBUG, log, ">>> Message received from Netty4 Http Server : ${body}"); } }
2301_81045437/zeus-iot
iot-server/server-camel-receiver/src/main/java/com/zmops/zeus/iot/server/receiver/routes/HttpRouteBuilder.java
Java
gpl-3.0
849
package com.zmops.zeus.iot.server.receiver.routes; import com.zmops.zeus.iot.server.receiver.ReceiverServerRoute; import java.util.Map; /** * @author nantian created at 2021/11/26 13:54 */ public class MqttBrokerRouteBuilder extends ReceiverServerRoute { public MqttBrokerRouteBuilder(String routeId, Map<String, Object> options) { super(routeId, options); } @Override public void configure() throws Exception { } }
2301_81045437/zeus-iot
iot-server/server-camel-receiver/src/main/java/com/zmops/zeus/iot/server/receiver/routes/MqttBrokerRouteBuilder.java
Java
gpl-3.0
452
package com.zmops.zeus.iot.server.receiver.routes; import com.zmops.zeus.iot.server.h2.module.LocalH2Module; import com.zmops.zeus.iot.server.h2.service.InsertDAO; import com.zmops.zeus.iot.server.receiver.ReceiverServerRoute; import com.zmops.zeus.server.library.module.ModuleManager; import org.apache.camel.Exchange; import org.apache.camel.LoggingLevel; import org.apache.camel.Message; import java.sql.ResultSet; import java.sql.SQLException; import java.util.HashMap; import java.util.List; import java.util.Map; /** * @author nantian created at 2021/10/24 0:11 * <p> * mqtt client */ public class MqttClientRouteBuilder extends ReceiverServerRoute { public MqttClientRouteBuilder(String routeId, Map<String, Object> options) { super(routeId, options); } @Override public void configure() throws Exception { fromF("paho-mqtt5:%s?brokerUrl=tcp://%s:%s", options.get("topicNames"), options.get("hostIp"), options.get("port")) .routeId(routeId) .log(LoggingLevel.DEBUG, log, ">>> Message received from Mqtt Client : \n${body}") .dynamicRouter(method(RouteJudge.class, "slip")).to("Zabbix:mqtt"); } static class RouteJudge { public static String slip(Exchange exchange) { Message message = exchange.getMessage(); if (message.getBody() instanceof List) { return null; } String topicName = exchange.getIn().getHeader("CamelMqttTopic").toString(); InsertDAO localH2InsertDAO = ModuleManager.getInstance() .find(LocalH2Module.NAME).provider().getService(InsertDAO.class); //TODO 这里需要动态加载规则 ResultSet rs = localH2InsertDAO.queryRes("select pm.topic,pc.unique_id from protocol_gateway_mqtt pm left join protocol_component pc on pc.id=pm.protocol_component_id"); Map<String, String> map = new HashMap<>(); while (true) { try { if (!rs.next()) { break; } map.put(rs.getString(1), rs.getString(2)); } catch (SQLException e) { e.printStackTrace(); } } if (map.containsKey(topicName)) { return "ArkBiz:mqtt?uniqueId=" + map.get(topicName); } // if ("zeus11".equals(topicName)) { // return "ArkBiz:mqtt?uniqueId=19890918"; // } // // if ("zeus22".equals(topicName)) { // return "ArkBiz:mqtt?uniqueId=20211225"; // } return null; } } }
2301_81045437/zeus-iot
iot-server/server-camel-receiver/src/main/java/com/zmops/zeus/iot/server/receiver/routes/MqttClientRouteBuilder.java
Java
gpl-3.0
2,705
package com.zmops.zeus.iot.server.receiver.routes; import com.zmops.zeus.iot.server.receiver.ReceiverServerRoute; import java.util.Map; /** * @author nantian created at 2021/10/24 0:11 */ public class TcpServerRouteBuilder extends ReceiverServerRoute { public TcpServerRouteBuilder(String routeId, Map<String, Object> options) { super(routeId, options); } @Override public void configure() throws Exception { } }
2301_81045437/zeus-iot
iot-server/server-camel-receiver/src/main/java/com/zmops/zeus/iot/server/receiver/routes/TcpServerRouteBuilder.java
Java
gpl-3.0
449
package com.zmops.zeus.iot.server.receiver.routes; import com.zmops.zeus.iot.server.receiver.ReceiverServerRoute; import java.util.Map; /** * @author nantian created at 2021/10/24 0:12 */ public class UdpServerRouteBuilder extends ReceiverServerRoute { public UdpServerRouteBuilder(String routeId, Map<String, Object> options) { super(routeId, options); } @Override public void configure() throws Exception { } }
2301_81045437/zeus-iot
iot-server/server-camel-receiver/src/main/java/com/zmops/zeus/iot/server/receiver/routes/UdpServerRouteBuilder.java
Java
gpl-3.0
449
package com.zmops.zeus.iot.server.receiver.routes; import com.zmops.zeus.iot.server.receiver.ReceiverServerRoute; import java.util.Map; /** * @author nantian created at 2021/10/24 14:23 */ public class WebSocketServerRouteBuilder extends ReceiverServerRoute { public WebSocketServerRouteBuilder(String routeId, Map<String, Object> options) { super(routeId, options); } @Override public void configure() throws Exception { } }
2301_81045437/zeus-iot
iot-server/server-camel-receiver/src/main/java/com/zmops/zeus/iot/server/receiver/routes/WebSocketServerRouteBuilder.java
Java
gpl-3.0
462
package com.zmops.zeus.iot.server.receiver.service; import com.zmops.zeus.server.library.module.ModuleManager; import com.zmops.zeus.server.library.module.Service; import lombok.extern.slf4j.Slf4j; import org.apache.camel.CamelContext; import org.apache.camel.Route; import org.apache.camel.RoutesBuilder; /** * @author nantian created at 2021/8/17 0:24 * <p> * CamelContextHolderService ,便于模块服务调用,全局只有一个 Camel 上下文 */ @Slf4j public class CamelContextHolderService implements Service { private final CamelContext camelContext; private final ModuleManager moduleManager; public CamelContextHolderService(CamelContext camelContext, ModuleManager moduleManager) { this.camelContext = camelContext; this.moduleManager = moduleManager; } /** * 配置路由 * * @param builder 路由 */ public void addRoutes(RoutesBuilder builder) { try { camelContext.addRoutes(builder); } catch (Exception e) { e.printStackTrace(); } } /** * 关闭路由 * * @param routeId 路由ID */ public void routeShutDown(String routeId) { Route route = camelContext.getRoute(routeId); if (route == null) { return; } try { camelContext.getRouteController().stopRoute(routeId); camelContext.removeRoute(routeId); } catch (Exception e) { e.printStackTrace(); } } /** * 启动路由 * * @param routeId 路由ID */ public void routeStartUp(String routeId) { Route route = camelContext.getRoute(routeId); try { route.getEndpoint().start(); route.getConsumer().start(); } catch (Exception e) { e.printStackTrace(); } } }
2301_81045437/zeus-iot
iot-server/server-camel-receiver/src/main/java/com/zmops/zeus/iot/server/receiver/service/CamelContextHolderService.java
Java
gpl-3.0
1,879
package com.zmops.zeus.iot.server.receiver.service; import com.zmops.zeus.facade.DynamicProcotol; import com.zmops.zeus.server.library.module.ModuleManager; import com.zmops.zeus.server.library.module.Service; import com.zmops.zeus.server.runtime.api.client.ReferenceClient; import com.zmops.zeus.server.runtime.api.client.param.ReferenceParam; import java.util.concurrent.ConcurrentHashMap; /** * @author nantian created at 2021/12/21 15:20 * <p> * 动态协议代理 */ public class ReferenceClientService implements Service { private final ReferenceClient referenceClient; private final ModuleManager moduleManager; // 缓存调用 客户端 private static final ConcurrentHashMap<String, DynamicProcotol> dynamicProtoMap = new ConcurrentHashMap<>(); public ReferenceClientService(ReferenceClient client, ModuleManager moduleManager) { this.referenceClient = client; this.moduleManager = moduleManager; } public ReferenceClient getReferenceClient() { return referenceClient; } /** * 根据服务ID,动态获取代理客户端 * * @param serviceId - * @return DynamicProcotol */ public DynamicProcotol getDynamicProtocolClient(String serviceId) { DynamicProcotol client = dynamicProtoMap.get(serviceId); if (client != null) { return client; } ReferenceParam<DynamicProcotol> referenceParam = new ReferenceParam<>(); referenceParam.setInterfaceType(DynamicProcotol.class); referenceParam.setUniqueId(serviceId); DynamicProcotol client2 = referenceClient.reference(referenceParam); dynamicProtoMap.put(serviceId, client2); return client2; } }
2301_81045437/zeus-iot
iot-server/server-camel-receiver/src/main/java/com/zmops/zeus/iot/server/receiver/service/ReferenceClientService.java
Java
gpl-3.0
1,740
/* * 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 com.zmops.zeus.iot.server.client; import java.io.IOException; public interface Client { void connect() throws Exception; void shutdown() throws IOException; }
2301_81045437/zeus-iot
iot-server/server-client/src/main/java/com/zmops/zeus/iot/server/client/Client.java
Java
gpl-3.0
985
/* * 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 com.zmops.zeus.iot.server.client; public abstract class ClientException extends Exception { public ClientException(String message) { super(message); } public ClientException(String message, Throwable cause) { super(message, cause); } }
2301_81045437/zeus-iot
iot-server/server-client/src/main/java/com/zmops/zeus/iot/server/client/ClientException.java
Java
gpl-3.0
1,084
/* * 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 com.zmops.zeus.iot.server.client.healthcheck; import com.zmops.zeus.server.library.util.HealthChecker; import java.util.Optional; import java.util.concurrent.atomic.AtomicReference; public class DelegatedHealthChecker implements HealthChecker { private final AtomicReference<HealthChecker> delegated = new AtomicReference<>(); @Override public void health() { Optional.ofNullable(delegated.get()).ifPresent(HealthChecker::health); } @Override public void unHealth(Throwable t) { Optional.ofNullable(delegated.get()).ifPresent(d -> d.unHealth(t)); } @Override public void unHealth(String reason) { Optional.ofNullable(delegated.get()).ifPresent(d -> d.unHealth(reason)); } public void register(HealthChecker healthChecker) { delegated.set(healthChecker); } }
2301_81045437/zeus-iot
iot-server/server-client/src/main/java/com/zmops/zeus/iot/server/client/healthcheck/DelegatedHealthChecker.java
Java
gpl-3.0
1,661
/* * 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 com.zmops.zeus.iot.server.client.healthcheck; import com.zmops.zeus.server.library.util.HealthChecker; /** * HealthCheckable indicate the client has the capacity of health check and need to register healthChecker. */ public interface HealthCheckable { /** * Register health checker. * * @param healthChecker HealthChecker to be registered. */ void registerChecker(HealthChecker healthChecker); }
2301_81045437/zeus-iot
iot-server/server-client/src/main/java/com/zmops/zeus/iot/server/client/healthcheck/HealthCheckable.java
Java
gpl-3.0
1,243
/* * 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 com.zmops.zeus.iot.server.client.jdbc; import java.io.IOException; public class JDBCClientException extends IOException { public JDBCClientException(String message) { super(message); } public JDBCClientException(String message, Throwable cause) { super(message, cause); } }
2301_81045437/zeus-iot
iot-server/server-client/src/main/java/com/zmops/zeus/iot/server/client/jdbc/JDBCClientException.java
Java
gpl-3.0
1,125
/* * 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 com.zmops.zeus.iot.server.client.jdbc.hikaricp; import com.zaxxer.hikari.HikariConfig; import com.zaxxer.hikari.HikariDataSource; import com.zmops.zeus.iot.server.client.Client; import com.zmops.zeus.iot.server.client.healthcheck.DelegatedHealthChecker; import com.zmops.zeus.iot.server.client.healthcheck.HealthCheckable; import com.zmops.zeus.iot.server.client.jdbc.JDBCClientException; import com.zmops.zeus.server.library.util.HealthChecker; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import java.sql.*; import java.util.Properties; /** * JDBC Client uses HikariCP connection management lib to execute SQL. */ public class JDBCHikariCPClient implements Client, HealthCheckable { private static final Logger LOGGER = LoggerFactory.getLogger(JDBCHikariCPClient.class); private final HikariConfig hikariConfig; private final DelegatedHealthChecker healthChecker; private HikariDataSource dataSource; public JDBCHikariCPClient(Properties properties) { hikariConfig = new HikariConfig(properties); this.healthChecker = new DelegatedHealthChecker(); } @Override public void connect() { dataSource = new HikariDataSource(hikariConfig); } @Override public void shutdown() { } /** * Default getConnection is set in auto-commit. */ public Connection getConnection() throws JDBCClientException { return getConnection(true); } public Connection getTransactionConnection() throws JDBCClientException { return getConnection(false); } public Connection getConnection(boolean autoCommit) throws JDBCClientException { try { Connection connection = dataSource.getConnection(); connection.setAutoCommit(autoCommit); return connection; } catch (SQLException e) { throw new JDBCClientException(e.getMessage(), e); } } public void execute(Connection connection, String sql) throws JDBCClientException { LOGGER.debug("execute sql: {}", sql); try (Statement statement = connection.createStatement()) { statement.execute(sql); healthChecker.health(); } catch (SQLException e) { healthChecker.unHealth(e); throw new JDBCClientException(e.getMessage(), e); } } public int executeUpdate(Connection connection, String sql, Object... params) throws JDBCClientException { LOGGER.debug("execute query with result: {}", sql); int result; PreparedStatement statement = null; try { statement = connection.prepareStatement(sql); setStatementParam(statement, params); result = statement.executeUpdate(); statement.closeOnCompletion(); healthChecker.health(); } catch (SQLException e) { if (statement != null) { try { statement.close(); } catch (SQLException e1) { } } healthChecker.unHealth(e); throw new JDBCClientException(e.getMessage(), e); } return result; } public ResultSet executeQuery(Connection connection, String sql, Object... params) throws JDBCClientException { LOGGER.debug("execute query with result: {}", sql); ResultSet rs; PreparedStatement statement = null; try { statement = connection.prepareStatement(sql); setStatementParam(statement, params); rs = statement.executeQuery(); statement.closeOnCompletion(); healthChecker.health(); } catch (SQLException e) { if (statement != null) { try { statement.close(); } catch (SQLException e1) { } } healthChecker.unHealth(e); throw new JDBCClientException(e.getMessage(), e); } return rs; } private void setStatementParam(PreparedStatement statement, Object[] params) throws SQLException, JDBCClientException { if (params != null) { int p = 0; for (int i = 0; i < params.length; i++) { Object param = params[i]; if (param == null) { continue; } ++p; if (param instanceof String) { statement.setString(p, (String) param); } else if (param instanceof Integer) { statement.setInt(p, (int) param); } else if (param instanceof Double) { statement.setDouble(p, (double) param); } else if (param instanceof Long) { statement.setLong(p, (long) param); } else { throw new JDBCClientException("Unsupported data type, type=" + param.getClass().getName()); } } } } @Override public void registerChecker(HealthChecker healthChecker) { this.healthChecker.register(healthChecker); } }
2301_81045437/zeus-iot
iot-server/server-client/src/main/java/com/zmops/zeus/iot/server/client/jdbc/hikaricp/JDBCHikariCPClient.java
Java
gpl-3.0
6,032
/* * 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 com.zmops.zeus.iot.server.client.request; public interface InsertRequest extends PrepareRequest { }
2301_81045437/zeus-iot
iot-server/server-client/src/main/java/com/zmops/zeus/iot/server/client/request/InsertRequest.java
Java
gpl-3.0
912
/* * 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 com.zmops.zeus.iot.server.client.request; public interface PrepareRequest { }
2301_81045437/zeus-iot
iot-server/server-client/src/main/java/com/zmops/zeus/iot/server/client/request/PrepareRequest.java
Java
gpl-3.0
890
package com.zmops.zeus.iot.server.core; /** * 核心模块 参数 */ public class CoreConst { public static final String CORE_MODULE_VERSION = "1.0.1"; }
2301_81045437/zeus-iot
iot-server/server-core/src/main/java/com/zmops/zeus/iot/server/core/CoreConst.java
Java
gpl-3.0
162
package com.zmops.zeus.iot.server.core; import com.zmops.zeus.server.library.module.ModuleDefine; import java.util.ArrayList; import java.util.List; /** * @author nantian created at 2021/8/16 22:27 */ public class CoreModule extends ModuleDefine { public static final String NAME = "core"; public CoreModule() { super(NAME); } @Override public Class<?>[] services() { List<Class<?>> classes = new ArrayList<>(); return classes.toArray(new Class[]{}); } }
2301_81045437/zeus-iot
iot-server/server-core/src/main/java/com/zmops/zeus/iot/server/core/CoreModule.java
Java
gpl-3.0
511
package com.zmops.zeus.iot.server.core; import com.zmops.zeus.server.library.module.ModuleConfig; import lombok.Getter; import lombok.Setter; /** * @author nantian created at 2021/8/16 22:29 */ @Setter @Getter public class CoreModuleConfig extends ModuleConfig { private String nameSpace; private String restHost; private int restPort; private String restContextPath; private int restMinThreads = 1; private int restMaxThreads = 200; private long restIdleTimeOut = 30000; private int restAcceptorPriorityDelta = 0; private int restAcceptQueueSize = 0; /** * Timeout for cluster internal communication, in seconds. */ private int remoteTimeout = 20; /** * The number of threads used to prepare metrics data to the storage. * * @since 8.7.0 */ @Setter @Getter private int prepareThreads = 2; /** * The maximum size in bytes allowed for request headers. * Use -1 to disable it. */ private int httpMaxRequestHeaderSize = 8192; }
2301_81045437/zeus-iot
iot-server/server-core/src/main/java/com/zmops/zeus/iot/server/core/CoreModuleConfig.java
Java
gpl-3.0
1,052
package com.zmops.zeus.iot.server.core; import com.zmops.zeus.iot.server.core.analysis.StreamAnnotationListener; import com.zmops.zeus.iot.server.core.annotation.AnnotationScan; import com.zmops.zeus.iot.server.core.storage.StorageException; import com.zmops.zeus.iot.server.receiver.module.CamelReceiverModule; import com.zmops.zeus.iot.server.telemetry.TelemetryModule; import com.zmops.zeus.server.jetty.JettyServer; import com.zmops.zeus.server.jetty.JettyServerConfig; import com.zmops.zeus.server.library.module.*; import java.io.IOException; /** * @author nantian created at 2021/8/16 22:26 */ public class CoreModuleProvider extends ModuleProvider { private final CoreModuleConfig moduleConfig; private JettyServer jettyServer; private final AnnotationScan annotationScan; public CoreModuleProvider() { super(); this.moduleConfig = new CoreModuleConfig(); this.annotationScan = new AnnotationScan(); } @Override public String name() { return "default"; } @Override public Class<? extends ModuleDefine> module() { return CoreModule.class; } @Override public ModuleConfig createConfigBeanIfAbsent() { return moduleConfig; } @Override public void prepare() throws ServiceNotProvidedException, ModuleStartException { annotationScan.registerListener(new StreamAnnotationListener(getManager())); JettyServerConfig jettyServerConfig = JettyServerConfig.builder() .host(moduleConfig.getRestHost()) .port(moduleConfig.getRestPort()) .contextPath(moduleConfig.getRestContextPath()) .jettyIdleTimeOut(moduleConfig.getRestIdleTimeOut()) .jettyAcceptorPriorityDelta(moduleConfig.getRestAcceptorPriorityDelta()) .jettyMinThreads(moduleConfig.getRestMinThreads()) .jettyMaxThreads(moduleConfig.getRestMaxThreads()) .jettyAcceptQueueSize(moduleConfig.getRestAcceptQueueSize()) .jettyHttpMaxRequestHeaderSize(moduleConfig.getHttpMaxRequestHeaderSize()) .build(); jettyServer = new JettyServer(jettyServerConfig); jettyServer.initialize(); jettyServer.setFilterInitParameter("configClass", "com.zmops.zeus.iot.web.config.IoTConfig"); } @Override public void start() throws ServiceNotProvidedException, ModuleStartException { try { annotationScan.scan(); } catch (IOException | StorageException e) { throw new ModuleStartException(e.getMessage(), e); } } public void shutdown() { } @Override public void notifyAfterCompleted() throws ServiceNotProvidedException, ModuleStartException { try { jettyServer.start(); } catch (Exception e) { throw new ModuleStartException(e.getMessage(), e); } } @Override public String[] requiredModules() { return new String[]{ TelemetryModule.NAME, CamelReceiverModule.NAME }; } }
2301_81045437/zeus-iot
iot-server/server-core/src/main/java/com/zmops/zeus/iot/server/core/CoreModuleProvider.java
Java
gpl-3.0
3,131
/* * 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 com.zmops.zeus.iot.server.core; import com.google.common.base.Strings; /** * The running mode of the zeus-server. */ public class RunningMode { private static String MODE = ""; private RunningMode() { } public static void setMode(String mode) { if (Strings.isNullOrEmpty(mode)) { return; } RunningMode.MODE = mode.toLowerCase(); } /** * Init mode, do all initialization things, and process should exit. * * @return true if in this status */ public static boolean isInitMode() { return "init".equals(MODE); } /** * No-init mode, the zeus-server just starts up, but wouldn't do storage init. * * @return true if in this status. */ public static boolean isNoInitMode() { return "no-init".equals(MODE); } }
2301_81045437/zeus-iot
iot-server/server-core/src/main/java/com/zmops/zeus/iot/server/core/RunningMode.java
Java
gpl-3.0
1,661
/* * 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 com.zmops.zeus.iot.server.core; public class UnexpectedException extends RuntimeException { public UnexpectedException(String message) { super(message); } public UnexpectedException(String message, Exception cause) { super(message, cause); } }
2301_81045437/zeus-iot
iot-server/server-core/src/main/java/com/zmops/zeus/iot/server/core/UnexpectedException.java
Java
gpl-3.0
1,092
/* * 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 com.zmops.zeus.iot.server.core.analysis; import com.zmops.zeus.iot.server.core.analysis.worker.RecordStreamProcessor; import java.lang.annotation.ElementType; import java.lang.annotation.Retention; import java.lang.annotation.RetentionPolicy; import java.lang.annotation.Target; /** * Stream annotation represents a metadata definition. * See {@link RecordStreamProcessor} */ @Target(ElementType.TYPE) @Retention(RetentionPolicy.RUNTIME) public @interface Stream { /** * @return name of this stream definition. */ String name(); /** * @return the stream processor type, {@link RecordStreamProcessor} for more details. */ Class<? extends StreamProcessor> processor(); }
2301_81045437/zeus-iot
iot-server/server-core/src/main/java/com/zmops/zeus/iot/server/core/analysis/Stream.java
Java
gpl-3.0
1,527
package com.zmops.zeus.iot.server.core.analysis; import com.zmops.zeus.iot.server.core.UnexpectedException; import com.zmops.zeus.iot.server.core.analysis.worker.RecordStreamProcessor; import com.zmops.zeus.iot.server.core.annotation.AnnotationListener; import com.zmops.zeus.iot.server.core.storage.StorageException; import com.zmops.zeus.server.library.module.ModuleDefineHolder; import java.lang.annotation.Annotation; /** * @author nantian created at 2021/9/6 17:37 */ public class StreamAnnotationListener implements AnnotationListener { private final ModuleDefineHolder moduleDefineHolder; public StreamAnnotationListener(ModuleDefineHolder moduleDefineHolder) { this.moduleDefineHolder = moduleDefineHolder; } @Override public Class<? extends Annotation> annotation() { return Stream.class; } @Override @SuppressWarnings("unchecked") public void notify(Class aClass) throws StorageException { if (aClass.isAnnotationPresent(Stream.class)) { Stream stream = (Stream) aClass.getAnnotation(Stream.class); if (stream.processor().equals(RecordStreamProcessor.class)) { RecordStreamProcessor.getInstance().create(moduleDefineHolder, stream, aClass); } else { throw new UnexpectedException("Unknown stream processor."); } } else { throw new UnexpectedException("Stream annotation listener could only parse the class present stream annotation."); } } }
2301_81045437/zeus-iot
iot-server/server-core/src/main/java/com/zmops/zeus/iot/server/core/analysis/StreamAnnotationListener.java
Java
gpl-3.0
1,534
package com.zmops.zeus.iot.server.core.analysis; /** * @author nantian created at 2021/9/6 16:49 */ public interface StreamProcessor<STREAM> { /** * 写入数据 * * @param stream record */ void in(STREAM stream); }
2301_81045437/zeus-iot
iot-server/server-core/src/main/java/com/zmops/zeus/iot/server/core/analysis/StreamProcessor.java
Java
gpl-3.0
248
package com.zmops.zeus.iot.server.core.analysis.manual.history; import com.zmops.zeus.iot.server.core.analysis.Stream; import com.zmops.zeus.iot.server.core.analysis.record.Record; import com.zmops.zeus.iot.server.core.analysis.worker.RecordStreamProcessor; import lombok.Getter; import lombok.Setter; import java.util.List; import java.util.Map; /** * @author nantian created at 2021/9/6 17:07 */ @Getter @Setter @Stream(name = "history", processor = RecordStreamProcessor.class) public class History extends Record { private Long clock; private Long ns; private String value; // 浮点数 private String deviceId; // host private Map<String, String> itemTags; private List<String> hostGroups; @Override public Integer itemid() { return getItemid(); } @Override public void setValue(String deviceId, String value, Long clock) { this.deviceId = deviceId; this.value = value; this.clock = clock; } }
2301_81045437/zeus-iot
iot-server/server-core/src/main/java/com/zmops/zeus/iot/server/core/analysis/manual/history/History.java
Java
gpl-3.0
992
package com.zmops.zeus.iot.server.core.analysis.manual.history; import com.zmops.zeus.iot.server.core.analysis.Stream; import com.zmops.zeus.iot.server.core.analysis.record.Record; import com.zmops.zeus.iot.server.core.analysis.worker.RecordStreamProcessor; import lombok.Getter; import lombok.Setter; import java.util.List; import java.util.Map; /** * @author nantian created at 2021/9/6 17:07 */ @Getter @Setter @Stream(name = "history_str", processor = RecordStreamProcessor.class) public class StrHistory extends Record { private Long clock; private Long ns; private String value; // 浮点数 private String deviceId; // host private Map<String, String> itemTags; private List<String> hostGroups; @Override public Integer itemid() { return getItemid(); } @Override public void setValue(String deviceId, String value, Long clock) { this.deviceId = deviceId; this.value = value; this.clock = clock; } }
2301_81045437/zeus-iot
iot-server/server-core/src/main/java/com/zmops/zeus/iot/server/core/analysis/manual/history/StrHistory.java
Java
gpl-3.0
999
package com.zmops.zeus.iot.server.core.analysis.manual.history; import com.zmops.zeus.iot.server.core.analysis.Stream; import com.zmops.zeus.iot.server.core.analysis.record.Record; import com.zmops.zeus.iot.server.core.analysis.worker.RecordStreamProcessor; import lombok.Getter; import lombok.Setter; import java.util.List; import java.util.Map; /** * @author nantian created at 2021/9/6 17:07 */ @Getter @Setter @Stream(name = "history_text", processor = RecordStreamProcessor.class) public class TextHistory extends Record { private Long clock; private Long ns; private String value; // 浮点数 private String deviceId; // host private Map<String, String> itemTags; private List<String> hostGroups; @Override public Integer itemid() { return getItemid(); } @Override public void setValue(String deviceId, String value, Long clock) { this.deviceId = deviceId; this.value = value; this.clock = clock; } }
2301_81045437/zeus-iot
iot-server/server-core/src/main/java/com/zmops/zeus/iot/server/core/analysis/manual/history/TextHistory.java
Java
gpl-3.0
1,001
package com.zmops.zeus.iot.server.core.analysis.manual.history; import com.zmops.zeus.iot.server.core.analysis.Stream; import com.zmops.zeus.iot.server.core.analysis.record.Record; import com.zmops.zeus.iot.server.core.analysis.worker.RecordStreamProcessor; import lombok.Getter; import lombok.Setter; import java.util.List; import java.util.Map; /** * @author nantian created at 2021/9/6 17:07 */ @Getter @Setter @Stream(name = "history_uint", processor = RecordStreamProcessor.class) public class UIntHistory extends Record { private Long clock; private Long ns; private String value; // 浮点数 private String deviceId; private Map<String, String> itemTags; private List<String> hostGroups; @Override public Integer itemid() { return getItemid(); } @Override public void setValue(String deviceId, String value, Long clock) { this.deviceId = deviceId; this.value = value; this.clock = clock; } }
2301_81045437/zeus-iot
iot-server/server-core/src/main/java/com/zmops/zeus/iot/server/core/analysis/manual/history/UIntHistory.java
Java
gpl-3.0
993
package com.zmops.zeus.iot.server.core.analysis.manual.trends; /** * @author nantian created at 2021/9/6 17:32 */ public class Trends { }
2301_81045437/zeus-iot
iot-server/server-core/src/main/java/com/zmops/zeus/iot/server/core/analysis/manual/trends/Trends.java
Java
gpl-3.0
141
package com.zmops.zeus.iot.server.core.analysis.manual.trends; /** * @author nantian created at 2021/9/6 17:32 */ public class UIntTrends { }
2301_81045437/zeus-iot
iot-server/server-core/src/main/java/com/zmops/zeus/iot/server/core/analysis/manual/trends/UIntTrends.java
Java
gpl-3.0
145
/* * 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 com.zmops.zeus.iot.server.core.analysis.record; import com.zmops.zeus.iot.server.core.storage.StorageData; import lombok.Getter; import lombok.Setter; public abstract class Record implements StorageData { @Getter @Setter private Integer itemid; public abstract void setValue(String deviceId, String value, Long clock); }
2301_81045437/zeus-iot
iot-server/server-core/src/main/java/com/zmops/zeus/iot/server/core/analysis/record/Record.java
Java
gpl-3.0
1,156
package com.zmops.zeus.iot.server.core.analysis.worker; import com.zmops.zeus.iot.server.core.analysis.record.Record; import com.zmops.zeus.iot.server.core.storage.IBatchDAO; import com.zmops.zeus.iot.server.core.storage.IRecordDAO; import com.zmops.zeus.iot.server.core.storage.StorageModule; import com.zmops.zeus.iot.server.core.storage.model.Model; import com.zmops.zeus.iot.server.core.worker.AbstractWorker; import com.zmops.zeus.iot.server.client.request.InsertRequest; import com.zmops.zeus.server.library.module.ModuleDefineHolder; import lombok.extern.slf4j.Slf4j; import java.io.IOException; @Slf4j public class RecordPersistentWorker extends AbstractWorker<Record> { private final Model model; private final IRecordDAO recordDAO; private final IBatchDAO batchDAO; public RecordPersistentWorker(ModuleDefineHolder moduleDefineHolder, Model model, IRecordDAO recordDAO) { super(moduleDefineHolder); this.model = model; this.recordDAO = recordDAO; this.batchDAO = moduleDefineHolder.find(StorageModule.NAME).provider().getService(IBatchDAO.class); } @Override public void in(Record record) { try { InsertRequest insertRequest = recordDAO.prepareBatchInsert(model, record); batchDAO.insert(insertRequest); } catch (IOException e) { log.error(e.getMessage(), e); } } }
2301_81045437/zeus-iot
iot-server/server-core/src/main/java/com/zmops/zeus/iot/server/core/analysis/worker/RecordPersistentWorker.java
Java
gpl-3.0
1,406
package com.zmops.zeus.iot.server.core.analysis.worker; import com.zmops.zeus.iot.server.core.analysis.Stream; import com.zmops.zeus.iot.server.core.analysis.StreamProcessor; import com.zmops.zeus.iot.server.core.analysis.record.Record; import com.zmops.zeus.iot.server.core.storage.IRecordDAO; import com.zmops.zeus.iot.server.core.storage.StorageDAO; import com.zmops.zeus.iot.server.core.storage.StorageModule; import com.zmops.zeus.iot.server.core.storage.model.Model; import com.zmops.zeus.server.library.module.ModuleDefineHolder; import java.util.HashMap; import java.util.Map; /** * @author nantian created at 2021/9/6 16:47 */ public class RecordStreamProcessor implements StreamProcessor<Record> { private final Map<Class<? extends Record>, RecordPersistentWorker> workers = new HashMap<>(); private final static RecordStreamProcessor PROCESSOR = new RecordStreamProcessor(); public static RecordStreamProcessor getInstance() { return PROCESSOR; } @Override public void in(Record record) { RecordPersistentWorker worker = workers.get(record.getClass()); if (worker != null) { worker.in(record); } } public void create(ModuleDefineHolder moduleDefineHolder, Stream stream, Class<? extends Record> recordClass) { StorageDAO storageDAO = moduleDefineHolder.find(StorageModule.NAME).provider().getService(StorageDAO.class); IRecordDAO recordDAO = storageDAO.newRecordDao(); Model model = new Model(stream.name()); RecordPersistentWorker persistentWorker = new RecordPersistentWorker(moduleDefineHolder, model, recordDAO); workers.put(recordClass, persistentWorker); } }
2301_81045437/zeus-iot
iot-server/server-core/src/main/java/com/zmops/zeus/iot/server/core/analysis/worker/RecordStreamProcessor.java
Java
gpl-3.0
1,710
/* * 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 com.zmops.zeus.iot.server.core.annotation; import com.zmops.zeus.iot.server.core.storage.StorageException; import java.lang.annotation.Annotation; public interface AnnotationListener { Class<? extends Annotation> annotation(); void notify(Class aClass) throws StorageException; }
2301_81045437/zeus-iot
iot-server/server-core/src/main/java/com/zmops/zeus/iot/server/core/annotation/AnnotationListener.java
Java
gpl-3.0
1,107
/* * 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 com.zmops.zeus.iot.server.core.annotation; import com.google.common.collect.ImmutableSet; import com.google.common.reflect.ClassPath; import com.zmops.zeus.iot.server.core.storage.StorageException; import java.io.IOException; import java.lang.annotation.Annotation; import java.util.Comparator; import java.util.LinkedList; import java.util.List; /** * Scan the annotation, and notify the listener(s) */ public class AnnotationScan { private final List<AnnotationListenerCache> listeners; public AnnotationScan() { this.listeners = new LinkedList<>(); } /** * Register the callback listener * * @param listener to be called after class found w/ annotation */ public void registerListener(AnnotationListener listener) { listeners.add(new AnnotationListenerCache(listener)); } /** * Begin to scan classes. */ public void scan() throws IOException, StorageException { ClassPath classpath = ClassPath.from(this.getClass().getClassLoader()); ImmutableSet<ClassPath.ClassInfo> classes = classpath.getTopLevelClassesRecursive("com.zmops.zeus.iot"); for (ClassPath.ClassInfo classInfo : classes) { Class<?> aClass = classInfo.load(); for (AnnotationListenerCache listener : listeners) { if (aClass.isAnnotationPresent(listener.annotation())) { listener.addMatch(aClass); } } } for (AnnotationListenerCache listener : listeners) { listener.complete(); } } private static class AnnotationListenerCache { private final AnnotationListener listener; private final List<Class<?>> matchedClass; private AnnotationListenerCache(AnnotationListener listener) { this.listener = listener; matchedClass = new LinkedList<>(); } private Class<? extends Annotation> annotation() { return this.listener.annotation(); } private void addMatch(Class aClass) { matchedClass.add(aClass); } private void complete() throws StorageException { matchedClass.sort(Comparator.comparing(Class::getName)); for (Class<?> aClass : matchedClass) { listener.notify(aClass); } } } }
2301_81045437/zeus-iot
iot-server/server-core/src/main/java/com/zmops/zeus/iot/server/core/annotation/AnnotationScan.java
Java
gpl-3.0
3,188
package com.zmops.zeus.iot.server.core.servlet; import com.google.gson.Gson; import com.google.gson.JsonElement; import com.zmops.zeus.server.jetty.ArgumentsParseException; import com.zmops.zeus.server.jetty.JettyJsonHandler; import com.zmops.zeus.server.library.module.ModuleManager; import lombok.extern.slf4j.Slf4j; import javax.servlet.http.HttpServletRequest; import java.io.BufferedReader; import java.io.IOException; /** * @author nantian created at 2021/8/20 1:04 * <p> * 设备 告警规则 触发动作,Http 统一入口 */ @Slf4j public class DeviceTriggerActionHandler extends JettyJsonHandler { private final ModuleManager moduleManager; private final Gson gson = new Gson(); public DeviceTriggerActionHandler(ModuleManager moduleManager) { this.moduleManager = moduleManager; } @Override public String pathSpec() { return "/device/action/exec"; } /** * 动作触发Http入口,可在设备 上面设置 宏 定义,动态传入 identifier * * @param req * @return JsonElement * @throws ArgumentsParseException ex * @throws IOException ex */ @Override protected JsonElement doPost(HttpServletRequest req) throws ArgumentsParseException, IOException { String request = getJsonBody(req); log.info("action command : {}", request); // EventBusService eventBusService = moduleManager.find(CoreModule.NAME).provider().getService(EventBusService.class); // // // ActionParam actionParam = new ActionParam(); // actionParam.setActionParamContent(request); // // eventBusService.postExecuteActionMsg(ActionRouteIdentifier.helloworld, actionParam); return null; } @Override public String getJsonBody(HttpServletRequest req) throws IOException { StringBuffer stringBuffer = new StringBuffer(); String line = null; BufferedReader reader = req.getReader(); while ((line = reader.readLine()) != null) { stringBuffer.append(line); } return stringBuffer.toString(); } }
2301_81045437/zeus-iot
iot-server/server-core/src/main/java/com/zmops/zeus/iot/server/core/servlet/DeviceTriggerActionHandler.java
Java
gpl-3.0
2,132
package com.zmops.zeus.iot.server.core.servlet; import com.google.gson.Gson; import com.google.gson.JsonElement; import com.google.gson.JsonObject; import com.google.gson.reflect.TypeToken; import com.zmops.zeus.iot.server.core.worker.data.ItemValue; import com.zmops.zeus.iot.server.core.worker.data.ZabbixTrapper; import com.zmops.zeus.iot.server.sender.module.ZabbixSenderModule; import com.zmops.zeus.iot.server.sender.service.ZabbixSenderService; import com.zmops.zeus.server.jetty.ArgumentsParseException; import com.zmops.zeus.server.jetty.JettyJsonHandler; import com.zmops.zeus.server.library.module.ModuleManager; import javax.servlet.http.HttpServletRequest; import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader; import java.lang.reflect.Type; import java.util.List; /** * @author nantian created at 2021/8/20 0:51 * <p> * Http Trapper 的方式给指定设备的指定属性 发送数据,方便手动调试 */ public class HttpItemTrapperHandler extends JettyJsonHandler { private final Gson gson = new Gson(); private final ModuleManager moduleManager; public HttpItemTrapperHandler(ModuleManager moduleManager) { this.moduleManager = moduleManager; } @Override public String pathSpec() { return "/device/attr/send"; } @Override protected JsonElement doPost(HttpServletRequest req) throws ArgumentsParseException, IOException { BufferedReader reader = new BufferedReader(new InputStreamReader(req.getInputStream())); String line; StringBuilder request = new StringBuilder(); while ((line = reader.readLine()) != null) { request.append(line); } JsonObject requestJson = gson.fromJson(request.toString(), JsonObject.class); Type listType = new TypeToken<List<ItemValue>>() {}.getType(); List<ItemValue> valueList = gson.fromJson(requestJson.getAsJsonArray("params").toString(), listType); ZabbixSenderService zabbixSenderService = moduleManager.find(ZabbixSenderModule.NAME).provider().getService(ZabbixSenderService.class); ZabbixTrapper zabbixTrapper = new ZabbixTrapper(valueList); zabbixSenderService.sendData(gson.toJson(zabbixTrapper)); return requestJson; } }
2301_81045437/zeus-iot
iot-server/server-core/src/main/java/com/zmops/zeus/iot/server/core/servlet/HttpItemTrapperHandler.java
Java
gpl-3.0
2,307
/* * 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 com.zmops.zeus.iot.server.core.storage; import com.zmops.zeus.server.library.module.Service; /** * A specific interface for storage layer services. */ public interface DAO extends Service { }
2301_81045437/zeus-iot
iot-server/server-core/src/main/java/com/zmops/zeus/iot/server/core/storage/DAO.java
Java
gpl-3.0
1,011
/* * 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 com.zmops.zeus.iot.server.core.storage; import com.zmops.zeus.iot.server.client.request.InsertRequest; import com.zmops.zeus.iot.server.client.request.PrepareRequest; import java.util.List; /** * IBatchDAO provides two modes of data persistence supported by most databases, including pure insert and batch hybrid * insert/update. */ public interface IBatchDAO extends DAO { /** * Push data into the database in async mode. This method is driven by streaming process. This method doesn't * request the data queryable immediately after the method finished. * * @param insertRequest data to insert. */ void insert(InsertRequest insertRequest); /** * Push data collection into the database in async mode. This method is driven by streaming process. This method * doesn't request the data queryable immediately after the method finished. * <p> * The method requires thread safe. The OAP core would call this concurrently. * * @param prepareRequests data to insert or update. No delete happens in streaming mode. */ void flush(List<PrepareRequest> prepareRequests); }
2301_81045437/zeus-iot
iot-server/server-core/src/main/java/com/zmops/zeus/iot/server/core/storage/IBatchDAO.java
Java
gpl-3.0
1,960
/* * 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 com.zmops.zeus.iot.server.core.storage; import com.zmops.zeus.iot.server.core.analysis.record.Record; import com.zmops.zeus.iot.server.core.storage.model.Model; import com.zmops.zeus.iot.server.client.request.InsertRequest; import java.io.IOException; /** * DAO specifically for {@link Record} implementations. */ public interface IRecordDAO extends DAO { InsertRequest prepareBatchInsert(Model model, Record record) throws IOException; }
2301_81045437/zeus-iot
iot-server/server-core/src/main/java/com/zmops/zeus/iot/server/core/storage/IRecordDAO.java
Java
gpl-3.0
1,264
/* * 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 com.zmops.zeus.iot.server.core.storage; import com.zmops.zeus.server.library.module.Service; /** * StorageDAO is a DAO factory for storage layer. Provide the implementations of typical DAO interfaces. */ public interface StorageDAO extends Service { // IMetricsDAO newMetricsDao(StorageBuilder storageBuilder); IRecordDAO newRecordDao(); }
2301_81045437/zeus-iot
iot-server/server-core/src/main/java/com/zmops/zeus/iot/server/core/storage/StorageDAO.java
Java
gpl-3.0
1,168
/* * 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 com.zmops.zeus.iot.server.core.storage; /** * Any persistent entity should be an implementation of this interface. */ public interface StorageData { /** * @return the unique id used in any storage option. */ Integer itemid(); }
2301_81045437/zeus-iot
iot-server/server-core/src/main/java/com/zmops/zeus/iot/server/core/storage/StorageData.java
Java
gpl-3.0
1,063
/* * 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 com.zmops.zeus.iot.server.core.storage; public class StorageException extends Exception { public StorageException(String message) { super(message); } public StorageException(String message, Throwable cause) { super(message, cause); } }
2301_81045437/zeus-iot
iot-server/server-core/src/main/java/com/zmops/zeus/iot/server/core/storage/StorageException.java
Java
gpl-3.0
1,085
/* * 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 com.zmops.zeus.iot.server.core.storage; import com.zmops.zeus.server.library.module.ModuleDefine; /** * StorageModule provides the capabilities(services) to interact with the database. With different databases, this * module could have different providers, such as currently, H2, MySQL, ES, TiDB. */ public class StorageModule extends ModuleDefine { public static final String NAME = "storage"; public StorageModule() { super(NAME); } @Override public Class[] services() { return new Class[]{ IBatchDAO.class, StorageDAO.class }; } }
2301_81045437/zeus-iot
iot-server/server-core/src/main/java/com/zmops/zeus/iot/server/core/storage/StorageModule.java
Java
gpl-3.0
1,437
/* * 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 com.zmops.zeus.iot.server.core.storage.model; import lombok.EqualsAndHashCode; import lombok.Getter; /** * The model definition of a logic entity. */ @Getter @EqualsAndHashCode public class Model { private final String name; public Model(final String name) { this.name = name; } }
2301_81045437/zeus-iot
iot-server/server-core/src/main/java/com/zmops/zeus/iot/server/core/storage/model/Model.java
Java
gpl-3.0
1,121
/* * 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 com.zmops.zeus.iot.server.core.worker; import com.zmops.zeus.server.library.module.ModuleDefineHolder; import lombok.Getter; /** * Abstract worker definition. Provide the {@link ModuleDefineHolder} to make sure the worker could find and access * services in different modules. Also, {@link #in(Object)} is provided as the primary entrance of every worker. * <p> * * @param <INPUT> the datatype this worker implementation processes. * @editor nantian * 数据从协议入口 发送到 zabbix 过程中的队列,to("zabbix") */ public abstract class AbstractWorker<INPUT> { @Getter private final ModuleDefineHolder moduleDefineHolder; public AbstractWorker(ModuleDefineHolder moduleDefineHolder) { this.moduleDefineHolder = moduleDefineHolder; } /** * Main entrance of this worker. */ public abstract void in(INPUT input); }
2301_81045437/zeus-iot
iot-server/server-core/src/main/java/com/zmops/zeus/iot/server/core/worker/AbstractWorker.java
Java
gpl-3.0
1,695
package com.zmops.zeus.iot.server.core.worker; import com.google.gson.Gson; import com.zmops.zeus.iot.server.core.UnexpectedException; import com.zmops.zeus.iot.server.core.worker.data.ItemValue; import com.zmops.zeus.iot.server.core.worker.data.ZabbixTrapper; import com.zmops.zeus.iot.server.sender.module.ZabbixSenderModule; import com.zmops.zeus.iot.server.sender.service.ZabbixSenderService; import com.zmops.zeus.iot.server.telemetry.TelemetryModule; import com.zmops.zeus.iot.server.telemetry.api.CounterMetrics; import com.zmops.zeus.iot.server.telemetry.api.MetricsCreator; import com.zmops.zeus.iot.server.telemetry.api.MetricsTag; import com.zmops.zeus.server.datacarrier.DataCarrier; import com.zmops.zeus.server.datacarrier.consumer.BulkConsumePool; import com.zmops.zeus.server.datacarrier.consumer.ConsumerPoolFactory; import com.zmops.zeus.server.datacarrier.consumer.IConsumer; import com.zmops.zeus.server.library.module.ModuleManager; import lombok.extern.slf4j.Slf4j; import java.io.IOException; import java.util.ArrayList; import java.util.Collection; import java.util.List; /** * @author nantian created at 2021/8/23 15:11 * <p> * 数据发送队列 */ @Slf4j public class ItemDataTransferWorker extends TransferWorker<ItemValue> { private final DataCarrier<ItemValue> dataCarrier; private final CounterMetrics iotDataTransferCounter; private final Gson gson = new Gson(); public ItemDataTransferWorker(ModuleManager moduleManager) { super(moduleManager); String name = "ITEMVALUE_TRANSFER_TUNNEL"; int size = BulkConsumePool.Creator.recommendMaxSize() / 8; if (size == 0) { size = 1; } BulkConsumePool.Creator creator = new BulkConsumePool.Creator(name, size, 20); try { ConsumerPoolFactory.INSTANCE.createIfAbsent(name, creator); } catch (Exception e) { throw new UnexpectedException(e.getMessage(), e); } this.dataCarrier = new DataCarrier<>("ZABBIX_SENDER", name, 4, 2000); this.dataCarrier.consume(ConsumerPoolFactory.INSTANCE.get(name), new SenderConsumer()); // #### 发送数量 指标采集 MetricsCreator metricsCreator = moduleManager.find(TelemetryModule.NAME) .provider() .getService(MetricsCreator.class); iotDataTransferCounter = metricsCreator.createCounter( "transfer_data_count", "The count number of iot device data in transfer", new MetricsTag.Keys("name"), new MetricsTag.Values("transfer_data_count") ); } @Override public void in(ItemValue itemValue) { iotDataTransferCounter.inc(); dataCarrier.produce(itemValue); } @Override public void prepareBatch(Collection<ItemValue> lastCollection) { long start = System.currentTimeMillis(); if (lastCollection.size() == 0) { return; } int maxBatchGetSize = 500; final int batchSize = Math.min(maxBatchGetSize, lastCollection.size()); List<ItemValue> valueList = new ArrayList<>(); for (ItemValue data : lastCollection) { valueList.add(data); if (valueList.size() == batchSize) { batchSenderDataToZabbix(valueList); } } if (valueList.size() > 0) { batchSenderDataToZabbix(valueList); } log.debug("batch sender data size:{}, took time: {}", lastCollection.size(), System.currentTimeMillis() - start); } private void batchSenderDataToZabbix(List<ItemValue> valueList) { ZabbixTrapper zabbixTrapper = new ZabbixTrapper(valueList); ZabbixSenderService senderService = getModuleDefineHolder() .find(ZabbixSenderModule.NAME).provider().getService(ZabbixSenderService.class); try { String sendResult = senderService.sendData(gson.toJson(zabbixTrapper)); log.debug(sendResult); } catch (IOException e) { log.error(" itemvalue data sender error,msg :{}", e.getMessage()); e.printStackTrace(); } finally { valueList.clear(); } } private class SenderConsumer implements IConsumer<ItemValue> { @Override public void init() { } @Override public void consume(List<ItemValue> data) { ItemDataTransferWorker.this.onWork(data); } @Override public void onError(List<ItemValue> data, Throwable t) { log.error(t.getMessage(), t); } @Override public void onExit() { } } }
2301_81045437/zeus-iot
iot-server/server-core/src/main/java/com/zmops/zeus/iot/server/core/worker/ItemDataTransferWorker.java
Java
gpl-3.0
4,697
/* * 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 com.zmops.zeus.iot.server.core.worker; import com.zmops.zeus.iot.server.core.worker.data.Item; import com.zmops.zeus.server.library.module.ModuleDefineHolder; import lombok.extern.slf4j.Slf4j; import java.util.Collection; import java.util.List; /** * 1. 协议入口 -> zabbix trapper item * * @param <INPUT> The type of worker input. */ @Slf4j public abstract class TransferWorker<INPUT extends Item> extends AbstractWorker<INPUT> { TransferWorker(ModuleDefineHolder moduleDefineHolder) { super(moduleDefineHolder); } void onWork(List<INPUT> input) { prepareBatch(input); } public abstract void prepareBatch(Collection<INPUT> lastCollection); }
2301_81045437/zeus-iot
iot-server/server-core/src/main/java/com/zmops/zeus/iot/server/core/worker/TransferWorker.java
Java
gpl-3.0
1,507
/* * 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 com.zmops.zeus.iot.server.core.worker.data; import java.util.List; /** * BufferedData represents a data collection in the memory. Data could be accepted and be drain to other collection. * <p> * {@link #accept(Object)} and {@link #read()} wouldn't be required to thread-safe. */ public interface BufferedData<T> { /** * Accept the data into the cache if it fits the conditions. The implementation maybe wouldn't accept the new input * data. * * @param data to be added potentially. */ void accept(T data); /** * Read all existing buffered data, and clear the memory. */ List<T> read(); }
2301_81045437/zeus-iot
iot-server/server-core/src/main/java/com/zmops/zeus/iot/server/core/worker/data/BufferedData.java
Java
gpl-3.0
1,460
package com.zmops.zeus.iot.server.core.worker.data; /** * @author nantian created at 2021/8/23 15:14 * <p> * 对应设备的属性 */ public interface Item { /** * 设备ID 唯一 * * @return string */ String host(); /** * 属性标识 唯一 * * @return string */ String key(); }
2301_81045437/zeus-iot
iot-server/server-core/src/main/java/com/zmops/zeus/iot/server/core/worker/data/Item.java
Java
gpl-3.0
344
package com.zmops.zeus.iot.server.core.worker.data; import lombok.Getter; import lombok.Setter; /** * @author nantian created at 2021/8/23 15:15 */ @Getter @Setter public class ItemValue implements Item { private String host; // 【设备ID】 private String key; // 【属性标识】 // 【设备上报 值】,都是文本 // Zabbix 会根据配置的ITEM 类型,进行转换,如果失败就报错 private String value; private Long clock; // 秒,如果为 Null,则 zabbix 以接收时间为准 private Long ns; // 纳秒,如果为 Null,则 zabbix 以接收时间为准 public ItemValue(String host, Long clock) { this.host = host; if (clock != null) { this.clock = clock; } } /** * 设置 数据时间,单独设置 以设备推送的时间数据为准 * * @param clock 毫秒,70年到现在 * @param ns 纳秒,0-9位数 */ public void setTime(Long clock, Long ns) { this.clock = clock; this.ns = ns; } @Override public String host() { return getHost(); } @Override public String key() { return getKey(); } }
2301_81045437/zeus-iot
iot-server/server-core/src/main/java/com/zmops/zeus/iot/server/core/worker/data/ItemValue.java
Java
gpl-3.0
1,216
package com.zmops.zeus.iot.server.core.worker.data; import lombok.Getter; import lombok.Setter; import java.util.ArrayList; import java.util.List; /** * @author nantian created at 2021/8/23 16:49 */ public class ZabbixTrapper { @Getter private final String request = "sender data"; @Setter @Getter private List<ItemValue> data; public ZabbixTrapper(List<ItemValue> itemValues) { data = new ArrayList<>(); data.addAll(itemValues); } }
2301_81045437/zeus-iot
iot-server/server-core/src/main/java/com/zmops/zeus/iot/server/core/worker/data/ZabbixTrapper.java
Java
gpl-3.0
487
/* * 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 com.zmops.zeus.iot.server.health.checker.module; import com.zmops.zeus.iot.server.health.checker.provider.HealthQueryService; import com.zmops.zeus.server.library.module.ModuleDefine; /** * HealthCheckerModule intends to provide a channel to expose the healthy status of modules to external. */ public class HealthCheckerModule extends ModuleDefine { public static final String NAME = "health-checker"; public HealthCheckerModule() { super(NAME); } @Override public Class[] services() { return new Class[]{HealthQueryService.class}; } }
2301_81045437/zeus-iot
iot-server/server-health-checker/src/main/java/com/zmops/zeus/iot/server/health/checker/module/HealthCheckerModule.java
Java
gpl-3.0
1,397
/* * 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 com.zmops.zeus.iot.server.health.checker.provider; import com.zmops.zeus.server.library.module.ModuleConfig; import lombok.Getter; /** * The Configuration of health checker module. */ @Getter public class HealthCheckerConfig extends ModuleConfig { private long checkIntervalSeconds = 5; }
2301_81045437/zeus-iot
iot-server/server-health-checker/src/main/java/com/zmops/zeus/iot/server/health/checker/provider/HealthCheckerConfig.java
Java
gpl-3.0
1,112
/* * 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 com.zmops.zeus.iot.server.health.checker.provider; import com.google.common.util.concurrent.AtomicDouble; import com.zmops.zeus.iot.server.health.checker.module.HealthCheckerModule; import com.zmops.zeus.iot.server.telemetry.TelemetryModule; import com.zmops.zeus.iot.server.telemetry.api.MetricsCollector; import com.zmops.zeus.iot.server.telemetry.api.MetricsCreator; import com.zmops.zeus.server.library.module.*; import io.vavr.collection.Stream; import lombok.extern.slf4j.Slf4j; import java.util.concurrent.Executors; import java.util.concurrent.ScheduledExecutorService; import java.util.concurrent.TimeUnit; import java.util.concurrent.atomic.AtomicReference; import java.util.stream.Collectors; /** * HealthCheckerProvider fetches health check metrics from telemetry module, then calculates health score and generates * details explains the score. External service or users can query health status by HealthCheckerService. */ @Slf4j public class HealthCheckerProvider extends ModuleProvider { private final AtomicDouble score = new AtomicDouble(); private final AtomicReference<String> details = new AtomicReference<>(); private final HealthCheckerConfig config = new HealthCheckerConfig(); private MetricsCollector collector; private MetricsCreator metricsCreator; private ScheduledExecutorService ses; @Override public String name() { return "default"; } @Override public Class<? extends ModuleDefine> module() { return HealthCheckerModule.class; } @Override public ModuleConfig createConfigBeanIfAbsent() { return config; } @Override public void prepare() throws ServiceNotProvidedException, ModuleStartException { score.set(-1); ses = Executors.newSingleThreadScheduledExecutor(); this.registerServiceImplementation(HealthQueryService.class, new HealthQueryService(score, details)); } @Override public void start() throws ServiceNotProvidedException, ModuleStartException { ModuleServiceHolder telemetry = getManager().find(TelemetryModule.NAME).provider(); metricsCreator = telemetry.getService(MetricsCreator.class); collector = telemetry.getService(MetricsCollector.class); } @Override public void notifyAfterCompleted() throws ServiceNotProvidedException, ModuleStartException { ses.scheduleAtFixedRate(() -> { StringBuilder unhealthyModules = new StringBuilder(); score.set(Stream.ofAll(collector.collect()) .flatMap(metricFamily -> metricFamily.samples) .filter(sample -> metricsCreator.isHealthCheckerMetrics(sample.name)) .peek(sample -> { if (sample.value > 0.0) { unhealthyModules.append(metricsCreator.extractModuleName(sample.name)).append(","); } }) .map(sample -> sample.value) .collect(Collectors.summingDouble(Double::doubleValue))); details.set(unhealthyModules.toString()); }, 2, config.getCheckIntervalSeconds(), TimeUnit.SECONDS); } @Override public String[] requiredModules() { return new String[]{TelemetryModule.NAME}; } }
2301_81045437/zeus-iot
iot-server/server-health-checker/src/main/java/com/zmops/zeus/iot/server/health/checker/provider/HealthCheckerProvider.java
Java
gpl-3.0
4,122
/* * 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 com.zmops.zeus.iot.server.health.checker.provider; import com.google.common.util.concurrent.AtomicDouble; import com.zmops.zeus.server.library.module.Service; import lombok.Getter; import lombok.RequiredArgsConstructor; import lombok.Setter; import java.util.concurrent.atomic.AtomicReference; @RequiredArgsConstructor public class HealthQueryService implements Service { private final AtomicDouble score; private final AtomicReference<String> details; public HealthStatus checkHealth() { HealthStatus s = new HealthStatus(); s.setScore(score.intValue()); s.setDetails(details.get()); return s; } @Getter @Setter static class HealthStatus { // score == 0 means healthy, otherwise it's unhealthy. private int score; private String details; } }
2301_81045437/zeus-iot
iot-server/server-health-checker/src/main/java/com/zmops/zeus/iot/server/health/checker/provider/HealthQueryService.java
Java
gpl-3.0
1,651
package com.zmops.zeus.iot.server.h2.module; import com.zmops.zeus.iot.server.h2.service.InsertDAO; import com.zmops.zeus.server.library.module.ModuleDefine; /** * @author nantian created at 2021/10/24 16:56 */ public class LocalH2Module extends ModuleDefine { public static final String NAME = "local-h2"; public LocalH2Module() { super(NAME); } @Override public Class[] services() { return new Class[]{ InsertDAO.class }; } }
2301_81045437/zeus-iot
iot-server/server-localdb/src/main/java/com/zmops/zeus/iot/server/h2/module/LocalH2Module.java
Java
gpl-3.0
499
package com.zmops.zeus.iot.server.h2.provider; import com.zmops.zeus.server.library.module.ModuleConfig; import lombok.Getter; import lombok.Setter; /** * @author nantian created at 2021/10/24 16:45 * <p> * H2 配置,用于 IoT Server 本地组件状态缓存 */ @Getter @Setter public class LocalH2Config extends ModuleConfig { private String driver = "org.h2.jdbcx.JdbcDataSource"; private String url = "jdbc:h2:~/zeus_iot_db;DB_CLOSE_DELAY=-1"; private String user = "sa"; private String password = "sa"; /** * 模块版本号 */ private String version; }
2301_81045437/zeus-iot
iot-server/server-localdb/src/main/java/com/zmops/zeus/iot/server/h2/provider/LocalH2Config.java
Java
gpl-3.0
604
package com.zmops.zeus.iot.server.h2.provider; import com.zmops.zeus.iot.server.client.jdbc.JDBCClientException; import com.zmops.zeus.iot.server.client.jdbc.hikaricp.JDBCHikariCPClient; import com.zmops.zeus.iot.server.h2.service.InsertDAO; import java.sql.ResultSet; import java.sql.SQLException; /** * @author yefei **/ public class LocalH2InsertDAO implements InsertDAO { private final JDBCHikariCPClient h2Client; public LocalH2InsertDAO(JDBCHikariCPClient h2Client) { this.h2Client = h2Client; } @Override public void insert(String sql) { try { h2Client.execute(h2Client.getConnection(), sql); } catch (JDBCClientException e) { e.printStackTrace(); } } @Override public int update(String sql, Object... params) { int r = 0; try { r = h2Client.executeUpdate(h2Client.getConnection(), sql, params); } catch (JDBCClientException e) { e.printStackTrace(); } return r; } @Override public ResultSet queryRes(String sql, Object... params) { ResultSet resultSet = null; try { resultSet = h2Client.executeQuery(h2Client.getConnection(), sql, params); } catch (JDBCClientException e) { e.printStackTrace(); } return resultSet; } @Override public void delete(String sql) { try { h2Client.execute(h2Client.getConnection(), sql); } catch (JDBCClientException e) { e.printStackTrace(); } } }
2301_81045437/zeus-iot
iot-server/server-localdb/src/main/java/com/zmops/zeus/iot/server/h2/provider/LocalH2InsertDAO.java
Java
gpl-3.0
1,588
package com.zmops.zeus.iot.server.h2.provider; import com.zmops.zeus.iot.server.client.jdbc.JDBCClientException; import com.zmops.zeus.iot.server.client.jdbc.hikaricp.JDBCHikariCPClient; import com.zmops.zeus.iot.server.h2.module.LocalH2Module; import com.zmops.zeus.iot.server.h2.service.InsertDAO; import com.zmops.zeus.server.library.module.*; import java.sql.Connection; import java.sql.ResultSet; import java.util.Properties; /** * @author nantian created at 2021/10/24 16:57 */ public class LocalH2Provider extends ModuleProvider { private final LocalH2Config localH2Config; private JDBCHikariCPClient h2Client; public LocalH2Provider() { this.localH2Config = new LocalH2Config(); } @Override public String name() { return "default"; } @Override public Class<? extends ModuleDefine> module() { return LocalH2Module.class; } @Override public ModuleConfig createConfigBeanIfAbsent() { return localH2Config; } @Override public void prepare() throws ServiceNotProvidedException, ModuleStartException { Properties settings = new Properties(); settings.setProperty("dataSourceClassName", localH2Config.getDriver()); settings.setProperty("dataSource.url", localH2Config.getUrl()); settings.setProperty("dataSource.user", localH2Config.getUser()); settings.setProperty("dataSource.password", localH2Config.getPassword()); h2Client = new JDBCHikariCPClient(settings); h2Client.connect(); this.registerServiceImplementation(InsertDAO.class, new LocalH2InsertDAO(h2Client)); try { Connection connection = h2Client.getConnection(); h2Client.execute( connection, "CREATE TABLE if not exists PROTOCOL_COMPONENT(" + " ID INT PRIMARY KEY," + " NAME VARCHAR(64)," + " UNIQUE_ID VARCHAR(32)," + " FILE_NAME VARCHAR(64)," + " STATUS VARCHAR(8)," + " REMARK VARCHAR(255)," + " BIZ_NAME VARCHAR(64)," + " BIZ_VERSION VARCHAR(32)" + ");"); h2Client.execute( connection, "CREATE TABLE if not exists PROTOCOL_GATEWAY(" + " ID INT PRIMARY KEY," + " NAME VARCHAR(64)," + " PROTOCOL_COMPONENT_ID INT," + " PROTOCOL_SERVICE_ID INT," + " REMARK VARCHAR(255)," + " STATUS VARCHAR(8)" + ");"); h2Client.execute( connection, "CREATE TABLE if not exists PROTOCOL_SERVICE(" + " ID INT PRIMARY KEY," + " NAME VARCHAR(64)," + " REMARK VARCHAR(255)," + " URL VARCHAR(128)," + " IP VARCHAR(16)," + " PORT INT," + " MSG_LENGTH INT," + " CLIENT_ID VARCHAR(32)," + " PROTOCOL VARCHAR(16)" + ");"); h2Client.execute( connection, "CREATE TABLE if not exists PROTOCOL_GATEWAY_MQTT(" + " TOPIC VARCHAR(64)," + " PROTOCOL_COMPONENT_ID INT," + " PROTOCOL_GATEWAY_ID INT" + ");"); ResultSet rs2 = h2Client.executeQuery(connection, "select * from PROTOCOL_COMPONENT;"); System.out.println(rs2); } catch (JDBCClientException e) { // throw new IOException(e.getMessage(), e); e.printStackTrace(); } } @Override public void start() throws ServiceNotProvidedException, ModuleStartException { } @Override public void notifyAfterCompleted() throws ServiceNotProvidedException, ModuleStartException { } @Override public String[] requiredModules() { return new String[0]; } }
2301_81045437/zeus-iot
iot-server/server-localdb/src/main/java/com/zmops/zeus/iot/server/h2/provider/LocalH2Provider.java
Java
gpl-3.0
4,382
package com.zmops.zeus.iot.server.h2.service; import com.zmops.zeus.server.library.module.Service; import java.sql.ResultSet; /** * @author yefei **/ public interface InsertDAO extends Service { void insert(String sql); int update(String sql, Object... params); ResultSet queryRes(String sql, Object... params); void delete(String sql); }
2301_81045437/zeus-iot
iot-server/server-localdb/src/main/java/com/zmops/zeus/iot/server/h2/service/InsertDAO.java
Java
gpl-3.0
364
package com.zmops.zeus.iot.server.sender.module; import com.zmops.zeus.iot.server.sender.service.ZabbixSenderService; import com.zmops.zeus.server.library.module.ModuleDefine; /** * @author nantian created at 2021/8/14 14:35 * <p> * 数据发送到 Zabbix Trapper,参数值:"sender data" */ public class ZabbixSenderModule extends ModuleDefine { public static final String NAME = "zabbix-sender"; public ZabbixSenderModule() { super(NAME); } @Override public Class[] services() { return new Class[]{ ZabbixSenderService.class }; } }
2301_81045437/zeus-iot
iot-server/server-sender/src/main/java/com/zmops/zeus/iot/server/sender/module/ZabbixSenderModule.java
Java
gpl-3.0
611
package com.zmops.zeus.iot.server.sender.provider; import lombok.extern.slf4j.Slf4j; import java.net.InetSocketAddress; import java.net.Socket; /** * @author nantian created at 2021/8/14 14:46 * <p> * Zabbix 发送 Socket Client */ @Slf4j public class ZabbixSenderClient { private static ZabbixSenderModuleConfig socketConfig; public ZabbixSenderClient(ZabbixSenderModuleConfig config) { socketConfig = config; } /** * 启动 TCP Sender 客户端 */ public void start() { log.debug("Zabbix Sender 模块已经启动,Trapper 服务地址:{}:{}", socketConfig.getHost(), socketConfig.getPort()); } /** * 获取 Socket 实例 * * @return Socket */ public static Socket getSocket() { Socket trapperSocket = new Socket(); try { trapperSocket.setSoTimeout(1000); trapperSocket.connect(new InetSocketAddress(socketConfig.getHost(), socketConfig.getPort())); } catch (Exception e) { e.printStackTrace(); } return trapperSocket; } }
2301_81045437/zeus-iot
iot-server/server-sender/src/main/java/com/zmops/zeus/iot/server/sender/provider/ZabbixSenderClient.java
Java
gpl-3.0
1,099
package com.zmops.zeus.iot.server.sender.provider; import com.zmops.zeus.server.library.module.ModuleConfig; import lombok.Getter; import lombok.Setter; /** * @author nantian created at 2021/8/14 14:41 */ @Setter @Getter public class ZabbixSenderModuleConfig extends ModuleConfig { /** * Export tcp port */ private int port = 10051; /** * Bind to host */ private String host = "127.0.0.1"; }
2301_81045437/zeus-iot
iot-server/server-sender/src/main/java/com/zmops/zeus/iot/server/sender/provider/ZabbixSenderModuleConfig.java
Java
gpl-3.0
435
package com.zmops.zeus.iot.server.sender.provider; import com.zmops.zeus.iot.server.sender.module.ZabbixSenderModule; import com.zmops.zeus.iot.server.sender.service.ZabbixSenderService; import com.zmops.zeus.server.library.module.*; import lombok.extern.slf4j.Slf4j; /** * @author nantian created at 2021/8/14 14:40 */ @Slf4j public class ZabbixSenderProvider extends ModuleProvider { private final ZabbixSenderModuleConfig senderConfig; public ZabbixSenderProvider() { this.senderConfig = new ZabbixSenderModuleConfig(); } @Override public String name() { return "default"; } @Override public Class<? extends ModuleDefine> module() { return ZabbixSenderModule.class; } @Override public ModuleConfig createConfigBeanIfAbsent() { return senderConfig; } @Override public void prepare() throws ServiceNotProvidedException, ModuleStartException { this.registerServiceImplementation(ZabbixSenderService.class, new ZabbixSenderService(getManager())); } @Override public void start() throws ServiceNotProvidedException, ModuleStartException { ZabbixSenderClient senderClient = new ZabbixSenderClient(senderConfig); senderClient.start(); } @Override public void notifyAfterCompleted() throws ServiceNotProvidedException, ModuleStartException { } @Override public String[] requiredModules() { return new String[0]; } }
2301_81045437/zeus-iot
iot-server/server-sender/src/main/java/com/zmops/zeus/iot/server/sender/provider/ZabbixSenderProvider.java
Java
gpl-3.0
1,485
package com.zmops.zeus.iot.server.sender.service; import com.google.gson.Gson; import com.zmops.zeus.iot.server.sender.provider.ZabbixSenderClient; import com.zmops.zeus.server.library.module.ModuleManager; import com.zmops.zeus.server.library.module.Service; import lombok.extern.slf4j.Slf4j; import java.io.IOException; import java.io.InputStream; import java.io.OutputStream; import java.net.Socket; import java.nio.ByteBuffer; import java.nio.charset.StandardCharsets; import java.util.Arrays; import java.util.HashMap; import java.util.Map; /** * @author nantian created at 2021/8/14 18:39 */ @Slf4j public class ZabbixSenderService implements Service { private final ModuleManager moduleManager; private static final Gson gson = new Gson(); public ZabbixSenderService(ModuleManager moduleManager) { this.moduleManager = moduleManager; } /** * 指定格式的 JSON * * @param message see * https://www.zabbix.com/documentation/current/manual/appendix/items/trapper * * { * "request":"sender data", * "data":[ * { * "host":"device.info", * "key":"device.temp", * "value":"86" * } * ] * } * @return String * @throws IOException ex */ public String sendData(String message) throws IOException { Socket trapperSocket = ZabbixSenderClient.getSocket(); int payloadLength = length(message); byte[] header = new byte[]{ 'Z', 'B', 'X', 'D', '\1', (byte) (payloadLength & 0xFF), (byte) ((payloadLength >> 8) & 0xFF), (byte) ((payloadLength >> 16) & 0xFF), (byte) ((payloadLength >> 24) & 0xFF), '\0', '\0', '\0', '\0'}; ByteBuffer byteBuffer = ByteBuffer.allocate(header.length + payloadLength); byteBuffer.put(header); byteBuffer.put(message.getBytes(StandardCharsets.UTF_8)); byte[] response = new byte[2048]; OutputStream reqStream = trapperSocket.getOutputStream(); reqStream.write(byteBuffer.array()); reqStream.flush(); byteBuffer = null; InputStream resStream = trapperSocket.getInputStream(); StringBuilder resp = new StringBuilder(); int headLength = 13; int bRead = 0; while (true) { bRead = resStream.read(response); if (bRead <= 0) break; resp.append(new String(Arrays.copyOfRange(response, headLength, bRead))); headLength = 0; } log.debug(" Zabbix Trapper 响应数据:{} ", resp.toString()); resStream.close(); reqStream.close(); trapperSocket.close(); trapperSocket = null; return zabbixResponseToMap(resp.toString()); } /** * zabbix 返回字符串 处理 * * @param resp * @return String */ private String zabbixResponseToMap(String resp) { Map<String, String> result = gson.fromJson(resp, Map.class); String info = result.get("info"); if (info == null) { return resp; } String[] infos = info.split(";"); Map<String, String> resultMap = new HashMap<>(); for (String i : infos) { String[] ii = i.split(":"); resultMap.put(ii[0].trim(), ii[1]); } resultMap.put("response", result.get("response")); return gson.toJson(resultMap); } /** * 计算字符串长度 中文3个字节 * @param value * @return */ public static int length(String value) { int valueLength = 0; String chinese = "[\u0391-\uFFE5]"; for (int i = 0; i < value.length(); i++) { String temp = value.substring(i, i + 1); if (temp.matches(chinese)) { valueLength += 3; } else { valueLength += 1; } } return valueLength; } }
2301_81045437/zeus-iot
iot-server/server-sender/src/main/java/com/zmops/zeus/iot/server/sender/service/ZabbixSenderService.java
Java
gpl-3.0
4,045
package com.zmops.zeus.iot.server.starter; import com.alipay.sofa.ark.support.startup.SofaArkBootstrap; import lombok.extern.slf4j.Slf4j; /** * @author nantian created at 2021/8/13 15:26 * <p> * 宙斯服务 协议层启动 */ @Slf4j public class IoTServerStartUp { public static void main(String[] args) { SofaArkBootstrap.launch(args); IoTServerBootstrap.start(); log.info("IoT Server Platform start successfully ..."); } }
2301_81045437/zeus-iot
iot-server/server-starter/src/main/java/com/zmops/zeus/iot/server/starter/IoTServerStartUp.java
Java
gpl-3.0
466
/* * 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 com.zmops.zeus.iot.server.storage.plugin.jdbc.influxdb; import com.zmops.zeus.iot.server.client.Client; import com.zmops.zeus.iot.server.client.healthcheck.DelegatedHealthChecker; import com.zmops.zeus.iot.server.client.healthcheck.HealthCheckable; import com.zmops.zeus.server.library.util.CollectionUtils; import com.zmops.zeus.server.library.util.HealthChecker; import lombok.extern.slf4j.Slf4j; import okhttp3.OkHttpClient; import org.influxdb.InfluxDB; import org.influxdb.InfluxDBFactory; import org.influxdb.dto.BatchPoints; import org.influxdb.dto.Point; import org.influxdb.dto.Query; import org.influxdb.dto.QueryResult; import org.influxdb.querybuilder.time.TimeInterval; import java.io.IOException; import java.util.List; import java.util.Objects; import java.util.concurrent.TimeUnit; import static org.influxdb.querybuilder.BuiltQuery.QueryBuilder.ti; /** * InfluxDB connection maintainer, provides base data write/query API. */ @Slf4j public class InfluxClient implements Client, HealthCheckable { private final DelegatedHealthChecker healthChecker = new DelegatedHealthChecker(); private final InfluxStorageConfig config; private InfluxDB influx; /** * A constant, the name of time field in Time-series database. */ public static final String TIME = "time"; private final String database; public InfluxClient(InfluxStorageConfig config) { this.config = config; this.database = config.getDatabase(); } public final String getDatabase() { return database; } @Override public void connect() { try { InfluxDB.ResponseFormat responseFormat = InfluxDB.ResponseFormat.valueOf(config.getConnectionResponseFormat()); influx = InfluxDBFactory.connect(config.getUrl(), config.getUser(), config.getPassword(), new OkHttpClient.Builder().readTimeout(3, TimeUnit.MINUTES) .writeTimeout(3, TimeUnit.MINUTES), responseFormat ); influx.query(new Query("CREATE DATABASE " + database)); influx.enableGzip(); if (config.isBatchEnabled()) { influx.enableBatch(config.getActions(), config.getDuration(), TimeUnit.MILLISECONDS); } influx.setDatabase(database); healthChecker.health(); } catch (Throwable e) { healthChecker.unHealth(e); throw e; } } /** * To get a connection of InfluxDB. * * @return InfluxDB's connection */ private InfluxDB getInflux() { return influx; } /** * Execute a query against InfluxDB and return a set of {@link QueryResult.Result}s. Normally, InfluxDB supports * combining multiple statements into one query, so that we do get multi-results. * * @throws IOException if there is an error on the InfluxDB server or communication error. */ public List<QueryResult.Result> query(Query query) throws IOException { if (log.isDebugEnabled()) { log.debug("SQL Statement: {}", query.getCommand()); } try { QueryResult result = getInflux().query(new Query(query.getCommand())); if (result.hasError()) { throw new IOException(result.getError()); } healthChecker.health(); return result.getResults(); } catch (Throwable e) { healthChecker.unHealth(e); throw new IOException(e.getMessage() + System.lineSeparator() + "SQL Statement: " + query.getCommand(), e); } } /** * Execute a query against InfluxDB with a single statement. * * @throws IOException if there is an error on the InfluxDB server or communication error */ public List<QueryResult.Series> queryForSeries(Query query) throws IOException { List<QueryResult.Result> results = query(query); if (CollectionUtils.isEmpty(results)) { return null; } return results.get(0).getSeries(); } /** * Execute a query against InfluxDB with a single statement but return a single {@link QueryResult.Series}. * * @throws IOException if there is an error on the InfluxDB server or communication error */ public QueryResult.Series queryForSingleSeries(Query query) throws IOException { List<QueryResult.Series> series = queryForSeries(query); if (CollectionUtils.isEmpty(series)) { return null; } return series.get(0); } /** * Execute a query against InfluxDB with a `select count(*)` statement and return the count only. * * @throws IOException if there is an error on the InfluxDB server or communication error */ public int getCounter(Query query) throws IOException { QueryResult.Series series = queryForSingleSeries(query); if (log.isDebugEnabled()) { log.debug("SQL: {} result: {}", query.getCommand(), series); } if (Objects.isNull(series)) { return 0; } return ((Number) series.getValues().get(0).get(1)).intValue(); } /** * Data management, to drop a time-series by measurement and time-series name specified. If an exception isn't * thrown, it means execution success. Notice, drop series don't support to drop series by range * * @throws IOException if there is an error on the InfluxDB server or communication error */ public void dropSeries(String measurement, long timeBucket) throws IOException { Query query = new Query("DROP SERIES FROM " + measurement + " WHERE time_bucket='" + timeBucket + "'"); this.query(query); } public void deleteByQuery(String measurement, long timestamp) throws IOException { this.query(new Query("delete from " + measurement + " where time < " + timestamp + "ms")); } /** * Write a {@link Point} into InfluxDB. Note that, the {@link Point} is written into buffer of InfluxDB Client and * wait for buffer flushing. */ public void write(Point point) { try { getInflux().write(point); this.healthChecker.health(); } catch (Throwable e) { healthChecker.unHealth(e); throw e; } } /** * A batch operation of write. {@link Point}s flush directly. */ public void write(BatchPoints points) { try { getInflux().write(points); this.healthChecker.health(); } catch (Throwable e) { healthChecker.unHealth(e); throw e; } } @Override public void shutdown() throws IOException { try { getInflux().close(); this.healthChecker.health(); } catch (Throwable e) { healthChecker.unHealth(e); throw new IOException(e); } } /** * Convert to InfluxDB {@link TimeInterval}. */ public static TimeInterval timeIntervalTS(long timestamp) { return ti(timestamp, "ms"); } // /** // * Convert to InfluxDB {@link TimeInterval}. // */ // public static TimeInterval timeIntervalTB(long timeBucket) { // return ti(TimeBucket.getTimestamp(timeBucket), "ms"); // } @Override public void registerChecker(HealthChecker healthChecker) { this.healthChecker.register(healthChecker); } }
2301_81045437/zeus-iot
iot-server/server-storage-plugin/server-influxdb-plugin/src/main/java/com/zmops/zeus/iot/server/storage/plugin/jdbc/influxdb/InfluxClient.java
Java
gpl-3.0
8,318
/* * 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 com.zmops.zeus.iot.server.storage.plugin.jdbc.influxdb; import com.zmops.zeus.server.library.module.ModuleConfig; import lombok.Getter; import lombok.Setter; @Setter @Getter public class InfluxStorageConfig extends ModuleConfig { private String url = ""; private String user = ""; private String password = ""; private String database = ""; private int actions; private int duration; private boolean batchEnabled = true; private int fetchTaskLogMaxSize = 5000; private String connectionResponseFormat = "MSGPACK"; }
2301_81045437/zeus-iot
iot-server/server-storage-plugin/server-influxdb-plugin/src/main/java/com/zmops/zeus/iot/server/storage/plugin/jdbc/influxdb/InfluxStorageConfig.java
Java
gpl-3.0
1,379
/* * 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 com.zmops.zeus.iot.server.storage.plugin.jdbc.influxdb; import com.zmops.zeus.iot.server.core.CoreModule; import com.zmops.zeus.iot.server.core.storage.IBatchDAO; import com.zmops.zeus.iot.server.core.storage.StorageDAO; import com.zmops.zeus.iot.server.core.storage.StorageModule; import com.zmops.zeus.iot.server.storage.plugin.jdbc.influxdb.dao.BatchDAO; import com.zmops.zeus.iot.server.storage.plugin.jdbc.influxdb.dao.InfluxStorageDAO; import com.zmops.zeus.iot.server.telemetry.TelemetryModule; import com.zmops.zeus.iot.server.telemetry.api.HealthCheckMetrics; import com.zmops.zeus.iot.server.telemetry.api.MetricsCreator; import com.zmops.zeus.iot.server.telemetry.api.MetricsTag; import com.zmops.zeus.server.library.module.*; import lombok.extern.slf4j.Slf4j; @Slf4j public class InfluxStorageProvider extends ModuleProvider { private final InfluxStorageConfig config; private InfluxClient client; public InfluxStorageProvider() { config = new InfluxStorageConfig(); } @Override public String name() { return "influxdb"; } @Override public Class<? extends ModuleDefine> module() { return StorageModule.class; } @Override public ModuleConfig createConfigBeanIfAbsent() { return config; } @Override public void prepare() throws ServiceNotProvidedException { client = new InfluxClient(config); this.registerServiceImplementation(IBatchDAO.class, new BatchDAO(client)); this.registerServiceImplementation(StorageDAO.class, new InfluxStorageDAO(client)); } @Override public void start() throws ServiceNotProvidedException, ModuleStartException { MetricsCreator metricCreator = getManager().find(TelemetryModule.NAME).provider().getService(MetricsCreator.class); HealthCheckMetrics healthChecker = metricCreator.createHealthCheckerGauge( "storage_influxdb", MetricsTag.EMPTY_KEY, MetricsTag.EMPTY_VALUE); client.registerChecker(healthChecker); client.connect(); } @Override public void notifyAfterCompleted() throws ServiceNotProvidedException { } @Override public String[] requiredModules() { return new String[]{CoreModule.NAME}; } }
2301_81045437/zeus-iot
iot-server/server-storage-plugin/server-influxdb-plugin/src/main/java/com/zmops/zeus/iot/server/storage/plugin/jdbc/influxdb/InfluxStorageProvider.java
Java
gpl-3.0
3,097
/* * 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 com.zmops.zeus.iot.server.storage.plugin.jdbc.influxdb.dao; import com.zmops.zeus.iot.server.client.request.InsertRequest; import com.zmops.zeus.iot.server.client.request.PrepareRequest; import com.zmops.zeus.iot.server.core.storage.IBatchDAO; import com.zmops.zeus.iot.server.storage.plugin.jdbc.influxdb.InfluxClient; import com.zmops.zeus.server.library.util.CollectionUtils; import lombok.extern.slf4j.Slf4j; import org.influxdb.dto.BatchPoints; import java.util.List; @Slf4j public class BatchDAO implements IBatchDAO { private final InfluxClient client; public BatchDAO(InfluxClient client) { this.client = client; } @Override public void insert(InsertRequest insertRequest) { client.write(((InfluxInsertRequest) insertRequest).getPoint()); } @Override public void flush(List<PrepareRequest> prepareRequests) { if (CollectionUtils.isEmpty(prepareRequests)) { return; } if (log.isDebugEnabled()) { log.debug("batch sql statements execute, data size: {}", prepareRequests.size()); } final BatchPoints.Builder builder = BatchPoints.builder(); prepareRequests.forEach(e -> { builder.point(((InfluxInsertRequest) e).getPoint()); }); client.write(builder.build()); } }
2301_81045437/zeus-iot
iot-server/server-storage-plugin/server-influxdb-plugin/src/main/java/com/zmops/zeus/iot/server/storage/plugin/jdbc/influxdb/dao/BatchDAO.java
Java
gpl-3.0
2,144
/* * 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 com.zmops.zeus.iot.server.storage.plugin.jdbc.influxdb.dao; import com.google.common.collect.Maps; import com.zmops.zeus.iot.server.client.request.InsertRequest; import com.zmops.zeus.iot.server.core.analysis.manual.history.History; import com.zmops.zeus.iot.server.core.analysis.manual.history.UIntHistory; import com.zmops.zeus.iot.server.core.storage.StorageData; import com.zmops.zeus.iot.server.core.storage.model.Model; import org.influxdb.dto.Point; import java.util.Map; import java.util.concurrent.TimeUnit; /** * InfluxDB Point wrapper. */ public class InfluxInsertRequest implements InsertRequest { private final Point.Builder builder; private final Map<String, Object> fields = Maps.newHashMap(); public <T extends StorageData> InfluxInsertRequest(Model model, T storageData) { String deviceid = ""; Integer itemid = 0; String value = ""; Long time = 0L; if (model.getName().equals("history")) { History history = (History) storageData; deviceid = history.getDeviceId(); itemid = history.getItemid(); value = history.getValue(); time = history.getClock(); fields.put("value", Double.parseDouble(value)); } else { UIntHistory uihistory = (UIntHistory) storageData; deviceid = uihistory.getDeviceId(); itemid = uihistory.getItemid(); value = uihistory.getValue(); time = uihistory.getClock(); fields.put("value", Long.parseLong(value)); } builder = Point.measurement("h_" + itemid) .fields(fields); builder.tag("deviceid", deviceid); builder.tag("itemid", itemid + ""); builder.time(time, TimeUnit.NANOSECONDS); } public InfluxInsertRequest time(long time, TimeUnit unit) { builder.time(time, unit); return this; } public Point getPoint() { return builder.build(); } }
2301_81045437/zeus-iot
iot-server/server-storage-plugin/server-influxdb-plugin/src/main/java/com/zmops/zeus/iot/server/storage/plugin/jdbc/influxdb/dao/InfluxInsertRequest.java
Java
gpl-3.0
2,827
/* * 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 com.zmops.zeus.iot.server.storage.plugin.jdbc.influxdb.dao; import com.zmops.zeus.iot.server.core.storage.IRecordDAO; import com.zmops.zeus.iot.server.core.storage.StorageDAO; import com.zmops.zeus.iot.server.storage.plugin.jdbc.influxdb.InfluxClient; public class InfluxStorageDAO implements StorageDAO { private final InfluxClient influxClient; public InfluxStorageDAO(InfluxClient influxClient) { this.influxClient = influxClient; } @Override public IRecordDAO newRecordDao() { return new RecordDAO(); } }
2301_81045437/zeus-iot
iot-server/server-storage-plugin/server-influxdb-plugin/src/main/java/com/zmops/zeus/iot/server/storage/plugin/jdbc/influxdb/dao/InfluxStorageDAO.java
Java
gpl-3.0
1,370
/* * 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 com.zmops.zeus.iot.server.storage.plugin.jdbc.influxdb.dao; import com.zmops.zeus.iot.server.client.request.InsertRequest; import com.zmops.zeus.iot.server.core.analysis.record.Record; import com.zmops.zeus.iot.server.core.storage.IRecordDAO; import com.zmops.zeus.iot.server.core.storage.model.Model; import com.zmops.zeus.server.datacarrier.common.AtomicRangeInteger; public class RecordDAO implements IRecordDAO { private static final int PADDING_SIZE = 1_000_000; private static final AtomicRangeInteger SUFFIX = new AtomicRangeInteger(0, PADDING_SIZE); public RecordDAO() { } @Override public InsertRequest prepareBatchInsert(Model model, Record record) { final InfluxInsertRequest request = new InfluxInsertRequest(model, record); return request; } }
2301_81045437/zeus-iot
iot-server/server-storage-plugin/server-influxdb-plugin/src/main/java/com/zmops/zeus/iot/server/storage/plugin/jdbc/influxdb/dao/RecordDAO.java
Java
gpl-3.0
1,646
package com.zmops.zeus.iot.server.storage.plugin.none; import com.zmops.zeus.iot.server.core.storage.IBatchDAO; import com.zmops.zeus.iot.server.client.request.InsertRequest; import com.zmops.zeus.iot.server.client.request.PrepareRequest; import java.util.List; /** * @author nantian created at 2021/9/27 21:28 */ public class BatchDaoNoop implements IBatchDAO { @Override public void insert(InsertRequest insertRequest) { } @Override public void flush(List<PrepareRequest> prepareRequests) { } }
2301_81045437/zeus-iot
iot-server/server-storage-plugin/server-none-storage/src/main/java/com/zmops/zeus/iot/server/storage/plugin/none/BatchDaoNoop.java
Java
gpl-3.0
530
package com.zmops.zeus.iot.server.storage.plugin.none; import com.zmops.zeus.iot.server.core.storage.IBatchDAO; import com.zmops.zeus.iot.server.core.storage.StorageDAO; import com.zmops.zeus.iot.server.core.storage.StorageModule; import com.zmops.zeus.server.library.module.*; /** * @author nantian created at 2021/9/27 21:18 * <p> * Proxy 模式下,或者 不使用默认的 TDEngine 时 */ public class NoneStorageProvider extends ModuleProvider { @Override public String name() { return "none"; } @Override public Class<? extends ModuleDefine> module() { return StorageModule.class; } @Override public ModuleConfig createConfigBeanIfAbsent() { return new ModuleConfig() { }; } @Override public void prepare() throws ServiceNotProvidedException, ModuleStartException { this.registerServiceImplementation(IBatchDAO.class, new BatchDaoNoop()); this.registerServiceImplementation(StorageDAO.class, new StorageDAONoop()); } @Override public void start() throws ServiceNotProvidedException, ModuleStartException { } @Override public void notifyAfterCompleted() throws ServiceNotProvidedException, ModuleStartException { } @Override public String[] requiredModules() { return new String[0]; } }
2301_81045437/zeus-iot
iot-server/server-storage-plugin/server-none-storage/src/main/java/com/zmops/zeus/iot/server/storage/plugin/none/NoneStorageProvider.java
Java
gpl-3.0
1,350
package com.zmops.zeus.iot.server.storage.plugin.none; import com.zmops.zeus.iot.server.core.storage.IRecordDAO; import com.zmops.zeus.iot.server.core.storage.StorageDAO; /** * @author nantian created at 2021/9/27 21:29 */ public class StorageDAONoop implements StorageDAO { @Override public IRecordDAO newRecordDao() { return null; } }
2301_81045437/zeus-iot
iot-server/server-storage-plugin/server-none-storage/src/main/java/com/zmops/zeus/iot/server/storage/plugin/none/StorageDAONoop.java
Java
gpl-3.0
362