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
|
|---|---|---|---|---|---|
/*
* 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;
/**
* SQLBuilder
*/
public class SQLBuilder {
private static String LINE_END = System.lineSeparator();
private StringBuilder text;
public SQLBuilder() {
this.text = new StringBuilder();
}
public SQLBuilder(String initLine) {
this();
this.appendLine(initLine);
}
public SQLBuilder append(String fragment) {
text.append(fragment);
return this;
}
public SQLBuilder appendLine(String line) {
text.append(line).append(LINE_END);
return this;
}
public String toStringInNewLine() {
return LINE_END + toString();
}
@Override
public String toString() {
return text.toString();
}
}
|
2301_81045437/zeus-iot
|
iot-server/server-storage-plugin/server-tdengine-plugin/src/main/java/com/zmops/zeus/iot/server/storage/plugin/jdbc/SQLBuilder.java
|
Java
|
gpl-3.0
| 1,575
|
/*
* 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;
import com.zmops.zeus.iot.server.client.request.InsertRequest;
import lombok.Getter;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.SQLException;
import java.util.List;
/**
* A SQL executor.
*/
public class SQLExecutor implements InsertRequest {
private static final Logger LOGGER = LoggerFactory.getLogger(SQLExecutor.class);
@Getter
private final String sql;
private final List<Object> param;
public SQLExecutor(String sql, List<Object> param) {
this.sql = sql;
this.param = param;
}
public void invoke(Connection connection) throws SQLException {
PreparedStatement preparedStatement = connection.prepareStatement(sql);
for (int i = 0; i < param.size(); i++) {
preparedStatement.setObject(i + 1, param.get(i));
}
if (LOGGER.isDebugEnabled()) {
LOGGER.debug("execute sql in batch: {}, parameters: {}", sql, param);
}
preparedStatement.execute();
}
}
|
2301_81045437/zeus-iot
|
iot-server/server-storage-plugin/server-tdengine-plugin/src/main/java/com/zmops/zeus/iot/server/storage/plugin/jdbc/SQLExecutor.java
|
Java
|
gpl-3.0
| 1,932
|
package com.zmops.zeus.iot.server.storage.plugin.jdbc.tdengine;
import com.zmops.zeus.iot.server.core.UnexpectedException;
import com.zmops.zeus.iot.server.core.storage.IBatchDAO;
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.client.request.InsertRequest;
import com.zmops.zeus.iot.server.client.request.PrepareRequest;
import com.zmops.zeus.iot.server.storage.plugin.jdbc.SQLBuilder;
import com.zmops.zeus.iot.server.storage.plugin.jdbc.SQLExecutor;
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.util.CollectionUtils;
import lombok.extern.slf4j.Slf4j;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.SQLException;
import java.util.List;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
/**
* @author nantian created at 2021/9/4 0:31
*/
@Slf4j
public class TDEngineBatchDAO implements IBatchDAO {
private final JDBCHikariCPClient tdengineClient;
private final DataCarrier<PrepareRequest> dataCarrier;
private final ExecutorService executor = Executors.newFixedThreadPool(10);
public TDEngineBatchDAO(JDBCHikariCPClient client) {
this.tdengineClient = client;
String name = "TDENGINE_ASYNCHRONOUS_BATCH_PERSISTENT";
BulkConsumePool.Creator creator = new BulkConsumePool.Creator(name, 1, 20);
try {
ConsumerPoolFactory.INSTANCE.createIfAbsent(name, creator);
} catch (Exception e) {
throw new UnexpectedException(e.getMessage(), e);
}
this.dataCarrier = new DataCarrier<>(4, 2500);
this.dataCarrier.consume(ConsumerPoolFactory.INSTANCE.get(name), new TDEngineBatchConsumer(this));
}
@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());
}
SQLBuilder execSql = new SQLBuilder(" INSERT INTO ");
for (PrepareRequest prepareRequest : prepareRequests) {
SQLExecutor sqlExecutor = (SQLExecutor) prepareRequest;
execSql.appendLine(sqlExecutor.getSql());
}
execSql.append(";");
executor.submit(() -> {
PreparedStatement preparedStatement;
Connection connection = null;
try {
connection = tdengineClient.getConnection();
preparedStatement = connection.prepareStatement(execSql.toString());
preparedStatement.execute();
} catch (SQLException | JDBCClientException e) {
e.printStackTrace();
} finally {
try {
if (connection != null) {
connection.close();
}
} catch (SQLException e) {
e.printStackTrace();
}
}
});
}
@Override
public void insert(InsertRequest insertRequest) {
this.dataCarrier.produce(insertRequest);
}
private static class TDEngineBatchConsumer implements IConsumer<PrepareRequest> {
private final TDEngineBatchDAO tdengineBatchDAO;
private TDEngineBatchConsumer(TDEngineBatchDAO h2BatchDAO) {
this.tdengineBatchDAO = h2BatchDAO;
}
@Override
public void init() {
}
@Override
public void consume(List<PrepareRequest> prepareRequests) {
tdengineBatchDAO.flush(prepareRequests);
}
@Override
public void onError(List<PrepareRequest> prepareRequests, Throwable t) {
log.error(t.getMessage(), t);
}
@Override
public void onExit() {
}
}
}
|
2301_81045437/zeus-iot
|
iot-server/server-storage-plugin/server-tdengine-plugin/src/main/java/com/zmops/zeus/iot/server/storage/plugin/jdbc/tdengine/TDEngineBatchDAO.java
|
Java
|
gpl-3.0
| 4,181
|
package com.zmops.zeus.iot.server.storage.plugin.jdbc.tdengine;
import com.zmops.zeus.iot.server.core.storage.StorageException;
import com.zmops.zeus.iot.server.client.Client;
import com.zmops.zeus.iot.server.client.jdbc.JDBCClientException;
import com.zmops.zeus.iot.server.client.jdbc.hikaricp.JDBCHikariCPClient;
import com.zmops.zeus.server.library.module.ModuleManager;
import java.sql.Connection;
import java.sql.SQLException;
/**
* @author nantian created at 2021/9/4 1:16
*/
public class TDEngineDatabaseInstaller {
protected final Client client;
private final ModuleManager moduleManager;
private final TDEngineStorageConfig config;
private static final String CREATE_ZEUS_STABLE_HISTORY = "create stable if not exists history(clock TIMESTAMP, value DOUBLE) tags (deviceid BINARY(64), itemid BINARY(20))";
private static final String CREATE_ZEUS_STABLE_HISTORY_UINT = "create stable if not exists history_uint(clock TIMESTAMP, value BIGINT) tags (deviceid BINARY(64), itemid BINARY(20))";
private static final String CREATE_ZEUS_STABLE_HISTORY_TEXT = "create stable if not exists history_text(clock TIMESTAMP, value NCHAR(2048)) tags (deviceid BINARY(64), itemid BINARY(20))";
private static final String CREATE_ZEUS_STABLE_HISTORY_STR = "create stable if not exists history_str(clock TIMESTAMP, value NCHAR(255)) tags (deviceid BINARY(64), itemid BINARY(20))";
private static final String CREATE_ZEUS_STABLE_TRENDS = "create stable if not exists trends(clock TIMESTAMP, value_min DOUBLE, value_avg DOUBLE, value_max DOUBLE) tags (hostid BINARY(64), itemid BINARY(20))";
private static final String CREATE_ZEUS_STABLE_TRENDS_UINT = "create stable if not exists trends_uint(clock TIMESTAMP, value_min BIGINT, value_avg BIGINT, value_max BIGINT) tags (hostid BINARY(64), itemid BINARY(20))";
public TDEngineDatabaseInstaller(Client client, ModuleManager moduleManager, TDEngineStorageConfig config) {
this.config = config;
this.client = client;
this.moduleManager = moduleManager;
}
protected void createDatabase() throws StorageException {
JDBCHikariCPClient jdbcHikariCPClient = (JDBCHikariCPClient) client;
try (Connection connection = jdbcHikariCPClient.getConnection()) {
jdbcHikariCPClient.execute(connection, CREATE_ZEUS_STABLE_HISTORY);
jdbcHikariCPClient.execute(connection, CREATE_ZEUS_STABLE_HISTORY_UINT);
jdbcHikariCPClient.execute(connection, CREATE_ZEUS_STABLE_HISTORY_TEXT);
jdbcHikariCPClient.execute(connection, CREATE_ZEUS_STABLE_HISTORY_STR);
jdbcHikariCPClient.execute(connection, CREATE_ZEUS_STABLE_TRENDS);
jdbcHikariCPClient.execute(connection, CREATE_ZEUS_STABLE_TRENDS_UINT);
} catch (JDBCClientException | SQLException e) {
throw new StorageException(e.getMessage(), e);
}
}
}
|
2301_81045437/zeus-iot
|
iot-server/server-storage-plugin/server-tdengine-plugin/src/main/java/com/zmops/zeus/iot/server/storage/plugin/jdbc/tdengine/TDEngineDatabaseInstaller.java
|
Java
|
gpl-3.0
| 2,918
|
package com.zmops.zeus.iot.server.storage.plugin.jdbc.tdengine;
import com.zmops.zeus.server.library.module.ModuleConfig;
import lombok.Getter;
import lombok.Setter;
/**
* @author nantian created at 2021/9/3 23:40
*/
@Setter
@Getter
public class TDEngineStorageConfig extends ModuleConfig {
private final String driver = "com.taosdata.jdbc.TSDBDriver";
private String url = "";
private String user = "";
private String password = "";
private int dataKeep = 365; //数据保留天数
private int oneFileDays = 10; // 每多少天一个数据文件
private int memoryBlocks = 6; // 内存块数
private int dataUpdate = 1; // 是否允许更新数据,1 允许
}
|
2301_81045437/zeus-iot
|
iot-server/server-storage-plugin/server-tdengine-plugin/src/main/java/com/zmops/zeus/iot/server/storage/plugin/jdbc/tdengine/TDEngineStorageConfig.java
|
Java
|
gpl-3.0
| 701
|
package com.zmops.zeus.iot.server.storage.plugin.jdbc.tdengine;
import com.zmops.zeus.iot.server.client.jdbc.hikaricp.JDBCHikariCPClient;
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.StorageException;
import com.zmops.zeus.iot.server.core.storage.StorageModule;
import com.zmops.zeus.iot.server.storage.plugin.jdbc.tdengine.dao.TDEngineStorageDAO;
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 java.util.Properties;
/**
* @author nantian created at 2021/9/3 23:39
*/
public class TDEngineStorageProvider extends ModuleProvider {
private final TDEngineStorageConfig config;
private JDBCHikariCPClient client;
public TDEngineStorageProvider() {
this.config = new TDEngineStorageConfig();
}
@Override
public String name() {
return "tdengine";
}
@Override
public Class<? extends ModuleDefine> module() {
return StorageModule.class;
}
@Override
public ModuleConfig createConfigBeanIfAbsent() {
return config;
}
@Override
public void prepare() throws ServiceNotProvidedException, ModuleStartException {
Properties settings = new Properties();
settings.setProperty("jdbcUrl", config.getUrl());
settings.setProperty("dataSource.user", config.getUser());
settings.setProperty("dataSource.password", config.getPassword());
client = new JDBCHikariCPClient(settings);
this.registerServiceImplementation(IBatchDAO.class, new TDEngineBatchDAO(client));
this.registerServiceImplementation(StorageDAO.class, new TDEngineStorageDAO(getManager(), client));
}
@Override
public void start() throws ServiceNotProvidedException, ModuleStartException {
MetricsCreator metricCreator = getManager().find(TelemetryModule.NAME).provider().getService(MetricsCreator.class);
HealthCheckMetrics healthChecker = metricCreator.createHealthCheckerGauge("storage_tdengine", MetricsTag.EMPTY_KEY, MetricsTag.EMPTY_VALUE);
client.registerChecker(healthChecker);
client.connect();
TDEngineDatabaseInstaller installer = new TDEngineDatabaseInstaller(client, getManager(), config);
try {
installer.createDatabase();
} catch (StorageException e) {
e.printStackTrace();
}
// getManager().find(CoreModule.NAME).provider().getService(ModelCreator.class).addModelListener(installer);
}
@Override
public void notifyAfterCompleted() throws ServiceNotProvidedException, ModuleStartException {
}
@Override
public String[] requiredModules() {
return new String[]{CoreModule.NAME};
}
}
|
2301_81045437/zeus-iot
|
iot-server/server-storage-plugin/server-tdengine-plugin/src/main/java/com/zmops/zeus/iot/server/storage/plugin/jdbc/tdengine/TDEngineStorageProvider.java
|
Java
|
gpl-3.0
| 3,073
|
package com.zmops.zeus.iot.server.storage.plugin.jdbc.tdengine.dao;
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.iot.server.client.jdbc.hikaricp.JDBCHikariCPClient;
import com.zmops.zeus.iot.server.client.request.InsertRequest;
import java.io.IOException;
/**
* @author nantian created at 2021/9/5 0:27
*/
public class TDEngineRecordDAO extends TDEngineSqlExecutor implements IRecordDAO {
private final JDBCHikariCPClient jdbcClient;
public TDEngineRecordDAO(JDBCHikariCPClient jdbcClient) {
this.jdbcClient = jdbcClient;
}
@Override
public InsertRequest prepareBatchInsert(Model model, Record record) throws IOException {
return getInsertExecutor(model.getName(), record);
}
}
|
2301_81045437/zeus-iot
|
iot-server/server-storage-plugin/server-tdengine-plugin/src/main/java/com/zmops/zeus/iot/server/storage/plugin/jdbc/tdengine/dao/TDEngineRecordDAO.java
|
Java
|
gpl-3.0
| 882
|
package com.zmops.zeus.iot.server.storage.plugin.jdbc.tdengine.dao;
import com.zmops.zeus.iot.server.core.analysis.manual.history.History;
import com.zmops.zeus.iot.server.core.analysis.manual.history.StrHistory;
import com.zmops.zeus.iot.server.core.analysis.manual.history.TextHistory;
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.storage.plugin.jdbc.SQLBuilder;
import com.zmops.zeus.iot.server.storage.plugin.jdbc.SQLExecutor;
import lombok.extern.slf4j.Slf4j;
import java.util.ArrayList;
import java.util.List;
/**
* @author nantian created at 2021/9/5 0:29
*/
@Slf4j
public class TDEngineSqlExecutor {
protected <T extends StorageData> SQLExecutor getInsertExecutor(String modelName, T metrics) {
SQLBuilder sqlBuilder = new SQLBuilder();
if (modelName.equals("history")) {
History history = (History) metrics;
sqlBuilder.append("h_").append(metrics.itemid() + " USING ").append("history (deviceid, itemid) TAGS")
.append("('").append(history.getDeviceId()).append("'")
.append(",").append(history.getItemid() + " )")
.append(" VALUES (")
.append(history.getClock() + "").append(",").append(history.getValue()).append(")");
} else if (modelName.equals("history_uint")) {
UIntHistory uihistory = (UIntHistory) metrics;
sqlBuilder.append("huint_").append(metrics.itemid() + " USING ").append("history_uint (deviceid, itemid) TAGS")
.append(" ('").append(uihistory.getDeviceId()).append("'")
.append(",").append(uihistory.getItemid() + " )")
.append(" VALUES (")
.append(uihistory.getClock() + "").append(",").append(uihistory.getValue()).append(")");
} else if (modelName.equals("history_text")) {
TextHistory textHistory = (TextHistory) metrics;
String value = textHistory.getValue().replaceAll(",", "\\,");
sqlBuilder.append("htxt_").append(metrics.itemid() + " USING ").append("history_text (deviceid, itemid) TAGS")
.append(" ('").append(textHistory.getDeviceId()).append("'")
.append(",").append(textHistory.getItemid() + " )")
.append(" VALUES (")
.append(textHistory.getClock() + "").append(",'").append(value).append("')");
} else if (modelName.equals("history_str")) {
StrHistory strHistory = (StrHistory) metrics;
String value = strHistory.getValue().replaceAll(",", "\\,");
sqlBuilder.append("hstr_").append(metrics.itemid() + " USING ").append("history_str (deviceid, itemid) TAGS")
.append(" ('").append(strHistory.getDeviceId()).append("'")
.append(",").append(strHistory.getItemid() + " )")
.append(" VALUES (")
.append(strHistory.getClock() + "").append(",'").append(value).append("')");
}
List<Object> param = new ArrayList<>();
return new SQLExecutor(sqlBuilder.toString(), param);
}
}
|
2301_81045437/zeus-iot
|
iot-server/server-storage-plugin/server-tdengine-plugin/src/main/java/com/zmops/zeus/iot/server/storage/plugin/jdbc/tdengine/dao/TDEngineSqlExecutor.java
|
Java
|
gpl-3.0
| 3,259
|
package com.zmops.zeus.iot.server.storage.plugin.jdbc.tdengine.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.client.jdbc.hikaricp.JDBCHikariCPClient;
import com.zmops.zeus.server.library.module.ModuleManager;
import lombok.RequiredArgsConstructor;
/**
* @author nantian created at 2021/9/6 16:33
*/
@RequiredArgsConstructor
public class TDEngineStorageDAO implements StorageDAO {
private final ModuleManager manager;
private final JDBCHikariCPClient client;
@Override
public IRecordDAO newRecordDao() {
return new TDEngineRecordDAO(client);
}
}
|
2301_81045437/zeus-iot
|
iot-server/server-storage-plugin/server-tdengine-plugin/src/main/java/com/zmops/zeus/iot/server/storage/plugin/jdbc/tdengine/dao/TDEngineStorageDAO.java
|
Java
|
gpl-3.0
| 688
|
/*
* 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.telemetry;
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.ModuleDefine;
/**
* Telemetry module definition
*/
public class TelemetryModule extends ModuleDefine {
public static final String NAME = "telemetry";
public TelemetryModule() {
super(NAME);
}
@Override
public Class[] services() {
return new Class[]{
MetricsCreator.class,
MetricsCollector.class
};
}
}
|
2301_81045437/zeus-iot
|
iot-server/server-telemetry/telemetry-api/src/main/java/com/zmops/zeus/iot/server/telemetry/TelemetryModule.java
|
Java
|
gpl-3.0
| 1,411
|
/*
* 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.telemetry.api;
/**
* A counter is a cumulative metrics that represents a single monotonically increasing counter whose value can only
* increase or be reset to zero on restart. For example, you can use a counter to represent the number of requests
* served, tasks completed, or errors.z
*/
public interface CounterMetrics {
/**
* Increase 1 to counter
*/
void inc();
/**
* Increase the given value to the counter
*/
void inc(double value);
}
|
2301_81045437/zeus-iot
|
iot-server/server-telemetry/telemetry-api/src/main/java/com/zmops/zeus/iot/server/telemetry/api/CounterMetrics.java
|
Java
|
gpl-3.0
| 1,324
|
/*
* 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.telemetry.api;
/**
* A gauge is a metrics that represents a single numerical value that can arbitrarily go up and down.
*/
public interface GaugeMetrics {
/**
* Increase 1 to gauge
*/
void inc();
/**
* Increase the given value to the gauge
*/
void inc(double value);
/**
* Decrease 1 to gauge
*/
void dec();
/**
* Decrease the given value to the gauge
*/
void dec(double value);
/**
* Set the given value to the gauge
*/
void setValue(double value);
/**
* Get the current value of the gauge
*/
double getValue();
}
|
2301_81045437/zeus-iot
|
iot-server/server-telemetry/telemetry-api/src/main/java/com/zmops/zeus/iot/server/telemetry/api/GaugeMetrics.java
|
Java
|
gpl-3.0
| 1,471
|
/*
* 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.telemetry.api;
import com.zmops.zeus.server.library.util.HealthChecker;
import lombok.extern.slf4j.Slf4j;
/**
* HealthCheckMetrics intends to record health status.
*/
@Slf4j
public class HealthCheckMetrics implements HealthChecker {
private final GaugeMetrics metrics;
public HealthCheckMetrics(GaugeMetrics metrics) {
this.metrics = metrics;
// The initial status is unhealthy with -1 code.
metrics.setValue(-1);
}
@Override
public void health() {
metrics.setValue(0);
}
@Override
public void unHealth(Throwable t) {
log.error("Health check fails", t);
metrics.setValue(1);
}
@Override
public void unHealth(String reason) {
log.warn("Health check fails. reason: {}", reason);
metrics.setValue(1);
}
}
|
2301_81045437/zeus-iot
|
iot-server/server-telemetry/telemetry-api/src/main/java/com/zmops/zeus/iot/server/telemetry/api/HealthCheckMetrics.java
|
Java
|
gpl-3.0
| 1,663
|
/*
* 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.telemetry.api;
import java.io.Closeable;
/**
* A histogram samples observations (usually things like request durations or response sizes) and counts them in
* configurable buckets. It also provides a sum of all observed values.
*/
public abstract class HistogramMetrics {
public Timer createTimer() {
return new Timer(this);
}
/**
* Observe an execution, get a duration in second.
*
* @param value duration in second.
*/
public abstract void observe(double value);
public class Timer implements Closeable {
private final HistogramMetrics metrics;
private final long startNanos;
private double duration;
public Timer(HistogramMetrics metrics) {
this.metrics = metrics;
startNanos = System.nanoTime();
}
public void finish() {
long endNanos = System.nanoTime();
duration = (double) (endNanos - startNanos) / 1.0E9D;
metrics.observe(duration);
}
@Override
public void close() {
finish();
}
}
}
|
2301_81045437/zeus-iot
|
iot-server/server-telemetry/telemetry-api/src/main/java/com/zmops/zeus/iot/server/telemetry/api/HistogramMetrics.java
|
Java
|
gpl-3.0
| 1,945
|
/*
* 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.telemetry.api;
import lombok.AllArgsConstructor;
import lombok.EqualsAndHashCode;
import lombok.ToString;
import java.util.List;
/**
* MetricFamily define a metric and all its samples.
*/
@AllArgsConstructor
@EqualsAndHashCode
@ToString
public class MetricFamily {
public final String name;
public final Type type;
public final String help;
public final List<Sample> samples;
public enum Type {
COUNTER, GAUGE, SUMMARY, HISTOGRAM, UNTYPED,
}
/**
* A single Sample, with a unique name and set of labels.
*/
@AllArgsConstructor
@EqualsAndHashCode
@ToString
public static class Sample {
public final String name;
public final List<String> labelNames;
public final List<String> labelValues; // Must have same length as labelNames.
public final double value;
public final Long timestampMs; // It's an epoch format with milliseconds value included (this field is subject to change).
}
}
|
2301_81045437/zeus-iot
|
iot-server/server-telemetry/telemetry-api/src/main/java/com/zmops/zeus/iot/server/telemetry/api/MetricFamily.java
|
Java
|
gpl-3.0
| 1,838
|
/*
* 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.telemetry.api;
import com.zmops.zeus.server.library.module.Service;
/**
* Collect all metrics from telemetry.
*/
public interface MetricsCollector extends Service {
/**
* Get all of metrics.
*
* @return all metrics
*/
Iterable<MetricFamily> collect();
}
|
2301_81045437/zeus-iot
|
iot-server/server-telemetry/telemetry-api/src/main/java/com/zmops/zeus/iot/server/telemetry/api/MetricsCollector.java
|
Java
|
gpl-3.0
| 1,128
|
/*
* 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.telemetry.api;
import com.google.common.base.Preconditions;
import com.google.common.base.Strings;
import com.zmops.zeus.server.library.module.Service;
/**
* Open API to telemetry module, allow to create metrics instance with different type. Types inherits from prometheus
* project, and plan to move to openmetrics APIs after it is ready.
*/
public interface MetricsCreator extends Service {
String HEALTH_METRIC_PREFIX = "health_check_";
/**
* Create a counter type metrics instance.
*/
CounterMetrics createCounter(String name, String tips, MetricsTag.Keys tagKeys, MetricsTag.Values tagValues);
/**
* Create a gauge type metrics instance.
*/
GaugeMetrics createGauge(String name, String tips, MetricsTag.Keys tagKeys, MetricsTag.Values tagValues);
/**
* Create a Histogram type metrics instance.
*
* @param buckets Time bucket for duration.
*/
HistogramMetrics createHistogramMetric(String name, String tips, MetricsTag.Keys tagKeys,
MetricsTag.Values tagValues, double... buckets);
/**
* Create a Health Check gauge.
*/
default HealthCheckMetrics createHealthCheckerGauge(String name, MetricsTag.Keys tagKeys, MetricsTag.Values tagValues) {
Preconditions.checkArgument(!Strings.isNullOrEmpty(name), "Require non-null or empty metric name");
return new HealthCheckMetrics(createGauge(Strings.lenientFormat("%s%s", HEALTH_METRIC_PREFIX, name),
Strings.lenientFormat("%s health check", name),
tagKeys, tagValues));
}
/**
* Find out whether it's a health check metric.
*/
default boolean isHealthCheckerMetrics(String name) {
Preconditions.checkArgument(!Strings.isNullOrEmpty(name), "Require non-null or empty metric name");
return name.startsWith(HEALTH_METRIC_PREFIX);
}
/**
* Extract the raw module name
*/
default String extractModuleName(String metricName) {
Preconditions.checkArgument(!Strings.isNullOrEmpty(metricName), "Require non-null or empty metric name");
return metricName.replace(HEALTH_METRIC_PREFIX, "");
}
}
|
2301_81045437/zeus-iot
|
iot-server/server-telemetry/telemetry-api/src/main/java/com/zmops/zeus/iot/server/telemetry/api/MetricsCreator.java
|
Java
|
gpl-3.0
| 3,039
|
/*
* 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.telemetry.api;
/**
* Tag for the target metrics.
* <p>
* The tag values should be set in putting value phase.
*/
public class MetricsTag {
public static final Keys EMPTY_KEY = new Keys();
public static final Values EMPTY_VALUE = new Values();
public static class Keys {
private String[] keys;
public Keys() {
this.keys = new String[0];
}
public Keys(String... keys) {
this.keys = keys;
}
public String[] getKeys() {
return keys;
}
}
public static class Values {
private String[] values;
public Values(Keys keys) {
this.values = new String[0];
}
public Values(String... keys) {
this.values = keys;
}
public String[] getValues() {
return values;
}
}
}
|
2301_81045437/zeus-iot
|
iot-server/server-telemetry/telemetry-api/src/main/java/com/zmops/zeus/iot/server/telemetry/api/MetricsTag.java
|
Java
|
gpl-3.0
| 1,711
|
/*
* 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.telemetry.api;
/**
* The telemetry context which the metrics instances may need to know.
*/
public enum TelemetryRelatedContext {
INSTANCE;
private volatile String id = null;
TelemetryRelatedContext() {
}
/**
* Set a global ID to represent the current iot instance
*/
public void setId(String id) {
this.id = id;
}
/**
* Get the iot instance ID, if be set before.
*
* @return id or null.
*/
public String getId() {
return id;
}
}
|
2301_81045437/zeus-iot
|
iot-server/server-telemetry/telemetry-api/src/main/java/com/zmops/zeus/iot/server/telemetry/api/TelemetryRelatedContext.java
|
Java
|
gpl-3.0
| 1,363
|
/*
* 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.telemetry.none;
import com.zmops.zeus.iot.server.telemetry.api.MetricFamily;
import com.zmops.zeus.iot.server.telemetry.api.MetricsCollector;
import java.util.Collections;
/**
* No-op MetricFamily Collector.
*/
public class MetricsCollectorNoop implements MetricsCollector {
@Override
public Iterable<MetricFamily> collect() {
return Collections.emptyList();
}
}
|
2301_81045437/zeus-iot
|
iot-server/server-telemetry/telemetry-api/src/main/java/com/zmops/zeus/iot/server/telemetry/none/MetricsCollectorNoop.java
|
Java
|
gpl-3.0
| 1,229
|
/*
* 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.telemetry.none;
import com.zmops.zeus.iot.server.telemetry.api.*;
/**
* A no-op metrics create, just create nut shell metrics instance.
*/
public class MetricsCreatorNoop implements MetricsCreator {
@Override
public CounterMetrics createCounter(String name, String tips, MetricsTag.Keys tagKeys,
MetricsTag.Values tagValues) {
return new CounterMetrics() {
@Override
public void inc() {
}
@Override
public void inc(double value) {
}
};
}
@Override
public GaugeMetrics createGauge(String name, String tips, MetricsTag.Keys tagKeys, MetricsTag.Values tagValues) {
return new GaugeMetrics() {
@Override
public void inc() {
}
@Override
public void inc(double value) {
}
@Override
public void dec() {
}
@Override
public void dec(double value) {
}
@Override
public void setValue(double value) {
}
@Override
public double getValue() {
return 0;
}
};
}
@Override
public HistogramMetrics createHistogramMetric(String name, String tips, MetricsTag.Keys tagKeys,
MetricsTag.Values tagValues, double... buckets) {
return new HistogramMetrics() {
@Override
public void observe(double value) {
}
};
}
}
|
2301_81045437/zeus-iot
|
iot-server/server-telemetry/telemetry-api/src/main/java/com/zmops/zeus/iot/server/telemetry/none/MetricsCreatorNoop.java
|
Java
|
gpl-3.0
| 2,464
|
/*
* 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.telemetry.none;
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.*;
/**
* A nutshell telemetry implementor.
*/
public class NoneTelemetryProvider extends ModuleProvider {
@Override
public String name() {
return "none";
}
@Override
public Class<? extends ModuleDefine> module() {
return TelemetryModule.class;
}
@Override
public ModuleConfig createConfigBeanIfAbsent() {
return new ModuleConfig() {
};
}
@Override
public void prepare() throws ServiceNotProvidedException, ModuleStartException {
this.registerServiceImplementation(MetricsCreator.class, new MetricsCreatorNoop());
this.registerServiceImplementation(MetricsCollector.class, new MetricsCollectorNoop());
}
@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-telemetry/telemetry-api/src/main/java/com/zmops/zeus/iot/server/telemetry/none/NoneTelemetryProvider.java
|
Java
|
gpl-3.0
| 2,113
|
/*
* 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.telemetry.prometheus;
import com.zmops.zeus.iot.server.telemetry.api.MetricsTag;
import com.zmops.zeus.iot.server.telemetry.api.TelemetryRelatedContext;
import io.prometheus.client.SimpleCollector;
import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.locks.ReentrantLock;
/**
* BaseMetrics parent class represents the metrics
*/
public abstract class BaseMetrics<T extends SimpleCollector, C> {
private static Map<String, Object> ALL_METRICS = new HashMap<>();
private volatile C metricsInstance;
protected final String name;
protected final String tips;
protected final MetricsTag.Keys labels;
protected final MetricsTag.Values values;
private ReentrantLock lock = new ReentrantLock();
public BaseMetrics(String name, String tips, MetricsTag.Keys labels, MetricsTag.Values values) {
this.name = name;
this.tips = tips;
this.labels = labels;
this.values = values;
}
protected boolean isIDReady() {
return TelemetryRelatedContext.INSTANCE.getId() != null;
}
/**
* Create real prometheus metrics with SkyWalking native labels, and provide to all metrics implementation. Metrics
* name should be unique.
*
* @return metric reference if the service instance id has been initialized. Or NULL.
*/
protected C getMetric() {
if (metricsInstance == null) {
if (isIDReady()) {
lock.lock();
try {
if (metricsInstance == null) {
String[] labelNames = new String[labels.getKeys().length + 1];
labelNames[0] = "sw_backend_instance";
for (int i = 0; i < labels.getKeys().length; i++) {
labelNames[i + 1] = labels.getKeys()[i];
}
String[] labelValues = new String[values.getValues().length + 1];
labelValues[0] = TelemetryRelatedContext.INSTANCE.getId();
for (int i = 0; i < values.getValues().length; i++) {
labelValues[i + 1] = values.getValues()[i];
}
if (!ALL_METRICS.containsKey(name)) {
synchronized (ALL_METRICS) {
if (!ALL_METRICS.containsKey(name)) {
ALL_METRICS.put(name, create(labelNames));
}
}
}
T metrics = (T) ALL_METRICS.get(name);
metricsInstance = (C) metrics.labels(labelValues);
}
} finally {
lock.unlock();
}
}
}
return metricsInstance;
}
protected abstract T create(String[] labelNames);
}
|
2301_81045437/zeus-iot
|
iot-server/server-telemetry/telemetry-prometheus/src/main/java/com/zmops/zeus/iot/server/telemetry/prometheus/BaseMetrics.java
|
Java
|
gpl-3.0
| 3,771
|
/*
* 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.telemetry.prometheus;
import com.zmops.zeus.server.library.module.ModuleConfig;
import lombok.Getter;
import lombok.Setter;
/**
* The Prometheus telemetry implementor settings.
*/
@Setter
@Getter
public class PrometheusConfig extends ModuleConfig {
private String host = "0.0.0.0";
private int port = 1234;
private boolean sslEnabled = false;
private String sslKeyPath;
private String sslCertChainPath;
}
|
2301_81045437/zeus-iot
|
iot-server/server-telemetry/telemetry-prometheus/src/main/java/com/zmops/zeus/iot/server/telemetry/prometheus/PrometheusConfig.java
|
Java
|
gpl-3.0
| 1,269
|
/*
* 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.telemetry.prometheus;
import com.zmops.zeus.iot.server.telemetry.api.CounterMetrics;
import com.zmops.zeus.iot.server.telemetry.api.MetricsTag;
import io.prometheus.client.Counter;
/**
* Counter metrics in Prometheus implementor.
*/
public class PrometheusCounterMetrics extends BaseMetrics<Counter, Counter.Child> implements CounterMetrics {
public PrometheusCounterMetrics(String name, String tips, MetricsTag.Keys labels, MetricsTag.Values values) {
super(name, tips, labels, values);
}
@Override
public void inc() {
Counter.Child metrics = this.getMetric();
if (metrics != null) {
metrics.inc();
}
}
@Override
public void inc(double value) {
Counter.Child metrics = this.getMetric();
if (metrics != null) {
metrics.inc(value);
}
}
@Override
protected Counter create(String[] labelNames) {
return Counter.build().name(name).help(tips).labelNames(labelNames).register();
}
}
|
2301_81045437/zeus-iot
|
iot-server/server-telemetry/telemetry-prometheus/src/main/java/com/zmops/zeus/iot/server/telemetry/prometheus/PrometheusCounterMetrics.java
|
Java
|
gpl-3.0
| 1,857
|
/*
* 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.telemetry.prometheus;
import com.zmops.zeus.iot.server.telemetry.api.GaugeMetrics;
import com.zmops.zeus.iot.server.telemetry.api.MetricsTag;
import io.prometheus.client.Gauge;
import java.util.Optional;
/**
* Gauge metrics in Prometheus implementor.
*/
public class PrometheusGaugeMetrics extends BaseMetrics<Gauge, Gauge.Child> implements GaugeMetrics {
public PrometheusGaugeMetrics(String name, String tips, MetricsTag.Keys labels, MetricsTag.Values values) {
super(name, tips, labels, values);
}
@Override
public void inc() {
Gauge.Child metrics = this.getMetric();
if (metrics != null) {
metrics.inc();
}
}
@Override
public void inc(double value) {
Gauge.Child metrics = this.getMetric();
if (metrics != null) {
metrics.inc(value);
}
}
@Override
public void dec() {
Gauge.Child metrics = this.getMetric();
if (metrics != null) {
metrics.dec();
}
}
@Override
public void dec(double value) {
Gauge.Child metrics = this.getMetric();
if (metrics != null) {
metrics.dec(value);
}
}
@Override
public void setValue(double value) {
Gauge.Child metrics = this.getMetric();
if (metrics != null) {
metrics.set(value);
}
}
@Override
public double getValue() {
return Optional.ofNullable(this.getMetric()).orElse(new Gauge.Child()).get();
}
@Override
protected Gauge create(String[] labelNames) {
return Gauge.build().name(name).help(tips).labelNames(labelNames).register();
}
}
|
2301_81045437/zeus-iot
|
iot-server/server-telemetry/telemetry-prometheus/src/main/java/com/zmops/zeus/iot/server/telemetry/prometheus/PrometheusGaugeMetrics.java
|
Java
|
gpl-3.0
| 2,520
|
/*
* 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.telemetry.prometheus;
import com.zmops.zeus.iot.server.telemetry.api.HistogramMetrics;
import com.zmops.zeus.iot.server.telemetry.api.MetricsTag;
import io.prometheus.client.Histogram;
/**
* HistogramMetrics metrics in Prometheus implementor.
*/
public class PrometheusHistogramMetrics extends HistogramMetrics {
private InnerMetricObject inner;
private final double[] buckets;
public PrometheusHistogramMetrics(String name, String tips, MetricsTag.Keys labels, MetricsTag.Values values,
double... buckets) {
inner = new InnerMetricObject(name, tips, labels, values);
this.buckets = buckets;
}
@Override
public void observe(double value) {
Histogram.Child metrics = inner.getMetric();
if (metrics != null) {
metrics.observe(value);
}
}
class InnerMetricObject extends BaseMetrics<Histogram, Histogram.Child> {
public InnerMetricObject(String name, String tips, MetricsTag.Keys labels, MetricsTag.Values values) {
super(name, tips, labels, values);
}
@Override
protected Histogram create(String[] labelNames) {
Histogram.Builder builder = Histogram.build().name(name).help(tips);
if (builder != null && buckets.length > 0) {
builder = builder.buckets(buckets);
}
return builder.labelNames(labelNames).register();
}
}
}
|
2301_81045437/zeus-iot
|
iot-server/server-telemetry/telemetry-prometheus/src/main/java/com/zmops/zeus/iot/server/telemetry/prometheus/PrometheusHistogramMetrics.java
|
Java
|
gpl-3.0
| 2,308
|
/*
* 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.telemetry.prometheus;
import com.zmops.zeus.iot.server.telemetry.api.MetricFamily;
import com.zmops.zeus.iot.server.telemetry.api.MetricsCollector;
import io.prometheus.client.Collector;
import io.prometheus.client.CollectorRegistry;
import java.util.ArrayList;
import java.util.Enumeration;
import java.util.LinkedList;
import java.util.List;
public class PrometheusMetricsCollector implements MetricsCollector {
@Override
public Iterable<MetricFamily> collect() {
Enumeration<Collector.MetricFamilySamples> mfs = CollectorRegistry.defaultRegistry.metricFamilySamples();
List<MetricFamily> result = new LinkedList<>();
while (mfs.hasMoreElements()) {
Collector.MetricFamilySamples metricFamilySamples = mfs.nextElement();
List<MetricFamily.Sample> samples = new ArrayList<>(metricFamilySamples.samples.size());
MetricFamily m = new MetricFamily(metricFamilySamples.name, MetricFamily.Type.valueOf(metricFamilySamples.type
.name()), metricFamilySamples.help, samples);
result.add(m);
for (Collector.MetricFamilySamples.Sample sample : metricFamilySamples.samples) {
samples.add(new MetricFamily.Sample(sample.name, sample.labelNames, sample.labelValues, sample.value, sample.timestampMs));
}
}
return result;
}
}
|
2301_81045437/zeus-iot
|
iot-server/server-telemetry/telemetry-prometheus/src/main/java/com/zmops/zeus/iot/server/telemetry/prometheus/PrometheusMetricsCollector.java
|
Java
|
gpl-3.0
| 2,216
|
/*
* 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.telemetry.prometheus;
import com.zmops.zeus.iot.server.telemetry.api.*;
/**
* Create metrics instance for Prometheus exporter.
*/
public class PrometheusMetricsCreator implements MetricsCreator {
@Override
public CounterMetrics createCounter(String name, String tips, MetricsTag.Keys tagKeys,
MetricsTag.Values tagValues) {
return new PrometheusCounterMetrics(name, tips, tagKeys, tagValues);
}
@Override
public GaugeMetrics createGauge(String name, String tips, MetricsTag.Keys tagKeys, MetricsTag.Values tagValues) {
return new PrometheusGaugeMetrics(name, tips, tagKeys, tagValues);
}
@Override
public HistogramMetrics createHistogramMetric(String name, String tips, MetricsTag.Keys tagKeys,
MetricsTag.Values tagValues, double... buckets) {
return new PrometheusHistogramMetrics(name, tips, tagKeys, tagValues, buckets);
}
}
|
2301_81045437/zeus-iot
|
iot-server/server-telemetry/telemetry-prometheus/src/main/java/com/zmops/zeus/iot/server/telemetry/prometheus/PrometheusMetricsCreator.java
|
Java
|
gpl-3.0
| 1,825
|
/*
* 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.telemetry.prometheus;
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.iot.server.telemetry.prometheus.httpserver.HttpServer;
import com.zmops.zeus.server.library.module.*;
import io.prometheus.client.hotspot.DefaultExports;
/**
* Start the Prometheus
*/
public class PrometheusTelemetryProvider extends ModuleProvider {
private PrometheusConfig config;
public PrometheusTelemetryProvider() {
config = new PrometheusConfig();
}
@Override
public String name() {
return "prometheus";
}
@Override
public Class<? extends ModuleDefine> module() {
return TelemetryModule.class;
}
@Override
public ModuleConfig createConfigBeanIfAbsent() {
return config;
}
@Override
public void prepare() throws ServiceNotProvidedException, ModuleStartException {
this.registerServiceImplementation(MetricsCreator.class, new PrometheusMetricsCreator());
this.registerServiceImplementation(MetricsCollector.class, new PrometheusMetricsCollector());
try {
new HttpServer(config).start();
} catch (InterruptedException e) {
throw new ModuleStartException(e.getMessage(), e);
}
DefaultExports.initialize();
}
@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-telemetry/telemetry-prometheus/src/main/java/com/zmops/zeus/iot/server/telemetry/prometheus/PrometheusTelemetryProvider.java
|
Java
|
gpl-3.0
| 2,574
|
/*
* 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.telemetry.prometheus.httpserver;
import com.google.common.util.concurrent.ThreadFactoryBuilder;
import com.zmops.zeus.iot.server.telemetry.prometheus.PrometheusConfig;
import com.zmops.zeus.server.ssl.HttpDynamicSslContext;
import io.netty.bootstrap.ServerBootstrap;
import io.netty.channel.EventLoopGroup;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.nio.NioServerSocketChannel;
import io.netty.handler.logging.LogLevel;
import io.netty.handler.logging.LoggingHandler;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import java.util.Optional;
import java.util.concurrent.ThreadFactory;
/**
* An HTTP server that sends back the content of the received HTTP request
* in a pretty plaintext form.
*/
@RequiredArgsConstructor
@Slf4j
public final class HttpServer {
private final PrometheusConfig config;
public void start() throws InterruptedException {
// Configure SSL.
final HttpDynamicSslContext sslCtx;
if (config.isSslEnabled()) {
sslCtx = HttpDynamicSslContext.forServer(config.getSslKeyPath(), config.getSslCertChainPath());
} else {
sslCtx = null;
}
// Configure the server.
ThreadFactory tf = new ThreadFactoryBuilder().setDaemon(true).build();
EventLoopGroup bossGroup = new NioEventLoopGroup(1, tf);
EventLoopGroup workerGroup = new NioEventLoopGroup(0, tf);
ServerBootstrap b = new ServerBootstrap();
b.group(bossGroup, workerGroup)
.channel(NioServerSocketChannel.class)
.handler(new LoggingHandler(LogLevel.INFO))
.childHandler(new HttpServerInitializer(sslCtx));
b.bind(config.getHost(), config.getPort()).sync();
Optional.ofNullable(sslCtx).ifPresent(HttpDynamicSslContext::start);
log.info("Prometheus exporter endpoint:" +
(config.isSslEnabled() ? "https" : "http") + "://" + config.getHost() + ":" + config.getPort() + '/');
}
}
|
2301_81045437/zeus-iot
|
iot-server/server-telemetry/telemetry-prometheus/src/main/java/com/zmops/zeus/iot/server/telemetry/prometheus/httpserver/HttpServer.java
|
Java
|
gpl-3.0
| 2,868
|
/*
* 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.telemetry.prometheus.httpserver;
import io.netty.buffer.Unpooled;
import io.netty.channel.ChannelFuture;
import io.netty.channel.ChannelFutureListener;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.SimpleChannelInboundHandler;
import io.netty.handler.codec.http.*;
import io.netty.util.CharsetUtil;
import io.prometheus.client.CollectorRegistry;
import io.prometheus.client.exporter.common.TextFormat;
import lombok.extern.slf4j.Slf4j;
import org.apache.logging.log4j.core.util.StringBuilderWriter;
import java.io.IOException;
import static io.netty.channel.ChannelFutureListener.CLOSE;
import static io.netty.handler.codec.http.HttpHeaderNames.*;
import static io.netty.handler.codec.http.HttpHeaderValues.KEEP_ALIVE;
import static io.netty.handler.codec.http.HttpHeaderValues.TEXT_PLAIN;
import static io.netty.handler.codec.http.HttpResponseStatus.INTERNAL_SERVER_ERROR;
import static io.netty.handler.codec.http.HttpResponseStatus.OK;
@Slf4j
public class HttpServerHandler extends SimpleChannelInboundHandler<HttpObject> {
private final CollectorRegistry registry = CollectorRegistry.defaultRegistry;
private final StringBuilderWriter buf = new StringBuilderWriter();
@Override
public void channelReadComplete(ChannelHandlerContext ctx) {
ctx.flush();
}
@Override
public void channelRead0(ChannelHandlerContext ctx, HttpObject msg) {
if (msg instanceof HttpRequest) {
HttpRequest req = (HttpRequest) msg;
boolean keepAlive = HttpUtil.isKeepAlive(req);
buf.getBuilder().setLength(0);
try {
TextFormat.write004(buf, registry.metricFamilySamples());
} catch (IOException e) {
ctx.fireExceptionCaught(e);
return;
}
FullHttpResponse response = new DefaultFullHttpResponse(req.protocolVersion(), OK,
Unpooled.copiedBuffer(buf.getBuilder().toString(), CharsetUtil.UTF_8));
response.headers()
.set(CONTENT_TYPE, TEXT_PLAIN)
.setInt(CONTENT_LENGTH, response.content().readableBytes());
if (keepAlive) {
if (!req.protocolVersion().isKeepAliveDefault()) {
response.headers().set(CONNECTION, KEEP_ALIVE);
}
} else {
// Tell the client we're going to close the connection.
response.headers().set(CONNECTION, CLOSE);
}
ChannelFuture f = ctx.write(response);
if (!keepAlive) {
f.addListener(CLOSE);
}
}
}
@Override
public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) {
log.error("Prometheus exporter error", cause);
FullHttpResponse response = new DefaultFullHttpResponse(HttpVersion.HTTP_1_1,
INTERNAL_SERVER_ERROR,
Unpooled.wrappedBuffer(cause.getMessage().getBytes()));
ctx.writeAndFlush(response).addListener(ChannelFutureListener.CLOSE);
ctx.close();
}
}
|
2301_81045437/zeus-iot
|
iot-server/server-telemetry/telemetry-prometheus/src/main/java/com/zmops/zeus/iot/server/telemetry/prometheus/httpserver/HttpServerHandler.java
|
Java
|
gpl-3.0
| 3,954
|
/*
* 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.telemetry.prometheus.httpserver;
import io.netty.channel.ChannelInitializer;
import io.netty.channel.ChannelPipeline;
import io.netty.channel.socket.SocketChannel;
import io.netty.handler.codec.http.HttpServerCodec;
import io.netty.handler.codec.http.HttpServerExpectContinueHandler;
import io.netty.handler.ssl.SslContext;
import lombok.RequiredArgsConstructor;
@RequiredArgsConstructor
public class HttpServerInitializer extends ChannelInitializer<SocketChannel> {
private final SslContext sslCtx;
@Override
public void initChannel(SocketChannel ch) {
ChannelPipeline p = ch.pipeline();
if (sslCtx != null) {
p.addLast(sslCtx.newHandler(ch.alloc()));
}
p.addLast(new HttpServerCodec());
p.addLast(new HttpServerExpectContinueHandler());
p.addLast(new HttpServerHandler());
}
}
|
2301_81045437/zeus-iot
|
iot-server/server-telemetry/telemetry-prometheus/src/main/java/com/zmops/zeus/iot/server/telemetry/prometheus/httpserver/HttpServerInitializer.java
|
Java
|
gpl-3.0
| 1,699
|
package com.zmops.zeus.iot.server.transfer.module;
import com.zmops.zeus.server.library.module.ModuleDefine;
/**
* @author nantian created at 2021/9/22 16:39
*/
public class ServerTransferModule extends ModuleDefine {
public static final String NAME = "server-transfer";
public ServerTransferModule() {
super(NAME);
}
@Override
public Class[] services() {
return new Class[0];
}
}
|
2301_81045437/zeus-iot
|
iot-server/server-transfer/src/main/java/com/zmops/zeus/iot/server/transfer/module/ServerTransferModule.java
|
Java
|
gpl-3.0
| 429
|
package com.zmops.zeus.iot.server.transfer.provider;
import com.zmops.zeus.server.library.module.ModuleConfig;
import lombok.Getter;
import lombok.Setter;
/**
* @author nantian created at 2021/9/22 16:46
* <p>
* ndjson 文件读取配置
*/
@Getter
@Setter
public class ServerTransferConfig extends ModuleConfig {
private String name;
private String pattern;
// 文件读取超时 线程回收
private Integer fileMaxWait;
}
|
2301_81045437/zeus-iot
|
iot-server/server-transfer/src/main/java/com/zmops/zeus/iot/server/transfer/provider/ServerTransferConfig.java
|
Java
|
gpl-3.0
| 451
|
package com.zmops.zeus.iot.server.transfer.provider;
import com.zmops.zeus.iot.server.core.CoreModule;
import com.zmops.zeus.iot.server.transfer.module.ServerTransferModule;
import com.zmops.zeus.server.library.module.*;
import com.zmops.zeus.server.transfer.core.TransferManager;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
/**
* @author nantian created at 2021/9/22 16:44
*/
public class ServerTransferProvider extends ModuleProvider {
private static final Logger LOGGER = LoggerFactory.getLogger(ServerTransferProvider.class);
private final ServerTransferConfig config;
public ServerTransferProvider() {
this.config = new ServerTransferConfig();
}
@Override
public String name() {
return "default";
}
@Override
public Class<? extends ModuleDefine> module() {
return ServerTransferModule.class;
}
@Override
public ModuleConfig createConfigBeanIfAbsent() {
return config;
}
@Override
public void prepare() throws ServiceNotProvidedException, ModuleStartException {
}
/**
* Stopping agent gracefully if get killed.
*
* @param manager - agent manager
*/
private static void stopManagerIfKilled(TransferManager manager) {
Runtime.getRuntime().addShutdownHook(new Thread(() -> {
try {
LOGGER.info("stopping agent gracefully");
manager.stop();
} catch (Exception ex) {
LOGGER.error("exception while stopping threads", ex);
}
}));
}
@Override
public void start() throws ServiceNotProvidedException, ModuleStartException {
// TransferManager manager = new TransferManager(config);
// try {
// manager.start();
// stopManagerIfKilled(manager);
//// manager.join();
// } catch (Exception e) {
// e.printStackTrace();
// }
}
@Override
public void notifyAfterCompleted() throws ServiceNotProvidedException, ModuleStartException {
}
@Override
public String[] requiredModules() {
return new String[]{
CoreModule.NAME
};
}
}
|
2301_81045437/zeus-iot
|
iot-server/server-transfer/src/main/java/com/zmops/zeus/iot/server/transfer/provider/ServerTransferProvider.java
|
Java
|
gpl-3.0
| 2,212
|
package com.zmops.zeus.iot.server.transfer.sender;
import com.alibaba.fastjson.JSON;
import com.zmops.zeus.iot.server.core.analysis.manual.history.History;
import com.zmops.zeus.iot.server.core.analysis.manual.history.StrHistory;
import com.zmops.zeus.iot.server.core.analysis.manual.history.TextHistory;
import com.zmops.zeus.iot.server.core.analysis.manual.history.UIntHistory;
import com.zmops.zeus.iot.server.core.analysis.record.Record;
import com.zmops.zeus.iot.server.core.analysis.worker.RecordStreamProcessor;
import com.zmops.zeus.server.transfer.conf.JobProfile;
import com.zmops.zeus.server.transfer.core.task.TaskPositionManager;
import com.zmops.zeus.server.transfer.metrics.PluginMetric;
import lombok.Getter;
import lombok.Setter;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.nio.charset.StandardCharsets;
import java.util.List;
import java.util.Map;
import java.util.concurrent.TimeUnit;
/**
* 发送管理
*/
public class SenderManager {
private static final Logger LOGGER = LoggerFactory.getLogger(SenderManager.class);
private final TaskPositionManager taskPositionManager;
private final String sourceFilePath;
private final PluginMetric metric = new PluginMetric();
public SenderManager(JobProfile jobConf, String bid, String sourceFilePath) {
taskPositionManager = TaskPositionManager.getTaskPositionManager();
this.sourceFilePath = sourceFilePath;
}
/**
* Send message to proxy by batch, use message cache.
*
* @param bid - bid 方便以后企业版 区分数据来源
* @param tid - tid
* @param bodyList - body list
* @param retry - retry time
*/
public void sendBatch(String jobId, String bid, String tid, List<byte[]> bodyList, int retry, long dataTime) {
try {
bodyList.forEach(body -> {
ItemValue itemValue = JSON.parseObject(new String(body, StandardCharsets.UTF_8), ItemValue.class);
Record record;
if (itemValue.getType() == 3) { //uint
record = new UIntHistory();
} else if (itemValue.getType() == 0) {
record = new History();
} else if (itemValue.getType() == 4) { //text
record = new TextHistory();
} else if (itemValue.getType() == 1) {
record = new StrHistory();
} else {
return;
}
record.setItemid(itemValue.itemid);
record.setValue(itemValue.getHost().get("host"), itemValue.value, itemValue.getTimestamp());
RecordStreamProcessor.getInstance().in(record);
});
metric.sendSuccessNum.incr(bodyList.size());
taskPositionManager.updateFileSinkPosition(jobId, sourceFilePath, bodyList.size());
String fileName;
if (!System.getProperty("os.name").toLowerCase().startsWith("win")) {
String[] i = sourceFilePath.split("/");
fileName = i[i.length - 1];
} else {
fileName = sourceFilePath;
}
LOGGER.info("send bid [{}] with message size [{}], the job id is [{}],the tid is [{}], read file is {}, "
+ "dataTime is {}", bid, bodyList.size(), jobId, tid, fileName, dataTime);
} catch (Exception exception) {
LOGGER.error("Exception caught", exception);
// retry time
try {
TimeUnit.SECONDS.sleep(1);
sendBatch(jobId, bid, tid, bodyList, retry + 1, dataTime);
} catch (Exception ignored) {
// ignore it.
}
}
}
@Setter
@Getter
static class ItemValue {
private Integer type;
private String name;
private Long clock;
private Integer itemid;
private List<Map<String, String>> item_tags;
private List<String> groups;
private Long ns;
private String value;
private Map<String, String> host;
public Long getTimestamp() {
return Long.valueOf(clock + String.format("%09d", ns).substring(0, 3));
}
}
}
|
2301_81045437/zeus-iot
|
iot-server/server-transfer/src/main/java/com/zmops/zeus/iot/server/transfer/sender/SenderManager.java
|
Java
|
gpl-3.0
| 4,272
|
package com.zmops.zeus.iot.web.config;
import com.zmops.zeus.server.library.web.config.*;
/**
* @author nantian created at 2021/11/22 20:48
*/
public class IoTConfig extends WebConfig {
@Override
public void configConstant(Constants constants) {
constants.setDevMode(true);
constants.setMaxPostSize(1024 * 1024 * 100);
if (!System.getProperty("os.name").toLowerCase().startsWith("win")) {
constants.setBaseUploadPath("D:\\protocol\\upload");
} else {
constants.setBaseUploadPath("//opt//zeus//zeus-iot-bin//upload");
}
}
@Override
public void configRoute(Routes routes) {
routes.setBaseViewPath("/pages");
routes.scan("com.zmops.zeus.iot.web.controller.");
}
@Override
public void configHandler(Handlers handlers) {
}
@Override
public void configInterceptor(Interceptors interceptors) {
}
}
|
2301_81045437/zeus-iot
|
iot-server/server-web/src/main/java/com/zmops/zeus/iot/web/config/IoTConfig.java
|
Java
|
gpl-3.0
| 929
|
package com.zmops.zeus.iot.web.controller;
import com.zmops.zeus.server.library.web.core.Controller;
import com.zmops.zeus.server.library.web.core.Path;
/**
* @author nantian created at 2021/11/23 23:24
*/
@Path(value = "/protocol", viewPath = "/")
public class IndexController extends Controller {
}
|
2301_81045437/zeus-iot
|
iot-server/server-web/src/main/java/com/zmops/zeus/iot/web/controller/IndexController.java
|
Java
|
gpl-3.0
| 308
|
package com.zmops.zeus.iot.web.controller;
import com.alipay.sofa.ark.api.ArkClient;
import com.alipay.sofa.ark.api.ClientResponse;
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.ModuleManager;
import com.zmops.zeus.server.library.web.core.Controller;
import com.zmops.zeus.server.library.web.core.Path;
import com.zmops.zeus.server.library.web.upload.UploadFile;
import java.io.File;
import java.io.IOException;
import java.sql.ResultSet;
import java.sql.SQLException;
/**
* @author yefei
**/
@Path(value = "/protocol/component")
public class ProtocolComponentController extends Controller {
public void saveProtocolComponent() {
String id = getPara("protocolComponentId");
String uniqueId = getPara("uniqueId");
InsertDAO localH2InsertDAO = ModuleManager.getInstance()
.find(LocalH2Module.NAME).provider().getService(InsertDAO.class);
localH2InsertDAO.insert("insert into protocol_component(id,unique_id) values(" + id + "," + uniqueId + ")");
renderNull();
}
public void upload() {
UploadFile file = getFile();
try {
String filePath = file.getFile().getCanonicalPath();
renderJson("filePath", filePath);
} catch (IOException e) {
e.printStackTrace();
}
}
public void installArk() throws SQLException {
String id = getPara("protocolComponentId");
String fileName = getPara("fileName");
InsertDAO localH2InsertDAO = ModuleManager.getInstance()
.find(LocalH2Module.NAME).provider().getService(InsertDAO.class);
ClientResponse response;
try {
if (!System.getProperty("os.name").toLowerCase().startsWith("win")) {
response = ArkClient.installBiz(new File("D:\\protocol\\upload\\" + fileName));
} else {
response = ArkClient.installBiz(new File("//opt//zeus//zeus-iot-bin//upload//" + fileName));
}
String bizName = response.getBizInfos().iterator().next().getBizName();
String bizVersion = response.getBizInfos().iterator().next().getBizVersion();
int r = localH2InsertDAO.update("update protocol_component set file_name=?, biz_name=?,biz_version = ? where id=?", fileName, bizName, bizVersion, id);
renderJson(response);
} catch (Throwable e) {
e.printStackTrace();
}
}
public void uninstallArk() throws SQLException {
String id = getPara("protocolComponentId");
InsertDAO localH2InsertDAO = ModuleManager.getInstance()
.find(LocalH2Module.NAME).provider().getService(InsertDAO.class);
ResultSet rs = localH2InsertDAO.queryRes("select * from protocol_component where id=?", id);
String bizName = "";
String bizVersion = "";
while (rs.next()) {
bizName = rs.getString(7);
bizVersion = rs.getString(8);
}
try {
ClientResponse response = ArkClient.uninstallBiz(bizName, bizVersion);
renderJson(response);
} catch (Throwable e) {
e.printStackTrace();
}
}
}
|
2301_81045437/zeus-iot
|
iot-server/server-web/src/main/java/com/zmops/zeus/iot/web/controller/ProtocolComponentController.java
|
Java
|
gpl-3.0
| 3,289
|
package com.zmops.zeus.iot.web.controller;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
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.ProtocolAction;
import com.zmops.zeus.iot.server.receiver.ProtocolEnum;
import com.zmops.zeus.iot.server.receiver.module.CamelReceiverModule;
import com.zmops.zeus.iot.server.receiver.routes.*;
import com.zmops.zeus.iot.server.receiver.service.CamelContextHolderService;
import com.zmops.zeus.iot.web.domain.ProtocolGatewayMqtt;
import com.zmops.zeus.server.library.module.ModuleManager;
import com.zmops.zeus.server.library.web.core.Controller;
import com.zmops.zeus.server.library.web.core.Path;
import lombok.Getter;
import lombok.Setter;
import org.apache.camel.builder.RouteBuilder;
import org.apache.commons.lang3.StringUtils;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.List;
import java.util.Map;
/**
* @author nantian created at 2021/11/23 23:24
*/
@Path(value = "/protocol/gateway")
public class ProtocolGatewayController extends Controller {
public void stopRoute() {
String routeId = getPara("routeId");
stopGateway(routeId);
renderNull();
}
public void stopGateway(String routeId) {
CamelContextHolderService camelContextHolderService = ModuleManager.getInstance()
.find(CamelReceiverModule.NAME).provider().getService(CamelContextHolderService.class);
camelContextHolderService.routeShutDown(routeId);
InsertDAO localH2InsertDAO = ModuleManager.getInstance()
.find(LocalH2Module.NAME).provider().getService(InsertDAO.class);
localH2InsertDAO.update("update protocol_gateway set status=1 where id=?", routeId);
}
public void startRoute() {
String routeId = getPara("routeId");
CamelContextHolderService camelContextHolderService = ModuleManager.getInstance()
.find(CamelReceiverModule.NAME).provider().getService(CamelContextHolderService.class);
camelContextHolderService.routeStartUp(routeId);
InsertDAO localH2InsertDAO = ModuleManager.getInstance()
.find(LocalH2Module.NAME).provider().getService(InsertDAO.class);
localH2InsertDAO.update("update protocol_gateway set status=0 where id=?", routeId);
renderNull();
}
public void createProtocolGateway() {
String routeId = getPara("routeId");
String name = getPara("name");
String protocolServiceId = getPara("protocolServiceId");
String protocolComponentId = getPara("protocolComponentId");
String status = getPara("status");
String protocol = getPara("protocol");
String option = getPara("option");
String mqttList = getPara("mqttList");
InsertDAO localH2InsertDAO = ModuleManager.getInstance()
.find(LocalH2Module.NAME).provider().getService(InsertDAO.class);
localH2InsertDAO.insert("insert into protocol_gateway(id,name,protocol_service_id,protocol_component_id,status) values(" + routeId + ",'" + name + "'," + protocolServiceId + "," + protocolComponentId + ",'" + status + "')");
if (StringUtils.isNotBlank(mqttList)) {
saveMqttList(mqttList);
}
Map<String, Object> options = JSON.parseObject(option, Map.class);
createRoute(routeId, ProtocolEnum.valueOf(protocol), options);
}
public void updateProtocolGateway() throws SQLException {
String routeId = getPara("routeId");
stopGateway(routeId);
String name = getPara("name");
String protocolServiceId = getPara("protocolServiceId");
String protocolComponentId = getPara("protocolComponentId");
String remark = getPara("remark");
String option = getPara("option");
String mqttList = getPara("mqttList");
InsertDAO localH2InsertDAO = ModuleManager.getInstance()
.find(LocalH2Module.NAME).provider().getService(InsertDAO.class);
StringBuilder sql = new StringBuilder("update protocol_gateway set protocol_service_id=?");
if (StringUtils.isNotBlank(name)) {
sql.append(" ,name =?");
}
if (StringUtils.isNotBlank(protocolComponentId)) {
sql.append(" ,protocolComponentId =?");
}
if (StringUtils.isNotBlank(remark)) {
sql.append(" ,remark =?");
}
sql.append(" where id=?");
localH2InsertDAO.update("", protocolServiceId, name, protocolComponentId, remark, routeId);
localH2InsertDAO.delete("delete from protocol_gateway_mqtt where protocol_gateway_id = " + routeId);
if (StringUtils.isNotBlank(mqttList)) {
saveMqttList(mqttList);
}
Map<String, Object> options = JSON.parseObject(option, Map.class);
ResultSet rs = localH2InsertDAO.queryRes("select * from protocol_service where id=?", protocolServiceId);
String protocol = "";
while (rs.next()) {
protocol = rs.getString(9);
}
createRoute(routeId, ProtocolEnum.valueOf(protocol), options);
}
public void createRoute(String routeId, ProtocolEnum protocol, Map<String, Object> options) {
CamelContextHolderService camelContextHolderService = ModuleManager.getInstance()
.find(CamelReceiverModule.NAME).provider().getService(CamelContextHolderService.class);
RouteBuilder route = null;
switch (protocol) {
case HttpServer:
route = new HttpRouteBuilder(routeId, options);
break;
case MqttClient:
route = new MqttClientRouteBuilder(routeId, options);
break;
case TcpServer:
route = new TcpServerRouteBuilder(routeId, options);
break;
case UdpServer:
route = new UdpServerRouteBuilder(routeId, options);
break;
case CoapServer:
route = new CoapServerRouteBuilder(routeId, options);
break;
case WebSocketServer:
route = new WebSocketServerRouteBuilder(routeId, options);
break;
default:
break;
}
if (route != null) {
camelContextHolderService.addRoutes(route);
}
renderNull();
}
private void saveMqttList(String mqttList) {
List<ProtocolGatewayMqtt> protocolGatewayMqtts = JSONObject.parseArray(mqttList, ProtocolGatewayMqtt.class);
if (protocolGatewayMqtts == null || protocolGatewayMqtts.size() <= 0) {
return;
}
InsertDAO localH2InsertDAO = ModuleManager.getInstance()
.find(LocalH2Module.NAME).provider().getService(InsertDAO.class);
protocolGatewayMqtts.forEach(mqtt -> {
localH2InsertDAO.insert("insert into protocol_gateway_mqtt(topic,protocol_component_id,protocol_gateway_id) values('" + mqtt.getTopic() + "'," + mqtt.getProtocolComponentId() + "," + mqtt.getProtocolGatewayId() + ")");
});
}
@Getter
@Setter
static class ProtocolService {
private String routeId;
private ProtocolEnum protocol;
private ProtocolAction action;
private Map<String, Object> options;
}
}
|
2301_81045437/zeus-iot
|
iot-server/server-web/src/main/java/com/zmops/zeus/iot/web/controller/ProtocolGatewayController.java
|
Java
|
gpl-3.0
| 7,457
|
package com.zmops.zeus.iot.web.controller;
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.ModuleManager;
import com.zmops.zeus.server.library.web.core.Controller;
import com.zmops.zeus.server.library.web.core.Path;
import org.apache.commons.lang3.StringUtils;
/**
* @author yefei
**/
@Path(value = "/protocol/service")
public class ProtocolServiceController extends Controller {
public void saveProtocolService() {
String id = getPara("protocolServiceId");
String name = getPara("name");
String remark = getPara("remark");
String url = getPara("url");
String ip = getPara("ip");
String port = getPara("port");
String msgLength = getPara("msgLength");
String clientId = getPara("clientId");
String protocol = getPara("protocol");
InsertDAO localH2InsertDAO = ModuleManager.getInstance()
.find(LocalH2Module.NAME).provider().getService(InsertDAO.class);
String sql = "insert into protocol_service(id,name,url,ip,port,msg_length,client_id,protocol,remark) " +
" values(" + id + ",'" + name + "','" + url + "','" + ip + "','" + port + "','" + msgLength + "','" + clientId + "','" + protocol + "','" + remark + "')";
localH2InsertDAO.insert(sql);
renderNull();
}
public void updateProtocolService() {
String id = getPara("protocolServiceId");
String name = getPara("name");
String remark = getPara("remark");
String url = getPara("url");
String ip = getPara("ip");
String port = getPara("port");
String msgLength = getPara("msgLength");
String clientId = getPara("clientId");
String protocol = getPara("protocol");
InsertDAO localH2InsertDAO = ModuleManager.getInstance()
.find(LocalH2Module.NAME).provider().getService(InsertDAO.class);
StringBuilder sql = new StringBuilder("update protocol_service set ip=?,port=?");
if(StringUtils.isNotBlank(name)){
sql.append(" ,name =?");
}
if(StringUtils.isNotBlank(remark)){
sql.append(" ,remark =?");
}
if(StringUtils.isNotBlank(url)){
sql.append(" ,url =?");
}
if(StringUtils.isNotBlank(msgLength)){
sql.append(" ,msg_length =?");
}
if(StringUtils.isNotBlank(clientId)){
sql.append(" ,client_id =?");
}
if(StringUtils.isNotBlank(protocol)){
sql.append(" ,protocol =?");
}
sql.append(" where id=?");
localH2InsertDAO.update(sql.toString(), ip, port, name, remark, url, msgLength, clientId, protocol, id);
renderNull();
}
}
|
2301_81045437/zeus-iot
|
iot-server/server-web/src/main/java/com/zmops/zeus/iot/web/controller/ProtocolServiceController.java
|
Java
|
gpl-3.0
| 2,832
|
package com.zmops.zeus.iot.web.controller;
import com.zmops.zeus.server.library.web.core.ActionKey;
import com.zmops.zeus.server.library.web.core.Controller;
import com.zmops.zeus.server.library.web.core.Path;
/**
* @author nantian created at 2021/12/1 22:10
*/
@Path("/")
public class WebConsole extends Controller {
public void index() {
redirect("/zeus/index.html");
}
@ActionKey("/zeus")
public void zeus() {
redirect("/zeus/index.html");
}
}
|
2301_81045437/zeus-iot
|
iot-server/server-web/src/main/java/com/zmops/zeus/iot/web/controller/WebConsole.java
|
Java
|
gpl-3.0
| 490
|
package com.zmops.zeus.iot.web.domain;
import lombok.Data;
import lombok.EqualsAndHashCode;
/**
* @author yefei
**/
@EqualsAndHashCode(callSuper = false)
@Data
public class ProtocolComponent {
private Long id;
private String name;
private String uniqueId;
private String status;
private String remark;
private String fileName;
}
|
2301_81045437/zeus-iot
|
iot-server/server-web/src/main/java/com/zmops/zeus/iot/web/domain/ProtocolComponent.java
|
Java
|
gpl-3.0
| 363
|
package com.zmops.zeus.iot.web.domain;
import lombok.Data;
import lombok.EqualsAndHashCode;
/**
* @author yefei
**/
@Data
public class ProtocolGateway {
private Long id;
private String name;
private Long protocolServiceId;
private Long protocolComponentId;
private String status;
private String remark;
}
|
2301_81045437/zeus-iot
|
iot-server/server-web/src/main/java/com/zmops/zeus/iot/web/domain/ProtocolGateway.java
|
Java
|
gpl-3.0
| 339
|
package com.zmops.zeus.iot.web.domain;
import lombok.AllArgsConstructor;
import lombok.Builder;
import lombok.Data;
import lombok.NoArgsConstructor;
/**
* @author yefei
**/
@Data
@Builder
@NoArgsConstructor
@AllArgsConstructor
public class ProtocolGatewayMqtt {
private Long protocolGatewayId;
private Long protocolComponentId;
private String topic;
}
|
2301_81045437/zeus-iot
|
iot-server/server-web/src/main/java/com/zmops/zeus/iot/web/domain/ProtocolGatewayMqtt.java
|
Java
|
gpl-3.0
| 372
|
package com.zmops.zeus.iot.web.domain;
import lombok.Data;
/**
* @author yefei
**/
@Data
public class ProtocolService {
private Long id;
private String name;
private String protocolType;
private String remark;
private String url;
private String ip;
private Integer port;
private Integer msgLength;
private String clientId;
}
|
2301_81045437/zeus-iot
|
iot-server/server-web/src/main/java/com/zmops/zeus/iot/web/domain/ProtocolService.java
|
Java
|
gpl-3.0
| 372
|
package com.zmops.iot.constant;
/**
* 配置的常量
*
* @author fengshuonan nantian
*/
public interface ConfigConstant {
/**
* 系统常量的前缀标识
*/
String SYSTEM_CONSTANT_PREFIX = "ZEUS_";
}
|
2301_81045437/zeus-iot
|
zeus-common/src/main/java/com/zmops/iot/constant/ConfigConstant.java
|
Java
|
gpl-3.0
| 228
|
package com.zmops.iot.constant;
public class Constants {
public static final int SEC_PER_MIN = 60;
public static final int SEC_PER_HOUR = 3600;
public static final int SEC_PER_DAY = 86400;
public static final int SEC_PER_WEEK = 604800;
public static final int SEC_PER_MONTH = 2592000;
public static final int SEC_PER_YEAR = 31536000;
public static final String DATE_TIME_FORMAT_SECONDS = "yyyy-MM-dd HH:mm:ss";
public static final Integer ARGUS_UNITS_ROUNDOFF_UPPER_LIMIT = 2;
public static final Integer ITEM_CONVERT_WITH_UNITS = 0;
}
|
2301_81045437/zeus-iot
|
zeus-common/src/main/java/com/zmops/iot/constant/Constants.java
|
Java
|
gpl-3.0
| 586
|
package com.zmops.iot.constant;
import com.zmops.iot.enums.CommonStatus;
import com.zmops.iot.util.ToolUtil;
import lombok.extern.slf4j.Slf4j;
import java.io.File;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;
import static com.zmops.iot.constant.ConfigConstant.SYSTEM_CONSTANT_PREFIX;
import static com.zmops.iot.util.ToolUtil.getTempPath;
/**
* 系统常量的容器
*
* @author fengshuonan nantian
*/
@Slf4j
public class ConstantsContext {
private static final String TIPS_END = ",若想忽略此提示,请在开发管理->系统配置->参数配置,设置相关参数!";
/**
* 所有的常量,可以增删改查
*/
private static final Map<String, Object> CONSTNTS_HOLDER = new ConcurrentHashMap<>();
/**
* 添加系统常量
*/
public static void putConstant(String key, Object value) {
if (ToolUtil.isOneEmpty(key, value)) {
return;
}
CONSTNTS_HOLDER.put(key, value);
}
/**
* 删除常量
*/
public static void deleteConstant(String key) {
if (ToolUtil.isOneEmpty(key)) {
return;
}
//如果是系统常量
if (!key.startsWith(SYSTEM_CONSTANT_PREFIX)) {
CONSTNTS_HOLDER.remove(key);
}
}
/**
* 获取系统常量
*/
public static Map<String, Object> getConstntsMap() {
return CONSTNTS_HOLDER;
}
/**
* 获取验证码开关
*/
public static Boolean getKaptchaOpen() {
String gunsKaptchaOpen = (String) CONSTNTS_HOLDER.get("ZEUS_KAPTCHA_OPEN");
if (CommonStatus.ENABLE.getCode().equalsIgnoreCase(gunsKaptchaOpen)) {
return true;
} else {
return false;
}
}
/**
* 获取管理系统名称
*/
public static String getSystemName() {
String systemName = (String) CONSTNTS_HOLDER.get("ZEUS_SYSTEM_NAME");
if (ToolUtil.isEmpty(systemName)) {
log.error("系统常量存在空值!常量名称:ZEUS_SYSTEM_NAME,采用默认名称:Zeus-IOT 物联网基础中台" + TIPS_END);
return "Zeus-IOT 物联网基础中台";
} else {
return systemName;
}
}
/**
* 获取管理系统名称
*/
public static String getDefaultPassword() {
String defaultPassword = (String) CONSTNTS_HOLDER.get("ZEUS_DEFAULT_PASSWORD");
if (ToolUtil.isEmpty(defaultPassword)) {
log.error("系统常量存在空值!常量名称:ZEUS_DEFAULT_PASSWORD,采用默认密码:111111" + TIPS_END);
return "111111";
} else {
return defaultPassword;
}
}
/**
* 获取管理系统名称
*/
public static String getOAuth2UserPrefix() {
String oauth2Prefix = (String) CONSTNTS_HOLDER.get("ZEUS_OAUTH2_PREFIX");
if (ToolUtil.isEmpty(oauth2Prefix)) {
log.error("系统常量存在空值!常量名称:ZEUS_OAUTH2_PREFIX,采用默认值:oauth2" + TIPS_END);
return "oauth2";
} else {
return oauth2Prefix;
}
}
/**
* 获取系统发布的版本号(防止css和js的缓存)
*/
public static String getReleaseVersion() {
String systemReleaseVersion = (String) CONSTNTS_HOLDER.get("ZEUS_SYSTEM_RELEASE_VERSION");
if (ToolUtil.isEmpty(systemReleaseVersion)) {
log.error("系统常量存在空值!常量名称:ZEUS_SYSTEM_RELEASE_VERSION,采用默认值:guns" + TIPS_END);
return ToolUtil.getRandomString(8);
} else {
return systemReleaseVersion;
}
}
/**
* 获取文件上传路径(用于头像和富文本编辑器)
*/
public static String getFileUploadPath() {
String gunsFileUploadPath = (String) CONSTNTS_HOLDER.get("ZEUS_FILE_UPLOAD_PATH");
if (ToolUtil.isEmpty(gunsFileUploadPath)) {
log.error("系统常量存在空值!常量名称:ZEUS_FILE_UPLOAD_PATH,采用默认值:系统tmp目录" + TIPS_END);
return getTempPath();
} else {
//判断有没有结尾符
if (!gunsFileUploadPath.endsWith(File.separator)) {
gunsFileUploadPath = gunsFileUploadPath + File.separator;
}
//判断目录存不存在
File file = new File(gunsFileUploadPath);
if (!file.exists()) {
boolean mkdirs = file.mkdirs();
if (mkdirs) {
return gunsFileUploadPath;
} else {
log.error("系统常量存在空值!常量名称:ZEUS_FILE_UPLOAD_PATH,采用默认值:系统tmp目录" + TIPS_END);
return getTempPath();
}
} else {
return gunsFileUploadPath;
}
}
}
/**
* 用于存放bpmn文件
*/
public static String getBpmnFileUploadPath() {
String bpmnFileUploadPath = (String) CONSTNTS_HOLDER.get("ZEUS_BPMN_FILE_UPLOAD_PATH");
if (ToolUtil.isEmpty(bpmnFileUploadPath)) {
log.error("系统常量存在空值!常量名称:ZEUS_BPMN_FILE_UPLOAD_PATH,采用默认值:系统tmp目录" + TIPS_END);
return getTempPath();
} else {
//判断有没有结尾符
if (!bpmnFileUploadPath.endsWith(File.separator)) {
bpmnFileUploadPath = bpmnFileUploadPath + File.separator;
}
//判断目录存不存在
File file = new File(bpmnFileUploadPath);
if (!file.exists()) {
boolean mkdirs = file.mkdirs();
if (mkdirs) {
return bpmnFileUploadPath;
} else {
log.error("系统常量存在空值!常量名称:ZEUS_BPMN_FILE_UPLOAD_PATH,采用默认值:系统tmp目录" + TIPS_END);
return getTempPath();
}
} else {
return bpmnFileUploadPath;
}
}
}
/**
* 获取系统密钥
*/
public static String getJwtSecret() {
String systemReleaseVersion = (String) CONSTNTS_HOLDER.get("ZEUS_JWT_SECRET");
if (ToolUtil.isEmpty(systemReleaseVersion)) {
String randomSecret = ToolUtil.getRandomString(32);
CONSTNTS_HOLDER.put("ZEUS_JWT_SECRET", randomSecret);
log.error("jwt密钥存在空值!常量名称:ZEUS_JWT_SECRET,采用默认值:随机字符串->" + randomSecret + TIPS_END);
return randomSecret;
} else {
return systemReleaseVersion;
}
}
/**
* 获取系统地密钥过期时间(单位:秒)
*/
public static Long getJwtSecretExpireSec() {
Long defaultSecs = 86400L;
String systemReleaseVersion = (String) CONSTNTS_HOLDER.get("ZEUS_JWT_SECRET_EXPIRE");
if (ToolUtil.isEmpty(systemReleaseVersion)) {
log.error("jwt密钥存在空值!常量名称:ZEUS_JWT_SECRET_EXPIRE,采用默认值:1天" + TIPS_END);
CONSTNTS_HOLDER.put("ZEUS_JWT_SECRET_EXPIRE", String.valueOf(defaultSecs));
return defaultSecs;
} else {
try {
return Long.valueOf(systemReleaseVersion);
} catch (NumberFormatException e) {
log.error("jwt密钥过期时间不是数字!常量名称:ZEUS_JWT_SECRET_EXPIRE,采用默认值:1天" + TIPS_END);
CONSTNTS_HOLDER.put("ZEUS_JWT_SECRET_EXPIRE", String.valueOf(defaultSecs));
return defaultSecs;
}
}
}
/**
* 获取token的header标识
*/
public static String getTokenHeaderName() {
String tokenHeaderName = (String) CONSTNTS_HOLDER.get("ZEUS_TOKEN_HEADER_NAME");
if (ToolUtil.isEmpty(tokenHeaderName)) {
String defaultName = "Authorization";
CONSTNTS_HOLDER.put("ZEUS_TOKEN_HEADER_NAME", defaultName);
log.error("获取token的header标识为空!常量名称:ZEUS_TOKEN_HEADER_NAME,采用默认值:" + defaultName + TIPS_END);
return defaultName;
} else {
return tokenHeaderName;
}
}
/**
* 获取租户是否开启的标识,默认是关的
*/
public static Boolean getTenantOpen() {
String tenantOpen = (String) CONSTNTS_HOLDER.get("ZEUS_TENANT_OPEN");
if (ToolUtil.isEmpty(tenantOpen)) {
log.error("系统常量存在空值!常量名称:ZEUS_TENANT_OPEN,采用默认值:DISABLE" + TIPS_END);
return false;
} else {
return CommonStatus.ENABLE.getCode().equalsIgnoreCase(tenantOpen);
}
}
}
|
2301_81045437/zeus-iot
|
zeus-common/src/main/java/com/zmops/iot/constant/ConstantsContext.java
|
Java
|
gpl-3.0
| 8,861
|
package com.zmops.iot.constant;
/**
* @author nantian created at 2021/8/1 19:11
*/
public interface IdTypeConsts {
String ID_SNOW = "IdSnow";
}
|
2301_81045437/zeus-iot
|
zeus-common/src/main/java/com/zmops/iot/constant/IdTypeConsts.java
|
Java
|
gpl-3.0
| 152
|
/**
* Copyright 2018-2020 stylefeng & fengshuonan (https://gitee.com/stylefeng)
* <p>
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
* <p>
* http://www.apache.org/licenses/LICENSE-2.0
* <p>
* 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.iot.dict;
import java.util.HashMap;
/**
* 字典映射抽象类
*
* @author fengshuonan
*/
public abstract class AbstractDictMap {
protected HashMap<String, String> dictory = new HashMap<>();
protected HashMap<String, String> fieldWarpperDictory = new HashMap<>();
public AbstractDictMap() {
put("id", "主键id");
init();
initBeWrapped();
}
/**
* 初始化字段英文名称和中文名称对应的字典
*
* @author stylefeng
*/
public abstract void init();
/**
* 初始化需要被包装的字段(例如:性别为1:男,2:女,需要被包装为汉字)
*
* @author stylefeng
*/
protected abstract void initBeWrapped();
public String get(String key) {
return this.dictory.get(key);
}
public void put(String key, String value) {
this.dictory.put(key, value);
}
public String getFieldWarpperMethodName(String key) {
return this.fieldWarpperDictory.get(key);
}
public void putFieldWrapperMethodName(String key, String methodName) {
this.fieldWarpperDictory.put(key, methodName);
}
}
|
2301_81045437/zeus-iot
|
zeus-common/src/main/java/com/zmops/iot/dict/AbstractDictMap.java
|
Java
|
gpl-3.0
| 1,823
|
/**
* Copyright 2018-2020 stylefeng & fengshuonan (https://gitee.com/stylefeng)
* <p>
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
* <p>
* http://www.apache.org/licenses/LICENSE-2.0
* <p>
* 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.iot.dict;
/**
* 系统相关的字典
*
* @author fengshuonan
*/
public class SystemDict extends AbstractDictMap {
@Override
public void init() {
}
@Override
protected void initBeWrapped() {
}
}
|
2301_81045437/zeus-iot
|
zeus-common/src/main/java/com/zmops/iot/dict/SystemDict.java
|
Java
|
gpl-3.0
| 895
|
package com.zmops.iot.domain;
import io.ebean.Model;
import io.ebean.annotation.WhenCreated;
import io.ebean.annotation.WhenModified;
import io.ebean.annotation.WhoCreated;
import io.ebean.annotation.WhoModified;
import lombok.Data;
import javax.persistence.MappedSuperclass;
import java.time.LocalDateTime;
/**
* @author nantian created at 2021/7/30 20:37
*/
@MappedSuperclass
@Data
public abstract class BaseEntity extends Model {
@WhenCreated
LocalDateTime createTime;
@WhenModified
LocalDateTime updateTime;
@WhoCreated
Long createUser;
@WhoModified
Long updateUser;
/**
* 数据校验组:新增
*/
public interface Create {
}
/**
* 数据校验组:更新
*/
public interface Update {
}
/**
* 数据校验组:删除
*/
public interface Delete {
}
/**
* 数据校验组:绑定设备
*/
public interface BindDevice {
}
/**
* 数据校验组:查询
*/
public interface Get {
}
/**
* 数据校验组:批量删除
*/
public interface MassRemove {
}
/**
* 数据校验组:状态
*/
public interface Status {
}
}
|
2301_81045437/zeus-iot
|
zeus-common/src/main/java/com/zmops/iot/domain/BaseEntity.java
|
Java
|
gpl-3.0
| 1,212
|
package com.zmops.iot.domain.alarm;
import lombok.AllArgsConstructor;
import lombok.Builder;
import lombok.Data;
import lombok.NoArgsConstructor;
/**
* Alarm message represents the details of each alarm.
*/
@Data
@Builder
@NoArgsConstructor
@AllArgsConstructor
public class AlarmMessage {
private int scopeId;
private String scope;
private String name;
private String id0;
private String id1;
private String ruleName;
private String alarmMessage;
private long startTime;
private transient int period;
private transient boolean onlyAsCondition;
}
|
2301_81045437/zeus-iot
|
zeus-common/src/main/java/com/zmops/iot/domain/alarm/AlarmMessage.java
|
Java
|
gpl-3.0
| 590
|
package com.zmops.iot.domain.alarm;
import lombok.Data;
import lombok.EqualsAndHashCode;
import javax.persistence.Entity;
import javax.persistence.Id;
import javax.persistence.Table;
/**
* @author yefei
**/
@EqualsAndHashCode(callSuper = false)
@Data
@Table(name = "media_type_setting")
@Entity
public class MediaTypeSetting {
@Id
private Integer id;
private String type;
private String template;
private String webhooks;
private Long tenantId;
}
|
2301_81045437/zeus-iot
|
zeus-common/src/main/java/com/zmops/iot/domain/alarm/MediaTypeSetting.java
|
Java
|
gpl-3.0
| 480
|
package com.zmops.iot.domain.alarm;
import lombok.Data;
import lombok.EqualsAndHashCode;
import javax.persistence.Entity;
import javax.persistence.Id;
import javax.persistence.Table;
import java.time.LocalDateTime;
/**
* @author yefei
**/
@EqualsAndHashCode(callSuper = false)
@Data
@Table(name = "problem")
@Entity
public class Problem {
@Id
private Long eventId;
private Long objectId;
private LocalDateTime clock;
private LocalDateTime rClock;
private String name;
private Integer acknowledged;
private Integer severity;
private String deviceId;
}
|
2301_81045437/zeus-iot
|
zeus-common/src/main/java/com/zmops/iot/domain/alarm/Problem.java
|
Java
|
gpl-3.0
| 601
|
package com.zmops.iot.domain.device;
import lombok.Data;
import javax.validation.constraints.NotBlank;
import javax.validation.constraints.NotNull;
import java.util.List;
/**
* @author yefei
**/
@Data
public class ApiParam {
@NotNull
private List<Params> params;
@NotBlank
private String deviceId;
@Data
public static class Params{
@NotBlank
private String deviceAttrKey;
@NotBlank
private String deviceAttrValue;
}
}
|
2301_81045437/zeus-iot
|
zeus-common/src/main/java/com/zmops/iot/domain/device/ApiParam.java
|
Java
|
gpl-3.0
| 486
|
package com.zmops.iot.domain.device;
import com.zmops.iot.domain.BaseEntity;
import io.ebean.annotation.Aggregation;
import io.ebean.annotation.TenantId;
import io.ebean.annotation.WhoCreated;
import lombok.Data;
import lombok.EqualsAndHashCode;
import javax.persistence.Entity;
import javax.persistence.Id;
import javax.persistence.Table;
import java.time.LocalDateTime;
/**
* @author yefei
**/
@EqualsAndHashCode(callSuper = false)
@Data
@Table(name = "device")
@Entity
public class Device extends BaseEntity {
@Id
private String deviceId;
private String name;
private Long productId;
private String status;
private String type;
private String remark;
private String zbxId;
private String addr;
private String position;
private Integer online;
private Long tenantId;
private Long proxyId;
private LocalDateTime latestOnline;
@Aggregation("count(*)")
Long totalCount;
}
|
2301_81045437/zeus-iot
|
zeus-common/src/main/java/com/zmops/iot/domain/device/Device.java
|
Java
|
gpl-3.0
| 954
|
package com.zmops.iot.domain.device;
import com.zmops.iot.domain.BaseEntity;
import lombok.Data;
import lombok.EqualsAndHashCode;
import javax.persistence.Entity;
import javax.persistence.Id;
import javax.persistence.Table;
/**
* @author yefei created at 2021/7/30 20:31
*/
@EqualsAndHashCode(callSuper = false)
@Data
@Table(name = "device_group")
@Entity
public class DeviceGroup extends BaseEntity {
@Id
Long deviceGroupId;
String name;
String zbxId;
String remark;
private Long tenantId;
}
|
2301_81045437/zeus-iot
|
zeus-common/src/main/java/com/zmops/iot/domain/device/DeviceGroup.java
|
Java
|
gpl-3.0
| 528
|
package com.zmops.iot.domain.device;
import lombok.*;
import javax.persistence.Entity;
import javax.persistence.Id;
import javax.persistence.Table;
/**
* @author yefei
**/
@EqualsAndHashCode
@Data
@Table(name = "device_online_report")
@Entity
@Builder
@NoArgsConstructor
@AllArgsConstructor
public class DeviceOnlineReport {
@Id
private Long id;
private String createTime;
private Long online;
private Long offline;
private Integer type;
private Long tenantId;
}
|
2301_81045437/zeus-iot
|
zeus-common/src/main/java/com/zmops/iot/domain/device/DeviceOnlineReport.java
|
Java
|
gpl-3.0
| 502
|
package com.zmops.iot.domain.device;
import lombok.Data;
import javax.persistence.Entity;
import javax.persistence.Table;
/**
* @author yefei
**/
@Data
@Entity
@Table(name = "device_service_method")
public class DeviceServiceMethod {
private String deviceId;
private String url;
private String method;
private String ip;
private Integer port;
private String topic;
}
|
2301_81045437/zeus-iot
|
zeus-common/src/main/java/com/zmops/iot/domain/device/DeviceServiceMethod.java
|
Java
|
gpl-3.0
| 401
|
package com.zmops.iot.domain.device;
import lombok.*;
import javax.persistence.Entity;
import javax.persistence.Id;
import javax.persistence.Table;
/**
* @author yefei
**/
@EqualsAndHashCode(callSuper = false)
@Data
@Table(name = "devices_groups")
@Entity
@Builder
@NoArgsConstructor
@AllArgsConstructor
public class DevicesGroups {
@Id
private Long id;
private String deviceId;
private Long deviceGroupId;
}
|
2301_81045437/zeus-iot
|
zeus-common/src/main/java/com/zmops/iot/domain/device/DevicesGroups.java
|
Java
|
gpl-3.0
| 432
|
package com.zmops.iot.domain.device;
import lombok.Data;
import javax.persistence.Entity;
import javax.persistence.Id;
import javax.persistence.Table;
import java.time.LocalDateTime;
/**
* @author yefei
**/
@Data
@Table(name = "event_trigger_record")
@Entity
public class EventTriggerRecord {
@Id
private Long id;
private LocalDateTime createTime;
private String eventName;
private String eventValue;
private String deviceId;
private Long tenantId;
private String key;
}
|
2301_81045437/zeus-iot
|
zeus-common/src/main/java/com/zmops/iot/domain/device/EventTriggerRecord.java
|
Java
|
gpl-3.0
| 515
|
package com.zmops.iot.domain.device;
import lombok.Data;
import javax.persistence.Entity;
import javax.persistence.Id;
import javax.persistence.Table;
import java.time.LocalDateTime;
/**
* @author yefei
**/
@Data
@Table(name = "scenes_trigger_record")
@Entity
public class ScenesTriggerRecord {
@Id
private Long id;
private LocalDateTime createTime;
private String ruleName;
private Long ruleId;
private Long tenantId;
private String triggerType;
private Long triggerUser;
}
|
2301_81045437/zeus-iot
|
zeus-common/src/main/java/com/zmops/iot/domain/device/ScenesTriggerRecord.java
|
Java
|
gpl-3.0
| 519
|
package com.zmops.iot.domain.device;
import lombok.Data;
import lombok.EqualsAndHashCode;
import javax.persistence.Entity;
import javax.persistence.Id;
import javax.persistence.Table;
import java.time.LocalDateTime;
/**
* @author yefei
**/
@EqualsAndHashCode(callSuper = false)
@Data
@Table(name = "service_execute_record")
@Entity
public class ServiceExecuteRecord {
@Id
private Long id;
private LocalDateTime createTime;
private String serviceName;
private String deviceId;
private String param;
private Long tenantId;
private String executeType;
private Long executeUser;
private Long executeRuleId;
}
|
2301_81045437/zeus-iot
|
zeus-common/src/main/java/com/zmops/iot/domain/device/ServiceExecuteRecord.java
|
Java
|
gpl-3.0
| 660
|
package com.zmops.iot.domain.device;
import lombok.Data;
import lombok.EqualsAndHashCode;
import javax.persistence.Entity;
import javax.persistence.Table;
/**
* @author yefei
**/
@EqualsAndHashCode(callSuper = false)
@Data
@Table(name = "sys_usrgrp_devicegrp")
@Entity
public class SysUserGrpDevGrp {
Long userGroupId;
Long deviceGroupId;
}
|
2301_81045437/zeus-iot
|
zeus-common/src/main/java/com/zmops/iot/domain/device/SysUserGrpDevGrp.java
|
Java
|
gpl-3.0
| 354
|
package com.zmops.iot.domain.device;
import com.zmops.iot.domain.BaseEntity;
import lombok.*;
import javax.persistence.Entity;
import javax.persistence.Id;
import javax.persistence.Table;
/**
* @author yefei
**/
@EqualsAndHashCode(callSuper = false)
@Data
@Builder
@NoArgsConstructor
@AllArgsConstructor
@Table(name = "tag")
@Entity
public class Tag extends BaseEntity {
@Id
private Long id;
private String sid;
private String tag;
private String value;
private Long templateId;
}
|
2301_81045437/zeus-iot
|
zeus-common/src/main/java/com/zmops/iot/domain/device/Tag.java
|
Java
|
gpl-3.0
| 515
|
package com.zmops.iot.domain.messages;
import com.zmops.iot.domain.messages.MailSetting;
import lombok.Data;
import javax.validation.constraints.NotNull;
/**
* @author yefei
**/
@Data
public class MailParam {
@NotNull
private String host;
@NotNull
private Integer port;
@NotNull
private String account;
@NotNull
private String password;
@NotNull
private String sender;
private Integer ssl;
private Integer tls;
@NotNull(groups = Test.class)
private String receiver;
@NotNull
private String severity;
@NotNull
private Integer silent;
public interface Test {
}
public MailSetting getSettings() {
return MailSetting.builder()
.host(host)
.password(password)
.port(port)
.account(account)
.sender(sender)
.ssl(ssl)
.tls(tls)
.severity(severity)
.silent(silent)
.build();
}
}
|
2301_81045437/zeus-iot
|
zeus-common/src/main/java/com/zmops/iot/domain/messages/MailParam.java
|
Java
|
gpl-3.0
| 1,042
|
package com.zmops.iot.domain.messages;
import lombok.AllArgsConstructor;
import lombok.Builder;
import lombok.Data;
import lombok.NoArgsConstructor;
import javax.persistence.Entity;
import javax.persistence.Id;
import javax.persistence.Table;
@Data
@Builder
@NoArgsConstructor
@AllArgsConstructor
@Entity
@Table(name = "mail_setting")
public class MailSetting {
@Id
private Integer id;
private String host;
private Integer port;
private String account;
private String password;
private String sender;
private Integer ssl;
private Integer tls;
private String severity;
private Integer silent;
private Long tenantId;
public boolean sslAvailable() {
return ssl != null && ssl == 1;
}
public boolean tlsAvailable() {
return tls != null && tls == 1;
}
}
|
2301_81045437/zeus-iot
|
zeus-common/src/main/java/com/zmops/iot/domain/messages/MailSetting.java
|
Java
|
gpl-3.0
| 844
|
package com.zmops.iot.domain.messages;
import lombok.AllArgsConstructor;
import lombok.Builder;
import lombok.Data;
import lombok.NoArgsConstructor;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
/**
* @author: yefei
**/
@Data
@Builder
@NoArgsConstructor
@AllArgsConstructor
public class MessageBody {
private String msg;
private String type;
private List<Long> to;
private Map<String, Object> body;
private boolean persist = false;
public void addBody(String k, Object v) {
if (this.body == null) {
this.body = new HashMap<>();
}
this.body.put(k, v);
}
}
|
2301_81045437/zeus-iot
|
zeus-common/src/main/java/com/zmops/iot/domain/messages/MessageBody.java
|
Java
|
gpl-3.0
| 651
|
package com.zmops.iot.domain.messages;
import lombok.Data;
import lombok.EqualsAndHashCode;
import javax.persistence.Entity;
import javax.persistence.Id;
import javax.persistence.Table;
/**
* @author yefei
*/
@EqualsAndHashCode(callSuper = false)
@Data
@Entity
@Table(name = "messages")
public class Messages {
@Id
private Integer id;
private Integer classify;
private String title;
private String content;
private Long clock;
private String module;
private Integer readed;
private Long userId;
}
|
2301_81045437/zeus-iot
|
zeus-common/src/main/java/com/zmops/iot/domain/messages/Messages.java
|
Java
|
gpl-3.0
| 540
|
package com.zmops.iot.domain.messages;
import lombok.AllArgsConstructor;
import lombok.Builder;
import lombok.Data;
import lombok.NoArgsConstructor;
import javax.persistence.Entity;
import javax.persistence.Id;
import javax.persistence.Table;
import java.time.LocalDateTime;
/**
* @author yefei
*/
@Data
@Builder
@NoArgsConstructor
@AllArgsConstructor
@Entity
@Table(name = "notice_record")
public class NoticeRecord {
@Id
private Integer recordId;
private Long userId;
private String problemId;
private Integer noticeType;
private String noticeStatus;
private String noticeMsg;
private LocalDateTime creatTime;
private String alarmInfo;
private String receiveAccount;
}
|
2301_81045437/zeus-iot
|
zeus-common/src/main/java/com/zmops/iot/domain/messages/NoticeRecord.java
|
Java
|
gpl-3.0
| 717
|
package com.zmops.iot.domain.messages;
import lombok.AllArgsConstructor;
import lombok.Builder;
import lombok.Data;
import lombok.NoArgsConstructor;
/**
* @author yefei
**/
@Data
@Builder
@AllArgsConstructor
@NoArgsConstructor
public class NoticeResult {
private NoticeStatus status;
private String msg;
/**
* 告警信息
*/
private String alarmInfo;
/**
* 接收账号
*/
private String receiveAccount;
public static NoticeResult skipped() {
return NoticeResult.builder()
.status(NoticeStatus.skipped).build();
}
public static NoticeResult success() {
return NoticeResult.builder()
.status(NoticeStatus.success).build();
}
public static NoticeResult success(String alarmInfo, String receiveAccount) {
return NoticeResult.builder()
.status(NoticeStatus.success).
alarmInfo(alarmInfo).
receiveAccount(receiveAccount).build();
}
public static NoticeResult failed(String error) {
return NoticeResult.builder()
.status(NoticeStatus.failed)
.msg(error).build();
}
public static NoticeResult failed(String error, String alarmInfo, String receiveAccount) {
return NoticeResult.builder()
.status(NoticeStatus.failed).
alarmInfo(alarmInfo).
receiveAccount(receiveAccount)
.msg(error).build();
}
public enum NoticeStatus {
skipped, success, failed;
}
}
|
2301_81045437/zeus-iot
|
zeus-common/src/main/java/com/zmops/iot/domain/messages/NoticeResult.java
|
Java
|
gpl-3.0
| 1,610
|
package com.zmops.iot.domain.product;
import com.zmops.iot.domain.BaseEntity;
import lombok.Data;
import lombok.EqualsAndHashCode;
import javax.persistence.Entity;
import javax.persistence.Id;
import javax.persistence.Table;
/**
* @author nantian created at 2021/8/3 20:08
* <p>
* 产品
*/
@EqualsAndHashCode(callSuper = false)
@Data
@Entity
@Table(name = "product")
public class Product extends BaseEntity {
@Id
private Long productId;
private Long groupId;
private String name;
private String type;
private String manufacturer;
private String model;
private String remark;
private String productCode;
private String zbxId;
private Long tenantId;
private String icon;
}
|
2301_81045437/zeus-iot
|
zeus-common/src/main/java/com/zmops/iot/domain/product/Product.java
|
Java
|
gpl-3.0
| 744
|
package com.zmops.iot.domain.product;
import com.fasterxml.jackson.annotation.JsonProperty;
import com.zmops.iot.domain.BaseEntity;
import lombok.Data;
import lombok.EqualsAndHashCode;
import javax.persistence.Entity;
import javax.persistence.Id;
import javax.persistence.Table;
import java.util.Objects;
/**
* @author nantian created at 2021/8/5 13:03
*/
@EqualsAndHashCode(callSuper = false)
@Data
@Entity
@Table(name = "product_attribute")
public class ProductAttribute extends BaseEntity {
@Id
private Long attrId; //属性ID
@JsonProperty("attrName")
private String name; // 属性名称
private String key; // 属性唯一Key
private String units; // 单位 0 3 才有
private String source; // 来源
private String remark; // 备注
private String valueType;
private Long depAttrId;
private String productId; // 产品ID
private String zbxId; // Zabbix itemId
private Long templateId;//继承的ID
private Integer delay;
private String unit;
private String valuemapid;
}
|
2301_81045437/zeus-iot
|
zeus-common/src/main/java/com/zmops/iot/domain/product/ProductAttribute.java
|
Java
|
gpl-3.0
| 1,063
|
package com.zmops.iot.domain.product;
import com.fasterxml.jackson.annotation.JsonProperty;
import com.zmops.iot.domain.BaseEntity;
import lombok.Data;
import lombok.EqualsAndHashCode;
import javax.persistence.Entity;
import javax.persistence.Id;
import javax.persistence.Table;
/**
* @author nantian created at 2021/8/5 13:03
*/
@EqualsAndHashCode(callSuper = false)
@Data
@Entity
@Table(name = "product_attribute_event")
public class ProductAttributeEvent extends BaseEntity {
@Id
private Long attrId; //属性ID
@JsonProperty("attrName")
private String name; // 属性名称
private String key; // 属性唯一Key
private String units; // 单位 0 3 才有
private Byte eventLevel;
private String remark; // 备注
private String valueType;
private String productId; // 产品ID
private String zbxId; // Zabbix itemId
private Long templateId;//继承的ID
private String source; // 来源
private Integer delay;
private String unit;
private String valuemapid;
private Long depAttrId;
}
|
2301_81045437/zeus-iot
|
zeus-common/src/main/java/com/zmops/iot/domain/product/ProductAttributeEvent.java
|
Java
|
gpl-3.0
| 1,080
|
package com.zmops.iot.domain.product;
import com.zmops.iot.domain.BaseEntity;
import lombok.Data;
import lombok.EqualsAndHashCode;
import javax.persistence.Entity;
import javax.persistence.Id;
import javax.persistence.Table;
/**
* @author nantian created at 2021/9/15 1:02
*/
@EqualsAndHashCode(callSuper = false)
@Data
@Entity
@Table(name = "product_event")
public class ProductEvent extends BaseEntity {
@Id
private Long eventRuleId;
private String eventRuleName;
private String eventLevel;
private String expLogic;
private String classify;
private String eventNotify;
private Long tenantId;
private String status;
private String remark;
private Integer taskId;
private Integer triggerType;
}
|
2301_81045437/zeus-iot
|
zeus-common/src/main/java/com/zmops/iot/domain/product/ProductEvent.java
|
Java
|
gpl-3.0
| 755
|
package com.zmops.iot.domain.product;
import lombok.Getter;
import lombok.Setter;
import javax.persistence.Entity;
import javax.persistence.Id;
import javax.persistence.Table;
/**
* @author nantian created at 2021/8/11 17:02
*/
@Getter
@Setter
@Entity
@Table(name = "product_event_relation")
public class ProductEventRelation {
@Id
private Long id;
private Long eventRuleId;
private String relationId;
private String zbxId;
private String inherit;
private String status;
private String remark;
}
|
2301_81045437/zeus-iot
|
zeus-common/src/main/java/com/zmops/iot/domain/product/ProductEventRelation.java
|
Java
|
gpl-3.0
| 539
|
package com.zmops.iot.domain.product;
import lombok.Data;
import lombok.EqualsAndHashCode;
import javax.persistence.Entity;
import javax.persistence.Table;
/**
* @author yefei
**/
@EqualsAndHashCode(callSuper = false)
@Data
@Entity
@Table(name = "product_event_service")
public class ProductEventService {
private Long eventRuleId;
private Long serviceId;
private String deviceId;
private String executeDeviceId;
}
|
2301_81045437/zeus-iot
|
zeus-common/src/main/java/com/zmops/iot/domain/product/ProductEventService.java
|
Java
|
gpl-3.0
| 437
|
package com.zmops.iot.domain.product;
import lombok.Data;
import javax.persistence.Entity;
import javax.persistence.Id;
import javax.persistence.Table;
/**
* @author yefei
* <p>
* 触发器 时间 表达式 函数
*/
@Data
@Entity
@Table(name = "product_event_time_interval")
public class ProductEventTimeInterval {
@Id
private Long eventTimeId;
private Long eventRuleId;
private String startTime;
private String endTime;
private String dayOfWeeks;
}
|
2301_81045437/zeus-iot
|
zeus-common/src/main/java/com/zmops/iot/domain/product/ProductEventTimeInterval.java
|
Java
|
gpl-3.0
| 489
|
package com.zmops.iot.domain.product;
import lombok.Data;
import lombok.EqualsAndHashCode;
import javax.persistence.Entity;
import javax.persistence.Id;
import javax.persistence.Table;
/**
* @author yefei
**/
@EqualsAndHashCode(callSuper = false)
@Data
@Entity
@Table(name = "product_service")
public class ProductService {
@Id
private Long id;
private String name;
private String mark;
private String remark;
private String async;
}
|
2301_81045437/zeus-iot
|
zeus-common/src/main/java/com/zmops/iot/domain/product/ProductService.java
|
Java
|
gpl-3.0
| 464
|
package com.zmops.iot.domain.product;
import lombok.Data;
import lombok.EqualsAndHashCode;
import javax.persistence.Entity;
import javax.persistence.Id;
import javax.persistence.Table;
/**
* @author yefei
**/
@EqualsAndHashCode(callSuper = false)
@Data
@Entity
@Table(name = "product_service_param")
public class ProductServiceParam {
@Id
private Long id;
private Long serviceId;
private String name;
private String key;
private String remark;
private String value;
private String deviceId;
}
|
2301_81045437/zeus-iot
|
zeus-common/src/main/java/com/zmops/iot/domain/product/ProductServiceParam.java
|
Java
|
gpl-3.0
| 535
|
package com.zmops.iot.domain.product;
import lombok.Getter;
import lombok.Setter;
import javax.persistence.Entity;
import javax.persistence.Id;
import javax.persistence.Table;
/**
* @author nantian created at 2021/8/11 17:02
*/
@Getter
@Setter
@Entity
@Table(name = "product_service_relation")
public class ProductServiceRelation {
@Id
private Long id;
private Long serviceId;
private String relationId;
private String inherit;
}
|
2301_81045437/zeus-iot
|
zeus-common/src/main/java/com/zmops/iot/domain/product/ProductServiceRelation.java
|
Java
|
gpl-3.0
| 461
|
package com.zmops.iot.domain.product;
import com.zmops.iot.domain.BaseEntity;
import lombok.Getter;
import lombok.Setter;
import javax.persistence.Entity;
import javax.persistence.Id;
import javax.persistence.Table;
/**
* @author nantian created at 2021/8/11 17:02
*/
@Getter
@Setter
@Entity
@Table(name = "product_status_function")
public class ProductStatusFunction extends BaseEntity {
@Id
private Long ruleId;
private String ruleFunction;
private Long attrId;
private String ruleCondition;
private Integer ruleStatus;
private String ruleFunctionRecovery;
private String ruleConditionRecovery;
private Long attrIdRecovery;
private String unit;
private String unitRecovery;
}
|
2301_81045437/zeus-iot
|
zeus-common/src/main/java/com/zmops/iot/domain/product/ProductStatusFunction.java
|
Java
|
gpl-3.0
| 739
|
package com.zmops.iot.domain.product;
import lombok.Getter;
import lombok.Setter;
import javax.persistence.Entity;
import javax.persistence.Id;
import javax.persistence.Table;
/**
* @author nantian created at 2021/8/11 17:02
*/
@Getter
@Setter
@Entity
@Table(name = "product_status_function_relation")
public class ProductStatusFunctionRelation {
@Id
private Long id;
private Long ruleId;
private String relationId;
private String inherit;
// 离线触发器ID
private String zbxId;
// 上线触发器ID
private String zbxIdRecovery;
}
|
2301_81045437/zeus-iot
|
zeus-common/src/main/java/com/zmops/iot/domain/product/ProductStatusFunctionRelation.java
|
Java
|
gpl-3.0
| 585
|
package com.zmops.iot.domain.product;
import com.zmops.iot.domain.BaseEntity;
import lombok.Data;
import lombok.EqualsAndHashCode;
import javax.persistence.Entity;
import javax.persistence.Id;
import javax.persistence.Table;
/**
* @author yefei
**/
@EqualsAndHashCode(callSuper = false)
@Data
@Entity
@Table(name = "product_type")
public class ProductType extends BaseEntity {
@Id
private Long id;
private Long pid = 0L;
private String pids;
private String name;
private String remark;
private Long tenantId;
}
|
2301_81045437/zeus-iot
|
zeus-common/src/main/java/com/zmops/iot/domain/product/ProductType.java
|
Java
|
gpl-3.0
| 549
|
package com.zmops.iot.domain.protocol;
import com.zmops.iot.domain.BaseEntity;
import lombok.Data;
import lombok.EqualsAndHashCode;
import javax.persistence.Entity;
import javax.persistence.Id;
import javax.persistence.Table;
/**
* @author yefei
**/
@EqualsAndHashCode(callSuper = false)
@Data
@Entity
@Table(name = "protocol_component")
public class ProtocolComponent extends BaseEntity {
@Id
private Long protocolComponentId;
private String name;
private String effectProxy;
private String status;
private String remark;
private Long tenantId;
private String fileName;
private String uniqueId;
}
|
2301_81045437/zeus-iot
|
zeus-common/src/main/java/com/zmops/iot/domain/protocol/ProtocolComponent.java
|
Java
|
gpl-3.0
| 643
|
package com.zmops.iot.domain.protocol;
import com.zmops.iot.domain.BaseEntity;
import lombok.Data;
import lombok.EqualsAndHashCode;
import javax.persistence.Entity;
import javax.persistence.Id;
import javax.persistence.Table;
/**
* @author yefei
**/
@EqualsAndHashCode(callSuper = false)
@Data
@Entity
@Table(name = "protocol_gateway")
public class ProtocolGateway extends BaseEntity {
@Id
private Long protocolGatewayId;
private String name;
private String protocolType;
private Long protocolServiceId;
private Long protocolComponentId;
private String status;
private String remark;
private Long tenantId;
private Integer qos;
}
|
2301_81045437/zeus-iot
|
zeus-common/src/main/java/com/zmops/iot/domain/protocol/ProtocolGateway.java
|
Java
|
gpl-3.0
| 685
|
package com.zmops.iot.domain.protocol;
import com.zmops.iot.domain.BaseEntity;
import lombok.*;
import javax.persistence.Entity;
import javax.persistence.Table;
/**
* @author yefei
**/
@EqualsAndHashCode(callSuper = false)
@Data
@Entity
@Table(name = "protocol_gateway_mqtt")
@Builder
@NoArgsConstructor
@AllArgsConstructor
public class ProtocolGatewayMqtt {
private Long protocolGatewayId;
private Long protocolComponentId;
private String topic;
}
|
2301_81045437/zeus-iot
|
zeus-common/src/main/java/com/zmops/iot/domain/protocol/ProtocolGatewayMqtt.java
|
Java
|
gpl-3.0
| 470
|
package com.zmops.iot.domain.protocol;
import com.zmops.iot.domain.BaseEntity;
import lombok.Data;
import lombok.EqualsAndHashCode;
import javax.persistence.Entity;
import javax.persistence.Id;
import javax.persistence.Table;
/**
* @author yefei
**/
@EqualsAndHashCode(callSuper = false)
@Data
@Entity
@Table(name = "protocol_service")
public class ProtocolService extends BaseEntity {
@Id
private Long protocolServiceId;
private String name;
private String effectProxy;
private String protocolType;
private String remark;
private Long tenantId;
private String url;
private String ip;
private Integer port;
private Integer msgLength;
private String clientId;
}
|
2301_81045437/zeus-iot
|
zeus-common/src/main/java/com/zmops/iot/domain/protocol/ProtocolService.java
|
Java
|
gpl-3.0
| 723
|
package com.zmops.iot.domain.proxy;
import com.zmops.iot.domain.BaseEntity;
import lombok.Data;
import lombok.EqualsAndHashCode;
import javax.persistence.Entity;
import javax.persistence.Id;
import javax.persistence.Table;
/**
* @author yefei
**/
@EqualsAndHashCode(callSuper = false)
@Data
@Entity
@Table(name = "proxy")
public class Proxy extends BaseEntity {
@Id
private Long id;
private String name;
private String mode = "1";
private String address;
private String remark;
private Integer tlsAccept = 1;
private String zbxId;
private Long tenantId;
}
|
2301_81045437/zeus-iot
|
zeus-common/src/main/java/com/zmops/iot/domain/proxy/Proxy.java
|
Java
|
gpl-3.0
| 612
|
package com.zmops.iot.domain.schedule;
import com.zmops.iot.domain.BaseEntity;
import lombok.Getter;
import lombok.Setter;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.Id;
import javax.persistence.Table;
/**
* @author nantian created at 2021/11/13 11:23
*/
@Getter
@Setter
@Table(name = "task_info")
@Entity
public class Task extends BaseEntity {
@Id
@Column(name = "id", nullable = false)
private Integer id;
private String scheduleType; // 调度类型
private String scheduleConf; // 调度配置,值含义取决于调度类型
private String misfireStrategy; // 调度过期策略
private Integer taskTimeout;
private Integer taskFailRetryCount;
private String triggerStatus; // 调度状态:DISABLE-停止,ENABLE-运行
private Long triggerLastTime; // 上次调度时间
private Long triggerNextTime;
private String remark;
private String executorParam;
}
|
2301_81045437/zeus-iot
|
zeus-common/src/main/java/com/zmops/iot/domain/schedule/Task.java
|
Java
|
gpl-3.0
| 1,016
|
package com.zmops.iot.domain.sys;
import lombok.AllArgsConstructor;
import lombok.Builder;
import lombok.Data;
import lombok.NoArgsConstructor;
import javax.persistence.Entity;
import javax.persistence.Id;
import javax.persistence.Table;
/**
* @author yefei
**/
@Data
@Table(name = "session")
@Entity
@Builder
@NoArgsConstructor
@AllArgsConstructor
public class Session {
@Id
private Integer id;
private String key;
private String value;
}
|
2301_81045437/zeus-iot
|
zeus-common/src/main/java/com/zmops/iot/domain/sys/Session.java
|
Java
|
gpl-3.0
| 465
|
package com.zmops.iot.domain.sys;
import com.zmops.iot.constant.IdTypeConsts;
import com.zmops.iot.domain.BaseEntity;
import lombok.Data;
import lombok.EqualsAndHashCode;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.Id;
import javax.persistence.Table;
import java.io.Serializable;
/**
* @author nantian created at 2021/8/1 20:51
*/
@EqualsAndHashCode(callSuper = false)
@Table(name = "sys_config")
@Entity
@Data
public class SysConfig extends BaseEntity implements Serializable {
private static final long serialVersionUID = 1L;
@Id
@GeneratedValue(generator = IdTypeConsts.ID_SNOW)
private Long id;
/**
* 名称
*/
private String name;
/**
* 属性编码标识
*/
private String code;
/**
* 是否是字典中的值
*/
private String dictFlag;
/**
* 字典类型的编码
*/
private Long dictTypeId;
/**
* 属性值,如果是字典中的类型,则为dict的code
*/
private String value;
/**
* 备注
*/
private String remark;
/**
* 是否可修改 ENABLE DISABLE
*/
private String status;
}
|
2301_81045437/zeus-iot
|
zeus-common/src/main/java/com/zmops/iot/domain/sys/SysConfig.java
|
Java
|
gpl-3.0
| 1,208
|
package com.zmops.iot.domain.sys;
import com.zmops.iot.constant.IdTypeConsts;
import com.zmops.iot.domain.BaseEntity;
import lombok.Data;
import lombok.EqualsAndHashCode;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.Id;
import javax.persistence.Table;
import java.io.Serializable;
/**
* <p>
* 基础字典
* </p>
*/
@EqualsAndHashCode(callSuper = false)
@Table(name = "sys_dict")
@Entity
@Data
public class SysDict extends BaseEntity implements Serializable {
private static final long serialVersionUID = 1L;
/**
* 字典id
*/
@Id
@GeneratedValue(generator = IdTypeConsts.ID_SNOW)
private Long dictId;
/**
* 所属字典类型的id
*/
private Long dictTypeId;
/**
* 字典编码
*/
private String code;
/**
* 字典名称
*/
private String name;
/**
* 状态
*/
private String status;
/**
* 排序
*/
private Integer sort;
/**
* 字典的描述
*/
private String remark;
private String groups;
}
|
2301_81045437/zeus-iot
|
zeus-common/src/main/java/com/zmops/iot/domain/sys/SysDict.java
|
Java
|
gpl-3.0
| 1,108
|
package com.zmops.iot.domain.sys;
import com.zmops.iot.constant.IdTypeConsts;
import com.zmops.iot.domain.BaseEntity;
import lombok.Data;
import lombok.EqualsAndHashCode;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.Id;
import javax.persistence.Table;
import java.io.Serializable;
/**
* <p>
* 字典类型表
* </p>
*/
@EqualsAndHashCode(callSuper = false)
@Table(name = "sys_dict_type")
@Entity
@Data
public class SysDictType extends BaseEntity implements Serializable {
private static final long serialVersionUID = 1L;
/**
* 字典类型id
*/
@Id
@GeneratedValue(generator = IdTypeConsts.ID_SNOW)
private Long dictTypeId;
/**
* 字典类型编码
*/
private String code;
/**
* 字典类型名称
*/
private String name;
/**
* 字典描述
*/
private String remark;
/**
* 是否是系统字典,Y-是,N-否
*/
private String systemFlag = "N";
/**
* 状态
*/
private String status;
/**
* 排序
*/
private Integer sort;
}
|
2301_81045437/zeus-iot
|
zeus-common/src/main/java/com/zmops/iot/domain/sys/SysDictType.java
|
Java
|
gpl-3.0
| 1,134
|
package com.zmops.iot.domain.sys;
import com.zmops.iot.constant.IdTypeConsts;
import com.zmops.iot.domain.BaseEntity;
import lombok.Data;
import lombok.EqualsAndHashCode;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.Id;
import javax.persistence.Table;
/**
* @author nantian created at 2021/8/2 1:20
*/
@EqualsAndHashCode(callSuper = false)
@Data
@Table(name = "sys_menu")
@Entity
public class SysMenu extends BaseEntity {
@Id
@GeneratedValue(generator = IdTypeConsts.ID_SNOW)
private Long menuId;
/**
* 菜单编号
*/
private String code;
/**
* 菜单父编号
*/
private String pcode;
/**
* 当前菜单的所有父菜单编号
*/
private String pcodes;
/**
* 菜单名称
*/
private String name;
/**
* 菜单图标
*/
private String icon;
/**
* url地址
*/
private String url;
/**
* 菜单排序号
*/
private Integer sort;
/**
* 菜单层级
*/
private Integer levels;
/**
* 是否是菜单(字典)
*/
private String menuFlag;
/**
* 备注
*/
private String remark;
/**
* 菜单状态(字典)
*/
private String status;
/**
* 是否超级管理员菜单
*/
private String adminFlag;
}
|
2301_81045437/zeus-iot
|
zeus-common/src/main/java/com/zmops/iot/domain/sys/SysMenu.java
|
Java
|
gpl-3.0
| 1,389
|
package com.zmops.iot.domain.sys;
import com.zmops.iot.constant.IdTypeConsts;
import com.zmops.iot.domain.BaseEntity;
import lombok.Data;
import lombok.EqualsAndHashCode;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.Id;
import javax.persistence.Table;
/**
* @author nantian created at 2021/7/30 23:29
*/
@EqualsAndHashCode(callSuper = false)
@Data
@Entity
@Table(name = "sys_role")
public class SysRole extends BaseEntity {
@Id
@GeneratedValue(generator = IdTypeConsts.ID_SNOW)
Long roleId;
String name;
String remark;
}
|
2301_81045437/zeus-iot
|
zeus-common/src/main/java/com/zmops/iot/domain/sys/SysRole.java
|
Java
|
gpl-3.0
| 603
|
package com.zmops.iot.domain.sys;
import lombok.Data;
import lombok.EqualsAndHashCode;
import javax.persistence.Entity;
import javax.persistence.Table;
/**
* @author yefei
* data 2021/8/3
**/
@EqualsAndHashCode(callSuper = false)
@Data
@Entity
@Table(name = "sys_role_menu")
public class SysRoleMenu {
Long roleId;
Long menuId;
}
|
2301_81045437/zeus-iot
|
zeus-common/src/main/java/com/zmops/iot/domain/sys/SysRoleMenu.java
|
Java
|
gpl-3.0
| 346
|