Compare commits

..

No commits in common. "master" and "v1.6.6" have entirely different histories.

125 changed files with 6841 additions and 7214 deletions

1
.gitignore vendored
View File

@ -1,4 +1,3 @@
/ypkcache
/BDWareProjectDir /BDWareProjectDir
/defaultLog/ /defaultLog/
/ContractDB /ContractDB

View File

@ -4,7 +4,6 @@ plugins {
} }
mainClassName = 'org.bdware.server.CMHttpServer' mainClassName = 'org.bdware.server.CMHttpServer'
apply from: '../spotless.gradle'
application { application {
@ -35,31 +34,18 @@ dependencies {
implementation project(":cm") implementation project(":cm")
implementation project(":mockjava") implementation project(":mockjava")
implementation project(":front-base") implementation project(":front-base")
implementation project(":consistency-sdk")
implementation 'io.prometheus:simpleclient_httpserver:0.12.0' implementation 'io.prometheus:simpleclient_httpserver:0.12.0'
implementation 'org.hyperic.sigar:sigar:1.6.4' implementation 'org.knowhowlab.osgi:sigar:1.6.5_01'
implementation 'io.grpc:grpc-all:1.43.1' implementation 'io.grpc:grpc-all:1.43.1'
implementation 'org.apache.velocity:velocity-engine-core:2.3' implementation 'org.apache.velocity:velocity-engine-core:2.3'
implementation 'com.nimbusds:nimbus-jose-jwt:9.10' implementation 'com.nimbusds:nimbus-jose-jwt:9.10'
implementation 'org.bdware.doip:doip-sdk:1.5.6'
implementation 'org.bdware.doip:doip-audit-tool:1.5.4'
implementation 'org.bdware.doip:bdosclient:0.1.0'
implementation fileTree(dir: 'lib', include: '*.jar')
testImplementation 'junit:junit:4.13.2' testImplementation 'junit:junit:4.13.2'
implementation 'io.netty:netty-tcnative-boringssl-static:2.0.59.Final'
implementation 'io.netty:netty-tcnative-boringssl-static:2.0.59.Final-linux-aarch_64-fedora'
// implementation 'io.netty:netty-tcnative-boringssl-static:2.0.59.Final'
// implementation 'io.netty:netty-tcnative-boringssl-static:2.0.59.Final'
// implementation 'io.netty:netty-tcnative-boringssl-static:2.0.59.Final'
// implementation 'io.netty:netty-tcnative-boringssl-static:2.0.59.Final'
} }
compileJava { compileJava {
options.compilerArgs << "-Xlint:unchecked" options.compilerArgs << "-Xlint:unchecked"
} }
repositories {
mavenCentral()
}
jar { jar {
String libs = '' String libs = ''
configurations.runtimeClasspath.each { configurations.runtimeClasspath.each {
@ -91,9 +77,6 @@ task copyScript(type: Copy) {
include 'cmstop.sh' include 'cmstop.sh'
include 'cmconfig.json.template' include 'cmconfig.json.template'
include 'killContracts.sh' include 'killContracts.sh'
include 'genKeyAndCMConfig.sh'
include 'cmvar.json'
include 'log4j2.properties'
} }
into "./build/output" into "./build/output"
println("copyScript done !") println("copyScript done !")
@ -124,12 +107,7 @@ task copyDynamicLibrary(type: Copy) {
into './build/output/dynamicLibrary' into './build/output/dynamicLibrary'
} }
task copyCustomPlugin(type: Copy, dependsOn: [":custom-plugin:jar"]) { task copyLibs(type: Copy, dependsOn: ["copyScript", 'copySsl']) {
from '../custom-plugin/build/libs/custom-plugin.jar'
into "./build/output/libs/"
}
task copyLibs(type: Copy, dependsOn: ["copyScript", 'copySsl', 'copyCustomPlugin']) {
from configurations.runtimeClasspath from configurations.runtimeClasspath
into "./build/output/libs/" into "./build/output/libs/"
} }
@ -172,6 +150,11 @@ task copyDockerfile(type: Copy) {
into "./build/" into "./build/"
} }
//task copyCP(type: Copy, dependsOn: ":cp:buildBundle") {
// from "../cp/build/output"
// into "./build/output"
//}
task copyKeys(type: Copy) { task copyKeys(type: Copy) {
from "./keys" from "./keys"
into "./build/output/keys" into "./build/output/keys"

View File

@ -1,80 +1,11 @@
# 配置项 # 配置项
## wsPluginActions: WS端,包括contractManagerFrameHandler和CMHttpHandler
## clientToAgentPlugins: client -> cluster 包括MasterClientFrameHandler
## clientToClusterPlugins:[], client -> NodeCenterClientHandler
## tcpPlugins:tcp 包括TcpserverFrameHandler
## 示例格式 # 配置说明
## 使用字符串分割如需添加多项在agent-backend/script/config.json.template里修改如:
```json
{
"cmi": "",
"debug": "",
"disableDoRepo": false,
"disableLocalLhs": false,
"doipCertPath": "",
"doipLhsAddress": "",
"doipPort": -1,
"doipUserHandle": "",
"enableEventPersistence": false,
"enableSsl": "./ssl/chained.pem:./ssl/domain.pem",
"ip": "127.0.0.1",
"isLAN": true,
"overwrite": false,
"servicePort": 21030,
"textFileSuffixes": ".yjs,.json,.txt,.css,.js,.html,.md,.conf,.csv",
"withBdledgerClient": "./runnable/bdledger_mac",
"withBdledgerServer": false,
"consistencyPlugins": "./libs/custom-plugin.jar",
"startContract": [],
"datachainConf": "021.node.internetapi.cn:21121"
}
```
## consistencyPlugins 配置
下述四项插件使用字符串分割如需添加多项以逗号分隔在cmconfig.json里修改如:
``````
"consistencyPlugins": "xxx/xxx.jar,xxx/xxx.jar"
``````
## 通讯插件配置
下述四项插件使用字符串分割如需添加多项在cmconfig.json里修改如:
`````` ``````
"wsPluginActions": "org.bdware.metering.MeteringAction" "wsPluginActions": "org.bdware.metering.MeteringAction"
`````` ``````
1. wsPluginActions: WS端,包括contractManagerFrameHandler和CMHttpHandler
2. clientToAgentPlugins: client -> cluster 包括MasterClientFrameHandler
3. clientToClusterPlugins:[], client -> NodeCenterClientHandler
4. tcpPlugins:tcp 包括TcpserverFrameHandler
## startContract配置说明
其中startConfig.json为json数组结构格式如下
```json
[
{
"path": "./BDWareProjectDir/publicCompiled/xxx.ypk",
"owner": "",
"killBeforeStart": "",
"createParam": {}
},
{
}
]
```
path为必填配置项。表示启动的ypk的路径。
owner为可选配置不填时使用NodeManger的key作为Owner。
killBeforeStart为可选配置填写kill的合约名称。
createParam为可选配置。表示合约的启动参数。
## datachainConf 配置说明
1.针对Window Docker/Mac Docker
可使用`"datachainConf":"host.docker.internal:2401"`进行配置。
2.针对Linux Docker可通过查看`docker 0`的网卡IP进行设置。
如:`"datachainConf":"172.16.10.1:2401"`
3.如果是在同一dockercompose.yml下启动可以使用
`"datachainConf":"bdledger:2401"`进行配置。

View File

@ -1,22 +1,19 @@
{ {
"cmi":"", "ip": "127.0.0.1",
"debug":"", "servicePort": 21030,
"disableDoRepo":false, "isLAN" : true,
"disableLocalLhs":false, "disableDoRepo": false,
"doipCertPath":"", "doipPort": 21032,
"doipLhsAddress":"", "doipCertPath": "",
"doipPort":21032, "doipUserHandle": "",
"doipUserHandle":"", "doipLhsAddress": "",
"enableEventPersistence":false, "withBdledgerServer": false,
"enableSsl":"./ssl/chained.pem:./ssl/domain.pem", "withBdledgerClient": "",
"ip":"127.0.0.1", "enableEventPersistence": false,
"isLAN":true, "enableSsl": "./ssl/chained.pem:./ssl/domain.pem",
"overwrite":false, "textFileSuffixes": ".yjs,.json,.txt,.css,.js,.html,.md,.conf,.csv",
"servicePort":21030, "wsPluginActions": "org.bdware.metering.MeteringAction",
"textFileSuffixes":".yjs,.json,.txt,.css,.js,.html,.md,.conf,.csv", "clientToAgentPlugins": "",
"withBdledgerClient":"./runnable/bdledger_mac", "clientToClusterPlugins": "",
"withBdledgerServer":false, "tcpPlugins": ""
"consistencyPlugins": "./libs/custom-plugin.jar",
"datachainConf": "_LEDGERHOSTCONF"
} }

View File

@ -18,7 +18,7 @@ fi
# ps -ef | grep java | grep bdserver | grep CM | awk '{print $2}' | xargs kill -9 # ps -ef | grep java | grep bdserver | grep CM | awk '{print $2}' | xargs kill -9
java -Dfile.encoding=UTF-8 -Djava.library.path="./dynamicLibrary" -Dlog4j.configurationFile=./log4j2.properties -cp "./libs/*:bdagent.jar" org.bdware.server.CMHttpServer 1>/dev/null 2>/dev/null & java -Dfile.encoding=UTF-8 -Djava.library.path="./dynamicLibrary" -cp "./libs/*:bdagent.jar" org.bdware.server.CMHttpServer 1>./log/cm.log 2>./log/cm.err &
#-Xmx3550m -Xms3550m -Xmn2g #-Xmx3550m -Xms3550m -Xmn2g
#-XX:+UseConcMarkSweepGC -XX:CMSFullGCsBeforeCompaction=5 #-XX:+UseConcMarkSweepGC -XX:CMSFullGCsBeforeCompaction=5
# 以下可启用https/wss其中./ssl/xxx.pfx为ssl证书的路径:后面的123456是密码。 # 以下可启用https/wss其中./ssl/xxx.pfx为ssl证书的路径:后面的123456是密码。

View File

@ -1,3 +0,0 @@
{
"_LEDGERHOSTCONF": "localhost:2401"
}

View File

@ -1,5 +0,0 @@
#!/bin/bash
echo "generate manger.key, manager.keypair!"
java -cp cp/libs:cp/yjs.jar org.bdware.sc.SM2Helper generateKeyToFile
echo "generate CMConfig!"
java -cp cp/libs/*:cp/yjs.jar org.bdware.sc.SM2Helper generateCMConfig

View File

@ -1,40 +0,0 @@
filter.threshold.type=ThresholdFilter
filter.threshold.level=debug
appender.console.type=Console
appender.console.name=STDOUT
appender.console.layout.type=PatternLayout
appender.console.layout.pattern=%highlight{[%-5p] %d{HH:mm:ss.SSS} %m (%F:%L)[%M]%n}{FATAL=Bright Red,ERROR=Red,WARN=Yellow,INFO=Green,DEBUG=Blue,TRACE=White}
appender.logrolling.type=RollingFile
appender.logrolling.name=infoLogFile
appender.logrolling.append=true
appender.logrolling.fileName=./log/cm.log
appender.logrolling.filePattern=./log/cm-%i.log
appender.logrolling.layout.type=PatternLayout
appender.logrolling.layout.pattern=[%-5p] %d{HH:mm:ss.SSS} %m (%F:%L)[%M]%n
appender.logrolling.policies.type = Policies
appender.logrolling.policies.size.type = SizeBasedTriggeringPolicy
appender.logrolling.policies.size.size = 100MB
appender.logrolling.strategy.type = DefaultRolloverStrategy
appender.logrolling.strategy.max = 5
appender.errrolling.type=RollingFile
appender.errrolling.name=errorLogFile
appender.errrolling.append=true
appender.errrolling.fileName=./log/cm.err
appender.errrolling.filePattern=./log/cm-%i.err
appender.errrolling.layout.type=PatternLayout
appender.errrolling.layout.pattern=[%-5p] %d{HH:mm:ss.SSS} %m (%F:%L)[%M]%n
appender.errrolling.policies.type = Policies
appender.errrolling.policies.size.type = SizeBasedTriggeringPolicy
appender.errrolling.policies.size.size = 100MB
appender.errrolling.strategy.type = DefaultRolloverStrategy
appender.errrolling.strategy.max = 5
rootLogger.level=info
rootLogger.appenderRef.stdout.ref=STDOUT
rootLogger.appenderRef.errorFile.ref=errorLogFile
rootLogger.appenderRef.errorFile.level=error
rootLogger.appenderRef.infoFile.ref=infoLogFile
rootLogger.appenderRef.infoFile.level=info
rootLogger.appenderRef.log.ref=log

View File

@ -1,5 +1,3 @@
#/bin/bash #/bin/bash
scp -P 222 ./build/bdserver.zip dev@47.95.110.68:/data/public/releases/bdcontract/$1/ scp -P 222 ./build/bdserver.zip dev@47.95.110.68:/data/public/releases/bdcontract/$1/
#In_235813

View File

@ -38,12 +38,12 @@ public class HeartBeatUtil {
public synchronized void schedule(TimerTask checkAliveTask, int delay, int period) { public synchronized void schedule(TimerTask checkAliveTask, int delay, int period) {
try { try {
if (recordedFuture.containsKey(checkAliveTask)) { if (!recordedFuture.containsKey(checkAliveTask)) {
cancel(checkAliveTask); ScheduledFuture<?> future =
ContractManager.scheduledThreadPool.scheduleWithFixedDelay(
checkAliveTask, delay, period, TimeUnit.MILLISECONDS);
recordedFuture.put(checkAliveTask, future);
} }
ScheduledFuture<?> future = ContractManager.scheduledThreadPool
.scheduleWithFixedDelay(checkAliveTask, delay, period, TimeUnit.MILLISECONDS);
recordedFuture.put(checkAliveTask, future);
} catch (Exception e) { } catch (Exception e) {
e.printStackTrace(); e.printStackTrace();
} }

View File

@ -24,8 +24,10 @@ public class ContractExecuteInfo implements Serializable {
public String invokeID; // TODO public String invokeID; // TODO
public ContractExecType type; public ContractExecType type;
public transient PriorityQueue<ContractRequest> queue; // contract request public transient PriorityQueue<ContractRequest> queue; // contract request
public transient Map<Integer, String> uniReqIDMap = new ConcurrentHashMap<>(); // 用于请求 public transient Map<Integer, String> uniReqIDMap =
public transient Map<Integer, ResultCallback> resultMap = new ConcurrentHashMap<>(); // 用于请求 new ConcurrentHashMap<>(); // 用于请求
public transient Map<Integer, ResultCallback> resultMap =
new ConcurrentHashMap<>(); // 用于请求
public transient PriorityQueue<TransRecord> trans_queue; // transRecord public transient PriorityQueue<TransRecord> trans_queue; // transRecord
private String contractID; private String contractID;
private boolean isPrivate = false; private boolean isPrivate = false;
@ -42,14 +44,10 @@ public class ContractExecuteInfo implements Serializable {
} }
public void init() { public void init() {
if (queue == null) if (queue == null) queue = new PriorityQueue<ContractRequest>();
queue = new PriorityQueue<ContractRequest>(); if (trans_queue == null) trans_queue = new PriorityQueue<TransRecord>();
if (trans_queue == null) if (uniReqIDMap == null) uniReqIDMap = new ConcurrentHashMap<Integer, String>();
trans_queue = new PriorityQueue<TransRecord>(); if (resultMap == null) resultMap = new ConcurrentHashMap<Integer, ResultCallback>();
if (uniReqIDMap == null)
uniReqIDMap = new ConcurrentHashMap<Integer, String>();
if (resultMap == null)
resultMap = new ConcurrentHashMap<Integer, ResultCallback>();
} }
public int getLastExeSeq() { public int getLastExeSeq() {
@ -58,15 +56,15 @@ public class ContractExecuteInfo implements Serializable {
public void setLastExeSeq(int lastExeSeq) { public void setLastExeSeq(int lastExeSeq) {
this.lastExeSeq.set(lastExeSeq); this.lastExeSeq.set(lastExeSeq);
if (KeyValueDBUtil.instance.containsKey(CMTables.LastExeSeq.toString(), contractID)) { // 如果现在是Stable模式就同步刷到磁盘 if (KeyValueDBUtil.instance.containsKey(
KeyValueDBUtil.instance.setValue(CMTables.LastExeSeq.toString(), contractID, CMTables.LastExeSeq.toString(), contractID)) { // 如果现在是Stable模式就同步刷到磁盘
lastExeSeq + ""); KeyValueDBUtil.instance.setValue(
CMTables.LastExeSeq.toString(), contractID, lastExeSeq + "");
} }
} }
public boolean isSequent(int a) { public boolean isSequent(int a) {
if (a - lastExeSeq.get() == 1) if (a - lastExeSeq.get() == 1) return true;
return true;
return false; return false;
} }
@ -87,8 +85,7 @@ public class ContractExecuteInfo implements Serializable {
} }
public String getPubKeyPath() { public String getPubKeyPath() {
if (!isPrivate) if (!isPrivate) return null;
return null;
return pubKeyPath; return pubKeyPath;
} }
@ -139,8 +136,7 @@ public class ContractExecuteInfo implements Serializable {
System.out.println("memory=" + (memory == null ? "null" : memory)); System.out.println("memory=" + (memory == null ? "null" : memory));
} }
public boolean isDirectExecute(ContractRequest request, String uniReqID, public boolean isDirectExecute(ContractRequest request, String uniReqID, ResultCallback result) {
ResultCallback result) {
synchronized (this) { synchronized (this) {
if (request.seq < lastExeSeq.get()) { if (request.seq < lastExeSeq.get()) {
if (request.getRequestID().endsWith("mul")) { if (request.getRequestID().endsWith("mul")) {

View File

@ -1,7 +1,5 @@
package org.bdware.server; package org.bdware.server;
import com.google.gson.JsonElement;
import com.google.gson.JsonObject;
import io.netty.bootstrap.ServerBootstrap; import io.netty.bootstrap.ServerBootstrap;
import io.netty.buffer.PooledByteBufAllocator; import io.netty.buffer.PooledByteBufAllocator;
import io.netty.channel.*; import io.netty.channel.*;
@ -17,26 +15,18 @@ import io.netty.handler.ssl.OptionalSslHandler;
import io.netty.handler.ssl.SslContext; import io.netty.handler.ssl.SslContext;
import io.netty.handler.ssl.SslContextBuilder; import io.netty.handler.ssl.SslContextBuilder;
import io.netty.handler.stream.ChunkedWriteHandler; import io.netty.handler.stream.ChunkedWriteHandler;
import io.netty.util.internal.StringUtil;
import io.prometheus.client.exporter.HTTPServer; import io.prometheus.client.exporter.HTTPServer;
import org.apache.commons.io.FileUtils; import org.apache.commons.io.FileUtils;
import org.apache.logging.log4j.Level; import org.apache.logging.log4j.Level;
import org.apache.logging.log4j.LogManager; import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger; import org.apache.logging.log4j.Logger;
import org.apache.logging.log4j.core.config.Configurator; import org.apache.logging.log4j.core.config.Configurator;
import org.bdware.sc.ContractClient; import org.bdware.sc.*;
import org.bdware.sc.ContractManager;
import org.bdware.sc.ContractPort;
import org.bdware.sc.RecoverMechTimeRecorder;
import org.bdware.sc.bean.Contract;
import org.bdware.sc.bean.ContractExecType;
import org.bdware.sc.db.CMTables; import org.bdware.sc.db.CMTables;
import org.bdware.sc.db.KeyValueDBUtil; import org.bdware.sc.db.KeyValueDBUtil;
import org.bdware.sc.db.MultiIndexTimeRocksDBUtil; import org.bdware.sc.db.MultiIndexTimeRocksDBUtil;
import org.bdware.sc.util.ExceptionUtil; import org.bdware.sc.util.ExceptionUtil;
import org.bdware.sdk.consistency.ConsistencyPluginManager;
import org.bdware.server.action.FileActions; import org.bdware.server.action.FileActions;
import org.bdware.server.action.UserManagerAction;
import org.bdware.server.doip.ContractRepositoryMain; import org.bdware.server.doip.ContractRepositoryMain;
import org.bdware.server.http.CMHttpHandler; import org.bdware.server.http.CMHttpHandler;
import org.bdware.server.nodecenter.client.NodeCenterClientHandler; import org.bdware.server.nodecenter.client.NodeCenterClientHandler;
@ -49,22 +39,19 @@ import java.lang.reflect.Field;
import java.net.MalformedURLException; import java.net.MalformedURLException;
import java.net.URL; import java.net.URL;
import java.net.URLClassLoader; import java.net.URLClassLoader;
import java.util.Arrays;
import java.util.Date; import java.util.Date;
import java.util.List;
import java.util.concurrent.TimeUnit; import java.util.concurrent.TimeUnit;
import java.util.concurrent.atomic.AtomicInteger; import java.util.concurrent.atomic.AtomicInteger;
import java.util.regex.Pattern;
public class CMHttpServer { public class CMHttpServer {
private static final Logger LOGGER = LogManager.getLogger(CMHttpServer.class); private static final Logger LOGGER = LogManager.getLogger(CMHttpServer.class);
private static final String CONFIG_PATH = "cmconfig.json"; private static final String CONFIG_PATH = "cmconfig.json";
public static EventLoopGroup workerGroup = new NioEventLoopGroup(); public static EventLoopGroup workerGroup = new NioEventLoopGroup();
public static MultiIndexTimeRocksDBUtil nodeLogDB = new MultiIndexTimeRocksDBUtil( public static MultiIndexTimeRocksDBUtil nodeLogDB =
"./ContractManagerDB", CMTables.LocalNodeLogDB.toString()); new MultiIndexTimeRocksDBUtil(
"./ContractManagerDB", CMTables.LocalNodeLogDB.toString());
public static URLClassLoader pluginLoader; public static URLClassLoader pluginLoader;
private static SslContext sslContext = null; private static SslContext sslContext = null;
private static CMDConf cmdConf;
final String PATH = "/SCIDE/SCExecutor"; final String PATH = "/SCIDE/SCExecutor";
private final int port; private final int port;
@ -73,54 +60,58 @@ public class CMHttpServer {
} }
private static void configServer(CMDConf cmdConf) throws IOException { private static void configServer(CMDConf cmdConf) throws IOException {
GlobalConf.DOAConf doaConf = new GlobalConf.DOAConf(); if (cmdConf.disableDoRepo) {
if (cmdConf.doipPort != -1) { DoConfig.callContractUsingDOI = false;
doaConf.doipAddress = "tcp://" + cmdConf.ip + ":" + cmdConf.doipPort;
} else {
doaConf.doipAddress = "tcp://" + cmdConf.ip + ":" + (cmdConf.servicePort + 2);
} }
if (!StringUtil.isNullOrEmpty(cmdConf.repoDoid)) { GlobalConf.instance.isLAN = cmdConf.isLAN;
doaConf.repoDoid = cmdConf.repoDoid; if (!cmdConf.doipCertPath.isEmpty()) {
String[] conf = cmdConf.doipCertPath.split(":");
// DOAConf.certPath = conf[0];
// DOAConf.certPassword = conf[1];
} }
if (!StringUtil.isNullOrEmpty(cmdConf.repoName)) {
doaConf.repoName = cmdConf.repoName;
}
if (!StringUtil.isNullOrEmpty(cmdConf.lhsAddress)) {
doaConf.lhsAddress = cmdConf.lhsAddress;
}
GlobalConf.initDOAConfig(doaConf);
if (!cmdConf.doipUserHandle.isEmpty()) {
DOAConf.repoDoid = cmdConf.doipUserHandle;
}
if (!cmdConf.doipLhsAddress.isEmpty()) {
DOAConf.lhsAddress = cmdConf.doipLhsAddress;
}
if (cmdConf.withBdledgerServer) { if (cmdConf.withBdledgerServer) {
ContractManager.threadPool ContractManager.threadPool.execute(
.execute(() -> NetworkManager.instance.initP2P(cmdConf.servicePort + 4)); () -> NetworkManager.instance.initP2P(cmdConf.servicePort + 4));
} }
// 可自动运行bdledger可执行文件也可在shell脚步中运行和停止 // 可自动运行bdledger可执行文件也可在shell脚步中运行和停止
if (!cmdConf.withBdledgerClient.isEmpty()) { if (!cmdConf.withBdledgerClient.isEmpty()) {
ContractManager.scheduledThreadPool.schedule(() -> { ContractManager.scheduledThreadPool.schedule(
File ledgerClient = new File(cmdConf.withBdledgerClient); () -> {
LOGGER.debug("canRead=" + ledgerClient.canRead() + " path=" File ledgerClient = new File(cmdConf.withBdledgerClient);
+ ledgerClient.getAbsolutePath()); LOGGER.debug("canRead=" + ledgerClient.canRead() +
try { " path=" + ledgerClient.getAbsolutePath());
Runtime.getRuntime().exec(ledgerClient.getAbsolutePath()); try {
} catch (IOException e) { Runtime.getRuntime().exec(ledgerClient.getAbsolutePath());
LOGGER.warn("start bdledger client failed: " + e.getMessage()); } catch (IOException e) {
} LOGGER.warn("start bdledger client failed: " + e.getMessage());
}, 1, TimeUnit.SECONDS); }
},
1, TimeUnit.SECONDS);
} }
if (cmdConf.enableEventPersistence) { if (cmdConf.enableEventPersistence) {
ContractManager.eventPersistenceEnabled = true; ContractManager.eventPersistenceEnabled = true;
} }
if (!StringUtil.isNullOrEmpty(cmdConf.enableSsl)) { if (!cmdConf.enableSsl.isEmpty()) {
try { try {
String[] filePaths = cmdConf.enableSsl.split(":"); String[] filePaths = cmdConf.enableSsl.split(":");
File chainedFile = new File(filePaths[0]), keyFile = new File(filePaths[1]); File chainedFile = new File(filePaths[0]), keyFile = new File(filePaths[1]);
if (chainedFile.exists() && keyFile.exists()) { if (chainedFile.exists() && keyFile.exists()) {
sslContext = SslContextBuilder.forServer(chainedFile, keyFile) sslContext =
.ciphers(null, SslContextBuilder.forServer(chainedFile, keyFile)
(ciphers, defaultCiphers, supportedCiphers) -> defaultCiphers .ciphers(
.stream().filter(x -> null != x && !x.contains("RC4")) null,
.toArray(String[]::new)) (ciphers, defaultCiphers, supportedCiphers) ->
.build(); defaultCiphers.stream()
.filter(x -> null != x && !x.contains("RC4"))
.toArray(String[]::new))
.build();
LOGGER.info("openssl isAvailable:" + OpenSsl.isAvailable()); LOGGER.info("openssl isAvailable:" + OpenSsl.isAvailable());
} }
} catch (Exception e) { } catch (Exception e) {
@ -140,10 +131,10 @@ public class CMHttpServer {
// plugins // plugins
CMHttpHandler.wsPluginActions = parseStrAsList(cmdConf.wsPluginActions); CMHttpHandler.wsPluginActions = parseStrAsList(cmdConf.wsPluginActions);
TCPClientFrameHandler.clientToAgentPlugins = parseStrAsList(cmdConf.clientToAgentPlugins); TCPClientFrameHandler.clientToAgentPlugins = parseStrAsList(cmdConf.clientToAgentPlugins);
NodeCenterClientHandler.clientToClusterPlugins = NodeCenterClientHandler.clientToClusterPlugins = parseStrAsList(cmdConf.clientToClusterPlugins);
parseStrAsList(cmdConf.clientToClusterPlugins);
org.bdware.units.tcp.TCPClientFrameHandler.tcpPlugins = parseStrAsList(cmdConf.tcpPlugins); org.bdware.units.tcp.TCPClientFrameHandler.tcpPlugins = parseStrAsList(cmdConf.tcpPlugins);
if (!StringUtil.isNullOrEmpty(cmdConf.debug)) {
if (!cmdConf.debug.isEmpty()) {
try { try {
String[] classes = cmdConf.debug.split(","); String[] classes = cmdConf.debug.split(",");
for (String clz : classes) { for (String clz : classes) {
@ -158,101 +149,14 @@ public class CMHttpServer {
LOGGER.warn(e.getMessage()); LOGGER.warn(e.getMessage());
} }
} }
if (cmdConf.datachainConf != null) {
GlobalConf.resetDataChain(cmdConf.datachainConf);
}
if (cmdConf.overwrite) { if (cmdConf.overwrite) {
cmdConf.write(CONFIG_PATH); cmdConf.write(CONFIG_PATH);
} }
} }
private static void startByPath(JsonObject jo) {
String path = jo.get("path").getAsString();
path = findNewestYPK(path);
File f = new File(path);
if (!f.getName().endsWith(".ypk") || !f.exists())
return;
Contract c = new Contract();
c.setScript(f.getAbsolutePath());
c.setType(ContractExecType.Sole);
if (jo.has("owner"))
c.setOwner(jo.get("owner").getAsString());
else
c.setOwner(UserManagerAction.getNodeManager());
if (jo.has("createParam"))
c.setCreateParam(jo.get("createParam"));
ContractManager.instance.startContract(c);
}
private static String findNewestYPK(String path) {
File toParse = new File(path);
if (!toParse.exists()) {
File dir = toParse.getParentFile();
String fileName = toParse.getName();
Pattern pattern = Pattern.compile(fileName);
if (dir.isDirectory() && dir.exists()) {
File[] available = dir.listFiles((f) -> {
String name = f.getName();
return pattern.matcher(name).matches();
});
List<File> result = Arrays.asList(available);
return findNewestFile(result).getAbsolutePath();
}
}
return path;
}
public static File findNewestFile(List<File> files) {
File newestFile = null;
String newestVersion = null;
for (File file : files) {
String fileName = file.getName();
String version = extractVersion(fileName);
if (newestVersion == null || compareVersions(version, newestVersion) > 0) {
newestFile = file;
newestVersion = version;
}
}
return newestFile;
}
private static String extractVersion(String fileName) {
// Assuming the version is between the last '-' and the last '.'
int lastDashIndex = fileName.lastIndexOf('-');
int lastDotIndex = fileName.lastIndexOf('.');
if (lastDashIndex == -1 || lastDotIndex == -1 || lastDashIndex >= lastDotIndex) {
throw new IllegalArgumentException("Invalid file name format: " + fileName);
}
return fileName.substring(lastDashIndex + 1, lastDotIndex);
}
public static int compareVersions(String v1, String v2) {
String[] parts1 = v1.split("\\.");
String[] parts2 = v2.split("\\.");
int length = Math.max(parts1.length, parts2.length);
for (int i = 0; i < length; i++) {
int num1 = i < parts1.length ? Integer.parseInt(parts1[i]) : 0;
int num2 = i < parts2.length ? Integer.parseInt(parts2[i]) : 0;
if (num1 < num2) {
return -1;
}
if (num1 > num2) {
return 1;
}
}
return 0; // Both versions are equal
}
private static String[] parseStrAsList(String str) { private static String[] parseStrAsList(String str) {
if (str == null) { if (str == null) {
return new String[] {}; return new String[]{};
} }
return str.split(","); return str.split(",");
} }
@ -260,7 +164,7 @@ public class CMHttpServer {
private static void addDirToPath(String s) { private static void addDirToPath(String s) {
try { try {
LOGGER.info("add to path: " + s); LOGGER.info("add to path: " + s);
// Field field = ClassLoader.class.getDeclaredField("sys_paths"); // Field field = ClassLoader.class.getDeclaredField("sys_paths");
Field field = ClassLoader.class.getDeclaredField("usr_paths"); Field field = ClassLoader.class.getDeclaredField("usr_paths");
field.setAccessible(true); field.setAccessible(true);
String[] path = (String[]) field.get(null); String[] path = (String[]) field.get(null);
@ -285,7 +189,7 @@ public class CMHttpServer {
if (!confFile.exists() && confTemplate.exists()) { if (!confFile.exists() && confTemplate.exists()) {
FileUtils.copyFile(confTemplate, confFile); FileUtils.copyFile(confTemplate, confFile);
} }
cmdConf = CMDConf.parseFile(CONFIG_PATH); CMDConf cmdConf = CMDConf.parseFile(CONFIG_PATH);
// addDirToPath(new File("./dynamicLibrary").getAbsolutePath()); // addDirToPath(new File("./dynamicLibrary").getAbsolutePath());
@ -304,50 +208,55 @@ public class CMHttpServer {
cmdConf.parseArgs(args); cmdConf.parseArgs(args);
configServer(cmdConf); configServer(cmdConf);
// check default key pair // check default key pair
File keyFile = new File("manager.key"); File keyFile = new File("manager.key");
if (keyFile.exists()) { if (keyFile.exists()) {
try { try {
BufferedReader br = new BufferedReader(new FileReader(keyFile)); BufferedReader br = new BufferedReader(new FileReader(keyFile));
String pubKey = br.readLine(); String pubKey = br.readLine();
String nowManager = KeyValueDBUtil.instance.getValue(CMTables.ConfigDB.toString(), String nowManager =
"__NodeManager__"); KeyValueDBUtil.instance.getValue(
CMTables.ConfigDB.toString(), "__NodeManager__");
// manager.key is used when node manager isn' set // manager.key is used when node manager isn' set
if (null == nowManager || nowManager.isEmpty()) { if (null == nowManager || nowManager.isEmpty()) {
KeyValueDBUtil.instance.setValue(CMTables.ConfigDB.toString(), KeyValueDBUtil.instance.setValue(
"__NodeManager__", pubKey); CMTables.ConfigDB.toString(), "__NodeManager__", pubKey);
KeyValueDBUtil.instance.setValue(CMTables.NodeRole.toString(), pubKey, KeyValueDBUtil.instance.setValue(
CMTables.NodeRole.toString(), pubKey,
"NodeManager,ContractProvider,ContractUser,ContractInstanceManager"); "NodeManager,ContractProvider,ContractUser,ContractInstanceManager");
KeyValueDBUtil.instance.setValue(CMTables.NodeTime.toString(), pubKey, KeyValueDBUtil.instance.setValue(
CMTables.NodeTime.toString(),
pubKey,
Long.toString(new Date().getTime())); Long.toString(new Date().getTime()));
LOGGER.info("set node manager from manager.key"); LOGGER.info("set node manager from manager.key");
} }
} catch (IOException ignored) { } catch (IOException ignored) {
} }
} }
GlobalConf.initIpPort(cmdConf.ip + ":" + cmdConf.servicePort);
// GlobalConf.initMasterAddress(cmdConf.ip + ":" + (cmdConf.servicePort + 1)); start(cmdConf.ip, cmdConf.servicePort, cmdConf);
start(cmdConf.servicePort);
} }
public static void start(int port) throws IOException { public static void start(String ip, int port, CMDConf cmdConf) throws IOException {
LOGGER.info("start server at:" + port); LOGGER.info("start server at:" + port);
GlobalConf.initMasterAddress(ip + ":" + (port + 1));
GlobalConf.initIpPort(ip + ":" + port);
LOGGER.debug("dir:" + new File("./").getAbsolutePath()); LOGGER.debug("dir:" + new File("./").getAbsolutePath());
new CMHttpServer(port).start(); new CMHttpServer(port).start();
// never reach here!! ContractRepositoryMain.start();
} }
/** /**
* port: http & websocket port port+1: tcp port port+2: doip port port+3: prometheus * port: http & websocket port port+1: tcp port port+2: doip port port+3: prometheus
*/ */
private void start() { private void start() {
ConsistencyPluginManager.setContext(new SDKContext());
// EpollEventLoopGroup // EpollEventLoopGroup
// EpollServerSocketChannel // EpollServerSocketChannel
// ContractManager.reconnectPort = (port - 18000) * 30 + 1630; // ContractManager.reconnectPort = (port - 18000) * 30 + 1630;
// if (ContractManager.reconnectPort < 0) ContractManager.reconnectPort = 1630; // if (ContractManager.reconnectPort < 0) ContractManager.reconnectPort = 1630;
File[] pluginJar = File[] pluginJar = new File("./pluginLib/")
new File("./pluginLib/").listFiles(pathname -> pathname.getName().endsWith(".jar")); .listFiles(pathname -> pathname.getName().endsWith(".jar"));
URL[] urls; URL[] urls;
if (pluginJar != null && pluginJar.length > 0) { if (pluginJar != null && pluginJar.length > 0) {
urls = new URL[pluginJar.length]; urls = new URL[pluginJar.length];
@ -360,7 +269,7 @@ public class CMHttpServer {
} }
} }
} else { } else {
urls = new URL[] {}; urls = new URL[]{};
} }
pluginLoader = new URLClassLoader(urls, CMHttpServer.class.getClassLoader()); pluginLoader = new URLClassLoader(urls, CMHttpServer.class.getClassLoader());
if (port >= 18000 && port < 18100) { if (port >= 18000 && port < 18100) {
@ -368,37 +277,39 @@ public class CMHttpServer {
} else { } else {
ContractManager.cPort = new ContractPort(1615); ContractManager.cPort = new ContractPort(1615);
} }
ContractRepositoryMain.start();
final CMHttpHandler serverHandler = new CMHttpHandler(); final CMHttpHandler serverHandler = new CMHttpHandler();
EventLoopGroup bossGroup = new NioEventLoopGroup(1); EventLoopGroup bossGroup = new NioEventLoopGroup(1);
// NettyConnectServerHandler trafficSharp = NettyConnectServerHandler trafficSharp =
// new NettyConnectServerHandler(new AtomicInteger(0)); new NettyConnectServerHandler(new AtomicInteger(0));
try { try {
ServerBootstrap b1 = new ServerBootstrap(); ServerBootstrap b1 = new ServerBootstrap();
b1.option(ChannelOption.ALLOCATOR, PooledByteBufAllocator.DEFAULT); b1.option(ChannelOption.ALLOCATOR, PooledByteBufAllocator.DEFAULT);
b1.group(bossGroup, workerGroup).channel(NioServerSocketChannel.class) b1.group(bossGroup, workerGroup)
.localAddress(port).childHandler(new ChannelInitializer<SocketChannel>() { .channel(NioServerSocketChannel.class)
@Override .localAddress(port)
protected void initChannel(SocketChannel arg0) { .childHandler(
if (sslContext != null) { new ChannelInitializer<SocketChannel>() {
arg0.pipeline().addLast(new OptionalSslHandler(sslContext)); @Override
} protected void initChannel(SocketChannel arg0) {
arg0.pipeline()// .addLast(trafficSharp) if (sslContext != null) {
.addLast(new HttpServerCodec()) arg0.pipeline().addLast(new OptionalSslHandler(sslContext));
.addLast(new HttpObjectAggregator(10 * 1024 * 1024)) }
.addLast(new WebSocketServerProtocolHandler(PATH, null, true)) arg0.pipeline()
.addLast(new ChunkedWriteHandler()).addLast(serverHandler) .addLast(trafficSharp)
.addLast(new ContractManagerFrameHandler()); .addLast(new HttpServerCodec())
} .addLast(new HttpObjectAggregator(10 * 1024 * 1024))
}); .addLast(
new WebSocketServerProtocolHandler(
PATH, null, true))
.addLast(new ChunkedWriteHandler())
.addLast(serverHandler)
.addLast(new ContractManagerFrameHandler());
}
});
final Channel ch = b1.bind(port).sync().channel(); final Channel ch = b1.bind(port).sync().channel();
LOGGER.debug("[CMHttpServer] listen master port at:" + port); LOGGER.debug("[CMHttpServer] listen master port at:" + port);
new HTTPServer(port + 3); new HTTPServer(port + 3);
NetworkManager.instance.initTCP(port + 1, workerGroup); NetworkManager.instance.initTCP(port + 1, workerGroup);
loadStartContractConfiguration();
ch.closeFuture().sync(); ch.closeFuture().sync();
} catch (Exception e) { } catch (Exception e) {
e.printStackTrace(); e.printStackTrace();
@ -409,37 +320,10 @@ public class CMHttpServer {
} }
} }
private void loadStartContractConfiguration() {
if (cmdConf.startContract != null && !cmdConf.startContract.isEmpty()) {
ContractManager.scheduledThreadPool.schedule(() -> {
for (JsonElement je : cmdConf.startContract) {
try {
JsonObject jo = je.getAsJsonObject();
if (!jo.has("path"))
continue;
if (!jo.has("owner"))
jo.addProperty("owner", UserManagerAction.getNodeManager());
if (jo.has("killBeforeStart")) {
ContractManager.instance
.stopContract(jo.get("killBeforeStart").getAsString());
}
if (jo.get("path").getAsString().startsWith("@")) {
jo.addProperty("bcoId", jo.get("path").getAsString().substring(1));
ContractRepositoryMain.currentHandler.startUsingJsonObject(jo);
} else {
startByPath(jo);
}
} catch (Exception e) {
e.printStackTrace();
}
}
}, 10, TimeUnit.SECONDS);
}
}
@Sharable @Sharable
public static class NettyConnectServerHandler extends ChannelInboundHandlerAdapter { public static class NettyConnectServerHandler extends ChannelInboundHandlerAdapter {
public NettyConnectServerHandler(AtomicInteger connectNum) {} public NettyConnectServerHandler(AtomicInteger connectNum) {
}
@Override @Override
public void channelRegistered(ChannelHandlerContext ctx) throws Exception { public void channelRegistered(ChannelHandlerContext ctx) throws Exception {

View File

@ -21,7 +21,7 @@ public class CongestionControl {
public static int maxMasterServerLoad = 0; public static int maxMasterServerLoad = 0;
// configurations // configurations
public static int maxHttpConnCount = 1000; public static int maxHttpConnCount = 100;
// TODO remove sync call of executeOnOthreNode // TODO remove sync call of executeOnOthreNode
public static void httpCControl(ChannelHandlerContext ctx) { public static void httpCControl(ChannelHandlerContext ctx) {
@ -47,6 +47,7 @@ public class CongestionControl {
jo.addProperty("slaveConn", slaveCounter.get()); jo.addProperty("slaveConn", slaveCounter.get());
jo.addProperty("slaveQueue", masterProxyLoad.get()); jo.addProperty("slaveQueue", masterProxyLoad.get());
jo.addProperty("masterQueue", masterServerLoad.get()); jo.addProperty("masterQueue", masterServerLoad.get());
jo.addProperty("maxConnCount", maxHttpConnCount); jo.addProperty("maxConnCount", maxHttpConnCount);
jo.addProperty("httpMaxQueue", currHttpMax); jo.addProperty("httpMaxQueue", currHttpMax);
jo.addProperty("slaveMaxQueue", maxMasterProxyLoad); jo.addProperty("slaveMaxQueue", maxMasterProxyLoad);

View File

@ -0,0 +1,6 @@
package org.bdware.server;
public class DOAConf {
public static String lhsAddress;
public static String repoDoid;
}

View File

@ -1,7 +1,6 @@
package org.bdware.server; package org.bdware.server;
import com.google.common.util.concurrent.ListenableFuture; import com.google.common.util.concurrent.ListenableFuture;
import com.google.gson.JsonArray;
import com.google.gson.JsonObject; import com.google.gson.JsonObject;
import com.google.gson.JsonParser; import com.google.gson.JsonParser;
import com.google.gson.reflect.TypeToken; import com.google.gson.reflect.TypeToken;
@ -67,13 +66,12 @@ public class GRPCPool implements ChainOpener {
RocksDB hash2Data; RocksDB hash2Data;
private String dataNodeIP; private String dataNodeIP;
private int dataNodePort; private int dataNodePort;
static final String DBDir = "ContractManagerDB/GRPCPool";
// public static OnHashCallback callback; //for CM write on chain // public static OnHashCallback callback; //for CM write on chain
GRPCPool() { GRPCPool() {
logIndex = new LenVarTimeSerialIndex("./" + DBDir + "/hashToData.index", 20); logIndex = new LenVarTimeSerialIndex("./log/hashToData.index", 20);
requestID2Hash = openDB("./" + DBDir + "/requestIDToHash", "req2Hash"); requestID2Hash = openDB("./log/requestIDToHash", "req2Hash");
hash2Data = openDB("./" + DBDir + "/hashToData", "hash2Data"); hash2Data = openDB("./log/hashToData", "hash2Data");
contractName2LogIndex = new HashMap<>(); contractName2LogIndex = new HashMap<>();
instances = new ArrayList<>(); instances = new ArrayList<>();
for (int i = 0; i < WORKER_COUNT; ++i) { for (int i = 0; i < WORKER_COUNT; ++i) {
@ -113,12 +111,15 @@ public class GRPCPool implements ChainOpener {
params.put("DOI", "86.5000.470/" + sucFix); params.put("DOI", "86.5000.470/" + sucFix);
params.put("Description", "DataWare Contract Info"); params.put("Description", "DataWare Contract Info");
params.put("Interface", ""); params.put("Interface", "");
params.put("Address", params.put(
"Address",
"http://39.106.6.6:8080/SCIDE/CMManager?action=queryDataByHash&hash=" + hash); "http://39.106.6.6:8080/SCIDE/CMManager?action=queryDataByHash&hash=" + hash);
byte[] signature; byte[] signature;
try { try {
signature = SM2Util.sign(GlobalConf.instance.keyPair.getPrivateKeyParameter(), signature =
origin.getBytes()); SM2Util.sign(
GlobalConf.instance.keyPair.getPrivateKeyParameter(),
origin.getBytes());
} catch (Exception e) { } catch (Exception e) {
signature = "no signature".getBytes(); signature = "no signature".getBytes();
} }
@ -128,8 +129,14 @@ public class GRPCPool implements ChainOpener {
HttpPostForm.postForm(url, params); HttpPostForm.postForm(url, params);
} }
private static Line wrapperLine(OnHashCallback cb, String from, String to, String data, private static Line wrapperLine(
String requestID, String contractName, String namedLedger) { OnHashCallback cb,
String from,
String to,
String data,
String requestID,
String contractName,
String namedLedger) {
Line l = new Line(); Line l = new Line();
l.cb = cb; l.cb = cb;
l.from = from; l.from = from;
@ -142,15 +149,24 @@ public class GRPCPool implements ChainOpener {
} }
public static void updateContractInfo(String contractName, long times, long traffic) { public static void updateContractInfo(String contractName, long times, long traffic) {
KeyValueDBUtil.instance.setValue(CMTables.ContractInfo.toString(), contractName + "-Times", KeyValueDBUtil.instance.setValue(
times + ""); CMTables.ContractInfo.toString(), contractName + "-Times", times + "");
KeyValueDBUtil.instance.setValue(CMTables.ContractInfo.toString(), KeyValueDBUtil.instance.setValue(
contractName + "-Traffic", traffic + ""); CMTables.ContractInfo.toString(), contractName + "-Traffic", traffic + "");
} }
public static void addLocalContractLog(String action, String contractID, String contractName, public static void addLocalContractLog(
String pubKey, String function, long startTime, long costTime, long totalGas, String action,
long executionGas, long extraGas, Map<String, String> logType) { String contractID,
String contractName,
String pubKey,
String function,
long startTime,
long costTime,
long totalGas,
long executionGas,
long extraGas,
Map<String, String> logType) {
// if (disable) return; // if (disable) return;
JsonObject jo = new JsonObject(); JsonObject jo = new JsonObject();
jo.addProperty("action", action); jo.addProperty("action", action);
@ -174,7 +190,8 @@ public class GRPCPool implements ChainOpener {
} }
@Override @Override
protected void finalize() {} protected void finalize() {
}
public void reloadConf(String confFile) { public void reloadConf(String confFile) {
loadConf(confFile); loadConf(confFile);
@ -204,14 +221,25 @@ public class GRPCPool implements ChainOpener {
} }
@Override @Override
public void writeToChain(OnHashCallback callback, String from, String to, String data, public void writeToChain(
String requestID, String namedLedger) { OnHashCallback callback,
String from,
String to,
String data,
String requestID,
String namedLedger) {
writeToChainWithContract(callback, from, to, data, requestID, null, namedLedger); writeToChainWithContract(callback, from, to, data, requestID, null, namedLedger);
} }
@Override @Override
public void writeToChainWithContract(OnHashCallback cb, String from, String to, String data, public void writeToChainWithContract(
String requestID, String contractName, String namedLedger) { OnHashCallback cb,
String from,
String to,
String data,
String requestID,
String contractName,
String namedLedger) {
Line l = wrapperLine(cb, from, to, data, requestID, contractName, namedLedger); Line l = wrapperLine(cb, from, to, data, requestID, contractName, namedLedger);
WorkerThread t = getNextWorkerThread(); WorkerThread t = getNextWorkerThread();
if (t != null) { if (t != null) {
@ -219,30 +247,9 @@ public class GRPCPool implements ChainOpener {
} }
} }
@Override
public JsonObject getLedgerParams() {
JsonObject jo = new JsonObject();
JsonArray jsonArray = new JsonArray();
String conf = GlobalConf.instance.datachainConf;
conf = conf.replaceAll(",", "\n");
Scanner sc = new Scanner(new ByteArrayInputStream(conf.getBytes()));
while (sc.hasNextLine()) {
String str = sc.nextLine();
String[] ipAndPort = str.split(":");
String ip = ipAndPort[0];
int port = Integer.parseInt(ipAndPort[1]);
JsonObject client = new JsonObject();
client.addProperty("ip", ip);
client.addProperty("port", port);
jsonArray.add(client);
}
jo.add("nodes", jsonArray);
return jo;
}
@Override @Override
public void reRegister(String doid) { public void reRegister(String doid) {
// TODO just success //TODO just success
// throw new IllegalStateException("TODO"); // throw new IllegalStateException("TODO");
} }
@ -251,8 +258,13 @@ public class GRPCPool implements ChainOpener {
} }
@Override @Override
public void writeContractResultToLocalAndLedger(String result, ContractClient client, public void writeContractResultToLocalAndLedger(
ContractRequest contractRequest, OnHashCallback cb, long start, long time) { String result,
ContractClient client,
ContractRequest contractRequest,
OnHashCallback cb,
long start,
long time) {
ContractResultLine l = new ContractResultLine(); ContractResultLine l = new ContractResultLine();
l.client = client; l.client = client;
l.contractRequest = contractRequest; l.contractRequest = contractRequest;
@ -309,14 +321,21 @@ public class GRPCPool implements ChainOpener {
ret.put("action", "onQueryHashByReqID"); ret.put("action", "onQueryHashByReqID");
if (args.has("requestID")) { if (args.has("requestID")) {
try { try {
ret.put("data", new String( ret.put(
requestID2Hash.get(args.get("requestID").getAsString().getBytes()))); "data",
new String(
requestID2Hash.get(
args.get("requestID").getAsString().getBytes())));
} catch (Exception e) { } catch (Exception e) {
ret.put("data", "Match failed! " + "Can't find hash by this requestID " ret.put(
+ args.get("requestID").getAsString()); "data",
"Match failed! "
+ "Can't find hash by this requestID "
+ args.get("requestID").getAsString());
} }
} else { } else {
ret.put("data", ret.put(
"data",
"Can't find hash by this requestID " + args.get("requestID").getAsString()); "Can't find hash by this requestID " + args.get("requestID").getAsString());
} }
resultCallback.onResult(JsonUtil.toJson(ret)); resultCallback.onResult(JsonUtil.toJson(ret));
@ -343,16 +362,13 @@ public class GRPCPool implements ChainOpener {
index = createIndexIfNotExist(args.get("contractName").getAsString()); index = createIndexIfNotExist(args.get("contractName").getAsString());
} }
// 根据事务类型查找 //根据事务类型查找
else if (args.has("type")) { else if (args.has("type")) {
index = createIndexIfNotExist(args.get("type").getAsString()); index = createIndexIfNotExist(args.get("type").getAsString());
} else } else index = logIndex;
index = logIndex;
List<byte[]> result; List<byte[]> result;
if (offset < 0) if (offset < 0) result = index.requestLast(count);
result = index.requestLast(count); else result = index.request(offset, count);
else
result = index.request(offset, count);
for (byte[] data : result) { for (byte[] data : result) {
long date = HashUtil.bytes2Long(data); long date = HashUtil.bytes2Long(data);
String hash = HashUtil.byteArray2Str(data, 8); String hash = HashUtil.byteArray2Str(data, 8);
@ -381,10 +397,12 @@ public class GRPCPool implements ChainOpener {
ret.put("action", "onQueryDataByHash"); ret.put("action", "onQueryDataByHash");
if (args.has("hash")) { if (args.has("hash")) {
try { try {
JsonObject jo = JsonParser JsonObject jo =
.parseString(new String( JsonParser.parseString(
hash2Data.get(args.get("hash").getAsString().getBytes()))) new String(
.getAsJsonObject(); hash2Data.get(
args.get("hash").getAsString().getBytes())))
.getAsJsonObject();
jo.addProperty("action", "onQueryDataByHash"); jo.addProperty("action", "onQueryDataByHash");
resultCallback.onResult(JsonUtil.toJson(jo)); resultCallback.onResult(JsonUtil.toJson(jo));
return; return;
@ -417,16 +435,19 @@ public class GRPCPool implements ChainOpener {
ret.put("action", "onQueryDataByHash"); ret.put("action", "onQueryDataByHash");
if (args.has("hash")) { if (args.has("hash")) {
try { try {
JsonObject jo = JsonParser JsonObject jo =
.parseString(new String( JsonParser.parseString(
hash2Data.get(args.get("hash").getAsString().getBytes()))) new String(
.getAsJsonObject(); hash2Data.get(
args.get("hash").getAsString().getBytes())))
.getAsJsonObject();
jo.addProperty("action", "onQueryDataByHash"); jo.addProperty("action", "onQueryDataByHash");
resultCallback.onResult(JsonUtil.toJson(jo)); resultCallback.onResult(JsonUtil.toJson(jo));
return; return;
} catch (Exception e) { } catch (Exception e) {
e.printStackTrace(); e.printStackTrace();
ret.put("data", ret.put(
"data",
"!!! " + "Can't find data by hash " + args.get("hash").getAsString()); "!!! " + "Can't find data by hash " + args.get("hash").getAsString());
} }
} else { } else {
@ -442,8 +463,7 @@ public class GRPCPool implements ChainOpener {
LenVarTimeSerialIndex index = null; LenVarTimeSerialIndex index = null;
if (args.has("contractName")) if (args.has("contractName"))
index = createIndexIfNotExist(args.get("contractName").getAsString()); index = createIndexIfNotExist(args.get("contractName").getAsString());
if (index == null) if (index == null) index = logIndex;
index = logIndex;
ret.put("count", index.size() + ""); ret.put("count", index.size() + "");
resultCallback.onResult(JsonUtil.toJson(ret)); resultCallback.onResult(JsonUtil.toJson(ret));
} }
@ -470,8 +490,11 @@ public class GRPCPool implements ChainOpener {
obj.put("hash", hash); obj.put("hash", hash);
obj.put("date", date); obj.put("date", date);
try { try {
obj.put("data", JsonParser.parseString( obj.put(
new String(hash2Data.get(args.get("hash").getAsString().getBytes())))); "data",
JsonParser.parseString(
new String(
hash2Data.get(args.get("hash").getAsString().getBytes()))));
} catch (Exception e) { } catch (Exception e) {
e.printStackTrace(); e.printStackTrace();
} }
@ -502,8 +525,11 @@ public class GRPCPool implements ChainOpener {
obj.put("hash", hash); obj.put("hash", hash);
obj.put("date", date); obj.put("date", date);
try { try {
obj.put("data", shortStr( obj.put(
new String(hash2Data.get(args.get("hash").getAsString().getBytes())))); "data",
shortStr(
new String(
hash2Data.get(args.get("hash").getAsString().getBytes()))));
} catch (Exception e) { } catch (Exception e) {
e.printStackTrace(); e.printStackTrace();
} }
@ -513,10 +539,8 @@ public class GRPCPool implements ChainOpener {
} }
private String shortStr(String str) { private String shortStr(String str) {
if (str != null && str.length() > 50) if (str != null && str.length() > 50) return str.substring(0, 50);
return str.substring(0, 50); else return str;
else
return str;
} }
@Action(async = true, userPermission = 1L << 24) @Action(async = true, userPermission = 1L << 24)
@ -529,7 +553,7 @@ public class GRPCPool implements ChainOpener {
RocksIterator iter = hash2Data.newIterator(); RocksIterator iter = hash2Data.newIterator();
iter.seekToFirst(); iter.seekToFirst();
List<String> hashes = new ArrayList<>(); List<String> hashes = new ArrayList<>();
for (; iter.isValid();) { for (; iter.isValid(); ) {
iter.value(); iter.value();
hashes.add(new String(iter.value())); hashes.add(new String(iter.value()));
iter.next(); iter.next();
@ -538,8 +562,7 @@ public class GRPCPool implements ChainOpener {
List<Long> times = new ArrayList<>(); List<Long> times = new ArrayList<>();
for (String str : hashes) { for (String str : hashes) {
Long time = getDataTime(str); Long time = getDataTime(str);
if (time < 0) if (time < 0) continue;
continue;
times.add(time); times.add(time);
memoryIndex.put(time, str); memoryIndex.put(time, str);
} }
@ -557,7 +580,8 @@ public class GRPCPool implements ChainOpener {
try { try {
String obj = new String(hash2Data.get(key.getBytes())); String obj = new String(hash2Data.get(key.getBytes()));
Map<String, String> parsedObj = Map<String, String> parsedObj =
JsonUtil.fromJson(obj, new TypeToken<Map<String, String>>() {}.getType()); JsonUtil.fromJson(obj, new TypeToken<Map<String, String>>() {
}.getType());
String data = parsedObj.get("data"); String data = parsedObj.get("data");
int len = "1575452533275".length(); int len = "1575452533275".length();
@ -574,8 +598,9 @@ public class GRPCPool implements ChainOpener {
private synchronized LenVarTimeSerialIndex createIndexIfNotExist(String contractName) { private synchronized LenVarTimeSerialIndex createIndexIfNotExist(String contractName) {
LenVarTimeSerialIndex index = contractName2LogIndex.get(contractName); LenVarTimeSerialIndex index = contractName2LogIndex.get(contractName);
if (index == null) { if (index == null) {
index = new LenVarTimeSerialIndex( index =
"./" + DBDir + "/hashByContract/" + contractName + ".index", 20); new LenVarTimeSerialIndex(
"./log/hashByContract/" + contractName + ".index", 20);
contractName2LogIndex.put(contractName, index); contractName2LogIndex.put(contractName, index);
} }
return index; return index;
@ -600,7 +625,8 @@ public class GRPCPool implements ChainOpener {
static SecureRandom random = new SecureRandom((System.currentTimeMillis() + "").getBytes()); static SecureRandom random = new SecureRandom((System.currentTimeMillis() + "").getBytes());
boolean exit = false; boolean exit = false;
WorkerThread() {} WorkerThread() {
}
public static byte[] getRandomByte(int len) { public static byte[] getRandomByte(int len) {
Random random = new Random(); Random random = new Random();
@ -614,7 +640,7 @@ public class GRPCPool implements ChainOpener {
public void run() { public void run() {
while (true) { while (true) {
// System.out.println("[GRPCPool] for circleing"); // System.out.println("[GRPCPool] for circleing");
Line l = uploadContent.poll(); Line l = uploadContent.poll();
if (l != null) { if (l != null) {
if (l instanceof ContractResultLine) { if (l instanceof ContractResultLine) {
@ -663,50 +689,65 @@ public class GRPCPool implements ChainOpener {
ListenableFuture<LedgerProto.SendTransactionResponse> ret2; ListenableFuture<LedgerProto.SendTransactionResponse> ret2;
if (l.ledgerName != null && !l.ledgerName.equals("")) { if (l.ledgerName != null && !l.ledgerName.equals("")) {
ret2 = client.sendTransaction(l.ledgerName, CommonProto.TransactionType.MESSAGE, ret2 =
l.from, random.nextLong(), l.to, client.sendTransaction(
l.data.getBytes(StandardCharsets.UTF_8)); l.ledgerName,
CommonProto.TransactionType.MESSAGE,
l.from,
random.nextLong(),
l.to,
l.data.getBytes(StandardCharsets.UTF_8));
} else { } else {
ret2 = client.sendTransaction(LEDGER_NAME, CommonProto.TransactionType.MESSAGE, ret2 =
l.from, random.nextLong(), l.to, client.sendTransaction(
l.data.getBytes(StandardCharsets.UTF_8)); LEDGER_NAME,
CommonProto.TransactionType.MESSAGE,
l.from, random.nextLong(),
l.to,
l.data.getBytes(StandardCharsets.UTF_8));
} }
if (ret2 != null) if (ret2 != null)
ret2.addListener(new Runnable() { ret2.addListener(
@Override new Runnable() {
public void run() { @Override
try { public void run() {
ByteString hash = ret2.get().getHash(); try {
String hashStr; ByteString hash = ret2.get().getHash();
if (hash == null) { String hashStr;
hash = ByteString.copyFrom(getRandomByte(20)); if (hash == null) {
hashStr = HashUtil.byteArray2Str(hash.toByteArray()); hash = ByteString.copyFrom(getRandomByte(20));
LOGGER.info("generate fake hash: " + hashStr); hashStr = HashUtil.byteArray2Str(hash.toByteArray());
} else { LOGGER.info("generate fake hash: " + hashStr);
hashStr = HashUtil.byteArray2Str(hash.toByteArray()); } else {
} hashStr = HashUtil.byteArray2Str(hash.toByteArray());
if (!l.data.startsWith("MockTransaction_")) { }
if (null != l.cb) { if (!l.data.startsWith("MockTransaction_")) {
l.cb.publishHash(l.requestID, hashStr); if (null != l.cb) {
l.cb.publishHash(l.requestID, hashStr);
}
instance.logIndex.index(HashUtil.str16ToBytes(hashStr));
if (null != l.contractName) {
LenVarTimeSerialIndex index =
instance.createIndexIfNotExist(
l.contractName);
index.index(HashUtil.str16ToBytes(hashStr));
}
instance.hash2Data.put(
hashStr.getBytes(), JsonUtil.toJson(l).getBytes());
instance.requestID2Hash.put(
l.requestID.getBytes(), hashStr.getBytes());
LOGGER.debug(
"put requestID: "
+ l.requestID
+ " hash: "
+ hashStr);
}
} catch (Exception e) {
LOGGER.warn(e.getMessage());
} }
instance.logIndex.index(HashUtil.str16ToBytes(hashStr));
if (null != l.contractName) {
LenVarTimeSerialIndex index =
instance.createIndexIfNotExist(l.contractName);
index.index(HashUtil.str16ToBytes(hashStr));
}
instance.hash2Data.put(hashStr.getBytes(),
JsonUtil.toJson(l).getBytes());
instance.requestID2Hash.put(l.requestID.getBytes(),
hashStr.getBytes());
LOGGER.debug(
"put requestID: " + l.requestID + " hash: " + hashStr);
} }
} catch (Exception e) { },
LOGGER.warn(e.getMessage()); executorService);
}
}
}, executorService);
// ByteString hash = ByteString.copyFrom(new byte[] { 1, 2, 2, 2 }); // ByteString hash = ByteString.copyFrom(new byte[] { 1, 2, 2, 2 });
} catch (Exception e) { } catch (Exception e) {
@ -716,8 +757,8 @@ public class GRPCPool implements ChainOpener {
} }
} }
public Map<String, String> analysisLocalContractLog(String data2, ContractRequest c, public Map<String, String> analysisLocalContractLog(
String detail) { String data2, ContractRequest c, String detail) {
// 本地日志 // 本地日志
JsonObject jo = JsonParser.parseString(data2).getAsJsonObject(); JsonObject jo = JsonParser.parseString(data2).getAsJsonObject();
Map<String, String> logType = new HashMap<>(); Map<String, String> logType = new HashMap<>();
@ -752,7 +793,7 @@ public class GRPCPool implements ChainOpener {
logType.put("branch", "branch log failure"); logType.put("branch", "branch log failure");
} }
} else if (info.equals("Result")) { } else if (info.equals("Result")) {
s = jo.get("result").toString(); s = jo.get("result").getAsString();
s = JsonUtil.toJson(s); s = JsonUtil.toJson(s);
if (s.length() > 2) { if (s.length() > 2) {
s = s.substring(1, s.length() - 1); s = s.substring(1, s.length() - 1);
@ -781,7 +822,7 @@ public class GRPCPool implements ChainOpener {
ContractClient client = l.client; ContractClient client = l.client;
cr = JsonUtil.fromJson(l.data, ContractResult.class); cr = JsonUtil.fromJson(l.data, ContractResult.class);
// updateContractInfo( // updateContractInfo(
// client.getContractName(), client.getTimes(), client.getTraffic()); // client.getContractName(), client.getTimes(), client.getTraffic());
String detail = client.getLogType(l.contractRequest.getAction()); String detail = client.getLogType(l.contractRequest.getAction());
Map<String, String> logType = Map<String, String> logType =
analysisLocalContractLog(l.data, l.contractRequest, detail); analysisLocalContractLog(l.data, l.contractRequest, detail);
@ -807,14 +848,32 @@ public class GRPCPool implements ChainOpener {
// LOGGER.debug("type: " + JsonUtil.toJson(logType) + " | detail: " + // LOGGER.debug("type: " + JsonUtil.toJson(logType) + " | detail: " +
// detail); // detail);
addLocalContractLog("executeContract", contractID, contractName, addLocalContractLog(
l.contractRequest.getPublicKey(), l.contractRequest.getAction(), l.start, "executeContract",
l.costTime, cr.totalGas, cr.executionGas, cr.extraGas, logType); contractID,
contractName,
l.contractRequest.getPublicKey(),
l.contractRequest.getAction(),
l.start,
l.costTime,
cr.totalGas,
cr.executionGas,
cr.extraGas,
logType);
// 929 1277 1448 1417 1507 // 929 1277 1448 1417 1507
if (l.contractRequest.fromContract != null) { if (l.contractRequest.fromContract != null) {
addLocalContractLog("executeContract", contractID, contractName, addLocalContractLog(
l.contractRequest.fromContract, l.contractRequest.getAction(), l.start, "executeContract",
l.costTime, cr.totalGas, cr.executionGas, cr.extraGas, logType); contractID,
contractName,
l.contractRequest.fromContract,
l.contractRequest.getAction(),
l.start,
l.costTime,
cr.totalGas,
cr.executionGas,
cr.extraGas,
logType);
} }
// 1027 1563 1461 1519 1501 // 1027 1563 1461 1519 1501
if (toBDContract || toNamedLedger) { if (toBDContract || toNamedLedger) {
@ -829,17 +888,29 @@ public class GRPCPool implements ChainOpener {
// 1025 1422 1497 1447 1445 // 1025 1422 1497 1447 1445
if (toBDContract) { if (toBDContract) {
Line l1 = wrapperLine(l.cb, l.contractRequest.getPublicKey(), "executeContract", Line l1 =
JsonUtil.toJson(logType), l.contractRequest.getRequestID(), wrapperLine(
contractName, ""); l.cb,
l.contractRequest.getPublicKey(),
"executeContract",
JsonUtil.toJson(logType),
l.contractRequest.getRequestID(),
contractName,
"");
writeChain(l1); writeChain(l1);
} }
// 1424 1421 1443 1160 1611 // 1424 1421 1443 1160 1611
if (toNamedLedger) { if (toNamedLedger) {
for (String name : namedLedger) { for (String name : namedLedger) {
Line l2 = wrapperLine(l.cb, l.contractRequest.getPublicKey(), Line l2 =
"executeContract", JsonUtil.toJson(logType), wrapperLine(
l.contractRequest.getRequestID(), contractName, name); l.cb,
l.contractRequest.getPublicKey(),
"executeContract",
JsonUtil.toJson(logType),
l.contractRequest.getRequestID(),
contractName,
name);
writeChain(l2); writeChain(l2);
} }
} }

View File

@ -17,23 +17,13 @@ import org.zz.gmhelper.SM2KeyPair;
import org.zz.gmhelper.SM2Util; import org.zz.gmhelper.SM2Util;
import java.io.File; import java.io.File;
import java.net.URL;
import java.util.logging.Level; import java.util.logging.Level;
public class GlobalConf { public class GlobalConf {
private static final Logger LOGGER = LogManager.getLogger(GlobalConf.class); private static final Logger LOGGER = LogManager.getLogger(GlobalConf.class);
public static GlobalConf instance = init(); public static GlobalConf instance = init();
public static class DOAConf {
public String doipAddress;
public String lhsAddress = "";
public String repoDoid = "";
public String repoName = "";
}
public DOAConf doaConf;
public String projectDir; // 从configDB读取默认./ProjectDir/ public String projectDir; // 从configDB读取默认./ProjectDir/
// 对于public-->SCIDEProjectDir/public/ // 对于public-->SCIDEProjectDir/public/
// 对于private-->SCIDEProjectDir/private/4567856786789/ // 对于private-->SCIDEProjectDir/private/4567856786789/
@ -50,24 +40,23 @@ public class GlobalConf {
public String publicCompiledDir; public String publicCompiledDir;
public String privateDir; public String privateDir;
public String privateCompiledDir; public String privateCompiledDir;
public String bcoDir;
public String memoryDir; public String memoryDir;
// public String masterAddress; public String masterAddress;
public String ipPort; public String ipPort;
public boolean isLAN = true; public boolean isLAN = true;
private String nodeCenterUrl; // 从ConfigDB读 private String nodeCenterUrl; // 从ConfigDB读
private String nodeCenterWSUrl;
private static GlobalConf init() { private static GlobalConf init() {
java.util.logging.Logger.getLogger(org.bdware.bdledger.api.grpc.Client.class.getName()) java.util.logging.Logger.getLogger(org.bdware.bdledger.api.grpc.Client.class.getName())
.setLevel(Level.OFF); .setLevel(Level.OFF);
Configurator.setLevel("io.netty.handler.codec.http.websocketx.WebSocket08FrameEncoder", Configurator.setLevel(
"io.netty.handler.codec.http.websocketx.WebSocket08FrameEncoder",
org.apache.logging.log4j.Level.OFF); org.apache.logging.log4j.Level.OFF);
Configurator.setLevel("io.netty.handler.codec.http.websocketx.WebSocket08FrameDecoder", Configurator.setLevel(
"io.netty.handler.codec.http.websocketx.WebSocket08FrameDecoder",
org.apache.logging.log4j.Level.OFF); org.apache.logging.log4j.Level.OFF);
Configurator.setLevel("io.netty.handler.codec.http.websocketx.WebSocketServerHandshaker", Configurator.setLevel(
"io.netty.handler.codec.http.websocketx.WebSocketServerHandshaker",
org.apache.logging.log4j.Level.OFF); org.apache.logging.log4j.Level.OFF);
KeyValueDBUtil.setupCM(); KeyValueDBUtil.setupCM();
@ -77,19 +66,29 @@ public class GlobalConf {
try { try {
String dbName = CMTables.ConfigDB.toString(); String dbName = CMTables.ConfigDB.toString();
Class<?> clz = com.sleepycat.je.utilint.Tracer.class;
URL uri = clz.getClassLoader().getResource("com/sleepycat/je/utilint/Tracer.class");
LOGGER.debug(null == uri ? "uri is null!" : uri.getPath());
clz = com.sleepycat.je.log.FileHeader.class;
uri = clz.getClassLoader().getResource("com/sleepycat/je/log/FileHeader.class");
LOGGER.debug(null == uri ? "uri is null!" : uri.getPath());
if (!KeyValueDBUtil.instance.getKeys(dbName).contains("hasInited")) { if (!KeyValueDBUtil.instance.getKeys(dbName).contains("hasInited")) {
KeyValueDBUtil.instance.setValue(dbName, "hasInited", "true"); KeyValueDBUtil.instance.setValue(dbName, "hasInited", "true");
KeyValueDBUtil.instance.setValue(dbName, "projectDir",
new File("./BDWareProjectDir/").getAbsolutePath()); KeyValueDBUtil.instance.setValue(
KeyValueDBUtil.instance.setValue(dbName, "ADSPDir", dbName, "projectDir", new File("./BDWareProjectDir/").getAbsolutePath());
KeyValueDBUtil.instance.setValue(
dbName,
"ADSPDir",
new File("./BDWareProjectDir/ADSPDir/").getAbsolutePath()); new File("./BDWareProjectDir/ADSPDir/").getAbsolutePath());
File f = new File("./yjs.jar"); File f = new File("./yjs.jar");
if (f.exists()) { if (f.exists()) {
KeyValueDBUtil.instance.setValue(dbName, "yjsPath", KeyValueDBUtil.instance.setValue(
new File("./yjs.jar").getAbsolutePath()); dbName, "yjsPath", new File("./yjs.jar").getAbsolutePath());
} else { } else {
KeyValueDBUtil.instance.setValue(dbName, "yjsPath", KeyValueDBUtil.instance.setValue(
new File("./cp/yjs.jar").getAbsolutePath()); dbName, "yjsPath", new File("./cp/yjs.jar").getAbsolutePath());
} }
conf.keyPairStr = SM2Util.generateSM2KeyPair().toJson(); conf.keyPairStr = SM2Util.generateSM2KeyPair().toJson();
@ -105,27 +104,43 @@ public class GlobalConf {
// long time = System.currentTimeMillis()+15811200000; // long time = System.currentTimeMillis()+15811200000;
String licence = String licence =
ByteHexUtil ByteHexUtil.encode(
.encode(SM2Util.encrypt(conf.keyPair.getPublicKey(), SM2Util.encrypt(
(HardwareInfo.getCPUID() + "==" conf.keyPair.getPublicKey(),
+ (System.currentTimeMillis() + 15811200000L)) (HardwareInfo.getCPUID()
.getBytes())); + "=="
+ (System.currentTimeMillis()
+ 15811200000L))
.getBytes()));
LOGGER.debug("licence:" + licence); LOGGER.debug("licence:" + licence);
LOGGER.debug(String.format("deviceName %s license %s %s==%d", deviceName, licence, LOGGER.debug(
HardwareInfo.getCPUID(), (System.currentTimeMillis() + 15811200000L))); String.format(
"deviceName %s license %s %s==%d",
deviceName,
licence,
HardwareInfo.getCPUID(),
(System.currentTimeMillis() + 15811200000L)));
KeyValueDBUtil.instance.setValue(dbName, "licence", licence); KeyValueDBUtil.instance.setValue(dbName, "licence", licence);
KeyValueDBUtil.instance.setValue(dbName, "nodeName", deviceName.substring(0, 10)); KeyValueDBUtil.instance.setValue(dbName, "nodeName", deviceName.substring(0, 10));
KeyValueDBUtil.instance.setValue(dbName, "masterAddress", "null"); KeyValueDBUtil.instance.setValue(dbName, "masterAddress", "null");
KeyValueDBUtil.instance.setValue(dbName, "ipPort", "null"); KeyValueDBUtil.instance.setValue(dbName, "ipPort", "null");
KeyValueDBUtil.instance.setValue(dbName, "nodeCenter", "ws://127.0.0.1:18005"); JsonObject doipConfig = new JsonObject();
KeyValueDBUtil.instance.setValue(dbName, "datachainConf", doipConfig.addProperty("lhsAddress", "tcp://127.0.0.1:2641");
"39.104.70.160:18091\n" + "47.98.247.70:18091\n" + "47.98.248.208:18091\n" doipConfig.addProperty("repoDoid", "bdware.trusted.test/Repo." + conf.keyPair.getPublicKeyStr().substring(0, 6));
+ "39.104.77.165:18091\n" + "47.98.249.131:18091"); KeyValueDBUtil.instance.setValue(dbName, "doipConfig", doipConfig.toString());
KeyValueDBUtil.instance.setValue(dbName, "nodeCenter", "ws://127.0.0.1:18002");
KeyValueDBUtil.instance.setValue(
dbName,
"datachainConf",
"39.104.70.160:18091\n"
+ "47.98.247.70:18091\n"
+ "47.98.248.208:18091\n"
+ "39.104.77.165:18091\n"
+ "47.98.249.131:18091");
} }
conf.projectDir = KeyValueDBUtil.instance.getValue(dbName, "projectDir"); conf.projectDir = KeyValueDBUtil.instance.getValue(dbName, "projectDir");
conf.bcoDir = conf.projectDir + "/bco";
conf.publicDir = KeyValueDBUtil.instance.getValue(dbName, "projectDir") + "/public"; conf.publicDir = KeyValueDBUtil.instance.getValue(dbName, "projectDir") + "/public";
conf.ADSPDir = KeyValueDBUtil.instance.getValue(dbName, "projectDir") + "/ADSPDir"; conf.ADSPDir = KeyValueDBUtil.instance.getValue(dbName, "projectDir") + "/ADSPDir";
conf.publicCompiledDir = conf.publicCompiledDir =
@ -140,18 +155,15 @@ public class GlobalConf {
conf.name = KeyValueDBUtil.instance.getValue(dbName, "nodeName"); conf.name = KeyValueDBUtil.instance.getValue(dbName, "nodeName");
conf.ipPort = KeyValueDBUtil.instance.getValue(dbName, "ipPort"); conf.ipPort = KeyValueDBUtil.instance.getValue(dbName, "ipPort");
conf.isLAN = "true".equals(KeyValueDBUtil.instance.getValue(dbName, "isLAN")); conf.isLAN = "true".equals(KeyValueDBUtil.instance.getValue(dbName, "isLAN"));
// conf.masterAddress = KeyValueDBUtil.instance.getValue(dbName, "masterAddress"); conf.masterAddress = KeyValueDBUtil.instance.getValue(dbName, "masterAddress");
conf.nodeCenterUrl = KeyValueDBUtil.instance.getValue(dbName, "nodeCenter"); conf.nodeCenterUrl = KeyValueDBUtil.instance.getValue(dbName, "nodeCenter");
conf.nodeCenterWSUrl = KeyValueDBUtil.instance.getValue(dbName, "nodeCenterWS");
conf.peerID = KeyValueDBUtil.instance.getValue(dbName, "peerID"); conf.peerID = KeyValueDBUtil.instance.getValue(dbName, "peerID");
conf.keyPairStr = KeyValueDBUtil.instance.getValue(dbName, "keyPairStr"); conf.keyPairStr = KeyValueDBUtil.instance.getValue(dbName, "keyPairStr");
// logger.debug("keyPairStr" + conf.keyPairStr); // logger.debug("keyPairStr" + conf.keyPairStr);
conf.keyPair = SM2KeyPair.fromJson(conf.keyPairStr); conf.keyPair = SM2KeyPair.fromJson(conf.keyPairStr);
conf.doaConf = new DOAConf(); loadDOAConfig(KeyValueDBUtil.instance.getValue(dbName, "doipConfig"));
loadDOAConfig(conf.doaConf, KeyValueDBUtil.instance.getValue(dbName, "doipConfig"));
} catch (Exception e) { } catch (Exception e) {
LOGGER.error(e.getMessage()); LOGGER.error(e.getMessage());
e.printStackTrace();
LOGGER.debug(ExceptionUtil.exceptionToString(e)); LOGGER.debug(ExceptionUtil.exceptionToString(e));
} }
// verifyLicence(conf); // verifyLicence(conf);
@ -192,8 +204,9 @@ public class GlobalConf {
LOGGER.debug("[GlobalConf] ProjectDir Path:" + new File(conf.projectDir).getAbsolutePath()); LOGGER.debug("[GlobalConf] ProjectDir Path:" + new File(conf.projectDir).getAbsolutePath());
LOGGER.debug("[GlobalConf] publicDir Path:" + new File(conf.publicDir).getAbsolutePath()); LOGGER.debug("[GlobalConf] publicDir Path:" + new File(conf.publicDir).getAbsolutePath());
LOGGER.debug("[GlobalConf] publicDir Path:" + new File(conf.ADSPDir).getAbsolutePath()); LOGGER.debug("[GlobalConf] publicDir Path:" + new File(conf.ADSPDir).getAbsolutePath());
LOGGER.debug("[GlobalConf] publicDirCompiled Path:" LOGGER.debug(
+ new File(conf.publicCompiledDir).getAbsolutePath()); "[GlobalConf] publicDirCompiled Path:"
+ new File(conf.publicCompiledDir).getAbsolutePath());
LOGGER.debug( LOGGER.debug(
"[GlobalConf] PersonalDir Path:" + new File(conf.privateDir).getAbsolutePath()); "[GlobalConf] PersonalDir Path:" + new File(conf.privateDir).getAbsolutePath());
LOGGER.debug("[GlobalConf] memorytDir Path:" + new File(conf.memoryDir).getAbsolutePath()); LOGGER.debug("[GlobalConf] memorytDir Path:" + new File(conf.memoryDir).getAbsolutePath());
@ -208,19 +221,23 @@ public class GlobalConf {
return conf; return conf;
} }
private static void loadDOAConfig(DOAConf doaConf, String val) { private static void loadDOAConfig(String val) {
try { try {
if (val != null && !"null".equals(val)) { JsonObject doipConfig = JsonUtil.parseStringAsJsonObject(val);
JsonObject doipConfig = JsonUtil.parseStringAsJsonObject(val); DOAConf.lhsAddress = doipConfig.get("lhsAddress").getAsString();
doaConf.lhsAddress = doipConfig.get("lhsAddress").getAsString(); DOAConf.repoDoid = doipConfig.get("repoDoid").getAsString();
doaConf.repoDoid = doipConfig.get("repoDoid").getAsString(); //TODO 这个怎么获取要通过啥来获取自己的repoDoid呢
doaConf.doipAddress = doipConfig.get("doipAddress").getAsString(); //所以现在的lhsAddress暂时没起作用
doaConf.repoName = doipConfig.get("repoName").getAsString();
}
} catch (Exception e) { } catch (Exception e) {
} }
} }
public static String getDOAConfig() {
JsonObject doipConfig = new JsonObject();
doipConfig.addProperty("lhsAddress", DOAConf.lhsAddress);
doipConfig.addProperty("repoDoid", DOAConf.repoDoid);
return doipConfig.toString();
}
private static void deleteJelck(File file) { private static void deleteJelck(File file) {
if (file.exists()) { if (file.exists()) {
@ -230,17 +247,16 @@ public class GlobalConf {
private static void verifyLicence(GlobalConf conf) { private static void verifyLicence(GlobalConf conf) {
try { try {
// String pubkey = // String pubkey =
// "OTIzNmUzMGNmOGI1ZjFkMDBjZjEyMWY4OThmM2ZmYTIwNjE2ODYxOWNiMDNhMTVlM2FiZTA0OThhNTlkZDg1MmRi" // "OTIzNmUzMGNmOGI1ZjFkMDBjZjEyMWY4OThmM2ZmYTIwNjE2ODYxOWNiMDNhMTVlM2FiZTA0OThhNTlkZDg1MmRi" +
// + // "MjA5Njc1NmM3ZDBhOWM3YTNkOTg2NWVlYzk2YzM1MmY0MDdkMGMyOTA4M2NkNDI4YmY1YjM5M2U5OTA1" +
// "MjA5Njc1NmM3ZDBhOWM3YTNkOTg2NWVlYzk2YzM1MmY0MDdkMGMyOTA4M2NkNDI4YmY1YjM5M2U5OTA1" + // "NWE0MzM0MTJhM2Y2ZDhkZWVmZDk4MmI4NmZiZTMyYjhlMGE3ZWFmZmE5ODM3M2E4ZTRmNTYyNDgxNTY0" +
// "NWE0MzM0MTJhM2Y2ZDhkZWVmZDk4MmI4NmZiZTMyYjhlMGE3ZWFmZmE5ODM3M2E4ZTRmNTYyNDgxNTY0" + // "Yjk2ZjFkMTZiODk2MGRhZDAwMTNjZDYwOGZmOTcxNjdiOWI1MDU1MjJlMzk0ODhmODczNDJjNWUwOGRj" +
// "Yjk2ZjFkMTZiODk2MGRhZDAwMTNjZDYwOGZmOTcxNjdiOWI1MDU1MjJlMzk0ODhmODczNDJjNWUwOGRj" + // "ZjFhZjFkYzBjODUxZjRlNDg2ZWIyOTM5NDI3MDc4MjA5NDg5ODliODVhZDNlOGJlNWJiYWEzZDUyMWU2" +
// "ZjFhZjFkYzBjODUxZjRlNDg2ZWIyOTM5NDI3MDc4MjA5NDg5ODliODVhZDNlOGJlNWJiYWEzZDUyMWU2" + // "MjdmZjE3NGY4Y2ZlZDk3NTY4OWNlNDEzOGYyMTgyOWIwMDVmMzE0YjM3MmNlZmFkZjBkNmUyOTY4ZGUz" +
// "MjdmZjE3NGY4Y2ZlZDk3NTY4OWNlNDEzOGYyMTgyOWIwMDVmMzE0YjM3MmNlZmFkZjBkNmUyOTY4ZGUz" + // "ZmFlNGUxNTFkMWFmNWE4Mjc4ZjQ2MDI5ODBjY2JkMDM0ZDE0YWRjZDk1ZjI1MjY3NmRlODRjYzdkNzU5" +
// "ZmFlNGUxNTFkMWFmNWE4Mjc4ZjQ2MDI5ODBjY2JkMDM0ZDE0YWRjZDk1ZjI1MjY3NmRlODRjYzdkNzU5" + // "NGYyYTAxMTliYWJmYjgyMGRjMWNjZWZjNThjNWUwYWRjMDQyM2MzYzA1ODNhZTU1MWZlN2Y5YTYwYjkx" +
// "NGYyYTAxMTliYWJmYjgyMGRjMWNjZWZjNThjNWUwYWRjMDQyM2MzYzA1ODNhZTU1MWZlN2Y5YTYwYjkx" + // "Zjg2YWViNDNlMzU0NzlhYWI5YmFjOTAwN2IsMTAwMDEsMA==";
// "Zjg2YWViNDNlMzU0NzlhYWI5YmFjOTAwN2IsMTAwMDEsMA==";
LOGGER.debug("beforedecode:" + conf.licence); LOGGER.debug("beforedecode:" + conf.licence);
if (conf.licence != null && conf.licence.length() > 8) { if (conf.licence != null && conf.licence.length() > 8) {
@ -248,8 +264,11 @@ public class GlobalConf {
try { try {
// byte[] arr = key.encode(new BASE64Decoder().decodeBuffer(conf.licence)); // byte[] arr = key.encode(new BASE64Decoder().decodeBuffer(conf.licence));
// String actualKey = new String(arr); // String actualKey = new String(arr);
String arr = new String(SM2Util.decrypt(conf.keyPair.getPrivateKeyParameter(), String arr =
ByteHexUtil.decode(conf.licence))); new String(
SM2Util.decrypt(
conf.keyPair.getPrivateKeyParameter(),
ByteHexUtil.decode(conf.licence)));
LOGGER.debug("[GlobalConf] actualKey:" + arr); LOGGER.debug("[GlobalConf] actualKey:" + arr);
@ -303,30 +322,25 @@ public class GlobalConf {
} }
} }
// public static void initMasterAddress(String val) { public static void initMasterAddress(String val) {
// if ("null".equals(instance.masterAddress) || instance.masterAddress.startsWith("127.0.0.1")) if ("null".equals(instance.masterAddress) || instance.masterAddress.startsWith("127.0.0.1")) {
// { resetMasterAddress(val);
// resetMasterAddress(val); }
// }
// }
public static void initDOAConfig(DOAConf doaConf) {
if (instance.doaConf == null || instance.doaConf.doipAddress == null)
resetDOAConfig(JsonUtil.toJson(doaConf));
} }
// public static boolean resetMasterAddress(String val) { public static boolean resetMasterAddress(String val) {
// try { try {
// instance.masterAddress = val; instance.masterAddress = val;
// KeyValueDBUtil.instance.setValue(CMTables.ConfigDB.toString(), "masterAddress", val); KeyValueDBUtil.instance.setValue(CMTables.ConfigDB.toString(), "masterAddress", val);
// NetworkManager.instance.reInitNodeCenter(); NetworkManager.instance.reInitNodeCenter();
// return true; ContractRepositoryMain.start();
// } catch (Exception e) { return true;
// LOGGER.error(e.getMessage()); } catch (Exception e) {
// LOGGER.debug(ExceptionUtil.exceptionToString(e)); LOGGER.error(e.getMessage());
// return false; LOGGER.debug(ExceptionUtil.exceptionToString(e));
// } return false;
// } }
}
public static boolean resetNodeCenter(String val) { public static boolean resetNodeCenter(String val) {
try { try {
@ -341,19 +355,6 @@ public class GlobalConf {
} }
} }
public static boolean resetNodeCenterWS(String val) {
try {
instance.nodeCenterWSUrl = val;
KeyValueDBUtil.instance.setValue(CMTables.ConfigDB.toString(), "nodeCenterWS", val);
return true;
} catch (Exception e) {
LOGGER.error(e.getMessage());
LOGGER.debug(ExceptionUtil.exceptionToString(e));
return false;
}
}
public static boolean resetDeviceName(String val) { public static boolean resetDeviceName(String val) {
try { try {
KeyValueDBUtil.instance.setValue(CMTables.ConfigDB.toString(), "nodeName", val); KeyValueDBUtil.instance.setValue(CMTables.ConfigDB.toString(), "nodeName", val);
@ -409,7 +410,7 @@ public class GlobalConf {
} }
public static void initIpPort(String val) { public static void initIpPort(String val) {
if ("null".equals(instance.ipPort) || instance.ipPort.startsWith("127.0.0.1")) { if ("null".equals(instance.ipPort) || instance.masterAddress.startsWith("127.0.0.1")) {
resetIpPort(val); resetIpPort(val);
} }
} }
@ -420,11 +421,11 @@ public class GlobalConf {
return true; return true;
} }
public static boolean resetDOAConfig(String val) { public static boolean resetDOIPConfig(String val) {
try { try {
loadDOAConfig(instance.doaConf, val); loadDOAConfig(val);
//TODO get prefix if needed!
KeyValueDBUtil.instance.setValue(CMTables.ConfigDB.toString(), "doipConfig", val); KeyValueDBUtil.instance.setValue(CMTables.ConfigDB.toString(), "doipConfig", val);
ContractRepositoryMain.start();
} catch (Exception e) { } catch (Exception e) {
LOGGER.error(e.getMessage()); LOGGER.error(e.getMessage());
LOGGER.debug(ExceptionUtil.exceptionToString(e)); LOGGER.debug(ExceptionUtil.exceptionToString(e));
@ -459,10 +460,6 @@ public class GlobalConf {
return instance.keyPair.getPublicKeyStr(); return instance.keyPair.getPublicKeyStr();
} }
public static String getNodeCenterWSUrl() {
return instance.nodeCenterWSUrl;
}
public boolean resetLicenceInternal(String licence2) { public boolean resetLicenceInternal(String licence2) {
licence2 = licence2.replaceAll(" ", "+"); licence2 = licence2.replaceAll(" ", "+");
LOGGER.info("resetLicence:" + licence2); LOGGER.info("resetLicence:" + licence2);

View File

@ -1,137 +0,0 @@
package org.bdware.server;
import com.google.gson.JsonObject;
import org.bdware.sc.ContractManager;
import org.bdware.sc.conn.ResultCallback;
import org.bdware.sc.units.RecoverFlag;
import org.bdware.sc.units.RequestCache;
import org.bdware.sdk.consistency.api.context.*;
import org.bdware.server.action.CMActions;
import org.bdware.server.action.SyncResult;
import org.bdware.server.action.p2p.MasterClientTCPAction;
import org.bdware.server.action.p2p.MasterServerRecoverMechAction;
import org.bdware.server.action.p2p.MasterServerTCPAction;
import org.bdware.server.trustedmodel.ResultCollector;
import org.bdware.units.NetworkManager;
import org.zz.gmhelper.SM2KeyPair;
import java.util.Map;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
public class SDKContext implements ISDKContext {
IMasterServerTCPAction masterServerTCPActionProxy = new MasterServerTCPActionProxy();
IMasterClientTCPAction masterClientTCPAction = new MasterClientTCPActionProxy();
INetworkManager networkManagerProxy = new NetworkManagerProxy();
ICMActions cmActionsProxy = new CMActionsProxy();
IMasterServerRecoverMechAction masterServerRecoverMechActionProxy =
new MasterServerRecoverMechActionProxy();
IGlobalConf globalConfProxy = new GlobalProxy();
@Override
public IMasterClientTCPAction getMasterClientTCPAction() {
return masterClientTCPAction;
}
@Override
public IMasterServerTCPAction getMasterServerTCPAction() {
return masterServerTCPActionProxy;
}
@Override
public INetworkManager getNetworkManager() {
return networkManagerProxy;
}
@Override
public ICMActions getCMActions() {
return cmActionsProxy;
}
@Override
public IMasterServerRecoverMechAction getMasterServerRecoverMechAction() {
return masterServerRecoverMechActionProxy;
}
@Override
public IGlobalConf getGlobalConf() {
return globalConfProxy;
}
public static class MasterServerTCPActionProxy implements IMasterServerTCPAction {
@Override
public SyncResult getSync() {
return MasterServerTCPAction.sync;
}
@Override
public Map<String, RequestCache> getReqCache() {
return MasterServerTCPAction.requestCache;
}
}
public static class MasterClientTCPActionProxy implements IMasterClientTCPAction {
private final ExecutorService executorService = Executors.newFixedThreadPool(10);
private final MasterClientTCPAction _masterClientTCPAction = new MasterClientTCPAction();
@Override
public void asyncExecuteContractLocally(JsonObject jo, ResultCallback rc) {
executorService.execute(() -> _masterClientTCPAction.executeContractLocally(jo, rc));
}
}
public static class NetworkManagerProxy implements INetworkManager {
@Override
public void sendToAgent(String pubkey, String content) {
NetworkManager.instance.sendToAgent(pubkey, content);
}
@Override
public boolean hasAgentConnection(String pubkey) {
return NetworkManager.instance.hasAgentConnection(pubkey);
}
@Override
public ResultCallback createResultCallback(String requestID, ResultCallback rc, int count) {
return new ResultCollector(requestID, rc, count);
}
}
public static class CMActionsProxy implements ICMActions {
@Override
public ContractManager getManager() {
return CMActions.manager;
}
}
public static class MasterServerRecoverMechActionProxy
implements IMasterServerRecoverMechAction {
@Override
public Map<String, Map<String, RecoverFlag>> getRecoverStatusMap() {
return MasterServerRecoverMechAction.recoverStatus;
}
@Override
public void restartContractFromCommonMode(String nodeID, String contractID) {
MasterServerRecoverMechAction.restartContractFromCommonMode(nodeID, contractID);
}
}
public static class GlobalProxy implements IGlobalConf {
@Override
public String getNodeID() {
return GlobalConf.getNodeID();
}
@Override
public SM2KeyPair getKeyPair() {
return GlobalConf.instance.keyPair;
}
}
}

File diff suppressed because it is too large Load Diff

View File

@ -17,7 +17,7 @@ import java.util.Map;
import java.util.Random; import java.util.Random;
public class CMLogAction { public class CMLogAction {
// static SocketGet get; // static SocketGet get;
@Action(async = true, userPermission = 0) @Action(async = true, userPermission = 0)
public void setLogStage(JsonObject json, ResultCallback result) { public void setLogStage(JsonObject json, ResultCallback result) {
@ -49,8 +49,7 @@ public class CMLogAction {
if (json.has("contractName")) { if (json.has("contractName")) {
contractName = json.get("contractName").getAsString(); contractName = json.get("contractName").getAsString();
} }
queryByOffset(ContractManager.logsDB, "onQueryContractLogByOffset", contractName, json, queryByOffset(ContractManager.logsDB, "onQueryContractLogByOffset", contractName, json, result);
result);
} }
@Action(async = true, userPermission = 1L << 22) @Action(async = true, userPermission = 1L << 22)
@ -221,8 +220,12 @@ public class CMLogAction {
JsonObject ret = new JsonObject(); JsonObject ret = new JsonObject();
ret.addProperty("action", "onQueryAEState"); ret.addProperty("action", "onQueryAEState");
if (json.has("caller")) { if (json.has("caller")) {
ret.add("result", JsonParser.parseString(JsonUtil ret.add(
.toJson(ActionExecutor.getStatistic(json.get("caller").getAsString())))); "result",
JsonParser.parseString(
JsonUtil.toJson(
ActionExecutor.getStatistic(
json.get("caller").getAsString()))));
} else { } else {
ret.add("result", JsonParser.parseString(JsonUtil.toJson(ActionExecutor.getAllData()))); ret.add("result", JsonParser.parseString(JsonUtil.toJson(ActionExecutor.getAllData())));
} }
@ -241,15 +244,17 @@ public class CMLogAction {
public void checkIsContract(JsonObject json, ResultCallback rc) { public void checkIsContract(JsonObject json, ResultCallback rc) {
String requestID = new Random().nextLong() + "_" + System.currentTimeMillis(); String requestID = new Random().nextLong() + "_" + System.currentTimeMillis();
json.addProperty("requestID", requestID); json.addProperty("requestID", requestID);
JsonObject ret = JsonObject ret = CMActions.manager.nodeCenterConn.checkIsContract(requestID, json.toString());
CMActions.manager.nodeCenterConn.checkIsContract(requestID, json.toString());
json.remove("list"); json.remove("list");
json.add("result", ret); json.add("result", ret);
json.addProperty("action", "onCheckIsContract"); json.addProperty("action", "onCheckIsContract");
rc.onResult(json.toString()); rc.onResult(json.toString());
} }
private void queryLogSize(MultiIndexTimeDBUtilIntf db, String action, String label, private void queryLogSize(
MultiIndexTimeDBUtilIntf db,
String action,
String label,
ResultCallback result) { ResultCallback result) {
try { try {
JsonObject ret = new JsonObject(); JsonObject ret = new JsonObject();
@ -269,14 +274,20 @@ public class CMLogAction {
} }
private void queryByDate(MultiIndexTimeDBUtilIntf db, String action, String label, private void queryByDate(
JsonObject json, ResultCallback result) { MultiIndexTimeDBUtilIntf db,
String action,
String label,
JsonObject json,
ResultCallback result) {
// TODO FixMe // TODO FixMe
// Caused by: com.google.gson.stream.MalformedJsonException: Unterminated object at line 1 // Caused by: com.google.gson.stream.MalformedJsonException: Unterminated object at line 1
// column 240 path $.function // column 240 path $.function
if (!json.has("start")) { if (!json.has("start")) {
result.onResult("{\"action\":\"" + action result.onResult(
+ "\",\"status\":\"failed\",\"data\":\"missing start\"}"); "{\"action\":\""
+ action
+ "\",\"status\":\"failed\",\"data\":\"missing start\"}");
return; return;
} }
long date = json.get("start").getAsLong(); long date = json.get("start").getAsLong();
@ -296,11 +307,17 @@ public class CMLogAction {
result.onResult(JsonUtil.toJson(ret)); result.onResult(JsonUtil.toJson(ret));
} }
private void queryByOffset(MultiIndexTimeDBUtilIntf db, String action, String label, private void queryByOffset(
JsonObject json, ResultCallback result) { MultiIndexTimeDBUtilIntf db,
String action,
String label,
JsonObject json,
ResultCallback result) {
if (!json.has("count")) { if (!json.has("count")) {
result.onResult("{\"action\":\"" + action result.onResult(
+ "\",\"status\":\"failed\",\"data\":\"missing count\"}"); "{\"action\":\""
+ action
+ "\",\"status\":\"failed\",\"data\":\"missing count\"}");
return; return;
} }
int count = json.get("count").getAsInt(); int count = json.get("count").getAsInt();

View File

@ -9,8 +9,8 @@ import java.util.HashMap;
import java.util.Map; import java.util.Map;
import java.util.concurrent.ConcurrentHashMap; import java.util.concurrent.ConcurrentHashMap;
// UNUSED //UNUSED
// TO Merge //TO Merge
public class CheckPointCallback implements OnHashCallback { public class CheckPointCallback implements OnHashCallback {
public static Map<String, String> lastHash = new ConcurrentHashMap<>(); // contractID,hash public static Map<String, String> lastHash = new ConcurrentHashMap<>(); // contractID,hash
@ -23,11 +23,11 @@ public class CheckPointCallback implements OnHashCallback {
reqStr.put("contractID", contractID); reqStr.put("contractID", contractID);
reqStr.put("hash", hashStr); reqStr.put("hash", hashStr);
String sendStr = JsonUtil.toJson(reqStr); String sendStr = JsonUtil.toJson(reqStr);
MultiContractMeta info = MultiContractMeta info = CMActions.manager.multiContractRecorder.getMultiContractMeta(contractID);
CMActions.manager.multiContractRecorder.getMultiContractMeta(contractID);
for (String node : info.getMembers()) { for (String node : info.getMembers()) {
NetworkManager.instance.sendToAgent(node, sendStr); NetworkManager.instance.sendToAgent(node, sendStr);
System.out.println("发送请求给 " + node.substring(0, 5) + " 更新ledger中最新检查点的hash!"); System.out.println(
"发送请求给 " + node.substring(0, 5) + " 更新ledger中最新检查点的hash!");
} }
} }
} }

View File

@ -8,7 +8,7 @@ import org.bdware.sc.util.JsonUtil;
public class EventActions { public class EventActions {
@Action(async = true, userPermission = 0) @Action(async = true, userPermission = 0)
public void deliverEvent(JsonObject args, final ResultCallback rcb) { public void deliverEvent(JsonObject args, final ResultCallback rcb) {
CMActions.manager CMActions.manager.deliverEvent(
.deliverEvent(JsonUtil.fromJson(args.get("data").getAsString(), REvent.class)); JsonUtil.fromJson(args.get("data").getAsString(), REvent.class));
} }
} }

View File

@ -3,13 +3,7 @@ package org.bdware.server.action;
import com.google.gson.JsonObject; import com.google.gson.JsonObject;
import org.bdware.sc.ContractClient; import org.bdware.sc.ContractClient;
import org.bdware.sc.conn.ResultCallback; import org.bdware.sc.conn.ResultCallback;
import org.bdware.sc.event.REvent;
import org.bdware.sc.util.HashUtil; import org.bdware.sc.util.HashUtil;
import org.zz.gmhelper.SM2KeyPair;
import org.zz.gmhelper.SM2Util;
import static org.bdware.sc.event.REvent.REventSemantics.valueOf;
import static org.bdware.sc.event.REvent.REventType.PUBLISH;
public class EventWSActions { public class EventWSActions {
@Action(async = true, userPermission = 0) @Action(async = true, userPermission = 0)
@ -31,7 +25,7 @@ public class EventWSActions {
ContractClient client = CMActions.manager.getClient(argCID); ContractClient client = CMActions.manager.getClient(argCID);
if (null == client) { if (null == client) {
ret.addProperty("data", "invalid contract ID or Name!"); ret.addProperty("data", "invalid contract ID or Name!");
rcb.onResult(ret); rcb.onResult(ret.toString());
return; return;
} }
String contractID = client.getContractID(); String contractID = client.getContractID();
@ -42,38 +36,4 @@ public class EventWSActions {
ret.addProperty("data", topic); ret.addProperty("data", topic);
rcb.onResult(ret); rcb.onResult(ret);
} }
@Action(async = true, userPermission = 0)
public void pubEvent(JsonObject args, final ResultCallback rcb) {
JsonObject ret = new JsonObject();
ret.addProperty("action", "onPubEvent");
if (!args.has("topic") || !args.has("content")) {
ret.addProperty("data", "topic or content are missed!");
rcb.onResult(ret);
return;
}
String requestID = args.has("requestID") ? args.get("requestID").getAsString()
: HashUtil.sha3(String.valueOf(System.currentTimeMillis()), "_",
String.valueOf(Math.random()));
REvent event = new REvent(args.get("topic").getAsString(), PUBLISH,
args.get("content").getAsString(), requestID);
if (args.has("semantics")) {
try {
event.setSemantics(valueOf(args.get("semantics").getAsString()));
} catch (Exception ignored) {
ret.addProperty("data", "unsupported semantics!");
rcb.onResult(ret);
return;
}
}
if (args.has("pubkey") && args.has("sign")) {
event.setPublicKey(args.get("pubkey").getAsString());
event.setSignature(args.get("sign").getAsString());
} else {
SM2KeyPair keyPair = SM2Util.generateSM2KeyPair();
event.doSignature(keyPair);
ret.addProperty("keys", keyPair.toJson());
}
rcb.onResult(ret);
}
} }

File diff suppressed because it is too large Load Diff

View File

@ -18,17 +18,25 @@ public class HttpFileAction {
LOGGER.debug("[HttpFileAction] donwloadContract : "); LOGGER.debug("[HttpFileAction] donwloadContract : ");
try { try {
/* /* already verified before into downloadContract!
* already verified before into downloadContract! String arg = "action=" + String arg = "action=" + json.get("action").getAsString();
* json.get("action").getAsString(); arg += "&projectName=" + arg += "&projectName=" + json.get("projectName").getAsString();
* json.get("projectName").getAsString(); arg += "&isPrivate=" + arg += "&isPrivate=" + json.get("isPrivate").getAsString();
* json.get("isPrivate").getAsString(); arg += "&pubKey=" + arg += "&pubKey=" + json.get("pubKey").getAsString();
* json.get("pubKey").getAsString(); arg += "&timestamp=" + arg += "&timestamp=" + json.get("timestamp").getAsString();
* json.get("timestamp").getAsString(); ECPoint pubKey = ECPoint pubKey = SM2KeyPair.publicKeyStr2ECPoint(json.get("pubKey").getAsString());
* SM2KeyPair.publicKeyStr2ECPoint(json.get("pubKey").getAsString()); boolean verify = boolean verify =
* new SM2() .verify( arg, SM2.Signature.loadFromString(json.get("sign").getAsString()), new SM2()
* "", pubKey); if (!verify) { result.onResult("/dev/null/2"); return; } .verify(
*/ arg,
SM2.Signature.loadFromString(json.get("sign").getAsString()),
"",
pubKey);
if (!verify) {
result.onResult("/dev/null/2");
return;
}
*/
String projectName = json.get("projectName").getAsString(); String projectName = json.get("projectName").getAsString();
if (projectName.contains("..")) { if (projectName.contains("..")) {

View File

@ -24,41 +24,41 @@ import java.util.Map;
public class LedgerActions { public class LedgerActions {
public static LedgerActions instance = new LedgerActions(); public static LedgerActions instance = new LedgerActions();
// @Action // @Action
// private void sendMockTransaction(JsonObject args, ResultCallback resultCallback) { // private void sendMockTransaction(JsonObject args, ResultCallback resultCallback) {
// Result r = new Result(); // Result r = new Result();
// r.data = "TODO"; // r.data = "TODO";
// r.status = true; // r.status = true;
// r.msg = null; // r.msg = null;
// resultCallback.onResult(gson.toJson(r)); // resultCallback.onResult(gson.toJson(r));
// } // }
// //
// @Action // @Action
// private void queryTransByHash(JsonObject args, ResultCallback resultCallback) { // private void queryTransByHash(JsonObject args, ResultCallback resultCallback) {
// Result r = new Result(); // Result r = new Result();
// r.data = "TODO"; // r.data = "TODO";
// r.status = true; // r.status = true;
// r.msg = null; // r.msg = null;
// resultCallback.onResult(gson.toJson(r)); // resultCallback.onResult(gson.toJson(r));
// } // }
// @Action // @Action
// private void queryHash(JsonObject args, ResultCallback resultCallback) { // private void queryHash(JsonObject args, ResultCallback resultCallback) {
// Result r = new Result(); // Result r = new Result();
// r.data = "TODO"; // r.data = "TODO";
// r.status = true; // r.status = true;
// r.msg = null; // r.msg = null;
// resultCallback.onResult(gson.toJson(r)); // resultCallback.onResult(gson.toJson(r));
// } // }
// //
// @Action // @Action
// private void queryRecent(JsonObject args, ResultCallback resultCallback) { // private void queryRecent(JsonObject args, ResultCallback resultCallback) {
// Result r = new Result(); // Result r = new Result();
// r.data = "TODO"; // r.data = "TODO";
// r.status = true; // r.status = true;
// r.msg = null; // r.msg = null;
// resultCallback.onResult(gson.toJson(r)); // resultCallback.onResult(gson.toJson(r));
// } // }
@Action @Action
public void queryLedgers(JsonObject jo, ResultCallback resultCallback) { public void queryLedgers(JsonObject jo, ResultCallback resultCallback) {
@ -69,8 +69,7 @@ public class LedgerActions {
LedgerProto.GetLedgersResponse ledgers = wt.getLedgersSync(); LedgerProto.GetLedgersResponse ledgers = wt.getLedgersSync();
List<String> array = new ArrayList<>(); List<String> array = new ArrayList<>();
ret.put("list", array); ret.put("list", array);
for (int i = 0; i < ledgers.getLedgersCount(); i++) for (int i = 0; i < ledgers.getLedgersCount(); i++) array.add(ledgers.getLedgers(i));
array.add(ledgers.getLedgers(i));
resultCallback.onResult(JsonUtil.toJson(ret)); resultCallback.onResult(JsonUtil.toJson(ret));
} catch (Exception e) { } catch (Exception e) {
ByteArrayOutputStream bo = new ByteArrayOutputStream(); ByteArrayOutputStream bo = new ByteArrayOutputStream();
@ -100,61 +99,67 @@ public class LedgerActions {
public void sendTransaction(JsonObject jo, ResultCallback resultCallback) { public void sendTransaction(JsonObject jo, ResultCallback resultCallback) {
Client wt = GRPCPool.grpcClients.get(0); Client wt = GRPCPool.grpcClients.get(0);
String ledgerName = "bdcontract"; String ledgerName = "bdcontract";
if (jo.has("ledger")) if (jo.has("ledger")) ledgerName = jo.get("ledger").getAsString();
ledgerName = jo.get("ledger").getAsString();
String from = jo.get("from").getAsString(); String from = jo.get("from").getAsString();
String to = jo.get("to").getAsString(); String to = jo.get("to").getAsString();
String data = jo.get("data").getAsString(); String data = jo.get("data").getAsString();
ListenableFuture<LedgerProto.SendTransactionResponse> future = ListenableFuture<LedgerProto.SendTransactionResponse> future =
wt.sendTransaction(ledgerName, CommonProto.TransactionType.MESSAGE, from, wt.sendTransaction(
random.nextLong(), to, data.getBytes()); ledgerName,
future.addListener(() -> { CommonProto.TransactionType.MESSAGE,
try { from,
ByteString hash = future.get().getHash(); random.nextLong(),
ReplyUtil.replyWithStatus(resultCallback, "onSendTransaction", true, to,
HashUtil.byteArray2Str(hash.toByteArray())); data.getBytes());
} catch (Exception e) { future.addListener(
ByteArrayOutputStream bo = new ByteArrayOutputStream(); () -> {
String dataStr = bo.toString(); try {
ReplyUtil.replyWithStatus(resultCallback, "onSendTransaction", false, dataStr); ByteString hash = future.get().getHash();
e.printStackTrace(); ReplyUtil.replyWithStatus(resultCallback, "onSendTransaction", true, HashUtil.byteArray2Str(hash.toByteArray()));
} } catch (Exception e) {
}, ContractManager.threadPool); ByteArrayOutputStream bo = new ByteArrayOutputStream();
String dataStr = bo.toString();
ReplyUtil.replyWithStatus(resultCallback, "onSendTransaction", false, dataStr);
e.printStackTrace();
}
},
ContractManager.threadPool);
} }
@Action @Action
public void queryTransactionByHash(JsonObject jo, ResultCallback resultCallback) { public void queryTransactionByHash(JsonObject jo, ResultCallback resultCallback) {
String hash = jo.get("hash").getAsString(); String hash = jo.get("hash").getAsString();
String ledgerName = "bdcontract"; String ledgerName = "bdcontract";
if (jo.has("ledger")) if (jo.has("ledger")) ledgerName = jo.get("ledger").getAsString();
ledgerName = jo.get("ledger").getAsString();
Client wt = GRPCPool.grpcClients.get(0); Client wt = GRPCPool.grpcClients.get(0);
if (wt == null) { if (wt == null) {
resultCallback resultCallback.onResult(
.onResult("{\"status\":\"Exception\",\"data\":\"no available worker thread\"}"); "{\"status\":\"Exception\",\"data\":\"no available worker thread\"}");
return; return;
} }
ListenableFuture<QueryProto.GetTransactionByHashResponse> future = ListenableFuture<QueryProto.GetTransactionByHashResponse> future =
wt.getTransactionByHash(ledgerName, hash); wt.getTransactionByHash(ledgerName, hash);
future.addListener(() -> { future.addListener(
try { () -> {
CommonProto.Transaction trans = future.get().getTransaction(); try {
Map<String, String> ret = new HashMap<>(); CommonProto.Transaction trans = future.get().getTransaction();
ret.put("from", HashUtil.byteArray2Str(trans.getFrom().toByteArray())); Map<String, String> ret = new HashMap<>();
ret.put("to", HashUtil.byteArray2Str(trans.getTo().toByteArray())); ret.put("from", HashUtil.byteArray2Str(trans.getFrom().toByteArray()));
ret.put("data", trans.getData().toStringUtf8()); ret.put("to", HashUtil.byteArray2Str(trans.getTo().toByteArray()));
ret.put("action", "onQueryTransactionByHash"); ret.put("data", trans.getData().toStringUtf8());
ret.put("type", trans.getType().name()); ret.put("action", "onQueryTransactionByHash");
resultCallback.onResult(JsonUtil.toJson(ret)); ret.put("type", trans.getType().name());
} catch (Exception e) { resultCallback.onResult(JsonUtil.toJson(ret));
ByteArrayOutputStream bo = new ByteArrayOutputStream(); } catch (Exception e) {
Map<String, String> ret = new HashMap<>(); ByteArrayOutputStream bo = new ByteArrayOutputStream();
ret.put("action", "onQueryTransactionByHash"); Map<String, String> ret = new HashMap<>();
e.printStackTrace(new PrintStream(bo)); ret.put("action", "onQueryTransactionByHash");
ret.put("data", bo.toString()); e.printStackTrace(new PrintStream(bo));
resultCallback.onResult(JsonUtil.toJson(ret)); ret.put("data", bo.toString());
e.printStackTrace(); resultCallback.onResult(JsonUtil.toJson(ret));
} e.printStackTrace();
}, ContractManager.threadPool); }
},
ContractManager.threadPool);
} }
} }

View File

@ -42,8 +42,11 @@ public class ManagerActions {
public void getEncodedUUID(JsonObject args, ResultCallback resultCallback) { public void getEncodedUUID(JsonObject args, ResultCallback resultCallback) {
String data = null; String data = null;
try { try {
data = ByteUtils.toHexString(SM2Util.encrypt(GlobalConf.instance.keyPair.getPublicKey(), data =
HardwareInfo.getCPUID().getBytes())); ByteUtils.toHexString(
SM2Util.encrypt(
GlobalConf.instance.keyPair.getPublicKey(),
HardwareInfo.getCPUID().getBytes()));
} catch (Exception e) { } catch (Exception e) {
e.printStackTrace(); e.printStackTrace();
} }
@ -62,7 +65,8 @@ public class ManagerActions {
try { try {
String key = args.get("key").getAsString(); String key = args.get("key").getAsString();
String val = args.get("val").getAsString(); String val = args.get("val").getAsString();
boolean status = true; boolean
status = true;
Object data; Object data;
switch (key) { switch (key) {
case "licence": case "licence":
@ -78,19 +82,17 @@ public class ManagerActions {
data = status = GlobalConf.resetDataChain(val); data = status = GlobalConf.resetDataChain(val);
break; break;
case "doipConfig": case "doipConfig":
data = status = GlobalConf.resetDOAConfig(val); data = status = GlobalConf.resetDOIPConfig(val);
break; break;
case "nodeCenter": case "nodeCenter":
data = status = GlobalConf.resetNodeCenter(val); data = status = GlobalConf.resetNodeCenter(val);
break; break;
case "nodeCenterWS":
data = status = GlobalConf.resetNodeCenterWS(val);
break;
case "nodeName": case "nodeName":
data = status = GlobalConf.resetNodeName(val); data = status = GlobalConf.resetNodeName(val);
break; break;
case "masterAddress": case "masterAddress":
// data = status = GlobalConf.resetMasterAddress(val); data = status = GlobalConf.resetMasterAddress(val);
break;
default: default:
status = false; status = false;
data = "unsupported key:" + key; data = "unsupported key:" + key;
@ -99,10 +101,8 @@ public class ManagerActions {
return; return;
} catch (Exception e) { } catch (Exception e) {
e.printStackTrace(); e.printStackTrace();
ReplyUtil.replyWithStatus(resultCallback, "onUpdateConfig", false,
"exception:" + e.getMessage());
} }
resultCallback.onResult("Exception");
} }
@Action(userPermission = 1L << 11) @Action(userPermission = 1L << 11)
@ -117,19 +117,19 @@ public class ManagerActions {
data.put("licence", GlobalConf.instance.licence); data.put("licence", GlobalConf.instance.licence);
data.put("expireTime", new Date(GlobalConf.instance.expireTime) + ""); data.put("expireTime", new Date(GlobalConf.instance.expireTime) + "");
data.put("nodeName", GlobalConf.instance.name); data.put("nodeName", GlobalConf.instance.name);
data.put("doipConfig", GlobalConf.instance.doaConf); data.put("doipConfig", GlobalConf.getDOAConfig());
data.put("nodePubKey", GlobalConf.instance.keyPair.getPublicKeyStr());
ReplyUtil.replyWithStatus(resultCallback, "onLoadConfig", true, data); ReplyUtil.replyWithStatus(resultCallback, "onLoadConfig", true, data);
} }
@Action(userPermission = 1L << 11) @Action(userPermission = 1L << 11)
public void listNodeInfos(JsonObject args, ResultCallback resultCallback) { public void listNodeInfos(JsonObject args, ResultCallback resultCallback) {
ControllerManager.getNodeCenterController().getNodeInfos(new ResultCallback() { ControllerManager.getNodeCenterController().getNodeInfos(
@Override new ResultCallback() {
public void onResult(String str) { @Override
ReplyUtil.replyWithStatus(resultCallback, "onListNodeInfos", true, str); public void onResult(String str) {
} ReplyUtil.replyWithStatus(resultCallback, "onListNodeInfos", true, str);
}); }
});
} }
@Action(userPermission = 1L << 26) @Action(userPermission = 1L << 26)
@ -147,14 +147,13 @@ public class ManagerActions {
data.put("licence", GlobalConf.instance.licence); data.put("licence", GlobalConf.instance.licence);
data.put("nodeName", GlobalConf.instance.name); data.put("nodeName", GlobalConf.instance.name);
data.put("ipPort", GlobalConf.instance.ipPort); data.put("ipPort", GlobalConf.instance.ipPort);
data.put("doipConfig", JsonUtil.toJson(GlobalConf.instance.doaConf)); data.put("doipConfig", GlobalConf.getDOAConfig());
data.put("isLAN", String.valueOf(GlobalConf.isLAN()));
data.put("peerID", GlobalConf.instance.peerID); data.put("peerID", GlobalConf.instance.peerID);
data.put("bdledger", GlobalConf.instance.datachainConf.replace("\n", " ")); data.put("bdledger", GlobalConf.instance.datachainConf.replace("\n", " "));
data.put("clusterConnected", data.put("clusterConnected", String.valueOf(NetworkManager.instance.isConnectedToNodeCenter()));
String.valueOf(NetworkManager.instance.isConnectedToNodeCenter()));
data.put("nodePubKey", GlobalConf.instance.keyPair.getPublicKeyStr()); data.put("nodePubKey", GlobalConf.instance.keyPair.getPublicKeyStr());
// data.put("masterAddress", GlobalConf.instance.masterAddress); data.put("masterAddress", GlobalConf.instance.masterAddress);
data.put("nodeCenterWS", GlobalConf.getNodeCenterWSUrl());
ReplyUtil.replyWithStatus(resultCallback, "onLoadNodeConfig", true, data); ReplyUtil.replyWithStatus(resultCallback, "onLoadNodeConfig", true, data);
} }
@ -162,61 +161,45 @@ public class ManagerActions {
public void changeNodeCenter(JsonObject args, ResultCallback resultCallback) { public void changeNodeCenter(JsonObject args, ResultCallback resultCallback) {
String val = args.get("data").getAsString(); String val = args.get("data").getAsString();
LOGGER.debug(JsonUtil.toJson(args)); LOGGER.debug(JsonUtil.toJson(args));
ReplyUtil.replyWithStatus(resultCallback, "onChangeNodeCenter", true, ReplyUtil.replyWithStatus(resultCallback, "onChangeNodeCenter", true, GlobalConf.resetNodeCenter(val));
GlobalConf.resetNodeCenter(val));
} }
@Action(userPermission = 1 << 10)
public void changeNodeCenterWS(JsonObject args, ResultCallback resultCallback) {
String val = args.get("data").getAsString();
LOGGER.debug(JsonUtil.toJson(args));
ReplyUtil.replyWithStatus(resultCallback, "onChangeNodeCenter", true,
GlobalConf.resetNodeCenterWS(val));
}
@Action(userPermission = 1 << 10) @Action(userPermission = 1 << 10)
public void changeBDledger(JsonObject args, ResultCallback resultCallback) { public void changeBDledger(JsonObject args, ResultCallback resultCallback) {
String val = args.get("data").getAsString(); String val = args.get("data").getAsString();
String lines = val.replace(" ", "\n"); String lines = val.replace(" ", "\n");
LOGGER.debug("changeBDledger " + lines); LOGGER.debug("changeBDledger " + lines);
ReplyUtil.replyWithStatus(resultCallback, "onChangeBDledger", true, ReplyUtil.replyWithStatus(resultCallback, "onChangeBDledger", true, GlobalConf.resetDataChain(lines));
GlobalConf.resetDataChain(lines));
} }
@Action(userPermission = 1 << 10) @Action(userPermission = 1 << 10)
public void changeNodeName(JsonObject args, ResultCallback resultCallback) { public void changeNodeName(JsonObject args, ResultCallback resultCallback) {
String val = args.get("data").getAsString(); String val = args.get("data").getAsString();
ReplyUtil.replyWithStatus(resultCallback, "onChangeNodeName", true, ReplyUtil.replyWithStatus(resultCallback, "onChangeNodeName", true, GlobalConf.resetNodeName(val));
GlobalConf.resetNodeName(val));
} }
@Action(userPermission = 1 << 10) @Action(userPermission = 1 << 10)
public void changeIpPort(JsonObject args, ResultCallback resultCallback) { public void changeIpPort(JsonObject args, ResultCallback resultCallback) {
String val = args.get("data").getAsString(); String val = args.get("data").getAsString();
ReplyUtil.replyWithStatus(resultCallback, "onChangeIpPort", true, ReplyUtil.replyWithStatus(resultCallback, "onChangeIpPort", true, GlobalConf.resetIpPort(val));
GlobalConf.resetIpPort(val));
} }
@Action(userPermission = 1 << 10) @Action(userPermission = 1 << 10)
public void changeDOIPConfig(JsonObject args, ResultCallback resultCallback) { public void changeDOIPConfig(JsonObject args, ResultCallback resultCallback) {
String val = args.get("data").getAsString(); String val = args.get("data").getAsString();
ReplyUtil.replyWithStatus(resultCallback, "onChangeDOIPConfig", true, ReplyUtil.replyWithStatus(resultCallback, "onChangeDOIPConfig", true, GlobalConf.resetDOIPConfig(val));
GlobalConf.resetDOAConfig(val));
} }
@Action(userPermission = 1 << 10) @Action(userPermission = 1 << 10)
public void changeYJSPath(JsonObject args, ResultCallback resultCallback) { public void changeYJSPath(JsonObject args, ResultCallback resultCallback) {
String val = args.get("data").getAsString(); String val = args.get("data").getAsString();
ReplyUtil.replyWithStatus(resultCallback, "onChangeYJSPath", true, ReplyUtil.replyWithStatus(resultCallback, "onChangeYJSPath", true, GlobalConf.resetYjsPath(val));
GlobalConf.resetYjsPath(val));
} }
@Action(userPermission = 1 << 10) @Action(userPermission = 1 << 10)
public void uploadLicence(JsonObject args, ResultCallback resultCallback) { public void uploadLicence(JsonObject args, ResultCallback resultCallback) {
String val = args.get("data").getAsString(); String val = args.get("data").getAsString();
ReplyUtil.replyWithStatus(resultCallback, "onUploadLicence", true, ReplyUtil.replyWithStatus(resultCallback, "onUploadLicence", true, GlobalConf.resetLicence(val));
GlobalConf.resetLicence(val));
} }
@Action(userPermission = 1 << 11) @Action(userPermission = 1 << 11)
@ -228,8 +211,7 @@ public class ManagerActions {
public void applyNodeRoleDeprecated(JsonObject json, ResultCallback resultCallback) { public void applyNodeRoleDeprecated(JsonObject json, ResultCallback resultCallback) {
try { try {
String pubKey = null; String pubKey = null;
if (json.has("verifiedPubKey")) if (json.has("verifiedPubKey")) pubKey = json.get("verifiedPubKey").getAsString();
pubKey = json.get("verifiedPubKey").getAsString();
if (pubKey == null) { if (pubKey == null) {
resultCallback.onResult( resultCallback.onResult(
"{\"action\":\"onApplyNodeRole\",\"data\":\"Failed: Illegal user\"}"); "{\"action\":\"onApplyNodeRole\",\"data\":\"Failed: Illegal user\"}");
@ -250,15 +232,17 @@ public class ManagerActions {
} }
if (str == null || str.length() == 0) { if (str == null || str.length() == 0) {
KeyValueDBUtil.instance.setValue(CMTables.ApplyRole.toString(), pubKey, KeyValueDBUtil.instance.setValue(
role.name()); CMTables.ApplyRole.toString(), pubKey, role.name());
} else { } else {
if (!str.contains(role.name())) if (!str.contains(role.name()))
KeyValueDBUtil.instance.setValue(CMTables.ApplyRole.toString(), pubKey, KeyValueDBUtil.instance.setValue(
str + "," + role.name()); CMTables.ApplyRole.toString(), pubKey, str + "," + role.name());
} }
KeyValueDBUtil.instance.setValue(CMTables.ApplyTime.toString(), pubKey, KeyValueDBUtil.instance.setValue(
CMTables.ApplyTime.toString(),
pubKey,
Long.toString(new Date().getTime())); Long.toString(new Date().getTime()));
ReplyUtil.simpleReply(resultCallback, "onApplyNodeRole", "success"); ReplyUtil.simpleReply(resultCallback, "onApplyNodeRole", "success");
@ -269,7 +253,8 @@ public class ManagerActions {
ret.addProperty("action", "onApplyNodeRole"); ret.addProperty("action", "onApplyNodeRole");
ret.addProperty("data", "success"); ret.addProperty("data", "success");
ret.addProperty("role", ro); ret.addProperty("role", ro);
resultCallback.onResult(ret); resultCallback.onResult(
ret);
} catch (Exception e) { } catch (Exception e) {
e.printStackTrace(); e.printStackTrace();

View File

@ -1,7 +1,5 @@
package org.bdware.server.action; package org.bdware.server.action;
import com.google.gson.JsonArray;
import com.google.gson.JsonElement;
import com.google.gson.JsonObject; import com.google.gson.JsonObject;
import org.apache.logging.log4j.LogManager; import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger; import org.apache.logging.log4j.Logger;
@ -13,40 +11,40 @@ import org.bdware.sc.db.CMTables;
import org.bdware.sc.db.KeyValueDBUtil; import org.bdware.sc.db.KeyValueDBUtil;
import org.bdware.sc.units.RecoverFlag; import org.bdware.sc.units.RecoverFlag;
import org.bdware.sc.util.JsonUtil; import org.bdware.sc.util.JsonUtil;
import org.bdware.server.GRPCPool;
import org.bdware.server.GlobalConf; import org.bdware.server.GlobalConf;
import org.bdware.server.action.p2p.MasterServerRecoverMechAction; import org.bdware.server.action.p2p.MasterServerRecoverMechAction;
import org.bdware.server.action.p2p.MasterServerTCPAction; import org.bdware.server.action.p2p.MasterServerTCPAction;
import org.bdware.server.trustedmodel.MultiPointContractInfo; import org.bdware.server.trustedmodel.MultiPointContractInfo;
import org.bdware.server.trustedmodel.MultiPointCooperateContractInfo; import org.bdware.server.trustedmodel.MultiPointCooperateContractInfo;
import org.bdware.server.trustedmodel.ResultCollector; import org.bdware.server.trustedmodel.ResultCollector;
import org.bdware.server.ws.ContractManagerFrameHandler;
import org.bdware.units.NetworkManager; import org.bdware.units.NetworkManager;
import org.zz.gmhelper.SM2KeyPair; import org.zz.gmhelper.SM2KeyPair;
import org.zz.gmhelper.SM2Util; import org.zz.gmhelper.SM2Util;
import java.util.Arrays; import java.util.Arrays;
import java.util.HashMap; import java.util.HashMap;
import java.util.List;
import java.util.Map; import java.util.Map;
import java.util.Set;
import java.util.concurrent.ConcurrentHashMap; import java.util.concurrent.ConcurrentHashMap;
import java.util.stream.Collectors; import java.util.stream.Collectors;
// WebSocket接口 // WebSocket接口
public class MasterWSAction { public class MasterWSAction {
private static final Logger LOGGER = LogManager.getLogger(MasterWSAction.class); private static final Logger LOGGER = LogManager.getLogger(MasterWSAction.class);
private final ContractManagerFrameHandler handler; private final UserManagerAction managerAction;
public MasterWSAction(ContractManagerFrameHandler handler) { public MasterWSAction(UserManagerAction userManagerAction) {
this.handler = handler; this.managerAction = userManagerAction;
} }
public static boolean hostMaster(String contractID) { public static boolean hostMaster(String contractID) {
return CMActions.manager.multiContractRecorder.getMultiContractMeta(contractID).isMaster(); return CMActions.manager.multiContractRecorder.getMultiContractMeta(contractID).isMaster();
} }
private boolean waitForConnection(List<String> nodeNames) { private boolean waitForConnection(Set<String> nodeNames) {
LOGGER.info("waitForAllNodes:" + JsonUtil.toJson(nodeNames)); LOGGER.info("waitForAllNodes:" + JsonUtil.toJson(nodeNames));
for (int i = 0; i < 500; i++) { for (int i = 0; i < 5; i++) {
boolean all = true; boolean all = true;
for (String str : nodeNames) { for (String str : nodeNames) {
if (!NetworkManager.instance.hasAgentConnection(str)) { if (!NetworkManager.instance.hasAgentConnection(str)) {
@ -70,16 +68,6 @@ public class MasterWSAction {
return false; return false;
} }
@Action(async = true)
public void warmConnection(JsonObject args, ResultCallback rc) {
long start = System.currentTimeMillis();
JsonArray pubkeys = args.get("pubKeys").getAsJsonArray();
for (JsonElement pri : pubkeys)
NetworkManager.instance.connectToAgent(pri.getAsString(), null);
long end = System.currentTimeMillis();
rc.onResult("{\"duration\":" + (end - start) + ", \"action\":\"onWarmConnection\"}");
}
@Action(async = true, userPermission = 1L << 26) @Action(async = true, userPermission = 1L << 26)
// zyx modified // zyx modified
public void startContractMultiPoint(JsonObject args, final ResultCallback rc) { public void startContractMultiPoint(JsonObject args, final ResultCallback rc) {
@ -104,36 +92,36 @@ public class MasterWSAction {
} else if (args.has("projectName")) { } else if (args.has("projectName")) {
contract.setScript("/" + args.get("projectName").getAsString()); contract.setScript("/" + args.get("projectName").getAsString());
} }
if (args.has("createParam"))
contract.setCreateParam(args.get("createParam"));
// contract.setScript("/" + args.get("projectName").getAsString() + "/manifest.json"); // contract.setScript("/" + args.get("projectName").getAsString() + "/manifest.json");
// String toVerify = // String toVerify =
// "MultiPoint|" // "MultiPoint|"
// + args.get("type").getAsString() // + args.get("type").getAsString()
// + "|" // + "|"
// + contract.getScriptStr() // + contract.getScriptStr()
// + "|" // + "|"
// + managerAction.getPubKey(); // + managerAction.getPubKey();
// boolean verify = // boolean verify =
// SM2Util.plainStrVerify( // SM2Util.plainStrVerify(
// managerAction.getPubKey(), toVerify, // managerAction.getPubKey(), toVerify,
// args.get("sign").getAsString()); // args.get("sign").getAsString());
// //
// if (!verify) { // if (!verify) {
// Map<String, String> ret = new HashMap<>(); // Map<String, String> ret = new HashMap<>();
// ret.put("action", "onStartContractTrustfullyResult"); // ret.put("action", "onStartContractTrustfullyResult");
// ret.put("data", "verify signature failed"); // ret.put("data", "verify signature failed");
// ret.put("status", "Error"); // ret.put("status", "Error");
// rc.onResult(JsonUtil.toJson(ret)); // rc.onResult(JsonUtil.toJson(ret));
// return; // return;
// } // }
SM2KeyPair sm2Key; SM2KeyPair sm2Key;
String parPath = GlobalConf.instance.publicCompiledDir; String parPath = GlobalConf.instance.publicCompiledDir;
if (args.has("isPrivate") && args.get("isPrivate").getAsBoolean()) { if (args.has("isPrivate") && args.get("isPrivate").getAsBoolean()) {
parPath = GlobalConf.instance.privateCompiledDir + "/" parPath =
+ args.get("verifiedPubKey").getAsString(); GlobalConf.instance.privateCompiledDir
+ "/"
+ args.get("verifiedPubKey").getAsString();
} }
String scriptOrPath = contract.getScriptStr(); String scriptOrPath = contract.getScriptStr();
@ -154,42 +142,55 @@ public class MasterWSAction {
contract.setPublicKey(sm2Key.getPublicKeyStr()); contract.setPublicKey(sm2Key.getPublicKeyStr());
// TODO // TODO
// contract.setNodeCenterRepoDOI(DOIPMainServer4NC.repoIdentifier); // contract.setNodeCenterRepoDOI(DOIPMainServer4NC.repoIdentifier);
// 多点合约部署时由NC预先注册一个DOI以备使用 // 多点合约部署时由NC预先注册一个DOI以备使用
/* /*
* if (DoConfig.openContractDORegister) { try { HandleService hs = new if (DoConfig.openContractDORegister) {
* HandleService(HandleServiceUtils.hrRegister); String tmpDOI = try {
* hs.registerContract(DOIPMainServer4NC.repoIdentifier); if (tmpDOI == "" || tmpDOI == HandleService hs = new HandleService(HandleServiceUtils.hrRegister);
* null) contract.setDOI("RegisterFailed"); else contract.setDOI(tmpDOI); } catch (Exception String tmpDOI = hs.registerContract(DOIPMainServer4NC.repoIdentifier);
* e) { e.printStackTrace(); contract.setDOI("RegisterFailed"); } } if (tmpDOI == "" || tmpDOI == null)
*/ contract.setDOI("RegisterFailed");
List<String> nodeNames; // nodes' peerID else
// if (contract.getType().equals(ContractExecType.SelfAdaptiveSharding)) { contract.setDOI(tmpDOI);
// if (ContractManager.instance.nodeCenterConn.listNodes().length < 3) { }
// rc.onResult( catch (Exception e) {
// "{\"status\":\"Error\",\"result\":\"No enough nodes!\"," e.printStackTrace();
// + "\"action\":\"onStartTrustfulContract\"}"); contract.setDOI("RegisterFailed");
// return; }
// } }
// int unitSize = args.get("selectUnitNum").getAsInt(); */
// nodeNames = Set<String> nodeNames; // nodes' peerID
// Arrays.asList(ContractManager.instance.nodeCenterConn.getClusterByKey( // if (contract.getType().equals(ContractExecType.SelfAdaptiveSharding)) {
// contractID, // if (ContractManager.instance.nodeCenterConn.listNodes().length < 3) {
// Math.max(unitSize, 3))); // rc.onResult(
// } else { // "{\"status\":\"Error\",\"result\":\"No enough nodes!\","
// + "\"action\":\"onStartTrustfulContract\"}");
// return;
// }
// int unitSize = args.get("selectUnitNum").getAsInt();
// nodeNames =
// Arrays.asList(ContractManager.instance.nodeCenterConn.getClusterByKey(
// contractID,
// Math.max(unitSize, 3)));
// } else {
// all nodes' peerID in the unit // all nodes' peerID in the unit
String[] nodeNamesStr = args.get("peersID").getAsString().split(","); String[] nodeNamesStr =
args.get("peersID").getAsString().split(",");
// record information of these nodes // record information of these nodes
nodeNames = Arrays.stream(nodeNamesStr).filter(x -> null != x && !x.isEmpty()) nodeNames =
.collect(Collectors.toList()); Arrays.stream(nodeNamesStr)
// } .filter(x -> null != x && !x.isEmpty())
.collect(Collectors.toSet());
// }
SM2KeyPair keyPair = GlobalConf.instance.keyPair; SM2KeyPair keyPair = GlobalConf.instance.keyPair;
String masterNode = keyPair.getPublicKeyStr(); String masterNode = keyPair.getPublicKeyStr();
assert nodeNames.contains(masterNode); nodeNames.add(masterNode);
// nodeNames.add(masterNode);
int nodeSize = nodeNames.size(); int nodeSize = nodeNames.size();
// 方式一向NodeCenter发要求Slave节点主动连接到Master节点. // 方式一向NodeCenter发要求Slave节点主动连接到Master节点.
Map<String, Object> requestConnect = new HashMap<>(); Map<String, Object> requestConnect = new HashMap<>();
requestConnect.put("action", "requestConnectToMaster"); requestConnect.put("action", "requestConnectToMaster");
LOGGER.debug(multiPointContractInfo.masterNode); LOGGER.debug(multiPointContractInfo.masterNode);
@ -198,34 +199,47 @@ public class MasterWSAction {
if (contract.getType() == ContractExecType.Sharding) { if (contract.getType() == ContractExecType.Sharding) {
requestConnect.put("connectAll", true); requestConnect.put("connectAll", true);
} }
// NetworkManager.instance.sendToNodeCenter(JsonUtil.toJson(requestConnect)); // 向NC发 NetworkManager.instance.sendToNodeCenter(JsonUtil.toJson(requestConnect)); // 向NC发
// waitForConnection(nodeNames); waitForConnection(nodeNames);
LOGGER.debug(JsonUtil.toPrettyJson(requestConnect)); LOGGER.debug(JsonUtil.toPrettyJson(requestConnect));
ContractManager.threadPool.execute(
() -> {
// 多点合约更新repository信息
if (contract.getDOI() != null && !contract.getDOI().equals("null")) {
LOGGER.info("multipoint contract doi register");
GRPCPool.instance.reRegister(contract.getDOI());
} else {
LOGGER.info(
"multipoint contract don't update register "
+ (null == contract.getDOI() ? "null" : contract.getDOI()));
}
});
final long curr = System.currentTimeMillis(); final long curr = System.currentTimeMillis();
String requestID = curr + "_" + (int) (Math.random() * 10000); String requestID = curr + "_" + (int) (Math.random() * 10000);
ResultCollector collector = new ResultCollector(requestID, new ResultCallback() { ResultCollector collector =
@Override new ResultCollector(
public void onResult(String str) { requestID,
Map<String, String> ret = new HashMap<>(); new ResultCallback() {
ret.put("action", "onStartContractTrustfullyResult"); @Override
if (args.has("requestID")) { public void onResult(String str) {
ret.put("responseID", args.get("requestID").getAsString()); Map<String, String> ret = new HashMap<>();
} ret.put("action", "onStartContractTrustfullyResult");
ret.put("data", str); if (args.has("requestID")) {
ret.put("executionTime", (System.currentTimeMillis() - curr) + ""); ret.put("responseID", args.get("requestID").getAsString());
rc.onResult(ret); }
} ret.put("data", str);
}, nodeSize); ret.put("executionTime", (System.currentTimeMillis() - curr) + "");
rc.onResult(ret);
}
},
nodeSize);
MasterServerTCPAction.sync.sleepWithTimeout(requestID, collector, 20); MasterServerTCPAction.sync.sleepWithTimeout(requestID, collector, 20);
Map<String, Object> request = new HashMap<>(); Map<String, Object> request = new HashMap<>();
request.put("master", keyPair.getPublicKeyStr()); request.put("master", keyPair.getPublicKeyStr());
if (args.has("isPrivate")) { if (args.has("isPrivate")) {
request.put("isPrivate", args.get("isPrivate").getAsString()); request.put("isPrivate", args.get("isPrivate").getAsString());
} }
if (args.has("isDebug")) { request.put("pubKey", managerAction.getPubKey());
contract.setDebug(args.get("isDebug").getAsBoolean());
}
request.put("pubKey", getPubKey(args));
request.put("action", "startContractTrustfully"); request.put("action", "startContractTrustfully");
request.put("requestID", requestID); request.put("requestID", requestID);
request.put("members", nodeNames); // 执行这个合约的所有节点的pubKey request.put("members", nodeNames); // 执行这个合约的所有节点的pubKey
@ -241,7 +255,7 @@ public class MasterWSAction {
contract.setNumOfCopies(nodeSize); contract.setNumOfCopies(nodeSize);
break; break;
default: default:
contract.setNumOfCopies(1); // TODO copies是1 contract.setNumOfCopies(1); // TODO copies是1
break; break;
} }
LOGGER.debug("contract " + contract.getID() + " has been added into contractID2Members"); LOGGER.debug("contract " + contract.getID() + " has been added into contractID2Members");
@ -264,17 +278,16 @@ public class MasterWSAction {
if (!MasterServerRecoverMechAction.recoverStatus.containsKey(nodeID)) { if (!MasterServerRecoverMechAction.recoverStatus.containsKey(nodeID)) {
MasterServerRecoverMechAction.recoverStatus.put(nodeID, new ConcurrentHashMap<>()); MasterServerRecoverMechAction.recoverStatus.put(nodeID, new ConcurrentHashMap<>());
} }
MasterServerRecoverMechAction.recoverStatus.get(nodeID).put(contractID, MasterServerRecoverMechAction.recoverStatus
RecoverFlag.Fine); .get(nodeID)
.put(contractID, RecoverFlag.Fine);
} }
rc.onResult("{\"status\":\"Success\",\"result\":\"" + contract.getID() + "\"," rc.onResult(
+ "\"action\":\"onStartTrustfulContract\"}"); "{\"status\":\"Success\",\"result\":\""
+ contract.getID()
+ "\","
+ "\"action\":\"onStartTrustfulContract\"}");
LOGGER.info("startContractMultiPoint succeed!"); LOGGER.info("startContractMultiPoint succeed!");
} }
public String getPubKey(JsonObject jo) {
if (handler != null)
return handler.getPubKey();
return jo.get("pubKey").getAsString();
}
} }

View File

@ -18,14 +18,13 @@ import java.util.concurrent.atomic.AtomicInteger;
public class MultiRequestInfo { public class MultiRequestInfo {
public static final Object lock = new Object(); public static final Object lock = new Object();
private static final Logger LOGGER = LogManager.getLogger(MultiRequestInfo.class); private static final Logger LOGGER = LogManager.getLogger(MultiRequestInfo.class);
public static Map<String, MultiRequestInfo> reqInfos = public static Map<String, MultiRequestInfo> reqInfos = new ConcurrentHashMap<String, MultiRequestInfo>(); //key为requestID
new ConcurrentHashMap<String, MultiRequestInfo>(); // key为requestID
public final String requestID; public final String requestID;
public final int seq; public final int seq;
private final int total; private final int total;
private final AtomicInteger count = new AtomicInteger(0); private final AtomicInteger count = new AtomicInteger(0);
private final Map<String, Boolean> flag = new HashMap<>(); // uniID是否执行 private final Map<String, Boolean> flag = new HashMap<>(); //uniID是否执行
public Map<String, ResultCallback> callbackMap = new ConcurrentHashMap<>(); // key是uniqueID这个map中存的是第2个及之后的请求的callback第1个请求的callback在正常的请求队列中 public Map<String, ResultCallback> callbackMap = new ConcurrentHashMap<>(); //key是uniqueID这个map中存的是第2个及之后的请求的callback第1个请求的callback在正常的请求队列中
public MultiRequestInfo(String id, int t) { public MultiRequestInfo(String id, int t) {
requestID = id; requestID = id;
@ -33,47 +32,41 @@ public class MultiRequestInfo {
total = Integer.parseInt(id.split("_")[1]); total = Integer.parseInt(id.split("_")[1]);
} }
// 交给线程池中线程完成不能是同一个线程跑 //交给线程池中线程完成不能是同一个线程跑
public static void exeMultiReq(ContractRequest request, String uniID) { public static void exeMultiReq(ContractRequest request, String uniID) {
ContractManagerFrameHandler.executorService.execute(() -> { ContractManagerFrameHandler.executorService.execute(
exeMultiReqInternal(request, uniID); () -> {
}); exeMultiReqInternal(request, uniID);
}
);
} }
// 多点合约请求第一个放入队列中其余的不放入队列完成此方法对于不放入队列中的多点合约请求 //多点合约请求第一个放入队列中其余的不放入队列完成此方法对于不放入队列中的多点合约请求
private static void exeMultiReqInternal(ContractRequest request, String uniID) { private static void exeMultiReqInternal(ContractRequest request, String uniID) {
// logger.info("【exeMultiReqInternal】 uniID=" + uniID + " Thread-id=" + //logger.info("【exeMultiReqInternal】 uniID=" + uniID + " Thread-id=" + Thread.currentThread().getId() + " ---1");
// Thread.currentThread().getId() + " ---1");
// TODO 2个线程都卡在这 //TODO 2个线程都卡在这
long start = System.currentTimeMillis(); long start = System.currentTimeMillis();
// logger.info("【exeMultiReqInternal】 uniID=" + uniID + " Thread-id=" + //logger.info("【exeMultiReqInternal】 uniID=" + uniID + " Thread-id=" + Thread.currentThread().getId() + " ---2");
// Thread.currentThread().getId() + " ---2");
MultiContractMeta cei = CMActions.manager.multiContractRecorder MultiContractMeta cei = CMActions.manager.multiContractRecorder.getMultiContractMeta(request.getContractID());
.getMultiContractMeta(request.getContractID()); //logger.info("【exeMultiReqInternal】 uniID=" + uniID + " Thread-id=" + Thread.currentThread().getId() + " ---3 " + (reqInfos.containsKey(request.getRequestID())));
// logger.info("【exeMultiReqInternal】 uniID=" + uniID + " Thread-id=" +
// Thread.currentThread().getId() + " ---3 " +
// (reqInfos.containsKey(request.getRequestID())));
MultiRequestInfo mri = reqInfos.get(request.getRequestID()); MultiRequestInfo mri = reqInfos.get(request.getRequestID());
// logger.info("【exeMultiReqInternal】 uniID=" + uniID + " Thread-id=" + //logger.info("【exeMultiReqInternal】 uniID=" + uniID + " Thread-id=" + Thread.currentThread().getId() + " ---4");
// Thread.currentThread().getId() + " ---4");
synchronized (mri.flag) { synchronized (mri.flag) {
// logger.info("【exeMultiReqInternal】 uniID=" + uniID + " Thread-id=" + //logger.info("【exeMultiReqInternal】 uniID=" + uniID + " Thread-id=" + Thread.currentThread().getId() + " ---5");
// Thread.currentThread().getId() + " ---5");
if (cei.curExeSeq > -1 && cei.curExeSeq < mri.seq) { if (cei.curExeSeq > -1 && cei.curExeSeq < mri.seq) {
// logger.info("还未执行到 " + mri.seq + " 当前序号是 " + cei.curExeSeq); // logger.info("还未执行到 " + mri.seq + " 当前序号是 " + cei.curExeSeq);
return; return;
} }
if (mri.flag.get(uniID)) { if (mri.flag.get(uniID)) {
// logger.info("uniID=" + uniID + " 已执行过 " + " Thread-id=" + //logger.info("uniID=" + uniID + " 已执行过 " + " Thread-id=" + Thread.currentThread().getId());
// Thread.currentThread().getId());
return; return;
} else { } else {
mri.flag.put(uniID, true); mri.flag.put(uniID, true);
@ -82,30 +75,28 @@ public class MultiRequestInfo {
if (-1 == cei.curExeSeq) if (-1 == cei.curExeSeq)
cei.curExeSeq = mri.seq; cei.curExeSeq = mri.seq;
// logger.info("调试位置 3 cei.curExeSeq=" + cei.curExeSeq + " MultiRequestInfo 执行请求 " + //logger.info("调试位置 3 cei.curExeSeq=" + cei.curExeSeq + " MultiRequestInfo 执行请求 " + request.seq + " uniID=" + uniID + " Thread-id=" + Thread.currentThread().getId());
// request.seq + " uniID=" + uniID + " Thread-id=" + Thread.currentThread().getId()); String data2 = CMActions.manager.executeLocally(request, null);
CMActions.manager.executeLocallyAsync(request, new ResultCallback() { // logger.info("本地执行的结果为\n" + data2);
@Override Map<String, String> ret = new HashMap<>();
public void onResult(String str) { ret.put("action", "receiveTrustfullyResult");
Map<String, String> ret = new HashMap<>(); SM2KeyPair keyPair = GlobalConf.instance.keyPair;
ret.put("action", "receiveTrustfullyResult"); ret.put("nodeID", keyPair.getPublicKeyStr());
SM2KeyPair keyPair = GlobalConf.instance.keyPair; int seq = request.seq;
ret.put("nodeID", keyPair.getPublicKeyStr());
int seq = request.seq;
ret.put("responseID", uniID); ret.put("responseID", uniID);
ret.put("executeTime", (System.currentTimeMillis() - start) + ""); ret.put("executeTime", (System.currentTimeMillis() - start) + "");
ret.put("data", str); ret.put("data", data2);
mri.countIncrease(); mri.countIncrease();
// logger.info("返回 uniID=" + uniID + " 的结果");
mri.callbackMap.get(uniID).onResult(JsonUtil.toJson(ret)); //logger.info("返回 uniID=" + uniID + " 的结果");
}
}, null); mri.callbackMap.get(uniID).onResult(JsonUtil.toJson(ret));
} }
public synchronized void countIncrease() { public synchronized void countIncrease() {
int tmp = count.incrementAndGet(); int tmp = count.incrementAndGet();
// logger.info("【MultiRequestInfo】 countIncrease tmp=" + tmp + " total=" + total); //logger.info("【MultiRequestInfo】 countIncrease tmp=" + tmp + " total=" + total);
if (tmp == total) { if (tmp == total) {
reqInfos.remove(requestID); reqInfos.remove(requestID);
} }

View File

@ -76,8 +76,7 @@ public class ProcessAction {
sc.nextLine(); sc.nextLine();
while (sc.hasNextLine()) { while (sc.hasNextLine()) {
String line = sc.nextLine(); String line = sc.nextLine();
if (!line.contains("yjs.jar") || !line.contains("java")) if (!line.contains("yjs.jar") || !line.contains("java")) continue;
continue;
LOGGER.debug("==ListLeakCP=:" + line); LOGGER.debug("==ListLeakCP=:" + line);
Scanner sc2 = new Scanner(new ByteArrayInputStream(line.getBytes())); Scanner sc2 = new Scanner(new ByteArrayInputStream(line.getBytes()));
sc2.next(); sc2.next();

View File

@ -23,7 +23,8 @@ public class ReadmeGenerator {
private String generateReadme() { private String generateReadme() {
VelocityEngine engine = new VelocityEngine(); VelocityEngine engine = new VelocityEngine();
engine.setProperty("file.resource.loader.path", engine.setProperty(
"file.resource.loader.path",
new File(templatePath, "ReadmeTemplate").getAbsolutePath()); new File(templatePath, "ReadmeTemplate").getAbsolutePath());
createREADMEIfNotExists(new File(templatePath, "ReadmeTemplate")); createREADMEIfNotExists(new File(templatePath, "ReadmeTemplate"));
VelocityContext ctx = new VelocityContext(); VelocityContext ctx = new VelocityContext();
@ -31,17 +32,18 @@ public class ReadmeGenerator {
readmeFuncs = new ArrayList<>(); readmeFuncs = new ArrayList<>();
} }
for (ReadmeFunction rm : readmeFuncs) { for (ReadmeFunction rm : readmeFuncs) {
/* /*if (rm.funcDefaultArg == null) {
* if (rm.funcDefaultArg == null) { rm.funcDefaultArg = "未提供默认参数"; } if rm.funcDefaultArg = "未提供默认参数";
* (rm.funcDefaultResult == null) { rm.funcDefaultResult = "暂无返回结果示例"; } }
*/ if (rm.funcDefaultResult == null) {
rm.funcDefaultResult = "暂无返回结果示例";
}*/
if (rm.funcDescription == null) { if (rm.funcDescription == null) {
rm.funcDescription = "暂无描述"; rm.funcDescription = "暂无描述";
} }
/* /*if (rm.funcMockTemplate == null) {
* if (rm.funcMockTemplate == null) { rm.funcMockTemplate = rm.funcMockTemplate = "{\"result\":\"emptyMock\"}";
* "{\"result\":\"emptyMock\"}"; } }*/
*/
if (rm.funcArgTemplate == null) { if (rm.funcArgTemplate == null) {
rm.funcArgTemplate = "暂无参数模板"; rm.funcArgTemplate = "暂无参数模板";
} }
@ -74,24 +76,63 @@ public class ReadmeGenerator {
readmeTemplate.mkdirs(); readmeTemplate.mkdirs();
File content = new File(readmeTemplate, "README.md.vm"); File content = new File(readmeTemplate, "README.md.vm");
try { try {
FileUtils.writeStringToFile(content, FileUtils.writeStringToFile(
/* content,
* "# 简介\n" + "\n" + "${contractDesp}\n" + "\n" + "#set($hash='#')\n" + /*"# 简介\n"
* "# 获取数据相关方法说明\n" + "#foreach($func in ${readmeFuncs})\n" + "\n" + + "\n"
* "$hash$hash ${func.funcName}\n" + "\n" + ">$func.funcDescription\n" + + "${contractDesp}\n"
* "\n" + "$hash$hash$hash 参数示例\n" + "```json\n" + "$func.funcDefaultArg\n" + "\n"
* + "```\n" + "\n" + "$hash$hash$hash 数据模板\n" + "```json\n" + + "#set($hash='#')\n"
* "$func.funcMockTemplate\n" + "```\n" + "\n" + "$hash$hash$hash 返回结果\n" + + "# 获取数据相关方法说明\n"
* "\n" + "```json\n" + "$func.funcDefaultResult\n" + "```\n" + "\n" + + "#foreach($func in ${readmeFuncs})\n"
* "#end\n" + "\n", + "\n"
*/ + "$hash$hash ${func.funcName}\n"
"# 简介\n" + "\n" + "${contractDesp}\n" + "\n" + "#set($hash='#')\n" + "\n"
+ "# 获取数据相关方法说明\n" + "#foreach($func in ${readmeFuncs})\n" + "\n" + ">$func.funcDescription\n"
+ "$hash$hash${func.funcName}\n" + "\n" + ">$func.funcDescription\n" + "\n"
+ "\n" + "$hash$hash$hash 参数模板\n" + "```json\n" + "$hash$hash$hash 参数示例\n"
+ "$func.funcDefaultArg\n" + "```\n" + "\n" + "```json\n"
+ "$hash$hash$hash 调用结果\n" + "\n" + "```json\n" + "$func.funcDefaultArg\n"
+ "$func.funcRecordsString\n" + "```\n" + "\n" + "#end\n" + "\n", + "```\n"
+ "\n"
+ "$hash$hash$hash 数据模板\n"
+ "```json\n"
+ "$func.funcMockTemplate\n"
+ "```\n"
+ "\n"
+ "$hash$hash$hash 返回结果\n"
+ "\n"
+ "```json\n"
+ "$func.funcDefaultResult\n"
+ "```\n"
+ "\n"
+ "#end\n"
+ "\n",*/
"# 简介\n"
+ "\n"
+ "${contractDesp}\n"
+ "\n"
+ "#set($hash='#')\n"
+ "# 获取数据相关方法说明\n"
+ "#foreach($func in ${readmeFuncs})\n"
+ "\n"
+ "$hash$hash${func.funcName}\n"
+ "\n"
+ ">$func.funcDescription\n"
+ "\n"
+ "$hash$hash$hash 参数模板\n"
+ "```json\n"
+ "$func.funcDefaultArg\n"
+ "```\n"
+ "\n"
+ "$hash$hash$hash 调用结果\n"
+ "\n"
+ "```json\n"
+ "$func.funcRecordsString\n"
+ "```\n"
+ "\n"
+ "#end\n"
+ "\n",
StandardCharsets.UTF_8); StandardCharsets.UTF_8);
} catch (IOException e) { } catch (IOException e) {
e.printStackTrace(); e.printStackTrace();
@ -108,8 +149,7 @@ public class ReadmeGenerator {
if (!name.exists()) { if (!name.exists()) {
FileUtils.writeStringToFile(name, generateReadme(), StandardCharsets.UTF_8); FileUtils.writeStringToFile(name, generateReadme(), StandardCharsets.UTF_8);
return "生成文档 " + name.getName(); return "生成文档 " + name.getName();
} else } else return "请删除已有README.md";
return "请删除已有README.md";
} catch (Exception e) { } catch (Exception e) {
e.printStackTrace(); e.printStackTrace();
return "生成文档异常"; return "生成文档异常";
@ -130,19 +170,19 @@ public class ReadmeGenerator {
public String funcDescription; public String funcDescription;
public String funcDefaultArg; public String funcDefaultArg;
public String funcDefaultResult; public String funcDefaultResult;
// public String funcMockTemplate; //public String funcMockTemplate;
public String funcRecordsString; public String funcRecordsString;
public String funcArgTemplate; public String funcArgTemplate;
public String funcArgSchema; public String funcArgSchema;
public String funcResultSchema; public String funcResultSchema;
public String funcResultTemplate; public String funcResultTemplate;
public ReadmeFunction(String name, String description, String argSchema, String argTemplate, public ReadmeFunction(
String resultSchema, String recordsString) { String name, String description, String argSchema, String argTemplate, String resultSchema, String recordsString) {
funcName = name; funcName = name;
funcDescription = description; funcDescription = description;
funcArgTemplate = argTemplate; funcArgTemplate = argTemplate;
// funcResultTemplate = resTemplate; //funcResultTemplate = resTemplate;
funcRecordsString = recordsString; funcRecordsString = recordsString;
funcArgSchema = argSchema; funcArgSchema = argSchema;
funcResultSchema = resultSchema; funcResultSchema = resultSchema;
@ -165,9 +205,9 @@ public class ReadmeGenerator {
return funcDefaultResult.replace("\\\"", "\""); return funcDefaultResult.replace("\\\"", "\"");
} }
/* /*public String getFuncMockTemplate() {
* public String getFuncMockTemplate() { return funcMockTemplate; } return funcMockTemplate;
*/ }*/
public String getFuncArgTemplate() { public String getFuncArgTemplate() {
return funcArgTemplate; return funcArgTemplate;

View File

@ -1,12 +1,11 @@
package org.bdware.server.action; package org.bdware.server.action;
import org.bdware.sc.bean.ContractRequest; import org.bdware.sc.bean.ContractRequest;
public class RequestToMaster { public class RequestToMaster {
long requestTime; long requestTime;
ContractRequest cr; ContractRequest cr;
public RequestToMaster(ContractRequest c) { public RequestToMaster(ContractRequest c){
requestTime = System.currentTimeMillis(); requestTime = System.currentTimeMillis();
cr = c; cr = c;
} }

View File

@ -3,7 +3,10 @@ package org.bdware.server.action;
import com.google.gson.JsonObject; import com.google.gson.JsonObject;
import org.apache.logging.log4j.LogManager; import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger; import org.apache.logging.log4j.Logger;
import org.bdware.sc.*; import org.bdware.sc.ContractClient;
import org.bdware.sc.ContractManager;
import org.bdware.sc.ContractMeta;
import org.bdware.sc.ContractStatusEnum;
import org.bdware.sc.bean.Contract; import org.bdware.sc.bean.Contract;
import org.bdware.sc.bean.ContractExecType; import org.bdware.sc.bean.ContractExecType;
import org.bdware.sc.conn.ResultCallback; import org.bdware.sc.conn.ResultCallback;
@ -37,7 +40,7 @@ public class TemporyTestAction {
@Action @Action
public void startContractForTest(JsonObject args, ResultCallback resultCallback) { public void startContractForTest(JsonObject args, ResultCallback resultCallback) {
FileActions.startIfManifestDetected( FileActions.startIfManifestDetected(
new File(args.get("path").getAsString()).getAbsoluteFile(), true); new File(args.get("path").getAsString()).getAbsoluteFile());
resultCallback.onResult("done"); resultCallback.onResult("done");
} }
@ -84,22 +87,25 @@ public class TemporyTestAction {
@Action(async = true) @Action(async = true)
public void batchCompile(JsonObject args, ResultCallback resultCallback) { public void batchCompile(JsonObject args, ResultCallback resultCallback) {
ContractManagerFrameHandler.executorService.execute(() -> { ContractManagerFrameHandler.executorService.execute(
File privateDir = new File(GlobalConf.instance.privateDir); () -> {
File[] list = privateDir.listFiles(new FileFilter() { File privateDir = new File(GlobalConf.instance.privateDir);
@Override File[] list =
public boolean accept(File pathname) { privateDir.listFiles(
return pathname.isDirectory(); new FileFilter() {
} @Override
}); public boolean accept(File pathname) {
totalCompile = list.length; return pathname.isDirectory();
compileProgress = 0; }
if (list != null) });
for (File userDir : list) { totalCompile = list.length;
compileProgress++; compileProgress = 0;
compileAllUserProject(userDir); if (list != null)
} for (File userDir : list) {
}); compileProgress++;
compileAllUserProject(userDir);
}
});
peekComplieProgress(args, resultCallback); peekComplieProgress(args, resultCallback);
} }
@ -166,10 +172,6 @@ public class TemporyTestAction {
Contract c = new Contract(); Contract c = new Contract();
c.setScript(args.get("script").getAsString()); c.setScript(args.get("script").getAsString());
c.setOwner(args.get("owner").getAsString()); c.setOwner(args.get("owner").getAsString());
if (args.has("doipStartPort")) {
c.setDoipPort(args.get("doipStartPort").getAsInt());
} else
c.setDoipPort(1716);
ContractManager.instance.allocateKeyIfNotExists(c); ContractManager.instance.allocateKeyIfNotExists(c);
JsonObject jo = JsonUtil.parseObjectAsJsonObject(c); JsonObject jo = JsonUtil.parseObjectAsJsonObject(c);
jo.addProperty("action", "onAllocateKeyPair"); jo.addProperty("action", "onAllocateKeyPair");
@ -177,17 +179,10 @@ public class TemporyTestAction {
} }
@Action(async = true) @Action(async = true)
public void reconnectPort(JsonObject args, ResultCallback resultCallback) { public void reconnectAll(JsonObject args, ResultCallback resultCallback) {
ContractPort.PortVisitor reconnectVisitor = CMActions.manager.statusRecorder.getVisitor(); ContractManager.instance.reconnectContractProcess();
String host = null; String data = ContractManager.instance.listContractsWithOwner(
if (args.has("host")) args.get("owner").getAsString(), null, 0);
host = args.get("host").getAsString();
if (host != null)
reconnectVisitor.visit(host, args.get("port").getAsInt());
else
reconnectVisitor.visit(args.get("port").getAsInt());
String data = ContractManager.instance
.listContractsWithOwner(args.get("owner").getAsString(), null, 0);
JsonObject ret = new JsonObject(); JsonObject ret = new JsonObject();
ret.addProperty("data", data); ret.addProperty("data", data);
ret.addProperty("action", "onReconnectAll"); ret.addProperty("action", "onReconnectAll");

View File

@ -21,15 +21,18 @@ import java.util.concurrent.ConcurrentLinkedQueue;
// 节点管理员用户管理页面 // 节点管理员用户管理页面
public class UserManagerAction { public class UserManagerAction {
public static final String NodeManager = "__NodeManager__"; public static final String NodeManager = "__NodeManager__";
static final Counter counter = Counter.build().name("contract_login_counter") static final Counter counter =
.help("contract login counter").register(); Counter.build()
.name("contract_login_counter")
.help("contract login counter")
.register();
private static final Logger LOGGER = LogManager.getLogger(UserManagerAction.class); private static final Logger LOGGER = LogManager.getLogger(UserManagerAction.class);
public static ConcurrentLinkedQueue<String> contractInstanceMangerPool = public static ConcurrentLinkedQueue<String> contractInstanceMangerPool =
new ConcurrentLinkedQueue<>(); new ConcurrentLinkedQueue<>();
private final Random random = new Random(); private final Random random = new Random();
ContractManagerFrameHandler handler; ContractManagerFrameHandler handler;
private String sessionID; private String sessionID;
private String publicKey; private String pubKey;
public static String getNodeManager() { public static String getNodeManager() {
return KeyValueDBUtil.instance.getValue(CMTables.ConfigDB.toString(), NodeManager); return KeyValueDBUtil.instance.getValue(CMTables.ConfigDB.toString(), NodeManager);
@ -39,36 +42,6 @@ public class UserManagerAction {
handler = contractManagerFrameHandler; handler = contractManagerFrameHandler;
} }
@Action(userPermission = 0)
public void resetNodeManager(JsonObject json, ResultCallback resultCallback) {
getNodeRole(json, new ResultCallback() {
@Override
public void onResult(String str) {
if (str.contains("NodeManager")) {
if (json.has("newPubKey")) {
String newPubKey = json.get("newPubKey").getAsString();
KeyValueDBUtil.instance.setValue(CMTables.ConfigDB.toString(), NodeManager,
newPubKey);
KeyValueDBUtil.instance.setValue(CMTables.NodeRole.toString(), newPubKey,
"NodeManager");
resultCallback.onResult(
"{\"action\":\"onResetNodeManager\",\"data\":\"success\",\"pubKey\":\""
+ newPubKey + "\"}");
} else {
// just keep the same
resultCallback.onResult(
"{\"action\":\"onResetNodeManager\",\"data\":\"success\",\"pubKey\":\""
+ getPubKey(json) + "\"}");
}
} else {
resultCallback.onResult(
"{\"action\":\"onResetNodeManager\",\"data\":\"failed, no permission\"}");
}
}
});
}
@Action(userPermission = 0) @Action(userPermission = 0)
public void getSessionID(JsonObject json, ResultCallback resultCallback) { public void getSessionID(JsonObject json, ResultCallback resultCallback) {
sessionID = random.nextLong() + "_session_node"; sessionID = random.nextLong() + "_session_node";
@ -78,13 +51,13 @@ public class UserManagerAction {
@Action(userPermission = 0) @Action(userPermission = 0)
public void login(JsonObject json, ResultCallback resultCallback) { public void login(JsonObject json, ResultCallback resultCallback) {
if (sessionID == null) { if (sessionID == null) {
resultCallback.onResult("{\"action\":\"onLogin\",\"status\":\"failed, no session\"," resultCallback.onResult("{\"action\":\"onLogin\",\"status\":\"failed, no session\"," +
+ "\"data\":\"" + Role.Anonymous.name() + "\"}"); "\"data\":\"" + Role.Anonymous.name() + "\"}");
} }
LOGGER.debug("[NodeManagerAction] session:" + (sessionID)); LOGGER.debug("[NodeManagerAction] session:" + (sessionID));
String pubKey = json.get("pubKey").getAsString(); String pubKey = json.get("pubKey").getAsString();
if (SM2Util.plainStrVerify(pubKey, sessionID, json.get("signature").getAsString())) { if (SM2Util.plainStrVerify(pubKey, sessionID, json.get("signature").getAsString())) {
this.publicKey = pubKey; this.pubKey = pubKey;
counter.inc(); counter.inc();
// 是否有该用户的私有目录,没有就创建 // 是否有该用户的私有目录,没有就创建
// BUG修复需要仅在验证通过后可创建 // BUG修复需要仅在验证通过后可创建
@ -94,22 +67,16 @@ public class UserManagerAction {
} }
getNodeRole(json, resultCallback); getNodeRole(json, resultCallback);
} else { } else {
handler.setPermission(0);
setHandlerPermission(0); resultCallback.onResult(
resultCallback.onResult("{\"action\":\"onLogin\",\"status\":\"verify sign failed\"," "{\"action\":\"onLogin\",\"status\":\"verify sign failed\"," +
+ "\"data\":\"" + Role.Anonymous.name() + "\"}"); "\"data\":\"" + Role.Anonymous.name() + "\"}");
} }
} }
private void setHandlerPermission(long i) {
if (handler != null)
handler.setPermission(i);
}
public void getNodeRole(JsonObject json, ResultCallback resultCallback) { public void getNodeRole(JsonObject json, ResultCallback resultCallback) {
String pubKey = getPubKey(json); if (pubKey == null) {
if (getPubKey(json) == null) {
resultCallback.onResult( resultCallback.onResult(
"{\"action\":\"onLogin\",\"data\":\"" + Role.Anonymous.name() + "\"}"); "{\"action\":\"onLogin\",\"data\":\"" + Role.Anonymous.name() + "\"}");
return; return;
@ -122,30 +89,30 @@ public class UserManagerAction {
ret = KeyValueDBUtil.instance.getValue(CMTables.NodeRole.toString(), pubKey); ret = KeyValueDBUtil.instance.getValue(CMTables.NodeRole.toString(), pubKey);
if (isNodeManager) { if (isNodeManager) {
if (ret != null && ret.length() > 0) { if (ret != null && ret.length() > 0) {
setHandlerPermission(0x86000f41L | Role.compoundValue(ret.split(","))); handler.setPermission(0x86000f41L | Role.compoundValue(ret.split(",")));
resultCallback resultCallback.onResult(
.onResult("{\"action\":\"onLogin\",\"data\":\"" + ret + "\"}"); "{\"action\":\"onLogin\",\"data\":\"" + ret + "\"}");
} else { } else {
setHandlerPermission(0x86000f41L); handler.setPermission(0x86000f41L);
resultCallback resultCallback.onResult(
.onResult("{\"action\":\"onLogin\",\"data\":\"NodeManager\"}"); "{\"action\":\"onLogin\",\"data\":\"NodeManager\"}");
} }
} else { } else {
if (ret == null || ret.equals("")) { if (ret == null || ret.equals("")) {
ret = Role.Anonymous.name(); ret = Role.Anonymous.name();
setHandlerPermission(0); handler.setPermission(0);
} else { } else {
setHandlerPermission(Role.compoundValue(ret.split(","))); handler.setPermission(Role.compoundValue(ret.split(",")));
} }
resultCallback.onResult("{\"action\":\"onLogin\",\"data\":\"" + ret + "\"}"); resultCallback.onResult("{\"action\":\"onLogin\",\"data\":\"" + ret + "\"}");
} }
} else { } else {
KeyValueDBUtil.instance.setValue(CMTables.ConfigDB.toString(), NodeManager, pubKey); KeyValueDBUtil.instance.setValue(CMTables.ConfigDB.toString(), NodeManager, pubKey);
KeyValueDBUtil.instance.setValue(CMTables.NodeRole.toString(), pubKey, KeyValueDBUtil.instance.setValue(
"NodeManager"); CMTables.NodeRole.toString(), pubKey, "NodeManager");
KeyValueDBUtil.instance.setValue(CMTables.NodeTime.toString(), pubKey, KeyValueDBUtil.instance.setValue(
Long.toString(new Date().getTime())); CMTables.NodeTime.toString(), pubKey, Long.toString(new Date().getTime()));
setHandlerPermission(0x86000d41L); handler.setPermission(0x86000d41L);
resultCallback.onResult("{\"action\":\"onLogin\",\"data\":\"NodeManager\"}"); resultCallback.onResult("{\"action\":\"onLogin\",\"data\":\"NodeManager\"}");
} }
} catch (Exception e) { } catch (Exception e) {
@ -157,7 +124,7 @@ public class UserManagerAction {
@Action(userPermission = 0) @Action(userPermission = 0)
public void applyNodeRole(JsonObject json, ResultCallback resultCallback) { public void applyNodeRole(JsonObject json, ResultCallback resultCallback) {
if (getPubKey(json) == null) { if (pubKey == null) {
resultCallback.onResult("{\"action\":\"onApplyNodeRole\",\"data\":\"missing pubKey\"}"); resultCallback.onResult("{\"action\":\"onApplyNodeRole\",\"data\":\"missing pubKey\"}");
return; return;
} }
@ -166,7 +133,7 @@ public class UserManagerAction {
LOGGER.debug("[role]" + ro); LOGGER.debug("[role]" + ro);
Role role = Role.parse(json.get("role").getAsString()); Role role = Role.parse(json.get("role").getAsString());
if (role != Role.Anonymous) { if (role != Role.Anonymous) {
applyNodeRoleAtDB(role, getPubKey(json), resultCallback); applyNodeRoleAtDB(role, resultCallback);
return; return;
} }
} }
@ -174,7 +141,7 @@ public class UserManagerAction {
"{\"action\":\"onApplyNodeRole\",\"data\":\"success\",\"role\":\"" + ro + "\"}"); "{\"action\":\"onApplyNodeRole\",\"data\":\"success\",\"role\":\"" + ro + "\"}");
} }
private void applyNodeRoleAtDB(Role role, String pubKey, ResultCallback resultCallback) { private void applyNodeRoleAtDB(Role role, ResultCallback resultCallback) {
String str = KeyValueDBUtil.instance.getValue(CMTables.ApplyRole.toString(), pubKey); String str = KeyValueDBUtil.instance.getValue(CMTables.ApplyRole.toString(), pubKey);
String already = KeyValueDBUtil.instance.getValue(CMTables.NodeRole.toString(), pubKey); String already = KeyValueDBUtil.instance.getValue(CMTables.NodeRole.toString(), pubKey);
if (already != null && already.contains(role.toString())) { if (already != null && already.contains(role.toString())) {
@ -187,11 +154,11 @@ public class UserManagerAction {
} else { } else {
if (!str.contains(role.name())) if (!str.contains(role.name()))
KeyValueDBUtil.instance.setValue(CMTables.ApplyRole.toString(), pubKey, KeyValueDBUtil.instance.setValue(
str + "," + role.name()); CMTables.ApplyRole.toString(), pubKey, str + "," + role.name());
} }
KeyValueDBUtil.instance.setValue(CMTables.ApplyTime.toString(), pubKey, KeyValueDBUtil.instance.setValue(
Long.toString(new Date().getTime())); CMTables.ApplyTime.toString(), pubKey, Long.toString(new Date().getTime()));
resultCallback.onResult("{\"action\":\"onApplyRole\",\"data\":\"success\"}"); resultCallback.onResult("{\"action\":\"onApplyRole\",\"data\":\"success\"}");
} }
@ -271,8 +238,8 @@ public class UserManagerAction {
if (roString.length() > 0) { if (roString.length() > 0) {
roString = new StringBuilder(roString.subSequence(0, roString.length() - 1).toString()); roString = new StringBuilder(roString.subSequence(0, roString.length() - 1).toString());
KeyValueDBUtil.instance.setValue(CMTables.NodeRole.toString(), pubKey, KeyValueDBUtil.instance.setValue(
roString.toString()); CMTables.NodeRole.toString(), pubKey, roString.toString());
} else { } else {
KeyValueDBUtil.instance.delete(CMTables.NodeRole.toString(), pubKey); KeyValueDBUtil.instance.delete(CMTables.NodeRole.toString(), pubKey);
KeyValueDBUtil.instance.delete(CMTables.NodeTime.toString(), pubKey); KeyValueDBUtil.instance.delete(CMTables.NodeTime.toString(), pubKey);
@ -283,9 +250,6 @@ public class UserManagerAction {
@Action(userPermission = 1 << 10) @Action(userPermission = 1 << 10)
public void authNodeRole(JsonObject json, ResultCallback resultCallback) { public void authNodeRole(JsonObject json, ResultCallback resultCallback) {
String pubKey = json.get("pubKey").getAsString(); String pubKey = json.get("pubKey").getAsString();
if (json.has("authorizedPubKey")) {
pubKey = json.get("authorizedPubKey").getAsString();
}
boolean isAccept = json.get("isAccept").getAsBoolean(); boolean isAccept = json.get("isAccept").getAsBoolean();
if (pubKey == null || pubKey.length() == 0) { if (pubKey == null || pubKey.length() == 0) {
resultCallback.onResult("{\"action\":\"onAuthNodeRole\",\"data\":\"missing pubKey\"}"); resultCallback.onResult("{\"action\":\"onAuthNodeRole\",\"data\":\"missing pubKey\"}");
@ -313,8 +277,8 @@ public class UserManagerAction {
already = roles; already = roles;
} }
KeyValueDBUtil.instance.setValue(CMTables.NodeRole.toString(), pubKey, already); KeyValueDBUtil.instance.setValue(CMTables.NodeRole.toString(), pubKey, already);
KeyValueDBUtil.instance.setValue(CMTables.NodeTime.toString(), pubKey, KeyValueDBUtil.instance.setValue(
Long.toString(new Date().getTime())); CMTables.NodeTime.toString(), pubKey, Long.toString(new Date().getTime()));
KeyValueDBUtil.instance.delete(CMTables.ApplyRole.toString(), pubKey); KeyValueDBUtil.instance.delete(CMTables.ApplyRole.toString(), pubKey);
KeyValueDBUtil.instance.delete(CMTables.ApplyTime.toString(), pubKey); KeyValueDBUtil.instance.delete(CMTables.ApplyTime.toString(), pubKey);
resultCallback.onResult("{\"action\":\"onAuthNodeRole\",\"data\":\"success\"}"); resultCallback.onResult("{\"action\":\"onAuthNodeRole\",\"data\":\"success\"}");
@ -322,26 +286,15 @@ public class UserManagerAction {
@Action(userPermission = 0) @Action(userPermission = 0)
public void queryRole(JsonObject args, final ResultCallback resultCallback) { public void queryRole(JsonObject args, final ResultCallback resultCallback) {
String pubkey = getPubKey(args); if (pubKey == null) {
if (pubkey == null) {
resultCallback.onResult("{\"action\":\"onQueryRole\",\"data\":\"anonymous\"}"); resultCallback.onResult("{\"action\":\"onQueryRole\",\"data\":\"anonymous\"}");
return; return;
} }
args.addProperty("pubKey", pubkey); args.addProperty("pubKey", pubKey);
args.addProperty("requestID", random.nextLong() + "_ID"); args.addProperty("requestID", random.nextLong() + "_ID");
} }
public String getPubKey() { public String getPubKey() {
return getPubKey(null); return pubKey;
}
private String getPubKey(JsonObject json) {
try {
if (this.publicKey != null)
return this.publicKey;
return json.get("pubKey").getAsString();
} catch (Exception e) {
return null;
}
} }
} }

View File

@ -20,8 +20,8 @@ import java.util.Map;
import java.util.TimerTask; import java.util.TimerTask;
public class AliveCheckClientAction { public class AliveCheckClientAction {
public static final int sendDelay = 20000; public static final int sendDelay = 2000;
public static final int checkDelay = 50000; public static final int checkDelay = 5000;
private static final Logger LOGGER = LogManager.getLogger(AliveCheckClientAction.class); private static final Logger LOGGER = LogManager.getLogger(AliveCheckClientAction.class);
private static final SimpleDateFormat DATE_FORMAT = new SimpleDateFormat("yyyy-MM-dd.HH:mm:ss"); private static final SimpleDateFormat DATE_FORMAT = new SimpleDateFormat("yyyy-MM-dd.HH:mm:ss");
private final String masterPubkey; private final String masterPubkey;
@ -57,65 +57,76 @@ public class AliveCheckClientAction {
public void checkMasterAlive(ResultCallback rc) { public void checkMasterAlive(ResultCallback rc) {
if (sendPingTask == null) if (sendPingTask == null)
sendPingTask = new TimerTask() { sendPingTask =
@Override new TimerTask() {
public void run() { @Override
try { public void run() {
LOGGER.debug(String.format("f %s", try {
DATE_FORMAT.format(System.currentTimeMillis()))); LOGGER.debug(
Map<String, String> ping = new HashMap<>(); String.format(
ping.put("action", "masterPing"); "f %s",
rc.onResult(JsonUtil.toJson(ping)); DATE_FORMAT
} catch (Throwable t) { .format(System.currentTimeMillis())));
t.printStackTrace(); Map<String, String> ping = new HashMap<>();
} ping.put("action", "masterPing");
} rc.onResult(JsonUtil.toJson(ping));
}; } catch (Throwable t) {
if (null == checkAliveTask) t.printStackTrace();
checkAliveTask = new TimerTask() {
@Override
public void run() {
try {
run1();
} catch (Throwable t) {
t.printStackTrace();
HeartBeatUtil.getInstance().cancel(this);
}
}
public void run1() {
long cur = System.currentTimeMillis();
if (cur - lastMasterPongTime >= (2 * sendDelay)) {
LOGGER.info("master maybe crash down, because lastMasterPongTime="
+ DATE_FORMAT.format(lastMasterPongTime) + "!");
// 向NC发通知重新选举master如果NC没有收到所有节点的重选请求就认为是这个节点和master连接断开
// 这个节点需要重连master
Map<String, String> request = new HashMap<>();
request.put("action", "electMaster");
SM2KeyPair keyPair = GlobalConf.instance.keyPair;
request.put("nodeID", keyPair.getPublicKeyStr());
for (MultiContractMeta meta : CMActions.manager.multiContractRecorder
.getStatus().values()) {
if (meta.getMasterNode().equals(masterPubkey)) {
LOGGER.info("master of contract " + meta.getContractID()
+ " maybe crash down! master=" + masterPubkey);
request.put("contractID", meta.getContractID());
int lastSeq = meta.getLastExeSeq();
request.put("lastExe", lastSeq + "");
request.put("master", masterPubkey);
request.put("members", meta.joinMembers(","));
NetworkManager.instance.sendToNodeCenter(JsonUtil.toJson(request));
MasterElectTimeRecorder.findMasterCrash =
System.currentTimeMillis();
} }
} }
NetworkManager.instance.closeAgent(masterPubkey); };
} // if if (null == checkAliveTask)
} checkAliveTask =
}; new TimerTask() {
@Override
public void run() {
try {
run1();
} catch (Throwable t) {
t.printStackTrace();
HeartBeatUtil.getInstance().cancel(this);
}
}
public void run1() {
long cur = System.currentTimeMillis();
if (cur - lastMasterPongTime >= (2 * sendDelay)) {
LOGGER.info(
"master maybe crash down, because lastMasterPongTime="
+ DATE_FORMAT.format(lastMasterPongTime)
+ "!");
// 向NC发通知重新选举master如果NC没有收到所有节点的重选请求就认为是这个节点和master连接断开
// 这个节点需要重连master
Map<String, String> request = new HashMap<>();
request.put("action", "electMaster");
SM2KeyPair keyPair = GlobalConf.instance.keyPair;
request.put("nodeID", keyPair.getPublicKeyStr());
for (MultiContractMeta meta : CMActions.manager.multiContractRecorder.getStatus().values()) {
if (meta.getMasterNode().equals(masterPubkey)) {
LOGGER.info(
"master of contract "
+ meta.getContractID()
+ " maybe crash down! master="
+ masterPubkey);
request.put("contractID", meta.getContractID());
int lastSeq = meta.getLastExeSeq();
request.put("lastExe", lastSeq + "");
request.put("master", masterPubkey);
request.put("members", meta.joinMembers(","));
NetworkManager.instance.sendToNodeCenter(
JsonUtil.toJson(request));
MasterElectTimeRecorder.findMasterCrash =
System.currentTimeMillis();
}
}
NetworkManager.instance.closeAgent(masterPubkey);
} // if
}
};
lastMasterPongTime = System.currentTimeMillis(); lastMasterPongTime = System.currentTimeMillis();
LOGGER.info("lastMasterPongTime=" + DATE_FORMAT.format(lastMasterPongTime)); LOGGER.info(
"lastMasterPongTime=" + DATE_FORMAT.format(lastMasterPongTime));
HeartBeatUtil.getInstance().schedule(sendPingTask, sendDelay / 2, checkDelay); HeartBeatUtil.getInstance().schedule(sendPingTask, sendDelay / 2, checkDelay);
HeartBeatUtil.getInstance().schedule(checkAliveTask, sendDelay, checkDelay); HeartBeatUtil.getInstance().schedule(checkAliveTask, sendDelay, checkDelay);
} }
@ -127,8 +138,7 @@ public class AliveCheckClientAction {
public void waitForSetNodeID() { public void waitForSetNodeID() {
for (int i = 0; i < 100; i++) { for (int i = 0; i < 100; i++) {
if (waitForSetNode) if (waitForSetNode) return;
return;
try { try {
Thread.sleep(30); Thread.sleep(30);
} catch (InterruptedException e) { } catch (InterruptedException e) {
@ -140,9 +150,9 @@ public class AliveCheckClientAction {
public void init() { public void init() {
LOGGER.info("init nodeID:"); LOGGER.info("init nodeID:");
assert masterPubkey != null; assert masterPubkey != null;
NetworkManager.instance.sendToAgent(masterPubkey, NetworkManager.instance.sendToAgent(masterPubkey, "{\"action\":\"setNodeInfo\",\"pubKey\":\""
"{\"action\":\"setNodeInfo\",\"pubKey\":\"" + GlobalConf.instance.keyPair.getPublicKeyStr()
+ GlobalConf.instance.keyPair.getPublicKeyStr() + "\"}"); + "\"}");
} }
} }

View File

@ -11,6 +11,7 @@ import org.bdware.server.action.Action;
import org.bdware.server.tcp.TCPServerFrameHandler; import org.bdware.server.tcp.TCPServerFrameHandler;
import org.bdware.units.NetworkManager; import org.bdware.units.NetworkManager;
import java.text.SimpleDateFormat;
import java.util.*; import java.util.*;
public class AliveCheckServerAction { public class AliveCheckServerAction {
@ -22,12 +23,18 @@ public class AliveCheckServerAction {
public String pubKey; public String pubKey;
public AliveCheckServerAction(TCPServerFrameHandler handler) { public AliveCheckServerAction(TCPServerFrameHandler handler) {
lastSlavePingTime = System.currentTimeMillis() + 5000L + AliveCheckClientAction.sendDelay lastSlavePingTime =
+ AliveCheckClientAction.checkDelay; System.currentTimeMillis()
+ 5000L
+ AliveCheckClientAction.sendDelay
+ AliveCheckClientAction.checkDelay;
checkAliveTask = new HeartBeatTask(AliveCheckClientAction.sendDelay); checkAliveTask = new HeartBeatTask(AliveCheckClientAction.sendDelay);
HeartBeatUtil.getInstance().schedule(checkAliveTask, AliveCheckClientAction.sendDelay, HeartBeatUtil.getInstance()
AliveCheckClientAction.checkDelay); .schedule(
checkAliveTask,
AliveCheckClientAction.sendDelay,
AliveCheckClientAction.checkDelay);
this.handler = handler; this.handler = handler;
} }
@ -50,10 +57,10 @@ public class AliveCheckServerAction {
try { try {
long cur = System.currentTimeMillis(); long cur = System.currentTimeMillis();
if (cur - lastSlavePingTime >= (2L * delay)) { if (cur - lastSlavePingTime >= (2L * delay)) {
// LOGGER.info( LOGGER.info(
// new SimpleDateFormat("yyyy-MM-dd.HH:mm:ss").format(lastSlavePingTime) new SimpleDateFormat("yyyy-MM-dd.HH:mm:ss").format(lastSlavePingTime)
// + " " + " "
// + delay); + delay);
Set<String> contracts = new HashSet<>(); Set<String> contracts = new HashSet<>();
String nodeID = pubKey; String nodeID = pubKey;
if (nodeID == null) { if (nodeID == null) {
@ -61,17 +68,21 @@ public class AliveCheckServerAction {
HeartBeatUtil.getInstance().cancel(this); HeartBeatUtil.getInstance().cancel(this);
return; return;
} }
LOGGER.info("Master心跳机制发现节点 " + nodeID.substring(0, 5) + " 下线! " LOGGER.info(
+ this.toString()); "Master心跳机制发现节点 "
+ nodeID.substring(0, 5)
+ " 下线! "
+ this.toString());
HeartBeatUtil.getInstance().cancel(this); HeartBeatUtil.getInstance().cancel(this);
for (String contractID : MasterServerRecoverMechAction.recoverStatus.get(nodeID) for (String contractID :
.keySet()) { MasterServerRecoverMechAction.recoverStatus.get(nodeID).keySet()) {
// RecoverFlag flag = // RecoverFlag flag =
// //
// MasterServerRecoverMechAction.recoverStatus.get(nodeID).get(contractID); // MasterServerRecoverMechAction.recoverStatus.get(nodeID).get(contractID);
// if (flag == RecoverFlag.Fine) // if (flag == RecoverFlag.Fine)
MasterServerRecoverMechAction.recoverStatus.get(nodeID).put(contractID, MasterServerRecoverMechAction.recoverStatus
RecoverFlag.ToRecover); .get(nodeID)
.put(contractID, RecoverFlag.ToRecover);
contracts.add(contractID); contracts.add(contractID);
MasterServerTCPAction.notifyNodeOffline(contractID, nodeID); MasterServerTCPAction.notifyNodeOffline(contractID, nodeID);
} }

View File

@ -14,7 +14,8 @@ import java.util.HashMap;
import java.util.Map; import java.util.Map;
public class CommunicationAction implements OnHashCallback { public class CommunicationAction implements OnHashCallback {
public CommunicationAction() {} public CommunicationAction() {
}
@Action(async = true) @Action(async = true)
public void updatePeerID(JsonObject jsonObject, final ResultCallback callback) { public void updatePeerID(JsonObject jsonObject, final ResultCallback callback) {
@ -25,14 +26,13 @@ public class CommunicationAction implements OnHashCallback {
@Action(async = true) @Action(async = true)
public void updateContractID(JsonObject jsonObject, final ResultCallback callback) { public void updateContractID(JsonObject jsonObject, final ResultCallback callback) {
ExecutionManager.instance.setNextContractID(jsonObject.get("content").getAsString()); ExecutionManager.instance.setNextContractID(jsonObject.get("content").getAsString());
// System.out.println("ContractID updated " + ExecutionManager.instance.nextContractID); // System.out.println("ContractID updated " + ExecutionManager.instance.nextContractID);
} }
@Action(async = true) @Action(async = true)
public void onGetP2PNodes(JsonObject args, final ResultCallback rc) { public void onGetP2PNodes(JsonObject args, final ResultCallback rc) {
String requestID = args.get(BaseFunctionManager.REQUEST_ID).getAsString(); String requestID = args.get(BaseFunctionManager.REQUEST_ID).getAsString();
ResultCallback resultCallback = ResultCallback resultCallback = CommunicationManager.instance.requestCallbacks.remove(requestID);
CommunicationManager.instance.requestCallbacks.remove(requestID);
String allPeers; String allPeers;
allPeers = args.get("content").getAsString(); allPeers = args.get("content").getAsString();
System.out.println("String coding " + allPeers); System.out.println("String coding " + allPeers);
@ -46,6 +46,6 @@ public class CommunicationAction implements OnHashCallback {
r.put("action", "onHashResult"); r.put("action", "onHashResult");
r.put("responseID", reqID); r.put("responseID", reqID);
r.put("data", hashStr); r.put("data", hashStr);
CommunicationManager.instance.send(JsonUtil.toJson(r), new String[] {}); CommunicationManager.instance.send(JsonUtil.toJson(r), new String[]{});
} }
} }

View File

@ -19,6 +19,8 @@ import org.bdware.server.GlobalConf;
import org.bdware.server.action.Action; import org.bdware.server.action.Action;
import org.bdware.server.action.CMActions; import org.bdware.server.action.CMActions;
import org.bdware.server.action.RequestToMaster; import org.bdware.server.action.RequestToMaster;
import org.bdware.server.executor.consistency.PBFTExecutor;
import org.bdware.server.executor.consistency.RequestAllExecutor;
import org.bdware.server.tcp.TCPClientFrameHandler; import org.bdware.server.tcp.TCPClientFrameHandler;
import org.bdware.server.trustedmodel.AgentManager; import org.bdware.server.trustedmodel.AgentManager;
import org.bdware.server.trustedmodel.ContractUnitStatus; import org.bdware.server.trustedmodel.ContractUnitStatus;
@ -34,24 +36,26 @@ import java.util.zip.GZIPOutputStream;
public class MasterClientRecoverMechAction { public class MasterClientRecoverMechAction {
private static final Logger LOGGER = LogManager.getLogger(MasterClientRecoverMechAction.class); private static final Logger LOGGER = LogManager.getLogger(MasterClientRecoverMechAction.class);
public static Set<String> recoverSet = new ConcurrentSkipListSet<>(); // contracts which don't public static Set<String> recoverSet =
// finish recoverRestart new ConcurrentSkipListSet<>(); // contracts which don't finish recoverRestart
public static Map<String, Queue<RequestToMaster>> requestsToMaster; // when master is public static Map<String, Queue<RequestToMaster>>
// re-electing,client node requestsToMaster; // when master is re-electing,client node cache ites received requests
// cache ites received
// requests
private final Map<String, OutputStream> stateFileMap = new HashMap<>(); private final Map<String, OutputStream> stateFileMap = new HashMap<>();
private final Map<String, OutputStream> transFileMap = new HashMap<>(); private final Map<String, OutputStream> transFileMap = new HashMap<>();
public MasterClientRecoverMechAction() {} public MasterClientRecoverMechAction() {
}
// 告知master自己需要恢复携带之前的运行模式如果是StableMode需要携带lastExeSeq信息 // 告知master自己需要恢复携带之前的运行模式如果是StableMode需要携带lastExeSeq信息
public static void askForRecover(String contractID, String masterID, String nodeID) { public static void askForRecover(String contractID, String masterID, String nodeID) {
RecoverMechTimeRecorder.startRecover = System.currentTimeMillis(); RecoverMechTimeRecorder.startRecover = System.currentTimeMillis();
// recoverSet.add(contractID); // recoverSet.add(contractID);
LOGGER.info("[MasterClientRecoverMechAction] askForRecover contractID=" + contractID LOGGER.info(
+ " masterID=" + masterID.substring(0, 5)); "[MasterClientRecoverMechAction] askForRecover contractID="
+ contractID
+ " masterID="
+ masterID.substring(0, 5));
TCPClientFrameHandler master = AgentManager.getHandler(masterID); TCPClientFrameHandler master = AgentManager.getHandler(masterID);
Map<String, String> ret = new HashMap<String, String>(); Map<String, String> ret = new HashMap<String, String>();
@ -59,22 +63,27 @@ public class MasterClientRecoverMechAction {
ret.put("contractID", contractID); ret.put("contractID", contractID);
ret.put("nodeID", nodeID); ret.put("nodeID", nodeID);
/* /* //没有这个合约进程
* //没有这个合约进程 if(!MasterClientTCPAction.requests.containsKey(contractID)){ if(!MasterClientTCPAction.requests.containsKey(contractID)){
* if(KeyValueDBUtil.instance.containsKey(CMTables.LastExeSeq.toString(),contractID)){ if(KeyValueDBUtil.instance.containsKey(CMTables.LastExeSeq.toString(),contractID)){
* logger.info("[MasterClientRecoverMechAction] delete database lastExeSeq"); logger.info("[MasterClientRecoverMechAction] delete database lastExeSeq");
* KeyValueDBUtil.instance.delete(CMTables.LastExeSeq.toString(),contractID); } }else{ KeyValueDBUtil.instance.delete(CMTables.LastExeSeq.toString(),contractID);
* ContractClient client = CMActions.manager.getClient(contractID); ContractExecuteInfo cei }
* = MasterClientTCPAction.requests.get(contractID); if (client == null || }else{
* !client.getContractType().equals(cei.type)){ ContractClient client = CMActions.manager.getClient(contractID);
* if(KeyValueDBUtil.instance.containsKey(CMTables.LastExeSeq.toString(),contractID)){ ContractExecuteInfo cei = MasterClientTCPAction.requests.get(contractID);
* logger.info("[MasterClientRecoverMechAction] delete database lastExeSeq"); if (client == null || !client.getContractType().equals(cei.type)){
* KeyValueDBUtil.instance.delete(CMTables.LastExeSeq.toString(),contractID); } } } if(KeyValueDBUtil.instance.containsKey(CMTables.LastExeSeq.toString(),contractID)){
*/ logger.info("[MasterClientRecoverMechAction] delete database lastExeSeq");
KeyValueDBUtil.instance.delete(CMTables.LastExeSeq.toString(),contractID);
}
}
}*/
if (KeyValueDBUtil.instance.containsKey(CMTables.LastExeSeq.toString(), contractID)) { if (KeyValueDBUtil.instance.containsKey(CMTables.LastExeSeq.toString(), contractID)) {
ret.put("mode", ContractUnitStatus.StableMode.toString()); ret.put("mode", ContractUnitStatus.StableMode.toString());
ret.put("lastExeSeq", ret.put(
"lastExeSeq",
KeyValueDBUtil.instance.getValue(CMTables.LastExeSeq.toString(), contractID)); KeyValueDBUtil.instance.getValue(CMTables.LastExeSeq.toString(), contractID));
} else { } else {
ret.put("mode", ContractUnitStatus.CommonMode.toString()); ret.put("mode", ContractUnitStatus.CommonMode.toString());
@ -91,17 +100,20 @@ public class MasterClientRecoverMechAction {
public static void stableModeCheckpoint(String contractID) { public static void stableModeCheckpoint(String contractID) {
LOGGER.info("设置合约" + contractID + " stable模式下的 checkpoint"); LOGGER.info("设置合约" + contractID + " stable模式下的 checkpoint");
final MultiContractMeta cei; final MultiContractMeta cei;
synchronized (cei = synchronized (
CMActions.manager.multiContractRecorder.getMultiContractMeta(contractID)) { cei = CMActions.manager.multiContractRecorder.getMultiContractMeta(contractID)) {
KeyValueDBUtil.instance.setValue(CMTables.LastExeSeq.toString(), contractID, KeyValueDBUtil.instance.setValue(
cei.getLastExeSeq() + ""); CMTables.LastExeSeq.toString(), contractID, cei.getLastExeSeq() + "");
CMActions.manager.clearSyncFiles(contractID); CMActions.manager.clearSyncFiles(contractID);
// TODO 将ContractExecuteInfo持久化 // TODO 将ContractExecuteInfo持久化
SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd-HH:mm:ss"); SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd-HH:mm:ss");
String fileName = "ContractExecuteInfo_" + format.format(new Date()) + "_" String fileName =
+ new Random().nextInt(); "ContractExecuteInfo_"
+ format.format(new Date())
+ "_"
+ new Random().nextInt();
String parPath = GlobalConf.instance.ADSPDir + "/" + contractID + "/cr"; String parPath = GlobalConf.instance.ADSPDir + "/" + contractID + "/cr";
File file = new File(parPath + "/" + fileName); File file = new File(parPath + "/" + fileName);
try { try {
@ -125,8 +137,7 @@ public class MasterClientRecoverMechAction {
public void saveStateFile(String path, ContractRecord record) { public void saveStateFile(String path, ContractRecord record) {
File file = new File(GlobalConf.instance.projectDir + "/stateFiles/" + path); File file = new File(GlobalConf.instance.projectDir + "/stateFiles/" + path);
File parent = file.getParentFile(); File parent = file.getParentFile();
if (!parent.exists()) if (!parent.exists()) parent.mkdirs();
parent.mkdirs();
ObjectOutputStream writer; ObjectOutputStream writer;
try { try {
FileOutputStream fileout = new FileOutputStream(file); FileOutputStream fileout = new FileOutputStream(file);
@ -161,8 +172,7 @@ public class MasterClientRecoverMechAction {
} catch (FileNotFoundException e) { } catch (FileNotFoundException e) {
e.printStackTrace(); e.printStackTrace();
} }
} else } else fout = (FileOutputStream) stateFileMap.get(fileName);
fout = (FileOutputStream) stateFileMap.get(fileName);
String data = args.get("data").getAsString(); String data = args.get("data").getAsString();
try { try {
@ -197,27 +207,27 @@ public class MasterClientRecoverMechAction {
recoverFromCommonMode(path, false, rc); recoverFromCommonMode(path, false, rc);
} }
// //无状态合约同步lastExeSeq之后发送恢复完成 // //无状态合约同步lastExeSeq之后发送恢复完成
// public void statelessContract(String contractID){ // public void statelessContract(String contractID){
// logger.info("无状态合约请求unitLastExeSeq"); // logger.info("无状态合约请求unitLastExeSeq");
// Map<String, String> ret = new HashMap<String, String>(); // Map<String, String> ret = new HashMap<String, String>();
// ret.put("action", "statelessUnitLastExe"); // ret.put("action", "statelessUnitLastExe");
// ret.put("contractID", contractID); // ret.put("contractID", contractID);
// ret.put("nodeID",GlobalConf.instance.keyPair.getPublicKeyStr()); // ret.put("nodeID",GlobalConf.instance.keyPair.getPublicKeyStr());
// handler.sendMsg(JsonUtil.toJson(ret)); // handler.sendMsg(JsonUtil.toJson(ret));
// } // }
// //
// @Action(async = true) // @Action(async = true)
// public void statelessReceiveLastExe(JsonObject args, final ResultCallback rc) { // public void statelessReceiveLastExe(JsonObject args, final ResultCallback rc) {
// String contractID = args.get("contractID").getAsString(); // String contractID = args.get("contractID").getAsString();
// int unitLast = args.get("unitLastExe").getAsInt(); // int unitLast = args.get("unitLastExe").getAsInt();
// //
// ContractExecuteInfo cei = MasterClientTCPAction.requests.get(contractID); // ContractExecuteInfo cei = MasterClientTCPAction.requests.get(contractID);
// synchronized(cei){ // synchronized(cei){
// cei.setLastExeSeq(unitLast); // cei.setLastExeSeq(unitLast);
// } // }
// sendRecoverFinish(contractID,"stateless"); // sendRecoverFinish(contractID,"stateless");
// } // }
// 普通节点从CommonMode恢复 // 普通节点从CommonMode恢复
public void recoverFromCommonMode(String path, boolean isMaster, ResultCallback rc) { public void recoverFromCommonMode(String path, boolean isMaster, ResultCallback rc) {
@ -244,8 +254,9 @@ public class MasterClientRecoverMechAction {
} }
// cei.printContent(); // cei.printContent();
if (cei.queue == null) { if (cei.queue == null) {
cei.init(CMActions.manager.multiContractRecorder cei.init(
.getMultiContractMeta(cei.getContractID())); CMActions.manager.multiContractRecorder.getMultiContractMeta(
cei.getContractID()));
} }
recoverSet.add(cei.getContractID()); recoverSet.add(cei.getContractID());
@ -255,12 +266,12 @@ public class MasterClientRecoverMechAction {
return; return;
} }
// //无状态合约 // //无状态合约
// String stateful = CMActions.manager.getContractStateful(cei.getContractID()); // String stateful = CMActions.manager.getContractStateful(cei.getContractID());
// if(stateful.equals("false")){ // if(stateful.equals("false")){
// statelessContract(cei.getContractID()); // statelessContract(cei.getContractID());
// return; // return;
// } // }
if (isMaster) { if (isMaster) {
CMActions.manager.setContractIsMaster(cei.getContractID(), "true"); CMActions.manager.setContractIsMaster(cei.getContractID(), "true");
@ -289,9 +300,12 @@ public class MasterClientRecoverMechAction {
try { try {
LOGGER.info(" 开始等待 checkAndRestart锁 : "); LOGGER.info(" 开始等待 checkAndRestart锁 : ");
time1 = System.currentTimeMillis(); time1 = System.currentTimeMillis();
LOGGER.info("time1=" LOGGER.info(
+ new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(new Date(time1)) "time1="
+ " " + time1); + new SimpleDateFormat("yyyy-MM-dd HH:mm:ss")
.format(new Date(time1))
+ " "
+ time1);
ContractManager.checkAndStartLock.wait(10000); ContractManager.checkAndStartLock.wait(10000);
} catch (InterruptedException e) { } catch (InterruptedException e) {
e.printStackTrace(); e.printStackTrace();
@ -300,8 +314,10 @@ public class MasterClientRecoverMechAction {
long time2 = System.currentTimeMillis(); long time2 = System.currentTimeMillis();
LOGGER.info( LOGGER.info(
"time2=" + new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(new Date(time2)) "time2="
+ " " + time2); + new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(new Date(time2))
+ " "
+ time2);
LOGGER.info("等待 checkAndRestart锁 结束 "); LOGGER.info("等待 checkAndRestart锁 结束 ");
if (time2 - time1 >= 10000) { if (time2 - time1 >= 10000) {
LOGGER.info("[ADSP]CheckAndStart 锁 等待超时"); LOGGER.info("[ADSP]CheckAndStart 锁 等待超时");
@ -319,27 +335,42 @@ public class MasterClientRecoverMechAction {
if (client == null) { if (client == null) {
System.out.println("恢复 checkAndRestart client == null\n"); System.out.println("恢复 checkAndRestart client == null\n");
} else { } else {
System.out.println("恢复 checkAndRestart client == null: false" System.out.println(
+ " client.getContractType=" + client.getContractType() + "\n"); "恢复 checkAndRestart client == null: false"
+ " client.getContractType="
+ client.getContractType()
+ "\n");
} }
ContractMeta meta = CMActions.manager.statusRecorder.getContractMeta(cei.getContractID()); ContractMeta meta = CMActions.manager.statusRecorder.getContractMeta(cei.getContractID());
meta.setContractExecutor(MasterClientTCPAction.createContractExecutor(meta.contract, meta.setContractExecutor(
contractID, cei.getMasterNode(), cei.getMembers())); MasterClientTCPAction.createContractExecutor(meta.contract, contractID, cei.getMasterNode(), cei.getMembers()));
Map<String, Object> args = new HashMap<>(); switch (meta.contract.getType()) {
args.put("ceiLastExeSeq", cei.getLastExeSeq()); case RequestAllResponseFirst:
meta.contractExecutor.onRecover(args); case RequestAllResponseHalf:
case RequestAllResponseAll:
((RequestAllExecutor) meta.contractExecutor).setSeq(cei.getLastExeSeq() + 1);
break;
case PBFT:
((PBFTExecutor) meta.contractExecutor).setSeq(cei.getLastExeSeq() + 1);
break;
case Sharding:
break;
default:
break;
}
// 认为contractID不会重 // 认为contractID不会重
if (client != null && client.isProcessAlive() if (client != null
&& client.isProcessAlive()
&& client.getContractType().equals(cei.type)) { && client.getContractType().equals(cei.type)) {
LOGGER.info("恢复节点已有这个合约进程!"); LOGGER.info("恢复节点已有这个合约进程!");
if (!KeyValueDBUtil.instance.containsKey(CMTables.UnitContracts.toString(), if (!KeyValueDBUtil.instance.containsKey(
cei.getContractID())) { CMTables.UnitContracts.toString(), cei.getContractID())) {
KeyValueDBUtil.instance.setValue(CMTables.UnitContracts.toString(), KeyValueDBUtil.instance.setValue(
cei.getContractID(), "exist"); CMTables.UnitContracts.toString(), cei.getContractID(), "exist");
} }
CMActions.manager.multiContractRecorder.updateValue(cei); CMActions.manager.multiContractRecorder.updateValue(cei);
// MasterClientTCPAction.contractID2MasterInfo.put(contractID, clientAction); //MasterClientTCPAction.contractID2MasterInfo.put(contractID, clientAction);
CMActions.manager.setContractIsMaster(contractID, "false"); CMActions.manager.setContractIsMaster(contractID, "false");
} else { } else {
LOGGER.info("[MasterClientRecoverMechAction] 恢复节点没有这个合约进程 : "); LOGGER.info("[MasterClientRecoverMechAction] 恢复节点没有这个合约进程 : ");
@ -355,18 +386,22 @@ public class MasterClientRecoverMechAction {
contract.setPublicKey(cei.publicKey); contract.setPublicKey(cei.publicKey);
int copies = cei.getMembers().length; int copies = cei.getMembers().length;
contract.setNumOfCopies(copies); contract.setNumOfCopies(copies);
if (!KeyValueDBUtil.instance.containsKey(CMTables.UnitContracts.toString(), if (!KeyValueDBUtil.instance.containsKey(
cei.getContractID())) { CMTables.UnitContracts.toString(), cei.getContractID())) {
KeyValueDBUtil.instance.setValue(CMTables.UnitContracts.toString(), KeyValueDBUtil.instance.setValue(
cei.getContractID(), "exist"); CMTables.UnitContracts.toString(), cei.getContractID(), "exist");
} }
CMActions.manager.multiContractRecorder.updateValue(cei); CMActions.manager.multiContractRecorder.updateValue(cei);
// MasterClientTCPAction.contractID2MasterInfo.put(contractID, clientAction); //MasterClientTCPAction.contractID2MasterInfo.put(contractID, clientAction);
parPath = GlobalConf.instance.publicCompiledDir + "/" + cei.getYpkName(); parPath = GlobalConf.instance.publicCompiledDir + "/" + cei.getYpkName();
if (cei.isPrivate()) { if (cei.isPrivate()) {
parPath = GlobalConf.instance.privateCompiledDir + "/" + cei.getPubKeyPath() parPath =
+ "/" + cei.getYpkName(); GlobalConf.instance.privateCompiledDir
+ "/"
+ cei.getPubKeyPath()
+ "/"
+ cei.getYpkName();
} }
} }
@ -432,8 +467,7 @@ public class MasterClientRecoverMechAction {
String path = contractID + "_temp_stateFile_" + new Random().nextLong(); String path = contractID + "_temp_stateFile_" + new Random().nextLong();
File file = new File(GlobalConf.instance.projectDir + "/stateFiles/" + path); File file = new File(GlobalConf.instance.projectDir + "/stateFiles/" + path);
File parent = file.getParentFile(); File parent = file.getParentFile();
if (!parent.exists()) if (!parent.exists()) parent.mkdirs();
parent.mkdirs();
ObjectOutputStream writer; ObjectOutputStream writer;
try { try {
FileOutputStream fileout = new FileOutputStream(file); FileOutputStream fileout = new FileOutputStream(file);
@ -470,7 +504,7 @@ public class MasterClientRecoverMechAction {
LOGGER.info("times=" + times); LOGGER.info("times=" + times);
int index = 1; // 数据包序号 int index = 1; // 数据包序号
for (int len = 0; (len = (fin.read(buff))) > 0;) { for (int len = 0; (len = (fin.read(buff))) > 0; ) {
// logger.info("len = " + len); // logger.info("len = " + len);
String data = ByteUtil.encodeBASE64(buff, len); String data = ByteUtil.encodeBASE64(buff, len);
req.put("data", data); req.put("data", data);
@ -490,9 +524,9 @@ public class MasterClientRecoverMechAction {
} }
fin.close(); fin.close();
// req.put("isDone", "true"); // req.put("isDone", "true");
// req.remove("data"); // req.remove("data");
// handler.sendMsg(JsonUtil.toJson(req)); // handler.sendMsg(JsonUtil.toJson(req));
// delete state file // delete state file
if (file.isFile() && file.exists()) { if (file.isFile() && file.exists()) {
@ -513,12 +547,17 @@ public class MasterClientRecoverMechAction {
int unitLastExeSeq = json.get("unitLastExeSeq").getAsInt(); int unitLastExeSeq = json.get("unitLastExeSeq").getAsInt();
recoverSet.add(contractID); recoverSet.add(contractID);
// 查看自己和master的lastExeSeq差距 // 查看自己和master的lastExeSeq差距
int lastExeSeq = Integer.parseInt( int lastExeSeq =
KeyValueDBUtil.instance.getValue(CMTables.LastExeSeq.toString(), contractID)); Integer.parseInt(
KeyValueDBUtil.instance.getValue(
CMTables.LastExeSeq.toString(), contractID));
LOGGER.info("unitLastExeSeq=" + unitLastExeSeq + " lastExeSeq=" + lastExeSeq); LOGGER.info("unitLastExeSeq=" + unitLastExeSeq + " lastExeSeq=" + lastExeSeq);
LOGGER.info("从StableMode恢复采用先从本地load的方式 unitLastExeSeq=" + unitLastExeSeq LOGGER.info(
+ " lastExeDeq=" + lastExeSeq); "从StableMode恢复采用先从本地load的方式 unitLastExeSeq="
+ unitLastExeSeq
+ " lastExeDeq="
+ lastExeSeq);
// Step 1 查看最新的sync file // Step 1 查看最新的sync file
String parPath = GlobalConf.instance.ADSPDir + "/" + contractID + "/sync"; String parPath = GlobalConf.instance.ADSPDir + "/" + contractID + "/sync";
@ -574,32 +613,50 @@ public class MasterClientRecoverMechAction {
} }
// record.printContent(); // record.printContent();
if (cei.queue == null) { if (cei.queue == null) {
cei.init(CMActions.manager.multiContractRecorder cei.init(
.getMultiContractMeta(cei.getContractID())); CMActions.manager.multiContractRecorder.getMultiContractMeta(
cei.getContractID()));
} }
CMActions.manager.multiContractRecorder.updateValue(cei); CMActions.manager.multiContractRecorder.updateValue(cei);
ContractMeta meta = CMActions.manager.statusRecorder.getContractMeta(contractID); ContractMeta meta = CMActions.manager.statusRecorder.getContractMeta(contractID);
Map<String, Object> args = new HashMap<>(); switch (meta.contract.getType()) {
args.put("ceiLastExeSeq", cei.getLastExeSeq()); case RequestAllResponseFirst:
meta.contractExecutor.onRecover(args); case RequestAllResponseHalf:
case RequestAllResponseAll:
((RequestAllExecutor) meta.contractExecutor).setSeq(cei.getLastExeSeq() + 1);
break;
case PBFT:
((PBFTExecutor) meta.contractExecutor).setSeq(cei.getLastExeSeq() + 1);
break;
case Sharding:
break;
default:
break;
}
boolean flag = checkAndRestart(cei); // if need,restart the contract process boolean flag = checkAndRestart(cei); // if need,restart the contract process
if (!flag) { if (!flag) {
return; return;
} }
// 无状态合约 // 无状态合约
// String stateful = CMActions.manager.getContractStateful(cei.getContractID()); // String stateful = CMActions.manager.getContractStateful(cei.getContractID());
// if(stateful.equals("false")){ // if(stateful.equals("false")){
// statelessContract(cei.getContractID()); // statelessContract(cei.getContractID());
// return; // return;
// } // }
// step3 loadMemory // step3 loadMemory
String memoryFileName = content[1].split(";")[1]; String memoryFileName = content[1].split(";")[1];
ContractClient client = ContractManager.instance.getClient(cei.getContractID()); ContractClient client = ContractManager.instance.getClient(cei.getContractID());
String temp1 = CMActions.manager.loadMemory(client, String temp1 =
GlobalConf.instance.ADSPDir + "/" + contractID + "/memory/" + memoryFileName); CMActions.manager.loadMemory(
client,
GlobalConf.instance.ADSPDir
+ "/"
+ contractID
+ "/memory/"
+ memoryFileName);
LOGGER.info("loadMemory结果" + temp1); LOGGER.info("loadMemory结果" + temp1);
// logger.info("测试位置 333 step3结束后状态为\n" + CMActions.manager.dumpContract(contractID, "")); // logger.info("测试位置 333 step3结束后状态为\n" + CMActions.manager.dumpContract(contractID, ""));
@ -607,8 +664,10 @@ public class MasterClientRecoverMechAction {
// step4 redo local trans // step4 redo local trans
String transFileName = content[2].split(";")[1]; String transFileName = content[2].split(";")[1];
String temp = CMActions.manager.redo(contractID, String temp =
GlobalConf.instance.ADSPDir + "/" + contractID + "/trans/" + transFileName); CMActions.manager.redo(
contractID,
GlobalConf.instance.ADSPDir + "/" + contractID + "/trans/" + transFileName);
LOGGER.info("redo from local结果" + temp); LOGGER.info("redo from local结果" + temp);
synchronized (cei) { synchronized (cei) {
cei.setLastExeSeq(lastExeSeq); // 通过数据库中值设置lastExeSeq和本地记录的ContractRecord是同步的 cei.setLastExeSeq(lastExeSeq); // 通过数据库中值设置lastExeSeq和本地记录的ContractRecord是同步的
@ -673,12 +732,13 @@ public class MasterClientRecoverMechAction {
SM2KeyPair keyPair = GlobalConf.instance.keyPair; SM2KeyPair keyPair = GlobalConf.instance.keyPair;
JsonObject jo = new JsonObject(); JsonObject jo = new JsonObject();
jo.addProperty("action", "onQueryUnitStatus"); jo.addProperty("action", "onQueryUnitStatus");
LOGGER.info("恢复节点查看自己的状态 " LOGGER.info(
+ KeyValueDBUtil.instance.containsKey(CMTables.LastExeSeq.toString(), contractID)); "恢复节点查看自己的状态 "
+ KeyValueDBUtil.instance.containsKey(
CMTables.LastExeSeq.toString(), contractID));
if (KeyValueDBUtil.instance.containsKey(CMTables.LastExeSeq.toString(), contractID)) if (KeyValueDBUtil.instance.containsKey(CMTables.LastExeSeq.toString(), contractID))
jo.addProperty("mode", ContractUnitStatus.StableMode.toString()); jo.addProperty("mode", ContractUnitStatus.StableMode.toString());
else else jo.addProperty("mode", ContractUnitStatus.CommonMode.toString());
jo.addProperty("mode", ContractUnitStatus.CommonMode.toString());
// jo.addProperty("mode", // jo.addProperty("mode",
// KeyValueDBUtil.instance.getValue(CMTables.UnitStatus.toString(),contractID)); // KeyValueDBUtil.instance.getValue(CMTables.UnitStatus.toString(),contractID));
jo.addProperty("nodeID", keyPair.getPublicKeyStr()); jo.addProperty("nodeID", keyPair.getPublicKeyStr());
@ -693,8 +753,7 @@ public class MasterClientRecoverMechAction {
ContractUnitStatus cur_mode; ContractUnitStatus cur_mode;
if (KeyValueDBUtil.instance.containsKey(CMTables.LastExeSeq.toString(), contractID)) if (KeyValueDBUtil.instance.containsKey(CMTables.LastExeSeq.toString(), contractID))
cur_mode = ContractUnitStatus.StableMode; cur_mode = ContractUnitStatus.StableMode;
else else cur_mode = ContractUnitStatus.CommonMode;
cur_mode = ContractUnitStatus.CommonMode;
LOGGER.info("合约" + contractID + "当前模式为" + cur_mode + " 期望设置为" + mode); LOGGER.info("合约" + contractID + "当前模式为" + cur_mode + " 期望设置为" + mode);
if (cur_mode == ContractUnitStatus.CommonMode if (cur_mode == ContractUnitStatus.CommonMode
&& mode.equals(ContractUnitStatus.StableMode.toString())) { && mode.equals(ContractUnitStatus.StableMode.toString())) {
@ -708,10 +767,10 @@ public class MasterClientRecoverMechAction {
KeyValueDBUtil.instance.delete(CMTables.LastExeSeq.toString(), contractID); KeyValueDBUtil.instance.delete(CMTables.LastExeSeq.toString(), contractID);
} }
} }
// else if(cur_mode == ContractUnitStatus.StableMode && // else if(cur_mode == ContractUnitStatus.StableMode &&
// mode.equals(ContractUnitStatus.StableMode.toString())){ // mode.equals(ContractUnitStatus.StableMode.toString())){
// stableModeCheckpoint(contractID); // stableModeCheckpoint(contractID);
// } // }
} }
@Action(async = true) @Action(async = true)
@ -744,8 +803,7 @@ public class MasterClientRecoverMechAction {
} catch (FileNotFoundException e) { } catch (FileNotFoundException e) {
e.printStackTrace(); e.printStackTrace();
} }
} else } else fout = (FileOutputStream) transFileMap.get(fileName);
fout = (FileOutputStream) transFileMap.get(fileName);
String data = args.get("data").getAsString(); String data = args.get("data").getAsString();
try { try {

View File

@ -15,12 +15,18 @@ import org.bdware.sc.db.KeyValueDBUtil;
import org.bdware.sc.units.MultiContractMeta; import org.bdware.sc.units.MultiContractMeta;
import org.bdware.sc.units.PubKeyNode; import org.bdware.sc.units.PubKeyNode;
import org.bdware.sc.util.JsonUtil; import org.bdware.sc.util.JsonUtil;
import org.bdware.sdk.consistency.ConsistencyPluginManager;
import org.bdware.server.GlobalConf; import org.bdware.server.GlobalConf;
import org.bdware.server.action.*; import org.bdware.server.action.*;
import org.bdware.server.executor.consistency.PBFTExecutor;
import org.bdware.server.executor.consistency.RequestAllExecutor;
import org.bdware.server.executor.unconsistency.MultiPointCooperationExecutor;
import org.bdware.server.executor.unconsistency.RequestOnceExecutor;
import org.bdware.server.executor.unconsistency.ResponseOnceExecutor;
import org.bdware.server.tcp.PubkeyResultCallback; import org.bdware.server.tcp.PubkeyResultCallback;
import org.bdware.server.trustedmodel.ContractExecutor; import org.bdware.server.trustedmodel.ContractExecutor;
import org.bdware.server.trustedmodel.KillUnitContractInfo; import org.bdware.server.trustedmodel.KillUnitContractInfo;
import org.bdware.server.trustedmodel.SelfAdaptiveShardingExecutor;
import org.bdware.server.trustedmodel.SingleNodeExecutor;
import org.bdware.units.NetworkManager; import org.bdware.units.NetworkManager;
import org.bdware.units.function.ExecutionManager; import org.bdware.units.function.ExecutionManager;
import org.zz.gmhelper.SM2KeyPair; import org.zz.gmhelper.SM2KeyPair;
@ -49,24 +55,28 @@ public class MasterClientTCPAction {
SM2KeyPair keyPair = GlobalConf.instance.keyPair; SM2KeyPair keyPair = GlobalConf.instance.keyPair;
request.put("nodeID", keyPair.getPublicKeyStr()); request.put("nodeID", keyPair.getPublicKeyStr());
// if (!contractID2MasterInfo.containsKey(contractID)) { // if (!contractID2MasterInfo.containsKey(contractID)) {
// contractID = cc.getContractID(); // contractID = cc.getContractID();
// } // }
// //
// MasterClientTCPAction mcta = contractID2MasterInfo.get(contractID); // MasterClientTCPAction mcta = contractID2MasterInfo.get(contractID);
// if (mcta != null) { // if (mcta != null) {
// mcta.closeMaster(); // mcta.closeMaster();
// } // }
request.put("contractID", contractID); request.put("contractID", contractID);
int lastSeq = CMActions.manager.multiContractRecorder.getMultiContractMeta(contractID) int lastSeq =
.getLastExeSeq(); CMActions.manager
.multiContractRecorder
.getMultiContractMeta(contractID)
.getLastExeSeq();
request.put("lastExe", lastSeq + ""); request.put("lastExe", lastSeq + "");
request.put("master", "null"); // 不管之前master是哪个NC处是null所有节点重选 request.put("master", "null"); // 不管之前master是哪个NC处是null所有节点重选
if (null != uniNumber) if (null != uniNumber) request.put("uniNumber", uniNumber);
request.put("uniNumber", uniNumber);
String members = CMActions.manager.multiContractRecorder.getMultiContractMeta(contractID) String members = CMActions.manager
.multiContractRecorder
.getMultiContractMeta(contractID)
.joinMembers(","); .joinMembers(",");
request.put("members", members); request.put("members", members);
@ -74,15 +84,47 @@ public class MasterClientTCPAction {
LOGGER.info("认为合约 " + contractID + " 的master崩溃 当前master为null 向NC发送重选信息"); LOGGER.info("认为合约 " + contractID + " 的master崩溃 当前master为null 向NC发送重选信息");
} }
public static ContractExecutor createContractExecutor(Contract contract, String contractID, public static ContractExecutor createContractExecutor(Contract contract, String contractID, String masterPubkey, String[] members) {
String masterPubkey, String[] members) { ContractExecutor executor = null;
Map<String, Object> args = new HashMap<>(); int nodeSize = contract.getNumOfCopies();
args.put("contractID", contractID); switch (contract.getType()) {
args.put("nodeSize", contract.getNumOfCopies()); case Sole:
args.put("masterPubkey", masterPubkey); LOGGER.info("Sole contract is not supported in multi-point mode");
args.put("members", members); return SingleNodeExecutor.instance;
return ConsistencyPluginManager.getInstance() case RequestOnce:
.createContractExecutor(contract.getType().name(), args); executor = new RequestOnceExecutor(contractID);
break;
case ResponseOnce:
executor = new ResponseOnceExecutor(contractID);
break;
case RequestAllResponseFirst:
executor =
new RequestAllExecutor(
ContractExecType.RequestAllResponseFirst, 1, contractID);
break;
case RequestAllResponseHalf:
executor =
new RequestAllExecutor(
ContractExecType.RequestAllResponseHalf,
nodeSize / 2 + 1,
contractID);
break;
case RequestAllResponseAll:
executor =
new RequestAllExecutor(
ContractExecType.RequestAllResponseAll, nodeSize, contractID);
break;
case Sharding:
executor = new MultiPointCooperationExecutor(ContractExecType.Sharding, nodeSize, contractID);
break;
case SelfAdaptiveSharding:
executor = new SelfAdaptiveShardingExecutor(contractID);
break;
case PBFT:
executor = new PBFTExecutor(nodeSize, contractID, masterPubkey, members);
break;
}
return executor;
} }
public static void dealRequests(String contractID) { public static void dealRequests(String contractID) {
@ -140,13 +182,13 @@ public class MasterClientTCPAction {
LOGGER.info("返回 uniID=" + cei.uniReqIDMap.get(seq) + " 的结果"); LOGGER.info("返回 uniID=" + cei.uniReqIDMap.get(seq) + " 的结果");
cei.resultMap.get(seq).onResult(JsonUtil.toJson(ret)); cei.resultMap.get(seq).onResult(JsonUtil.toJson(ret));
cei.setLastExeSeq(seq); cei.setLastExeSeq(seq);
if (KeyValueDBUtil.instance.containsKey(CMTables.LastExeSeq.toString(), if (KeyValueDBUtil.instance.containsKey(
contractID)) { CMTables.LastExeSeq.toString(), contractID)) {
KeyValueDBUtil.instance.setValue(CMTables.LastExeSeq.toString(), contractID, KeyValueDBUtil.instance.setValue(
seq + ""); CMTables.LastExeSeq.toString(), contractID, seq + "");
} }
// ledger检查点 public static final int LEDGER_PERIOD = 100; //账本检查点 // ledger检查点 public static final int LEDGER_PERIOD = 100; //账本检查点
if (seq % 100 == 0) { if (seq % 100 == 0) {
LOGGER.info("遇到ledger检查点 seq=" + cei.getLastExeSeq()); LOGGER.info("遇到ledger检查点 seq=" + cei.getLastExeSeq());
boolean isMaster = CMActions.manager.getContractIsMaster(contractID); boolean isMaster = CMActions.manager.getContractIsMaster(contractID);
@ -154,8 +196,9 @@ public class MasterClientTCPAction {
String lastHash; String lastHash;
if (KeyValueDBUtil.instance.containsKey( if (KeyValueDBUtil.instance.containsKey(
CMTables.CheckPointLastHash.toString(), contractID)) { CMTables.CheckPointLastHash.toString(), contractID)) {
lastHash = KeyValueDBUtil.instance.getValue( lastHash =
CMTables.CheckPointLastHash.toString(), contractID); KeyValueDBUtil.instance.getValue(
CMTables.CheckPointLastHash.toString(), contractID);
} else { } else {
lastHash = "firstCheckPoint"; lastHash = "firstCheckPoint";
} }
@ -191,8 +234,10 @@ public class MasterClientTCPAction {
SM2KeyPair keyPair = GlobalConf.instance.keyPair; SM2KeyPair keyPair = GlobalConf.instance.keyPair;
ret.put("nodeID", keyPair.getPublicKeyStr()); ret.put("nodeID", keyPair.getPublicKeyStr());
ret.put("responseID", responseID); ret.put("responseID", responseID);
ContractResult cr = new ContractResult(ContractResult.Status.Error, ContractResult cr =
new JsonPrimitive(ComponedContractResult.EXPIRED_REQ)); new ContractResult(
ContractResult.Status.Error,
new JsonPrimitive(ComponedContractResult.EXPIRED_REQ));
ret.put("data", JsonUtil.toJson(cr)); ret.put("data", JsonUtil.toJson(cr));
cb.onResult(JsonUtil.toJson(ret)); cb.onResult(JsonUtil.toJson(ret));
} }
@ -223,7 +268,8 @@ public class MasterClientTCPAction {
public void onKillContractProcess(JsonObject jo, ResultCallback result) { public void onKillContractProcess(JsonObject jo, ResultCallback result) {
LOGGER.info("[MasterClientTCPAction] : onKillContractProcess"); LOGGER.info("[MasterClientTCPAction] : onKillContractProcess");
if (killUnitContractMap.containsKey(jo.get("requestID").getAsString())) { if (killUnitContractMap.containsKey(jo.get("requestID").getAsString())) {
KillUnitContractInfo info = killUnitContractMap.get(jo.get("requestID").getAsString()); KillUnitContractInfo info =
killUnitContractMap.get(jo.get("requestID").getAsString());
Map<String, Object> r = new HashMap<>(); Map<String, Object> r = new HashMap<>();
r.put("action", "onKillContractProcess"); r.put("action", "onKillContractProcess");
r.put("data", jo.get("data")); r.put("data", jo.get("data"));
@ -245,12 +291,12 @@ public class MasterClientTCPAction {
ContractClient cc = CMActions.manager.getClient(id); ContractClient cc = CMActions.manager.getClient(id);
if (KeyValueDBUtil.instance.containsKey(CMTables.LastExeSeq.toString(), if (KeyValueDBUtil.instance.containsKey(
cc.getContractID())) { CMTables.LastExeSeq.toString(), cc.getContractID())) {
KeyValueDBUtil.instance.delete(CMTables.LastExeSeq.toString(), cc.getContractID()); KeyValueDBUtil.instance.delete(CMTables.LastExeSeq.toString(), cc.getContractID());
} }
if (KeyValueDBUtil.instance.containsKey(CMTables.UnitContracts.toString(), if (KeyValueDBUtil.instance.containsKey(
cc.getContractID())) { CMTables.UnitContracts.toString(), cc.getContractID())) {
KeyValueDBUtil.instance.delete(CMTables.UnitContracts.toString(), cc.getContractID()); KeyValueDBUtil.instance.delete(CMTables.UnitContracts.toString(), cc.getContractID());
} }
File file = new File(GlobalConf.instance.ADSPDir + "/" + cc.getContractID()); File file = new File(GlobalConf.instance.ADSPDir + "/" + cc.getContractID());
@ -290,11 +336,11 @@ public class MasterClientTCPAction {
// 需要计算出自己的ShardingID路由规则id/requester/arg-->shardingId) // 需要计算出自己的ShardingID路由规则id/requester/arg-->shardingId)
// 也在MultiPointCooperationExecutor中实现 // 也在MultiPointCooperationExecutor中实现
} }
// TODO master连接 //TODO master连接
// contractID2MasterInfo.put(contractID, this); // 记录contractID master之间的对应关系 // contractID2MasterInfo.put(contractID, this); // 记录contractID master之间的对应关系
MultiContractMeta multiContractMeta = MultiContractMeta cei =
CMActions.manager.multiContractRecorder.createIfNotExist(contractID); CMActions.manager.multiContractRecorder.createIfNotExist(contractID);
multiContractMeta.setLastExeSeq(-1); cei.setLastExeSeq(-1);
if (!contract.getScriptStr().startsWith("/")) { if (!contract.getScriptStr().startsWith("/")) {
contract.setScript(dumpToDisk(contract, jo)); contract.setScript(dumpToDisk(contract, jo));
} }
@ -302,31 +348,33 @@ public class MasterClientTCPAction {
String[] pp = contract.getScriptStr().split("/"); String[] pp = contract.getScriptStr().split("/");
String parPath = GlobalConf.instance.publicCompiledDir; String parPath = GlobalConf.instance.publicCompiledDir;
// TODO 第一次来的meta没有cid!!! synchronized (cei) { // 合约执行信息
synchronized (multiContractMeta) { // 合约执行信息 cei.setYpkName(pp[pp.length - 1]);
multiContractMeta.setYpkName(pp[pp.length - 1]); cei.setMembers(jo.get("members").getAsJsonArray());
multiContractMeta.setMembers(jo.get("members").getAsJsonArray()); cei.type = contract.getType();
multiContractMeta.type = contract.getType(); cei.key = contract.getKey();
multiContractMeta.key = contract.getKey(); cei.publicKey = contract.getPublicKey();
multiContractMeta.publicKey = contract.getPublicKey();
if (jo.has("isPrivate") && jo.get("isPrivate").getAsBoolean()) { if (jo.has("isPrivate") && jo.get("isPrivate").getAsBoolean()) {
parPath = GlobalConf.instance.privateCompiledDir + "/" parPath =
+ jo.get("pubKey").getAsString(); GlobalConf.instance.privateCompiledDir
+ "/"
+ jo.get("pubKey").getAsString();
multiContractMeta.setIsPrivate(true); cei.setIsPrivate(true);
multiContractMeta.setPubKeyPath(jo.get("pubKey").getAsString()); cei.setPubKeyPath(jo.get("pubKey").getAsString());
multiContractMeta.setYpkName(pp[pp.length - 1]); cei.setYpkName(pp[pp.length - 1]);
} }
} }
try { try {
File temp = new File(parPath, pp[pp.length - 1]); File temp = new File(parPath, pp[pp.length - 1]);
if (!temp.exists()) { if (!temp.exists()) {
result.onResult(String.format( result.onResult(
"{\"action\":\"onStartContractTrustfully\",\"result\":\"missing contract files\"," String.format(
+ "\"requestID\":\"%s\",\"pubKey\":\"%s\"}", "{\"action\":\"onStartContractTrustfully\",\"result\":\"missing contract files\"," +
jo.get("requestID").getAsString(), "\"requestID\":\"%s\",\"pubKey\":\"%s\"}",
GlobalConf.instance.keyPair.getPublicKeyStr())); jo.get("requestID").getAsString(),
GlobalConf.instance.keyPair.getPublicKeyStr()));
return; return;
} }
contract.setScript(temp.getAbsolutePath()); contract.setScript(temp.getAbsolutePath());
@ -334,30 +382,31 @@ public class MasterClientTCPAction {
e.printStackTrace(); e.printStackTrace();
} }
// 这个地方判定从参数中的master数据 globalConf中的数据 进行对比如果一致的话说明该节点为master // 这个地方判定从参数中的master数据 globalConf中的数据 进行对比如果一致的话说明该节点为master
multiContractMeta.setMaster(jo.get("master").getAsString()); cei.setMaster(jo.get("master").getAsString());
if (contract.getType().needSeq()) if (contract.getType().needSeq())
multiContractMeta cei.setIsMaster(GlobalConf.getNodeID().equals(jo.get("master").getAsString()));
.setIsMaster(GlobalConf.getNodeID().equals(jo.get("master").getAsString()));
else { else {
multiContractMeta.setIsMaster(true); cei.setIsMaster(true);
} }
CMActions.manager.multiContractRecorder.updateValue(multiContractMeta);
LOGGER.info("startup arguments: " + JsonUtil.toJson(contract)); LOGGER.debug("startup arguments: " + JsonUtil.toJson(contract));
String ret = CMActions.manager.startContract(contract); // 调用CMActions 里的启动合约的方法,启动结果 String ret = CMActions.manager.startContract(contract); // 调用CMActions 里的启动合约的方法,启动结果
LOGGER.info("startup result: " + ret);
// IMPORTANT!!!!!!!!!! LOGGER.debug("startup result: " + ret);
// meta should get after manger.startContract, because startContract reInitilized it! CMActions.manager.multiContractRecorder.updateValue(cei);
ContractMeta meta = CMActions.manager.statusRecorder.getContractMeta(contractID); ContractMeta meta = CMActions.manager.statusRecorder.createIfNotExist(contractID);
// IMPORTANT!!!!!!!!!!
meta.setContractExecutor(createContractExecutor(contract, contractID, meta.setContractExecutor(createContractExecutor(contract, contractID, jo.get("master").getAsString(), cei.getMembers())); // 分配不同的Executor
jo.get("master").getAsString(), multiContractMeta.getMembers())); // 分配不同的Executor // TODO 合约终止后从数据库中移除但是为了测试可以人为制造合约终止但不从数据库中移除异常停止
// TODO 合约终止后从数据库中移除但是为了测试可以人为制造合约终止但不从数据库中移除异常停止
KeyValueDBUtil.instance.setValue(CMTables.UnitContracts.toString(), contractID, "exist"); KeyValueDBUtil.instance.setValue(CMTables.UnitContracts.toString(), contractID, "exist");
if (CMActions.manager.getClient(contract.getID()) != null) { if (CMActions.manager.getClient(contract.getID()) != null) {
result.onResult( result.onResult(
"{\"action\":\"onStartContractTrustfully\",\"result\":\"success\",\"requestID\":\"" "{\"action\":\"onStartContractTrustfully\",\"result\":\"success\",\"requestID\":\""
+ jo.get("requestID").getAsString() + "\",\"pubKey\":\"" + jo.get("requestID").getAsString()
+ GlobalConf.instance.keyPair.getPublicKeyStr() + "\"}"); + "\",\"pubKey\":\""
+ GlobalConf.instance.keyPair.getPublicKeyStr()
+ "\"}");
ExecutionManager.instance.updateLocalContractToNodeCenter(); ExecutionManager.instance.updateLocalContractToNodeCenter();
} else { } else {
Map<String, Object> resultMap = new HashMap<>(); Map<String, Object> resultMap = new HashMap<>();
@ -368,11 +417,11 @@ public class MasterClientTCPAction {
resultMap.put("pubKey", GlobalConf.instance.keyPair.getPublicKeyStr()); resultMap.put("pubKey", GlobalConf.instance.keyPair.getPublicKeyStr());
result.onResult(JsonUtil.toJson(resultMap)); result.onResult(JsonUtil.toJson(resultMap));
} }
// if (contract.getType() == ContractExecType.Sharding) { // if (contract.getType() == ContractExecType.Sharding) {
// for (String str : cei.getMembers()) { // for (String str : cei.getMembers()) {
// NetworkManager.instance.getNCClientHandler().controller.connectToMaster(str, null); // NetworkManager.instance.getNCClientHandler().controller.connectToMaster(str, null);
// } // }
// } // }
} }
private String dumpToDisk(Contract contract, JsonObject jo) { private String dumpToDisk(Contract contract, JsonObject jo) {
@ -380,8 +429,9 @@ public class MasterClientTCPAction {
String.format("Script_%s", Math.abs(contract.getScriptStr().hashCode())); String.format("Script_%s", Math.abs(contract.getScriptStr().hashCode()));
try { try {
jo.addProperty("isPrivate", true); jo.addProperty("isPrivate", true);
File scriptDir = new File(GlobalConf.instance.privateCompiledDir, File scriptDir =
jo.get("pubKey").getAsString()); new File(
GlobalConf.instance.privateCompiledDir, jo.get("pubKey").getAsString());
if (!scriptDir.exists()) { if (!scriptDir.exists()) {
scriptDir.mkdirs(); scriptDir.mkdirs();
} }
@ -404,14 +454,14 @@ public class MasterClientTCPAction {
return "/" + scriptName + ".ypk"; return "/" + scriptName + ".ypk";
} }
// TODO 这个奇怪的action可以放到这个SelfAdaptiveSharding的相关类里 //TODO 这个奇怪的action可以放到这个SelfAdaptiveSharding的相关类里
@Action(async = true) @Action(async = true)
public void deliverBlock(JsonObject jo, ResultCallback result) { public void deliverBlock(JsonObject jo, ResultCallback result) {
if (jo.has("contractID") && jo.has("data")) { if (jo.has("contractID") && jo.has("data")) {
String contractID = jo.get("contractID").getAsString(); String contractID = jo.get("contractID").getAsString();
ContractMeta meta = CMActions.manager.statusRecorder.getContractMeta(contractID); ContractMeta meta = CMActions.manager.statusRecorder.getContractMeta(contractID);
if (null != meta && meta.contractExecutor != null) { if (null != meta && meta.contractExecutor instanceof SelfAdaptiveShardingExecutor) {
meta.contractExecutor.onDeliverBlock(jo.get("data").getAsString()); ((SelfAdaptiveShardingExecutor) meta.contractExecutor).execute(jo.get("data").getAsString());
} }
} }
} }
@ -420,10 +470,15 @@ public class MasterClientTCPAction {
public void executeContractLocally(JsonObject jo, ResultCallback result) { public void executeContractLocally(JsonObject jo, ResultCallback result) {
final ContractRequest request = final ContractRequest request =
JsonUtil.fromJson(jo.get("data").toString(), ContractRequest.class); JsonUtil.fromJson(jo.get("data").toString(), ContractRequest.class);
// LOGGER.info("[MasterCientTCPAction] executeContractLocally " + JsonUtil.toJson(jo)); LOGGER.info("[MasterCientTCPAction] executeContractLocally " + JsonUtil.toJson(jo));
// LOGGER.info("[MasterClient] executeLocally,uniReq:" + jo.get("uniReqID").getAsString() + LOGGER.info(
// " ->reqID:" + request.getRequestID() + " " + jo.get("data").toString()); "[MasterClient] executeLocally,uniReq:"
+ jo.get("uniReqID").getAsString()
+ " ->reqID:"
+ request.getRequestID()
+ " "
+ jo.get("data").toString());
// requestOne and responseOne do not need sequencing // requestOne and responseOne do not need sequencing
if (!request.needSeq) { if (!request.needSeq) {
@ -450,8 +505,8 @@ public class MasterClientTCPAction {
boolean isFirst = false; boolean isFirst = false;
synchronized (MultiRequestInfo.lock) { // 加锁防止同时放入多个同requestID的请求到cei的队列中 synchronized (MultiRequestInfo.lock) { // 加锁防止同时放入多个同requestID的请求到cei的队列中
if (MultiRequestInfo.reqInfos.containsKey(request.getRequestID())) { if (MultiRequestInfo.reqInfos.containsKey(request.getRequestID())) {
// logger.info("【收到多点合约请求】request.seq=" + request.seq + " cei.curExeSeq=" + // logger.info("【收到多点合约请求】request.seq=" + request.seq + " cei.curExeSeq=" +
// cei.curExeSeq + " cei.getLastExeSeq()=" + cei.getLastExeSeq() + " // cei.curExeSeq + " cei.getLastExeSeq()=" + cei.getLastExeSeq() + "
// 非第一个请求"); // 非第一个请求");
MultiRequestInfo mri = MultiRequestInfo mri =
@ -466,8 +521,8 @@ public class MasterClientTCPAction {
mri.putFlag(jo.get("uniReqID").getAsString(), false); mri.putFlag(jo.get("uniReqID").getAsString(), false);
} }
} else { } else {
// logger.info("【收到多点合约请求】request.seq=" + request.seq + " cei.curExeSeq=" + // logger.info("【收到多点合约请求】request.seq=" + request.seq + " cei.curExeSeq=" +
// cei.curExeSeq + " cei.getLastExeSeq()=" + cei.getLastExeSeq() + " // cei.curExeSeq + " cei.getLastExeSeq()=" + cei.getLastExeSeq() + "
// 是第一个请求"); // 是第一个请求");
MultiRequestInfo mri = MultiRequestInfo mri =
new MultiRequestInfo(request.getRequestID(), request.seq); new MultiRequestInfo(request.getRequestID(), request.seq);
@ -485,8 +540,13 @@ public class MasterClientTCPAction {
} }
} else { } else {
synchronized (cei) { synchronized (cei) {
LOGGER.info("合约" + contractID + " 请求序号为 " + request.seq + " 上一次执行请求序号为 " LOGGER.info(
+ cei.getLastExeSeq()); "合约"
+ contractID
+ " 请求序号为 "
+ request.seq
+ " 上一次执行请求序号为 "
+ cei.getLastExeSeq());
// cei.printContent(); // cei.printContent();
if (request.seq <= cei.getLastExeSeq()) { if (request.seq <= cei.getLastExeSeq()) {
@ -519,17 +579,15 @@ public class MasterClientTCPAction {
} }
@Action(async = true) @Action(async = true)
public void receiveContractExecutionServer(JsonObject jsonObject, public void receiveContractExecutionServer(JsonObject jsonObject, ResultCallback resultCallback) {
ResultCallback resultCallback) { MasterServerTCPAction.sync.wakeUp(
MasterServerTCPAction.sync.wakeUp(jsonObject.get("responseID").getAsString(), jsonObject.get("responseID").getAsString(), jsonObject.get("data").getAsString());
jsonObject.get("data").getAsString());
} }
@Action(async = true) @Action(async = true)
public void contractSyncMessage(JsonObject jsonObject, ResultCallback resultCallback) { public void contractSyncMessage(JsonObject jsonObject, ResultCallback resultCallback) {
String contractID = jsonObject.get("contractID").getAsString(); String contractID = jsonObject.get("contractID").getAsString();
MultiContractMeta mcm = MultiContractMeta mcm = CMActions.manager.multiContractRecorder.getMultiContractMeta(contractID);
CMActions.manager.multiContractRecorder.getMultiContractMeta(contractID);
ContractMeta meta = CMActions.manager.statusRecorder.getContractMeta(contractID); ContractMeta meta = CMActions.manager.statusRecorder.getContractMeta(contractID);
byte[] data = ByteUtil.decodeBASE64(jsonObject.get("data").getAsString()); byte[] data = ByteUtil.decodeBASE64(jsonObject.get("data").getAsString());
PubKeyNode node = new PubKeyNode(); PubKeyNode node = new PubKeyNode();
@ -543,7 +601,8 @@ public class MasterClientTCPAction {
@Action(async = true) @Action(async = true)
public void reRouteContract(JsonObject jo, ResultCallback result) { public void reRouteContract(JsonObject jo, ResultCallback result) {
LOGGER.info("Receive Reroute Info:" + jo.toString()); LOGGER.info("Receive Reroute Info:" + jo.toString());
MasterServerTCPAction.sync.instrumentWakeUp(jo.get("responseID").getAsString(), MasterServerTCPAction.sync.instrumentWakeUp(
jo.get("responseID").getAsString(),
(resultCallback, result1) -> { (resultCallback, result1) -> {
resultCallback.cancelTimeOut(); resultCallback.cancelTimeOut();
LOGGER.info("try To reRoute"); LOGGER.info("try To reRoute");
@ -554,58 +613,67 @@ public class MasterClientTCPAction {
(SyncResult.ContractResultCallback) resultCallback; (SyncResult.ContractResultCallback) resultCallback;
if (cb.getReRouteCount() > 0) { if (cb.getReRouteCount() > 0) {
ContractResult contractResult = ContractResult contractResult =
new ContractResult(ContractResult.Status.Error, new ContractResult(
ContractResult.Status.Error,
new JsonPrimitive( new JsonPrimitive(
"Contract " + cr.get("contractID").getAsString() "Contract "
+ cr.get("contractID").getAsString()
+ "can't be located in router")); + "can't be located in router"));
resultCallback.onResult(JsonUtil.toJson(contractResult)); resultCallback.onResult(JsonUtil.toJson(contractResult));
return; return;
} else } else cb.incReRouteCount();
cb.incReRouteCount();
LOGGER.info("inc reRoute:" + cb.getReRouteCount()); LOGGER.info("inc reRoute:" + cb.getReRouteCount());
} }
String pubkey = CMActions.manager.nodeCenterConn String pubkey =
.reRouteContract(cr.get("contractID").getAsString()); CMActions.manager.nodeCenterConn.reRouteContract(
LOGGER.info("ReRoute Result:" + cr.get("contractID").getAsString() + " pubKey:" cr.get("contractID").getAsString());
+ pubkey); LOGGER.info(
"ReRoute Result:"
+ cr.get("contractID").getAsString()
+ " pubKey:"
+ pubkey);
if (pubkey == null) { if (pubkey == null) {
ContractResult contractResult = ContractResult contractResult =
new ContractResult(ContractResult.Status.Error, new ContractResult(
new JsonPrimitive("Contract " ContractResult.Status.Error,
+ cr.get("contractID").getAsString() new JsonPrimitive(
+ "can't be located in router using reroute")); "Contract "
+ cr.get("contractID").getAsString()
+ "can't be located in router using reroute"));
resultCallback.onResult(JsonUtil.toJson(contractResult)); resultCallback.onResult(JsonUtil.toJson(contractResult));
return; return;
} }
LOGGER.debug("Receive Reroute Result:" + pubkey); LOGGER.debug("Receive Reroute Result:" + pubkey);
ContractRequest contractRequest = JsonUtil.fromJson(cr, ContractRequest.class); ContractRequest contractRequest =
CMActions.manager.masterStub.executeByOtherNodeAsync(pubkey, contractRequest, JsonUtil.fromJson(cr, ContractRequest.class);
resultCallback); CMActions.manager.masterStub.executeByOtherNodeAsync(
}, jo); pubkey, contractRequest, resultCallback);
},
jo);
} }
// public String requestContractExecution(ContractRequest c) { // public String requestContractExecution(ContractRequest c) {
// try { // try {
// LOGGER.info("[MasterClientTCPAction] requestContractExecution " + JsonUtil.toJson(c)); // LOGGER.info("[MasterClientTCPAction] requestContractExecution " + JsonUtil.toJson(c));
// Map<String, Object> req = new HashMap<>(); // Map<String, Object> req = new HashMap<>();
// req.put("action", "requestContractExecution"); // req.put("action", "requestContractExecution");
// req.put("requestID", c.getRequestID()); // req.put("requestID", c.getRequestID());
// req.put("data", c); // req.put("data", c);
// handler.sendMsg(JsonUtil.toJson(req)); // handler.sendMsg(JsonUtil.toJson(req));
// // 这里可能出错是不是在这里校验CollectResult? // // 这里可能出错是不是在这里校验CollectResult?
// ContractResult str = MasterServerTCPAction.sync.syncSleep(c.getRequestID()); // ContractResult str = MasterServerTCPAction.sync.syncSleep(c.getRequestID());
// LOGGER.info("[RequestContractGet]" + JsonUtil.toJson(str)); // LOGGER.info("[RequestContractGet]" + JsonUtil.toJson(str));
// return JsonUtil.toJson(str); // return JsonUtil.toJson(str);
// } catch (Exception e) { // } catch (Exception e) {
// ByteArrayOutputStream bo = new ByteArrayOutputStream(); // ByteArrayOutputStream bo = new ByteArrayOutputStream();
// e.printStackTrace(new PrintStream(bo)); // e.printStackTrace(new PrintStream(bo));
// ContractResult cr = // ContractResult cr =
// new ContractResult( // new ContractResult(
// ContractResult.Status.Exception, new JsonPrimitive(bo.toString())); // ContractResult.Status.Exception, new JsonPrimitive(bo.toString()));
// return JsonUtil.toJson(cr); // return JsonUtil.toJson(cr);
// } // }
// } // }
} }

View File

@ -25,14 +25,15 @@ public class MasterClientTransferAction {
private final Map<String, String> id2Memory = new HashMap<>(); private final Map<String, String> id2Memory = new HashMap<>();
private MasterClientTransferAction() {} private MasterClientTransferAction() {
}
public void transferInstance(String agentPubkey, String contractID) { public void transferInstance(String agentPubkey, String contractID) {
LOGGER.info("transferInstance contractID=" + contractID); LOGGER.info("transferInstance contractID=" + contractID);
// step2 save state //step2 save state
String mem = CMActions.manager.dumpContract(contractID, ""); String mem = CMActions.manager.dumpContract(contractID, "");
id2Memory.put(contractID, mem); id2Memory.put(contractID, mem);
// step3 send ypk or script and start other,kill local //step3 send ypk or script and start other,kill local
sendAndStart(agentPubkey, contractID); sendAndStart(agentPubkey, contractID);
} }
@ -47,7 +48,7 @@ public class MasterClientTransferAction {
String script = cc.contractMeta.contract.getScriptStr(); String script = cc.contractMeta.contract.getScriptStr();
ContractStartInfo csi = cc.contractMeta.contract.startInfo; ContractStartInfo csi = cc.contractMeta.contract.startInfo;
// kill //kill
LOGGER.info("sendAndRestart stopContract"); LOGGER.info("sendAndRestart stopContract");
CMActions.manager.stopContract(contractID); CMActions.manager.stopContract(contractID);
@ -65,8 +66,7 @@ public class MasterClientTransferAction {
File file; File file;
String path; String path;
if (csi.isPrivate) { if (csi.isPrivate) {
file = new File(GlobalConf.instance.privateCompiledDir + "/" + csi.pubKeyPath + "/" file = new File(GlobalConf.instance.privateCompiledDir + "/" + csi.pubKeyPath + "/" + csi.ypkName);
+ csi.ypkName);
path = csi.pubKeyPath + "/" + csi.ypkName; path = csi.pubKeyPath + "/" + csi.ypkName;
} else { } else {
file = new File(GlobalConf.instance.publicCompiledDir + "/" + csi.ypkName); file = new File(GlobalConf.instance.publicCompiledDir + "/" + csi.ypkName);
@ -90,7 +90,7 @@ public class MasterClientTransferAction {
long count = 0; long count = 0;
long total = file.length(); long total = file.length();
for (int len = 0; (len = (fin.read(buff))) > 0;) { for (int len = 0; (len = (fin.read(buff))) > 0; ) {
String data = ByteUtil.encodeBASE64(buff, len); String data = ByteUtil.encodeBASE64(buff, len);
req.put("data", data); req.put("data", data);
count += len; count += len;
@ -116,7 +116,7 @@ public class MasterClientTransferAction {
@Action(async = true) @Action(async = true)
public void onSendAndStart(JsonObject jo, ResultCallback result) { public void onSendAndStart(JsonObject jo, ResultCallback result) {
// step4 send memory //step4 send memory
String contractID = jo.get("contractID").getAsString(); String contractID = jo.get("contractID").getAsString();
LOGGER.info("onSendAndStart contractID=" + contractID); LOGGER.info("onSendAndStart contractID=" + contractID);
String mem = id2Memory.get(contractID); String mem = id2Memory.get(contractID);
@ -130,13 +130,11 @@ public class MasterClientTransferAction {
public boolean sendMemory(String contractID, String memory, ResultCallback cb) { public boolean sendMemory(String contractID, String memory, ResultCallback cb) {
LOGGER.info("sendMemory contractID=" + contractID); LOGGER.info("sendMemory contractID=" + contractID);
String path = contractID + "_temp_stateFile_" + new Random().nextLong() + "_" String path = contractID + "_temp_stateFile_" + new Random().nextLong() + "_" + System.currentTimeMillis();
+ System.currentTimeMillis();
File file = new File(GlobalConf.instance.projectDir + "/stateFiles/" + path); File file = new File(GlobalConf.instance.projectDir + "/stateFiles/" + path);
LOGGER.info(file.getAbsolutePath()); LOGGER.info(file.getAbsolutePath());
File parent = file.getParentFile(); File parent = file.getParentFile();
if (!parent.exists()) if (!parent.exists()) parent.mkdirs();
parent.mkdirs();
ObjectOutputStream writer; ObjectOutputStream writer;
try { try {
FileOutputStream fileout = new FileOutputStream(file); FileOutputStream fileout = new FileOutputStream(file);
@ -162,7 +160,7 @@ public class MasterClientTransferAction {
byte[] buff = new byte[30 * 1024]; byte[] buff = new byte[30 * 1024];
long count = 0; long count = 0;
for (int len = 0; (len = (fin.read(buff))) > 0;) { for (int len = 0; (len = (fin.read(buff))) > 0; ) {
String data = ByteUtil.encodeBASE64(buff, len); String data = ByteUtil.encodeBASE64(buff, len);
req.put("data", data); req.put("data", data);
count += len; count += len;
@ -177,7 +175,7 @@ public class MasterClientTransferAction {
req.put("contractID", contractID); req.put("contractID", contractID);
req.remove("data"); req.remove("data");
cb.onResult(JsonUtil.toJson(req)); cb.onResult(JsonUtil.toJson(req));
// delete state file //delete state file
if (file.isFile() && file.exists()) { if (file.isFile() && file.exists()) {
file.delete(); file.delete();
} }
@ -192,16 +190,16 @@ public class MasterClientTransferAction {
@Action(async = true) @Action(async = true)
public void onSendMemory(JsonObject jo, ResultCallback result) { public void onSendMemory(JsonObject jo, ResultCallback result) {
// step5 close connect //step5 close connect
LOGGER.info("onSendMemory done"); LOGGER.info("onSendMemory done");
// if (handler != null) { // if (handler != null) {
// LOGGER.info("handler close"); // LOGGER.info("handler close");
// NetworkManager.instance.closeAgent(master); // NetworkManager.instance.closeAgent(master);
// //
// } // }
// if (NetworkManager.CONNECTORS.containsKey(master)) { // if (NetworkManager.CONNECTORS.containsKey(master)) {
// NetworkManager.CONNECTORS.remove(master); // NetworkManager.CONNECTORS.remove(master);
// } // }
LOGGER.info("transfer contract instance finished."); LOGGER.info("transfer contract instance finished.");
} }
} }

View File

@ -16,6 +16,8 @@ import org.bdware.sc.util.JsonUtil;
import org.bdware.server.GlobalConf; import org.bdware.server.GlobalConf;
import org.bdware.server.action.Action; import org.bdware.server.action.Action;
import org.bdware.server.action.CMActions; import org.bdware.server.action.CMActions;
import org.bdware.server.executor.consistency.PBFTExecutor;
import org.bdware.server.executor.consistency.RequestAllExecutor;
import org.bdware.server.trustedmodel.ContractUnitStatus; import org.bdware.server.trustedmodel.ContractUnitStatus;
import org.bdware.units.NetworkManager; import org.bdware.units.NetworkManager;
import org.zz.gmhelper.SM2KeyPair; import org.zz.gmhelper.SM2KeyPair;
@ -30,7 +32,8 @@ public class MasterServerRecoverMechAction {
public static Map<String, Map<String, RecoverFlag>> recoverStatus = new ConcurrentHashMap<>(); public static Map<String, Map<String, RecoverFlag>> recoverStatus = new ConcurrentHashMap<>();
private final Map<String, OutputStream> stateFileMap = new HashMap<>(); private final Map<String, OutputStream> stateFileMap = new HashMap<>();
public MasterServerRecoverMechAction() {} public MasterServerRecoverMechAction() {
}
// 从disk-durable恢复 // 从disk-durable恢复
public static void restartContractFromStableMode(String nodeID, String contractID) { public static void restartContractFromStableMode(String nodeID, String contractID) {
@ -45,8 +48,8 @@ public class MasterServerRecoverMechAction {
Map<String, String> request = new HashMap<String, String>(); Map<String, String> request = new HashMap<String, String>();
request.put("action", "recoverFromStableMode"); request.put("action", "recoverFromStableMode");
request.put("contractID", contractID); request.put("contractID", contractID);
int temp = CMActions.manager.multiContractRecorder.getMultiContractMeta(contractID) int temp =
.getCurSeqAtMaster(); CMActions.manager.multiContractRecorder.getMultiContractMeta(contractID).getCurSeqAtMaster();
request.put("unitLastExeSeq", temp + ""); request.put("unitLastExeSeq", temp + "");
NetworkManager.instance.sendToAgent(nodeID, JsonUtil.toJson(request)); NetworkManager.instance.sendToAgent(nodeID, JsonUtil.toJson(request));
} }
@ -80,15 +83,15 @@ public class MasterServerRecoverMechAction {
RecoverMechTimeRecorder.writeCEIStart.put(nodeID, System.currentTimeMillis()); RecoverMechTimeRecorder.writeCEIStart.put(nodeID, System.currentTimeMillis());
MultiContractMeta cei = MultiContractMeta cei =
CMActions.manager.multiContractRecorder.getMultiContractMeta(contractID); // master的server直接调client端因为master自己的client端就在自己本地 CMActions.manager.multiContractRecorder.getMultiContractMeta(
contractID); // master的server直接调client端因为master自己的client端就在自己本地
cei.memory = CMActions.manager.dumpContract(contractID, ""); cei.memory = CMActions.manager.dumpContract(contractID, "");
// cei.printContent(); // cei.printContent();
String path = contractID + "_temp_stateFile_" + new Random().nextLong(); String path = contractID + "_temp_stateFile_" + new Random().nextLong();
File file = new File(GlobalConf.instance.projectDir + "/stateFiles/" + path); File file = new File(GlobalConf.instance.projectDir + "/stateFiles/" + path);
File parent = file.getParentFile(); File parent = file.getParentFile();
if (!parent.exists()) if (!parent.exists()) parent.mkdirs();
parent.mkdirs();
ObjectOutputStream writer; ObjectOutputStream writer;
try { try {
FileOutputStream fileout = new FileOutputStream(file); FileOutputStream fileout = new FileOutputStream(file);
@ -124,7 +127,7 @@ public class MasterServerRecoverMechAction {
times++; times++;
LOGGER.info("times=" + times); LOGGER.info("times=" + times);
int index = 1; // 数据包序号 int index = 1; // 数据包序号
for (int len = 0; (len = (fin.read(buff))) > 0;) { for (int len = 0; (len = (fin.read(buff))) > 0; ) {
// logger.info("len = " + len); // logger.info("len = " + len);
String data = ByteUtil.encodeBASE64(buff, len); String data = ByteUtil.encodeBASE64(buff, len);
req.put("data", data); req.put("data", data);
@ -142,10 +145,10 @@ public class MasterServerRecoverMechAction {
// Thread.sleep(300); // Thread.sleep(300);
} }
fin.close(); fin.close();
// req.put("isDone", "true"); // req.put("isDone", "true");
// req.remove("data"); // req.remove("data");
// //
// node.connection.sendMsg(JsonUtil.toJson(req)); // node.connection.sendMsg(JsonUtil.toJson(req));
// master delete state file // master delete state file
if (file.isFile() && file.exists()) { if (file.isFile() && file.exists()) {
@ -162,8 +165,8 @@ public class MasterServerRecoverMechAction {
public static void masterRestartFromOther(String contractID) { public static void masterRestartFromOther(String contractID) {
LOGGER.info("Master从别的节点load当前状态"); LOGGER.info("Master从别的节点load当前状态");
String masterID = CMActions.manager.multiContractRecorder.getMultiContractMeta(contractID) String masterID =
.getMasterNode(); CMActions.manager.multiContractRecorder.getMultiContractMeta(contractID).getMasterNode();
if (recoverStatus.get(masterID).get(contractID) != RecoverFlag.ToRecover) { if (recoverStatus.get(masterID).get(contractID) != RecoverFlag.ToRecover) {
return; return;
} }
@ -171,15 +174,15 @@ public class MasterServerRecoverMechAction {
// 找一个普通节点来dump // 找一个普通节点来dump
String relyNode = null; String relyNode = null;
for (String nodeID : CMActions.manager.multiContractRecorder for (String nodeID :
.getMultiContractMeta(contractID).getMembers()) { CMActions.manager.multiContractRecorder.getMultiContractMeta(contractID).getMembers()) {
if (nodeID.equals(masterID)) { if (nodeID.equals(masterID)) {
continue; continue;
} }
if (recoverStatus.get(nodeID).get(contractID) != RecoverFlag.Fine) { if (recoverStatus.get(nodeID).get(contractID) != RecoverFlag.Fine) {
continue; continue;
} }
// TODO????似乎人重连接 //TODO????似乎人重连接
if (NetworkManager.instance.hasAgentConnection(nodeID)) { if (NetworkManager.instance.hasAgentConnection(nodeID)) {
relyNode = nodeID; relyNode = nodeID;
break; break;
@ -201,16 +204,12 @@ public class MasterServerRecoverMechAction {
public static void unitModeCheck(String contractID) { public static void unitModeCheck(String contractID) {
String stateful = CMActions.manager.getContractStateful(contractID); String stateful = CMActions.manager.getContractStateful(contractID);
// just disable unitModeCheck
if (stateful != null)
return;
if (stateful.equals("false")) { if (stateful.equals("false")) {
LOGGER.info("无状态集群合约无需运行模式检查及切换!"); LOGGER.info("无状态集群合约无需运行模式检查及切换!");
return; return;
} }
MultiContractMeta mpci = MultiContractMeta mpci = CMActions.manager.multiContractRecorder.getMultiContractMeta(contractID);
CMActions.manager.multiContractRecorder.getMultiContractMeta(contractID);
synchronized (mpci) { synchronized (mpci) {
int total = 0, fineNum = 0; int total = 0, fineNum = 0;
for (String nodeId : mpci.getMembers()) { for (String nodeId : mpci.getMembers()) {
@ -224,17 +223,27 @@ public class MasterServerRecoverMechAction {
total++; total++;
} }
LOGGER.info("合约" + contractID + "的集群,正常运行的节点有" + fineNum + "个,总共节点有" + total LOGGER.info(
+ "个. Math.ceil(total / 2)=" + Math.ceil((double) total / 2) "合约"
+ " online > Math.ceil(total / 2)" + (fineNum > Math.ceil(total / 2)) + contractID
+ " mpci.unitStatus=" + mpci.unitStatus); + "的集群,正常运行的节点有"
+ fineNum
+ "个,总共节点有"
+ total
+ "个. Math.ceil(total / 2)="
+ Math.ceil((double) total / 2)
+ " online > Math.ceil(total / 2)"
+ (fineNum > Math.ceil(total / 2))
+ " mpci.unitStatus="
+ mpci.unitStatus);
ContractUnitStatus unitStatus = ContractUnitStatus.CommonMode; ContractUnitStatus unitStatus = ContractUnitStatus.CommonMode;
if (fineNum <= Math.ceil((double) total / 2)) { if (fineNum <= Math.ceil((double) total / 2)) {
unitStatus = ContractUnitStatus.StableMode; unitStatus = ContractUnitStatus.StableMode;
} }
LOGGER.info("合约" + contractID + "的集群更改模式为" + unitStatus); LOGGER.info(
"合约" + contractID + "的集群更改模式为" + unitStatus);
Map<String, String> req = new HashMap<String, String>(); Map<String, String> req = new HashMap<String, String>();
req.put("action", "changeUnitStatus"); req.put("action", "changeUnitStatus");
@ -242,8 +251,12 @@ public class MasterServerRecoverMechAction {
req.put("mode", unitStatus.toString()); req.put("mode", unitStatus.toString());
for (String nodeId : mpci.getMembers()) { for (String nodeId : mpci.getMembers()) {
NetworkManager.instance.sendToAgentIfConnected(nodeId, JsonUtil.toJson(req)); NetworkManager.instance.sendToAgentIfConnected(nodeId, JsonUtil.toJson(req));
LOGGER.info("发消息给节点 " + nodeId.substring(0, 5) + " 设置合约" + contractID LOGGER.info(
+ "的集群模式为StableMode"); "发消息给节点 "
+ nodeId.substring(0, 5)
+ " 设置合约"
+ contractID
+ "的集群模式为StableMode");
} }
@ -252,15 +265,14 @@ public class MasterServerRecoverMechAction {
} }
// 新选出的Master恢复 // 新选出的Master恢复
public static void newMasterRecover(String contractID, String allMembers, public static void newMasterRecover(
List<String> onlineMembers) { String contractID, String allMembers, List<String> onlineMembers) {
LOGGER.info("[MasterServerRecoverMechAction] 新master开始恢复 : "); LOGGER.info("[MasterServerRecoverMechAction] 新master开始恢复 : ");
MasterElectTimeRecorder.masterStartRecover = System.currentTimeMillis(); MasterElectTimeRecorder.masterStartRecover = System.currentTimeMillis();
// step1 恢复MultiContractInfo // step1 恢复MultiContractInfo
MultiContractMeta cei = MultiContractMeta cei = CMActions.manager.multiContractRecorder.getMultiContractMeta(contractID);
CMActions.manager.multiContractRecorder.getMultiContractMeta(contractID);
synchronized (cei) { synchronized (cei) {
cei.setSeqAtMaster(cei.getLastExeSeq()); cei.setSeqAtMaster(cei.getLastExeSeq());
} }
@ -282,18 +294,29 @@ public class MasterServerRecoverMechAction {
} }
ContractMeta meta = CMActions.manager.statusRecorder.getContractMeta(contractID); ContractMeta meta = CMActions.manager.statusRecorder.getContractMeta(contractID);
meta.setContractExecutor(MasterClientTCPAction.createContractExecutor(meta.contract, meta.setContractExecutor(
contractID, cei.getMasterNode(), cei.getMembers())); MasterClientTCPAction.createContractExecutor(meta.contract, contractID, cei.getMasterNode(), cei.getMembers()));
Map<String, Object> args = new HashMap<>(); switch (meta.contract.getType()) {
args.put("ceiLastExeSeq", cei.getLastExeSeq()); case RequestAllResponseFirst:
meta.contractExecutor.onRecover(args); case RequestAllResponseHalf:
case RequestAllResponseAll:
((RequestAllExecutor) meta.contractExecutor).setSeq(cei.getLastExeSeq() + 1);
break;
case PBFT:
((PBFTExecutor) meta.contractExecutor).setSeq(cei.getLastExeSeq() + 1);
break;
case Sharding:
break;
default:
break;
}
CMActions.manager.multiContractRecorder.updateValue(cei); CMActions.manager.multiContractRecorder.updateValue(cei);
LOGGER.info("[master recover] contractID2Members put 合约 " + contractID); LOGGER.info("[master recover] contractID2Members put 合约 " + contractID);
LOGGER.info("新master恢复 MultiPointContractInfo 完成!"); LOGGER.info("新master恢复 MultiPointContractInfo 完成!");
LOGGER.info( LOGGER.info(
"[MasterServerRecoverMechAction] step1 新master恢复 MultiPointContractInfo 完成! \n"); "[MasterServerRecoverMechAction] step1 新master恢复 MultiPointContractInfo 完成! \n");
// step2 恢复recoverStatues这个map // step2 恢复recoverStatues这个map
for (String nodeID : nodeNames) { for (String nodeID : nodeNames) {
if (onlineMembers.contains(nodeID)) { // 设置所有在线的节点Fine状态 if (onlineMembers.contains(nodeID)) { // 设置所有在线的节点Fine状态
if (!recoverStatus.containsKey(nodeID)) { if (!recoverStatus.containsKey(nodeID)) {
@ -307,8 +330,12 @@ public class MasterServerRecoverMechAction {
recoverStatus.put(nodeID, new ConcurrentHashMap<>()); recoverStatus.put(nodeID, new ConcurrentHashMap<>());
} }
recoverStatus.get(nodeID).put(contractID, RecoverFlag.ToRecover); recoverStatus.get(nodeID).put(contractID, RecoverFlag.ToRecover);
LOGGER.info("新master设置 合约 " + contractID + " 节点 " + nodeID.substring(0, 5) LOGGER.info(
+ " 为ToRecover"); "新master设置 合约 "
+ contractID
+ " 节点 "
+ nodeID.substring(0, 5)
+ " 为ToRecover");
} }
} }
LOGGER.info("新master恢复 recoverStatus map 完成!"); LOGGER.info("新master恢复 recoverStatus map 完成!");
@ -316,7 +343,7 @@ public class MasterServerRecoverMechAction {
MasterElectTimeRecorder.masterRecoverFinish = System.currentTimeMillis(); MasterElectTimeRecorder.masterRecoverFinish = System.currentTimeMillis();
// step3 告知NC更新路由信息 // step3 告知NC更新路由信息
Map<String, String> re = new HashMap<>(); Map<String, String> re = new HashMap<>();
re.put("action", "changeMaster"); re.put("action", "changeMaster");
re.put("contractID", contractID); re.put("contractID", contractID);
@ -324,35 +351,35 @@ public class MasterServerRecoverMechAction {
NetworkManager.instance.sendToNodeCenter(JsonUtil.toJson(re)); NetworkManager.instance.sendToNodeCenter(JsonUtil.toJson(re));
LOGGER.info("[MasterServerRecoverMechAction] step3 告知NC更新路由信息! \n"); LOGGER.info("[MasterServerRecoverMechAction] step3 告知NC更新路由信息! \n");
// step4 查看集群当前状态 // step4 查看集群当前状态
unitModeCheck(contractID); unitModeCheck(contractID);
LOGGER.info("新master 查看当前集群状态 完成!"); LOGGER.info("新master 查看当前集群状态 完成!");
LOGGER.info("[MasterServerRecoverMechAction] step4 新master查看当前集群状态 完成!"); LOGGER.info("[MasterServerRecoverMechAction] step4 新master查看当前集群状态 完成!");
// step5 向其他可能和旧的master断连但和NC连接的节点发请求让连新的master // step5 向其他可能和旧的master断连但和NC连接的节点发请求让连新的master
// String off = ""; // String off = "";
// for (String str : offlines) { // for (String str : offlines) {
// if (off.equals("")) { // if (off.equals("")) {
// off = str; // off = str;
// } else { // } else {
// off += ","; // off += ",";
// off += str; // off += str;
// } // }
// } // }
// //
// Map<String, String> request = new HashMap<>(); // Map<String, String> request = new HashMap<>();
// request.put("action", "updateFormerMaster"); // request.put("action", "updateFormerMaster");
// request.put("contractID", contractID); // request.put("contractID", contractID);
// request.put("offlines", off); // request.put("offlines", off);
// request.put("master", mpci.masterNode); // request.put("master", mpci.masterNode);
// CMActions.client.sendMsg(JsonUtil.toJson(request)); // CMActions.client.sendMsg(JsonUtil.toJson(request));
LOGGER.info("新的master恢复完毕!"); LOGGER.info("新的master恢复完毕!");
LOGGER.info("[MasterServerRecoverMechAction] 新master恢复完成!"); LOGGER.info("[MasterServerRecoverMechAction] 新master恢复完成!");
} }
public String judegeRecoverMethod(String contractID, String nodeMode, String unitMode, public String judegeRecoverMethod(
int nodeLastExe, int unitLastExe) { String contractID, String nodeMode, String unitMode, int nodeLastExe, int unitLastExe) {
if (nodeMode.equals(ContractUnitStatus.CommonMode.toString()) if (nodeMode.equals(ContractUnitStatus.CommonMode.toString())
&& nodeLastExe == unitLastExe) { && nodeLastExe == unitLastExe) {
return ""; return "";
@ -389,14 +416,13 @@ public class MasterServerRecoverMechAction {
String unitMode; String unitMode;
if (KeyValueDBUtil.instance.containsKey(CMTables.LastExeSeq.toString(), contractID)) if (KeyValueDBUtil.instance.containsKey(CMTables.LastExeSeq.toString(), contractID))
unitMode = ContractUnitStatus.StableMode.toString(); unitMode = ContractUnitStatus.StableMode.toString();
else else unitMode = ContractUnitStatus.CommonMode.toString();
unitMode = ContractUnitStatus.CommonMode.toString();
int nodeLastExe = Integer.MIN_VALUE; int nodeLastExe = Integer.MIN_VALUE;
if (jo.has("lastExeSeq")) { if (jo.has("lastExeSeq")) {
nodeLastExe = jo.get("lastExeSeq").getAsInt(); nodeLastExe = jo.get("lastExeSeq").getAsInt();
} }
int unitLastExe = CMActions.manager.multiContractRecorder.getMultiContractMeta(contractID) int unitLastExe =
.getCurSeqAtMaster(); CMActions.manager.multiContractRecorder.getMultiContractMeta(contractID).getCurSeqAtMaster();
RecoverMechTimeRecorder.startJudgeRecoverMethod.put(nodeID, System.currentTimeMillis()); RecoverMechTimeRecorder.startJudgeRecoverMethod.put(nodeID, System.currentTimeMillis());
@ -405,8 +431,15 @@ public class MasterServerRecoverMechAction {
RecoverMechTimeRecorder.judgeRecoverMethodFinish.put(nodeID, System.currentTimeMillis()); RecoverMechTimeRecorder.judgeRecoverMethodFinish.put(nodeID, System.currentTimeMillis());
LOGGER.info("[MasterServerRecoverMechAciton] askForRecover mode=" + nodeMode LOGGER.info(
+ " contractID=" + contractID + " nodeID=" + nodeID + " method=" + method); "[MasterServerRecoverMechAciton] askForRecover mode="
+ nodeMode
+ " contractID="
+ contractID
+ " nodeID="
+ nodeID
+ " method="
+ method);
if (method.equals("common")) { if (method.equals("common")) {
LOGGER.info("restartContractFromCommonMode"); LOGGER.info("restartContractFromCommonMode");
restartContractFromCommonMode(nodeID, contractID); restartContractFromCommonMode(nodeID, contractID);
@ -425,8 +458,8 @@ public class MasterServerRecoverMechAction {
@Action(async = true) @Action(async = true)
public void restartContractFromCommonMode(JsonObject jo, ResultCallback cb) { public void restartContractFromCommonMode(JsonObject jo, ResultCallback cb) {
restartContractFromCommonMode(jo.get("nodeID").getAsString(), restartContractFromCommonMode(
jo.get("contractID").getAsString()); jo.get("nodeID").getAsString(), jo.get("contractID").getAsString());
} }
@Action(async = true) @Action(async = true)
@ -435,8 +468,7 @@ public class MasterServerRecoverMechAction {
LOGGER.info("master查询缓存的 trans records 从 " + startSeq + " 开始"); LOGGER.info("master查询缓存的 trans records 从 " + startSeq + " 开始");
String nodeId = jo.get("nodeID").getAsString(); String nodeId = jo.get("nodeID").getAsString();
String contractID = jo.get("contractID").getAsString(); String contractID = jo.get("contractID").getAsString();
MultiContractMeta mpci = MultiContractMeta mpci = CMActions.manager.multiContractRecorder.getMultiContractMeta(contractID);
CMActions.manager.multiContractRecorder.getMultiContractMeta(contractID);
synchronized (mpci) { synchronized (mpci) {
if (mpci.unitStatus == ContractUnitStatus.CommonMode) { if (mpci.unitStatus == ContractUnitStatus.CommonMode) {
restartContractFromCommonMode(nodeId, contractID); restartContractFromCommonMode(nodeId, contractID);
@ -456,8 +488,7 @@ public class MasterServerRecoverMechAction {
String path = contractID + "_temp_TransFile_" + new Random().nextLong(); String path = contractID + "_temp_TransFile_" + new Random().nextLong();
File file = new File(GlobalConf.instance.projectDir + "/stateFiles/" + path); File file = new File(GlobalConf.instance.projectDir + "/stateFiles/" + path);
File parent = file.getParentFile(); File parent = file.getParentFile();
if (!parent.exists()) if (!parent.exists()) parent.mkdirs();
parent.mkdirs();
try { try {
FileWriter fw = new FileWriter(file, true); FileWriter fw = new FileWriter(file, true);
@ -496,7 +527,7 @@ public class MasterServerRecoverMechAction {
int index = 1; // 数据包序号 int index = 1; // 数据包序号
long count = 0; long count = 0;
for (int len = 0; (len = (fin.read(buff))) > 0;) { for (int len = 0; (len = (fin.read(buff))) > 0; ) {
// logger.info("len = " + len); // logger.info("len = " + len);
String data = ByteUtil.encodeBASE64(buff, len); String data = ByteUtil.encodeBASE64(buff, len);
req.put("data", data); req.put("data", data);
@ -517,12 +548,12 @@ public class MasterServerRecoverMechAction {
} }
fin.close(); fin.close();
// req.put("isDone", "true"); // req.put("isDone", "true");
// req.put("contractID", contractID); // req.put("contractID", contractID);
// req.put("last", last); // req.put("last", last);
// req.remove("data"); // req.remove("data");
// //
// node.connection.sendMsg(JsonUtil.toJson(req)); // node.connection.sendMsg(JsonUtil.toJson(req));
// master delete state file // master delete state file
if (file.isFile() && file.exists()) { if (file.isFile() && file.exists()) {
@ -579,8 +610,7 @@ public class MasterServerRecoverMechAction {
} catch (FileNotFoundException e) { } catch (FileNotFoundException e) {
e.printStackTrace(); e.printStackTrace();
} }
} else } else fout = (FileOutputStream) stateFileMap.get(fileName);
fout = (FileOutputStream) stateFileMap.get(fileName);
String data = args.get("data").getAsString(); String data = args.get("data").getAsString();
try { try {
@ -601,26 +631,25 @@ public class MasterServerRecoverMechAction {
req.put("isMaster", "true"); req.put("isMaster", "true");
req.put("filePath", dir.getAbsolutePath()); req.put("filePath", dir.getAbsolutePath());
SM2KeyPair keyPair = GlobalConf.instance.keyPair; SM2KeyPair keyPair = GlobalConf.instance.keyPair;
NetworkManager.instance.sendToAgent(keyPair.getPublicKeyStr(), NetworkManager.instance.sendToAgent(keyPair.getPublicKeyStr(), JsonUtil.toJson(req));
JsonUtil.toJson(req));
} }
} catch (IOException e) { } catch (IOException e) {
e.printStackTrace(); e.printStackTrace();
} }
} }
// @Action(async = true) // @Action(async = true)
// public void statelessUnitLastExe(JsonObject jo, ResultCallback cb) { // public void statelessUnitLastExe(JsonObject jo, ResultCallback cb) {
// String contractID = jo.get("contractID").getAsString(); // String contractID = jo.get("contractID").getAsString();
// String unitLastExe = // String unitLastExe =
// MasterServerTCPAction.contractID2Members.get(contractID).getCurSeq() + ""; // MasterServerTCPAction.contractID2Members.get(contractID).getCurSeq() + "";
// String nodeID = jo.get("nodeID").getAsString(); // String nodeID = jo.get("nodeID").getAsString();
// //
// Map<String, String> request = new HashMap<String, String>(); // Map<String, String> request = new HashMap<String, String>();
// request.put("action", "statelessReceiveLastExe"); // request.put("action", "statelessReceiveLastExe");
// request.put("contractID", contractID); // request.put("contractID", contractID);
// request.put("unitLastExe", unitLastExe); // request.put("unitLastExe", unitLastExe);
// SlaveNode node = MasterServerTCPAction.id2Slaves.get(nodeID); // SlaveNode node = MasterServerTCPAction.id2Slaves.get(nodeID);
// node.connection.sendMsg(JsonUtil.toJson(request)); // node.connection.sendMsg(JsonUtil.toJson(request));
// } // }
} }

View File

@ -14,15 +14,17 @@ import org.bdware.sc.conn.ResultCallback;
import org.bdware.sc.units.MultiContractMeta; import org.bdware.sc.units.MultiContractMeta;
import org.bdware.sc.units.RequestCache; import org.bdware.sc.units.RequestCache;
import org.bdware.sc.util.JsonUtil; import org.bdware.sc.util.JsonUtil;
import org.bdware.sdk.consistency.api.NotifiableResultMerger;
import org.bdware.server.CongestionControl; import org.bdware.server.CongestionControl;
import org.bdware.server.action.Action; import org.bdware.server.action.Action;
import org.bdware.server.action.CMActions; import org.bdware.server.action.CMActions;
import org.bdware.server.action.SyncResult; import org.bdware.server.action.SyncResult;
import org.bdware.server.executor.consistency.RequestAllExecutor;
import org.bdware.server.trustedmodel.KillUnitContractResultCollector; import org.bdware.server.trustedmodel.KillUnitContractResultCollector;
import org.bdware.server.trustedmodel.ResultCollector; import org.bdware.server.trustedmodel.ResultCollector;
import org.bdware.units.NetworkManager; import org.bdware.units.NetworkManager;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.HashMap; import java.util.HashMap;
import java.util.Map; import java.util.Map;
import java.util.concurrent.ConcurrentHashMap; import java.util.concurrent.ConcurrentHashMap;
@ -39,21 +41,26 @@ public class MasterServerTCPAction {
static { static {
final Object flag = new Object(); final Object flag = new Object();
ContractManager.scheduledThreadPool.scheduleWithFixedDelay(() -> { ContractManager.scheduledThreadPool.scheduleWithFixedDelay(
boolean cleared = clearCache(); () -> {
if (cleared) { boolean cleared = clearCache();
try { if (cleared) {
synchronized (flag) { try {
flag.wait(14000L); synchronized (flag) {
flag.wait(14000L);
}
} catch (InterruptedException e) {
e.printStackTrace();
}
} }
} catch (InterruptedException e) { },
e.printStackTrace(); 0,
} 1,
} TimeUnit.SECONDS);
}, 0, 1, TimeUnit.SECONDS);
} }
public MasterServerTCPAction() {} public MasterServerTCPAction() {
}
public static void notifyNodeOffline(String contractID, String nodeID) { public static void notifyNodeOffline(String contractID, String nodeID) {
synchronized (sync) { synchronized (sync) {
@ -61,22 +68,24 @@ public class MasterServerTCPAction {
ResultCallback cb = sync.waitObj.get(requestID); ResultCallback cb = sync.waitObj.get(requestID);
if (cb instanceof ResultCollector) { if (cb instanceof ResultCollector) {
ResultCollector rc = (ResultCollector) cb; ResultCollector rc = (ResultCollector) cb;
if (rc.getCommitter() instanceof NotifiableResultMerger) { if (rc.getCommitter() instanceof RequestAllExecutor.ResultMerger) {
NotifiableResultMerger merger = (NotifiableResultMerger) rc.getCommitter(); RequestAllExecutor.ResultMerger merger =
(RequestAllExecutor.ResultMerger) rc.getCommitter();
if (merger.getContractID().equals(contractID)) { if (merger.getContractID().equals(contractID)) {
LOGGER.info("node " + nodeID + " offline! in the cluster of contract " LOGGER.info("node " + nodeID + " offline! in the cluster of contract " + contractID);
+ contractID); LOGGER.debug("nodeID=" + nodeID + " contractID=" + contractID +
LOGGER.debug("nodeID=" + nodeID + " contractID=" + contractID + ": " ": " + merger.getInfo());
+ merger.getInfo()); ContractResult cr =
ContractResult cr = new ContractResult(ContractResult.Status.Exception, new ContractResult(
new JsonPrimitive("node offline")); ContractResult.Status.Exception,
new JsonPrimitive("node offline"));
JsonObject jo = new JsonObject(); JsonObject jo = new JsonObject();
jo.addProperty("data", JsonUtil.toJson(cr)); jo.addProperty("data", JsonUtil.toJson(cr));
jo.addProperty("responseID", requestID); jo.addProperty("responseID", requestID);
jo.addProperty("action", "receiveTrustfullyResult"); jo.addProperty("action", "receiveTrustfullyResult");
jo.addProperty("nodeID", nodeID); jo.addProperty("nodeID", nodeID);
LOGGER.debug("[cb] nodeID=" + nodeID + " contractID=" + contractID LOGGER.debug("[cb] nodeID=" + nodeID + " contractID=" + contractID +
+ ": " + jo); ": " + jo);
sync.wakeUp(requestID, jo.toString()); sync.wakeUp(requestID, jo.toString());
} }
} }
@ -88,8 +97,7 @@ public class MasterServerTCPAction {
static RequestCache getCache(String contractID) { static RequestCache getCache(String contractID) {
if (contractID != null) { if (contractID != null) {
RequestCache cache = requestCache.get(contractID); RequestCache cache = requestCache.get(contractID);
if (cache != null) if (cache != null) return cache;
return cache;
else { else {
LOGGER.info("[MasterServerTCPAction] create requestcache:" + contractID); LOGGER.info("[MasterServerTCPAction] create requestcache:" + contractID);
RequestCache reqc = new RequestCache(); RequestCache reqc = new RequestCache();
@ -101,18 +109,17 @@ public class MasterServerTCPAction {
} }
static boolean clearCache() { static boolean clearCache() {
if (requestCache.isEmpty()) if (requestCache.isEmpty()) return true;
return true;
// final long time = System.currentTimeMillis() - 120000L; // 120s // final long time = System.currentTimeMillis() - 120000L; // 120s
// requestCache // requestCache
// .entrySet() // .entrySet()
// .removeIf( // .removeIf(
// entry -> { // entry -> {
// RequestCache cache = entry.getValue(); // RequestCache cache = entry.getValue();
// if (cache == null) return true; // if (cache == null) return true;
// return cache.getTime() < time; // return cache.getTime() < time;
// }); // });
for (RequestCache cache : requestCache.values()) { for (RequestCache cache : requestCache.values()) {
cache.decSize(); cache.decSize();
@ -124,8 +131,15 @@ public class MasterServerTCPAction {
ContractMeta meta = CMActions.manager.statusRecorder.getContractMeta(contractID); ContractMeta meta = CMActions.manager.statusRecorder.getContractMeta(contractID);
MultiContractMeta ret = MultiContractMeta ret =
CMActions.manager.multiContractRecorder.getMultiContractMeta(contractID); CMActions.manager.multiContractRecorder.getMultiContractMeta(contractID);
LOGGER.debug(String.format("getCMInfo: %s %s %s", meta.getName(), meta.getID(), System.out.println(
meta.getStatus())); new SimpleDateFormat("yyyy-MM-dd HH:mm:ss")
.format(new Date(System.currentTimeMillis()))
+ " [MasterServerTCPAction] getCMInfo: "
+ meta.getName()
+ " "
+ meta.getID()
+ " "
+ meta.getStatus());
return ret; return ret;
} }
@ -164,8 +178,9 @@ public class MasterServerTCPAction {
jo.addProperty("action", "killContractProcessAtSlave"); jo.addProperty("action", "killContractProcessAtSlave");
MultiContractMeta contractMeta = MultiContractMeta contractMeta =
CMActions.manager.multiContractRecorder.getMultiContractMeta(cl.getContractID()); CMActions.manager.multiContractRecorder.getMultiContractMeta(cl.getContractID());
KillUnitContractResultCollector collector = new KillUnitContractResultCollector( KillUnitContractResultCollector collector =
jo.get("requestID").getAsString(), cb, contractMeta.getMembers().length); new KillUnitContractResultCollector(
jo.get("requestID").getAsString(), cb, contractMeta.getMembers().length);
sync.sleep(jo.get("requestID").getAsString(), collector); sync.sleep(jo.get("requestID").getAsString(), collector);
for (String member : contractMeta.getMembers()) { for (String member : contractMeta.getMembers()) {
NetworkManager.instance.sendToAgent(member, jo.toString()); NetworkManager.instance.sendToAgent(member, jo.toString());
@ -175,27 +190,27 @@ public class MasterServerTCPAction {
@Action(async = true) @Action(async = true)
public void receiveTrustfullyResult(JsonObject jo, ResultCallback cb) { public void receiveTrustfullyResult(JsonObject jo, ResultCallback cb) {
String responseID = jo.get("responseID").getAsString(); String responseID = jo.get("responseID").getAsString();
// LOGGER.info("========== ExecuteContractLocally wakeUp:" + responseID); LOGGER.info("========== ExecuteContractLocally wakeUp:" + responseID);
MasterServerTCPAction.sync.wakeUp(responseID, jo.toString()); MasterServerTCPAction.sync.wakeUp(responseID, jo.toString());
} }
// TODO to Remove // TODO to Remove
// @Action(async = true) // @Action(async = true)
// // 假设该结点有运行这个合约调用的合约 // // 假设该结点有运行这个合约调用的合约
// public void executeContractLocallyServer(JsonObject jo, ResultCallback cb) { // public void executeContractLocallyServer(JsonObject jo, ResultCallback cb) {
// final ContractRequest request = // final ContractRequest request =
// JsonUtil.fromJson(jo.get("data").toString(), ContractRequest.class); // JsonUtil.fromJson(jo.get("data").toString(), ContractRequest.class);
// long start = System.currentTimeMillis(); // long start = System.currentTimeMillis();
// String data2 = CMActions.manager.executeLocally(request, null); // String data2 = CMActions.manager.executeLocally(request, null);
// Map<String, String> ret = new HashMap<>(); // Map<String, String> ret = new HashMap<>();
// ret.put("action", "receiveTrustfullyResultServer"); // ret.put("action", "receiveTrustfullyResultServer");
// SM2KeyPair keyPair = GlobalConf.instance.keyPair; // SM2KeyPair keyPair = GlobalConf.instance.keyPair;
// ret.put("nodeID", keyPair.getPublicKeyStr()); // ret.put("nodeID", keyPair.getPublicKeyStr());
// ret.put("responseID", jo.get("uniReqID").getAsString()); // ret.put("responseID", jo.get("uniReqID").getAsString());
// ret.put("executeTime", (System.currentTimeMillis() - start) + ""); // ret.put("executeTime", (System.currentTimeMillis() - start) + "");
// ret.put("data", data2); // ret.put("data", data2);
// cb.onResult(JsonUtil.toJson(ret)); // cb.onResult(JsonUtil.toJson(ret));
// } // }
@Action(async = true) @Action(async = true)
@ -215,15 +230,15 @@ public class MasterServerTCPAction {
// 调用方向为MasterClient->MasterServer // 调用方向为MasterClient->MasterServer
// 如果为多节点则为MasterServer executeLocally-> MasterClient // 如果为多节点则为MasterServer executeLocally-> MasterClient
// executeLocally否则为MasterServer->Local // executeLocally否则为MasterServer->Local
// LOGGER.info("[requestContractExecution]:" + jo.toString()); // LOGGER.info("[requestContractExecution]:" + jo.toString());
// loggger.bug // loggger.bug
JsonObject cr = jo.get("data").getAsJsonObject(); JsonObject cr = jo.get("data").getAsJsonObject();
String requestID = cr.get("requestID").getAsString(); String requestID = cr.get("requestID").getAsString();
String contractID = cr.get("contractID").getAsString(); String contractID = cr.get("contractID").getAsString();
ContractMeta contractMeta = ContractMeta contractMeta =
CMActions.manager.statusRecorder.getContractMeta(contractID); CMActions.manager.statusRecorder.getContractMeta(contractID);
if (contractMeta == null || contractMeta.getStatus() == KILLED) { if (contractMeta == null || contractMeta.getStatus() == KILLED) {
LOGGER.debug("send ReRoute response: " + cr); LOGGER.debug("send ReRoute response:" + cr.toString());
JsonObject result = new JsonObject(); JsonObject result = new JsonObject();
result.addProperty("action", "reRouteContract"); result.addProperty("action", "reRouteContract");
result.addProperty("responseID", cr.get("requestID").getAsString()); result.addProperty("responseID", cr.get("requestID").getAsString());
@ -233,20 +248,20 @@ public class MasterServerTCPAction {
return; return;
} }
MultiContractMeta info = MasterServerTCPAction.getMPCInfo(contractMeta.getID()); MultiContractMeta info = MasterServerTCPAction.getMPCInfo(contractMeta.getID());
// LOGGER.info("[MasterServerTCPAction] requestContractExecution " + new // LOGGER.info("[MasterServerTCPAction] requestContractExecution " + new
// Gson().toJson(jo)); // Gson().toJson(jo));
// LOGGER.info("MultiPointContractInfo info=" + (info == null ? "null" : "not // LOGGER.info("MultiPointContractInfo info=" + (info == null ? "null" : "not
// null") + // null") +
// "\n"); // "\n");
if (info != null && ContractExecType.Sharding != contractMeta.contract.getType() if (info != null && contractMeta.contract.getType() != ContractExecType.Sharding) {
&& !ContractExecType.SelfAdaptiveSharding
.equals(contractMeta.contract.getType())) {
// 这个是个多节点的合约 // 这个是个多节点的合约
// Just forward it to the correct Node // Just forward it to the correct Node
// Master节点直接发3个聚合后返回结果 // Master节点直接发3个聚合后返回结果
contractMeta.contractExecutor.execute(requestID, contractMeta.contractExecutor.execute(
JsonUtil.fromJson(cr, ContractRequest.class), new ResultCallback() { requestID,
JsonUtil.fromJson(cr, ContractRequest.class),
new ResultCallback() {
@Override @Override
public void onResult(String str) { public void onResult(String str) {
Map<String, String> result = new HashMap<>(); Map<String, String> result = new HashMap<>();
@ -268,20 +283,19 @@ public class MasterServerTCPAction {
// 这个是个单节点的合约 // 这个是个单节点的合约
// executeContract(CacheTest应该要有多个进来 // executeContract(CacheTest应该要有多个进来
if (null != client && !client.getContractType().needSeq()) { if (null != client && !client.getContractType().needSeq()) {
contractMeta.contractExecutor.execute(requestID, contractRequest, contractMeta.contractExecutor.execute(requestID, contractRequest, new ResultCallback() {
new ResultCallback() { @Override
@Override public void onResult(String str) {
public void onResult(String str) { Map<String, String> result = new HashMap<>();
Map<String, String> result = new HashMap<>(); result.put("action", "receiveContractExecutionServer");
result.put("action", "receiveContractExecutionServer"); result.put("responseID", cr.get("requestID").getAsString());
result.put("responseID", cr.get("requestID").getAsString()); result.put("data", str);
result.put("data", str); cb.onResult(JsonUtil.toJson(result));
cb.onResult(JsonUtil.toJson(result)); CongestionControl.masterServerLoad.decrementAndGet();
CongestionControl.masterServerLoad.decrementAndGet(); }
} }, null);
}, null);
} else { } else {
LOGGER.debug("send ReRoute response:" + cr); LOGGER.debug("send ReRoute response:" + cr.toString());
JsonObject result = new JsonObject(); JsonObject result = new JsonObject();
result.addProperty("action", "reRouteContract"); result.addProperty("action", "reRouteContract");
result.addProperty("responseID", cr.get("requestID").getAsString()); result.addProperty("responseID", cr.get("requestID").getAsString());

View File

@ -22,7 +22,8 @@ public class MasterServerTransferAction {
private static final Logger LOGGER = LogManager.getLogger(MasterServerTransferAction.class); private static final Logger LOGGER = LogManager.getLogger(MasterServerTransferAction.class);
private Map<String, OutputStream> fileMap = new HashMap<>(); private Map<String, OutputStream> fileMap = new HashMap<>();
public MasterServerTransferAction() {} public MasterServerTransferAction() {
}
@Action(async = true) @Action(async = true)
public void transferByYPK(JsonObject args, ResultCallback cb) { public void transferByYPK(JsonObject args, ResultCallback cb) {
@ -53,8 +54,7 @@ public class MasterServerTransferAction {
} catch (FileNotFoundException e) { } catch (FileNotFoundException e) {
e.printStackTrace(); e.printStackTrace();
} }
} else } else fout = (FileOutputStream) fileMap.get(fileKey);
fout = (FileOutputStream) fileMap.get(fileKey);
if (isDone) { if (isDone) {
if (fout != null) if (fout != null)
try { try {
@ -88,10 +88,11 @@ public class MasterServerTransferAction {
c.setID(contractID); c.setID(contractID);
c.setOwner(GlobalConf.instance.keyPair.getPublicKeyStr()); c.setOwner(GlobalConf.instance.keyPair.getPublicKeyStr());
c.doSignature(GlobalConf.instance.keyPair);
try { try {
File temp = new File(path); File temp = new File(path);
if (temp.isFile() && temp.exists()) if (temp.isFile() && temp.exists()) c.setScript(temp.getAbsolutePath());
c.setScript(temp.getAbsolutePath());
} catch (Exception e) { } catch (Exception e) {
e.printStackTrace(); e.printStackTrace();
} }
@ -118,6 +119,7 @@ public class MasterServerTransferAction {
c.setID(contractID); c.setID(contractID);
c.setOwner(GlobalConf.instance.keyPair.getPublicKeyStr()); c.setOwner(GlobalConf.instance.keyPair.getPublicKeyStr());
c.doSignature(GlobalConf.instance.keyPair);
c.setScript(script); c.setScript(script);
return CMActions.manager.startContract(c); return CMActions.manager.startContract(c);
@ -143,8 +145,7 @@ public class MasterServerTransferAction {
} catch (FileNotFoundException e) { } catch (FileNotFoundException e) {
e.printStackTrace(); e.printStackTrace();
} }
} else } else fout = (FileOutputStream) fileMap.get(fileName);
fout = (FileOutputStream) fileMap.get(fileName);
if (isDone) { if (isDone) {
if (fout != null) if (fout != null)
try { try {

View File

@ -4,17 +4,20 @@ import com.google.gson.JsonObject;
import org.bdware.sc.conn.ResultCallback; import org.bdware.sc.conn.ResultCallback;
import org.bdware.sc.util.JsonUtil; import org.bdware.sc.util.JsonUtil;
import org.bdware.server.action.Action; import org.bdware.server.action.Action;
import org.bdware.units.NetworkManager;
import org.bdware.units.beans.MultiPointContractInfo; import org.bdware.units.beans.MultiPointContractInfo;
import org.bdware.units.function.ContractUnitManager; import org.bdware.units.function.ContractUnitManager;
import org.bdware.units.function.ExecutionManager; import org.bdware.units.function.ExecutionManager;
import org.bdware.units.function.SequencingManager; import org.bdware.units.function.SequencingManager;
/** /**
* 负责集群信息的方法 如获取集群信息master信息等 * 负责集群信息的方法
* 如获取集群信息master信息等
*/ */
public class UnitsInfoAction { public class UnitsInfoAction {
public UnitsInfoAction() {} public UnitsInfoAction() {
}
@Action(async = true) @Action(async = true)
public void getContractUnit(String contractId, final ResultCallback callback) { public void getContractUnit(String contractId, final ResultCallback callback) {
@ -26,8 +29,7 @@ public class UnitsInfoAction {
JsonObject jsonObject = new JsonObject(); JsonObject jsonObject = new JsonObject();
jsonObject.addProperty("action", "getContractUnit"); jsonObject.addProperty("action", "getContractUnit");
jsonObject.addProperty("contractId", contractId); jsonObject.addProperty("contractId", contractId);
ContractUnitManager.instance.send(jsonObject.toString(), ContractUnitManager.instance.send(jsonObject.toString(), new String[]{"NetworkManager.instance.getTcpNodeCenter()"}, callback);
new String[] {"NetworkManager.instance.getTcpNodeCenter()"}, callback);
} }
} }
@ -41,8 +43,7 @@ public class UnitsInfoAction {
JsonObject jsonObject = new JsonObject(); JsonObject jsonObject = new JsonObject();
jsonObject.addProperty("action", "getContractUnitMaster"); jsonObject.addProperty("action", "getContractUnitMaster");
jsonObject.addProperty("content", contractId); jsonObject.addProperty("content", contractId);
ContractUnitManager.instance.send(jsonObject.toString(), ContractUnitManager.instance.send(jsonObject.toString(), new String[]{"NetworkManager.instance.getTcpNodeCenter()"}, callback);
new String[] {"NetworkManager.instance.getTcpNodeCenter()"}, callback);
} }
} }
@ -57,8 +58,7 @@ public class UnitsInfoAction {
@Action(async = true) @Action(async = true)
public void updateContractStartInfo(JsonObject args, final ResultCallback callback) { public void updateContractStartInfo(JsonObject args, final ResultCallback callback) {
System.out.println("[updateContractStartInfo] " + args); System.out.println("[updateContractStartInfo] " + args);
MultiPointContractInfo contractInfo = MultiPointContractInfo contractInfo = JsonUtil.fromJson(args.get("content").getAsString(), MultiPointContractInfo.class);
JsonUtil.fromJson(args.get("content").getAsString(), MultiPointContractInfo.class);
String contractID = args.get("contractID").getAsString(); String contractID = args.get("contractID").getAsString();
ContractUnitManager.instance.addContractInfo(contractID, contractInfo); ContractUnitManager.instance.addContractInfo(contractID, contractInfo);
SequencingManager.instance.updateConsensusCenter(contractID, contractInfo); SequencingManager.instance.updateConsensusCenter(contractID, contractInfo);

View File

@ -35,7 +35,8 @@ import java.io.File;
public class _UNUSED_ExecutionAction implements OnHashCallback { public class _UNUSED_ExecutionAction implements OnHashCallback {
private static final Logger LOGGER = LogManager.getLogger(_UNUSED_ExecutionAction.class); private static final Logger LOGGER = LogManager.getLogger(_UNUSED_ExecutionAction.class);
public _UNUSED_ExecutionAction() {} public _UNUSED_ExecutionAction() {
}
// TODO TOMerge // TODO TOMerge
@Action(async = true) @Action(async = true)
@ -58,6 +59,7 @@ public class _UNUSED_ExecutionAction implements OnHashCallback {
// contractID not hash // contractID not hash
c.setID(contractID); c.setID(contractID);
c.setOwner(GlobalConf.instance.keyPair.getPublicKeyStr()); c.setOwner(GlobalConf.instance.keyPair.getPublicKeyStr());
c.doSignature(GlobalConf.instance.keyPair);
// c.setConsensusType(sequencing); // c.setConsensusType(sequencing);
// c.setNetworkType(network); // c.setNetworkType(network);
if (content != null && content.startsWith("/")) { if (content != null && content.startsWith("/")) {
@ -70,18 +72,23 @@ public class _UNUSED_ExecutionAction implements OnHashCallback {
} else { } else {
unitContractMessage.msgType = unitContractMessage.msgType =
UnitContractMessageType.ContractUnitResponse.getValue(); UnitContractMessageType.ContractUnitResponse.getValue();
// unitContractMessage.cuType = // unitContractMessage.cuType =
// UnitContractRequestType.START.getValue(); // UnitContractRequestType.START.getValue();
unitContractMessage.action = "startContractResponse"; unitContractMessage.action = "startContractResponse";
unitContractMessage.content = unitContractMessage.content =
JsonUtil.toJson(new ContractResult(ContractResult.Status.Exception, JsonUtil.toJson(
new JsonPrimitive("Contract not found"))); new ContractResult(
reply = UnitMessage.newBuilder() ContractResult.Status.Exception,
.setMsgType(BDLedgerContract.UnitMessageType.UnitContractMessage) new JsonPrimitive("Contract not found")));
.setSender(GlobalConf.instance.peerID).addReceiver(sender) reply =
.setContent(ByteString.copyFromUtf8(JsonUtil.toJson(unitContractMessage))) UnitMessage.newBuilder()
.build(); .setMsgType(BDLedgerContract.UnitMessageType.UnitContractMessage)
// byte[] bytes = reply.toByteArray(); .setSender(GlobalConf.instance.peerID)
.addReceiver(sender)
.setContent(
ByteString.copyFromUtf8(JsonUtil.toJson(unitContractMessage)))
.build();
// byte[] bytes = reply.toByteArray();
callback.onResult(JsonUtil.toJson(reply)); callback.onResult(JsonUtil.toJson(reply));
return; return;
} }
@ -90,21 +97,24 @@ public class _UNUSED_ExecutionAction implements OnHashCallback {
c.setScript(content); c.setScript(content);
} }
content = CMActions.manager.startContract(c); content = CMActions.manager.startContractAndRedirect(c, System.out);
LOGGER.info("[START] result: " + content); LOGGER.info("[START] result: " + content);
result = JsonUtil.fromJson(content, ContractResult.class); result = JsonUtil.fromJson(content, ContractResult.class);
unitContractMessage.msgType = UnitContractMessageType.ContractUnitResponse.getValue(); unitContractMessage.msgType = UnitContractMessageType.ContractUnitResponse.getValue();
// unitContractMessage.statusType = result.status == // unitContractMessage.statusType = result.status ==
// ContractResult.Status.Success?0:1; // ContractResult.Status.Success?0:1;
unitContractMessage.action = "startContractResponse"; unitContractMessage.action = "startContractResponse";
// Collector investigates success or fail // Collector investigates success or fail
unitContractMessage.content = JsonUtil.toJson(result); unitContractMessage.content = JsonUtil.toJson(result);
// TODO save privKey in contractClient // TODO save privKey in contractClient
unitContractMessage.pubkey = ""; unitContractMessage.pubkey = "";
reply = UnitMessage.newBuilder() reply =
.setMsgType(BDLedgerContract.UnitMessageType.UnitContractMessage) UnitMessage.newBuilder()
.setSender(GlobalConf.instance.peerID).addReceiver(sender) .setMsgType(BDLedgerContract.UnitMessageType.UnitContractMessage)
.setContent(ByteString.copyFromUtf8(JsonUtil.toJson(unitContractMessage))).build(); .setSender(GlobalConf.instance.peerID)
.addReceiver(sender)
.setContent(ByteString.copyFromUtf8(JsonUtil.toJson(unitContractMessage)))
.build();
byte[] bytes = reply.toByteArray(); byte[] bytes = reply.toByteArray();
callback.onResult(ByteUtil.encodeBASE64(bytes)); callback.onResult(ByteUtil.encodeBASE64(bytes));
if (result.status == ContractResult.Status.Success) { if (result.status == ContractResult.Status.Success) {
@ -121,8 +131,10 @@ public class _UNUSED_ExecutionAction implements OnHashCallback {
System.out.println("[BaseFunctionManager] handleResponse null"); System.out.println("[BaseFunctionManager] handleResponse null");
return; return;
} }
if (responseCenter.updateReply(arg.get("content").getAsString(), if (responseCenter.updateReply(
arg.get("sender").getAsString(), arg.get("pubkey").getAsString())) { arg.get("content").getAsString(),
arg.get("sender").getAsString(),
arg.get("pubkey").getAsString())) {
// save contractInfo // save contractInfo
String contractID = arg.get("contractID").getAsString(); String contractID = arg.get("contractID").getAsString();
int sequencing = arg.get("sequencing").getAsInt(); int sequencing = arg.get("sequencing").getAsInt();
@ -147,54 +159,62 @@ public class _UNUSED_ExecutionAction implements OnHashCallback {
@Action(async = true) @Action(async = true)
public void executeContractAtSlave(JsonObject args, final ResultCallback callback) { public void executeContractAtSlave(JsonObject args, final ResultCallback callback) {
String sender = args.get("sender").getAsString(); String sender = args.get("sender").getAsString();
UnitContractMessage unitContractMessage = UnitContractMessage unitContractMessage = JsonUtil.fromJson(args, UnitContractMessage.class);
JsonUtil.fromJson(args, UnitContractMessage.class);
String requestID = unitContractMessage.requestID; String requestID = unitContractMessage.requestID;
int sequencing = unitContractMessage.sequencing; int sequencing = unitContractMessage.sequencing;
int network = unitContractMessage.network; int network = unitContractMessage.network;
// int rcheck = unitContractMessage.rcheck; // int rcheck = unitContractMessage.rcheck;
String contractID = unitContractMessage.contractID; String contractID = unitContractMessage.contractID;
String operation = unitContractMessage.operation; String operation = unitContractMessage.operation;
String arg = unitContractMessage.arg; String arg = unitContractMessage.arg;
// String content = unitContractMessage.content; // String content = unitContractMessage.content;
LOGGER.info("[executeContractAtSlave] [EXECUTE] " + args); LOGGER.info("[executeContractAtSlave] [EXECUTE] " + args);
final ContractRequest c = new ContractRequest(); final ContractRequest c = new ContractRequest();
c.setContractID(contractID); c.setContractID(contractID);
c.setRequestID(requestID); c.setRequestID(requestID);
// c.withDynamicAnalysis = args.get("withDynamicAnalysis").getAsBoolean(); // c.withDynamicAnalysis = args.get("withDynamicAnalysis").getAsBoolean();
// c.withEvaluatesAnalysis = args.get("withEvaluatesAnalysis").getAsBoolean(); // c.withEvaluatesAnalysis = args.get("withEvaluatesAnalysis").getAsBoolean();
c.setAction(operation); c.setAction(operation);
c.setArg(arg); c.setArg(arg);
// if (c.withEvaluatesAnalysis) { // if (c.withEvaluatesAnalysis) {
// c.setValue(jo.get("hasValue").getAsLong()); // c.setValue(jo.get("hasValue").getAsLong());
// } // }
// if (jo.has("gasLimit")) { // if (jo.has("gasLimit")) {
// c.setGasLimit(jo.get("gasLimit").getAsLong()); // c.setGasLimit(jo.get("gasLimit").getAsLong());
// } // }
// if (args.has("requester")) { // if (args.has("requester")) {
// c.setPublicKey(args.get("requester").getAsString()); // c.setPublicKey(args.get("requester").getAsString());
// c.setSignature(args.get("signature").getAsString()); // c.setSignature(args.get("signature").getAsString());
// } // }
// c.setPublicKey(args.get("pubkey").getAsString()); // c.setPublicKey(args.get("pubkey").getAsString());
// c.setSignature(args.get("signature").getAsString()); // c.setSignature(args.get("signature").getAsString());
String reqID; String reqID;
long start = System.currentTimeMillis(); long start = System.currentTimeMillis();
CMActions.manager.executeContractInternal(c, new ResultCallback() { CMActions.manager.executeContractInternal(
@Override c,
public void onResult(String str) { new ResultCallback() {
// TODO qianming @Override
unitContractMessage.signature = str; public void onResult(String str) {
unitContractMessage.action = "executeContractResponse"; // TODO qianming
unitContractMessage.content = str; unitContractMessage.signature = str;
UnitMessage unitMessage = UnitMessage.newBuilder() unitContractMessage.action = "executeContractResponse";
.setMsgType(BDLedgerContract.UnitMessageType.UnitContractMessage) unitContractMessage.content = str;
.setSender(GlobalConf.instance.peerID).addReceiver(sender) UnitMessage unitMessage =
.setContent(ByteString.copyFromUtf8(JsonUtil.toJson(unitContractMessage))) UnitMessage.newBuilder()
.build(); .setMsgType(
byte[] bytes = unitMessage.toByteArray(); BDLedgerContract.UnitMessageType
callback.onResult(ByteUtil.encodeBASE64(bytes)); .UnitContractMessage)
} .setSender(GlobalConf.instance.peerID)
}, null); .addReceiver(sender)
.setContent(
ByteString.copyFromUtf8(
JsonUtil.toJson(unitContractMessage)))
.build();
byte[] bytes = unitMessage.toByteArray();
callback.onResult(ByteUtil.encodeBASE64(bytes));
}
},
null);
} }
@Action(async = true) @Action(async = true)
@ -206,8 +226,10 @@ public class _UNUSED_ExecutionAction implements OnHashCallback {
System.out.println("[BaseFunctionManager] responseCenter null"); System.out.println("[BaseFunctionManager] responseCenter null");
return; return;
} }
if (responseCenter.updateReply(arg.get("content").getAsString(), if (responseCenter.updateReply(
arg.get("sender").getAsString(), arg.get("signature").getAsString())) { arg.get("content").getAsString(),
arg.get("sender").getAsString(),
arg.get("signature").getAsString())) {
// call back // call back
responseCenter.formReply(); responseCenter.formReply();
ExecutionManager.instance.responseCenters.remove(requestID); ExecutionManager.instance.responseCenters.remove(requestID);
@ -217,30 +239,38 @@ public class _UNUSED_ExecutionAction implements OnHashCallback {
@Action(async = true) @Action(async = true)
public void stopContractAtSlave(JsonObject args, final ResultCallback callback) { public void stopContractAtSlave(JsonObject args, final ResultCallback callback) {
String sender = args.get("sender").getAsString(); String sender = args.get("sender").getAsString();
UnitContractMessage unitContractMessage = UnitContractMessage unitContractMessage = JsonUtil.fromJson(args, UnitContractMessage.class);
JsonUtil.fromJson(args, UnitContractMessage.class);
String requestID = unitContractMessage.requestID; String requestID = unitContractMessage.requestID;
int sequencing = unitContractMessage.sequencing; int sequencing = unitContractMessage.sequencing;
int network = unitContractMessage.network; int network = unitContractMessage.network;
// int rcheck = unitContractMessage.rcheck; // int rcheck = unitContractMessage.rcheck;
String contractID = unitContractMessage.contractID; String contractID = unitContractMessage.contractID;
LOGGER.info("[stopContractAtSlave] [EXECUTE] " + args); LOGGER.info("[stopContractAtSlave] [EXECUTE] " + args);
final ContractRequest c = new ContractRequest(); final ContractRequest c = new ContractRequest();
c.setContractID(contractID); c.setContractID(contractID);
c.setRequestID(requestID); c.setRequestID(requestID);
String ret = CMActions.manager String ret =
.stopContractWithOwner(GlobalConf.instance.keyPair.getPublicKeyStr(), contractID); CMActions.manager.stopContractWithOwner(
GRPCPool.instance.writeToChain(this, contractID, "stopContract", ret, GlobalConf.instance.keyPair.getPublicKeyStr(), contractID);
args.has("requestID") ? args.get("requestID").getAsString() : null, ""); GRPCPool.instance.writeToChain(
this,
contractID,
"stopContract",
ret,
args.has("requestID") ? args.get("requestID").getAsString() : null,
"");
ContractResult contractResult = ContractResult contractResult =
new ContractResult(ContractResult.Status.Success, new JsonPrimitive("success")); new ContractResult(ContractResult.Status.Success, new JsonPrimitive("success"));
unitContractMessage.signature = ret; unitContractMessage.signature = ret;
unitContractMessage.action = "stopContractResponse"; unitContractMessage.action = "stopContractResponse";
unitContractMessage.content = JsonUtil.toJson(contractResult); unitContractMessage.content = JsonUtil.toJson(contractResult);
UnitMessage unitMessage = UnitMessage.newBuilder() UnitMessage unitMessage =
.setMsgType(BDLedgerContract.UnitMessageType.UnitContractMessage) UnitMessage.newBuilder()
.setSender(GlobalConf.instance.peerID).addReceiver(sender) .setMsgType(BDLedgerContract.UnitMessageType.UnitContractMessage)
.setContent(ByteString.copyFromUtf8(JsonUtil.toJson(unitContractMessage))).build(); .setSender(GlobalConf.instance.peerID)
.addReceiver(sender)
.setContent(ByteString.copyFromUtf8(JsonUtil.toJson(unitContractMessage)))
.build();
byte[] bytes = unitMessage.toByteArray(); byte[] bytes = unitMessage.toByteArray();
callback.onResult(ByteUtil.encodeBASE64(bytes)); callback.onResult(ByteUtil.encodeBASE64(bytes));
} }
@ -255,8 +285,10 @@ public class _UNUSED_ExecutionAction implements OnHashCallback {
System.out.println("[BaseFunctionManager] responseCenter null"); System.out.println("[BaseFunctionManager] responseCenter null");
return; return;
} }
if (responseCenter.updateReply(arg.get("content").getAsString(), if (responseCenter.updateReply(
arg.get("sender").getAsString(), arg.get("signature").getAsString())) { arg.get("content").getAsString(),
arg.get("sender").getAsString(),
arg.get("signature").getAsString())) {
// call back // call back
boolean allSuccess = responseCenter.isAllSuccess(); boolean allSuccess = responseCenter.isAllSuccess();
responseCenter.formReply(); responseCenter.formReply();
@ -268,5 +300,6 @@ public class _UNUSED_ExecutionAction implements OnHashCallback {
} }
@Override @Override
public void publishHash(String reqID, String hashStr) {} public void publishHash(String reqID, String hashStr) {
}
} }

View File

@ -1,144 +0,0 @@
package org.bdware.server.doip;
import com.google.gson.Gson;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import org.bdware.bdosclient.CodeRepoClient;
import org.bdware.bdosclient.bean.UploadingStatus;
import org.bdware.bdosclient.bean.YPKInfo;
import org.bdware.doip.audit.EndpointConfig;
import org.bdware.doip.audit.client.AuditIrpClient;
import org.bdware.doip.audit.writer.AuditType;
import org.bdware.doip.codec.doipMessage.DoipMessage;
import org.bdware.doip.endpoint.client.DoipMessageCallback;
import org.bdware.server.GlobalConf;
import org.zz.gmhelper.SM2KeyPair;
import java.io.File;
public class BCOManager {
private final String codeRepoDoid;
private final String routerURI;
private final SM2KeyPair keyPair;
CodeRepoClient client;
File bcodir;
static Logger LOGGER = LogManager.getLogger(BCOManager.class);
public BCOManager(String doid, File bcoDir, String routerURI, SM2KeyPair keyPair) {
this.bcodir = bcoDir;
this.codeRepoDoid = CodeRepoClient.getDefaultCodeRepo(doid);
this.routerURI = routerURI;
this.keyPair = keyPair;
}
public String download(String bcoId) {
if (client == null) {
EndpointConfig config = new EndpointConfig();
config.routerURI = GlobalConf.instance.doaConf.lhsAddress;
config.auditType = AuditType.None;
AuditIrpClient irpClient = new AuditIrpClient(codeRepoDoid, config);
client = new CodeRepoClient(codeRepoDoid, irpClient, keyPair);
}
YPKInfo ypkInfo = new YPKInfo();
client.retrieveBCO(bcoId, new DoipMessageCallback() {
@Override
public void onResult(DoipMessage doipMessage) {
String body = doipMessage.body.getDataAsJsonString();
LOGGER.info("Retrieve " + bcoId + " Result:" + body);
YPKInfo parsed = new Gson().fromJson(body, YPKInfo.class);
if (parsed != null && parsed.md5 != null
&& parsed.status == UploadingStatus.Finished) {
ypkInfo.copyFrom(parsed);
}
synchronized (ypkInfo) {
ypkInfo.notify();
}
}
});
synchronized (ypkInfo) {
try {
if (ypkInfo.status == null)
ypkInfo.wait(4000L);
} catch (Exception e) {
}
}
LOGGER.info("Download:" + new Gson().toJson(ypkInfo));
if (ypkInfo.status == UploadingStatus.Finished) {
File target = getYpkFile(ypkInfo);
if (target.exists() && (client.calFileMd5(target.getAbsolutePath()) + ".ypk")
.equals(target.getName()))
return target.getAbsolutePath();
DownloadProgressChecker checker = new DownloadProgressChecker();
client.downloadYPK(bcoId, checker, target);
LOGGER.info("start Download:" + new Gson().toJson(ypkInfo));
checker.waitForResult(30000);
LOGGER.info("checker:" + checker.isSuccess);
if (checker.isSuccess)
return target.getAbsolutePath();
}
return null;
}
static class DownloadProgressChecker implements CodeRepoClient.ProgressCallback {
boolean finished = false;
boolean isSuccess = false;
@Override
public void onStart(String s) {
}
@Override
public void onProgress(String s, int i, int i1) {
LOGGER.info(s + " " + i + " /" + i1);
}
@Override
public void onFinish(String s) {
finished = true;
isSuccess = true;
synchronized (this) {
this.notify();
}
}
@Override
public void onError(String s, DoipMessage doipMessage) {
finished = true;
isSuccess = false;
synchronized (this) {
this.notify();
}
LOGGER.info("[Download error]" + s + " doipMessage:"
+ doipMessage.body.getDataAsJsonString());
}
public void waitForResult(long timeout) {
synchronized (this) {
if (!this.finished) {
try {
this.wait(timeout);
} catch (InterruptedException e) {
}
}
}
}
}
private File getYpkFile(YPKInfo ypkInfo) {
File f = new File(bcodir, ypkInfo.pkgName);
if (ypkInfo.version != null)
f = new File(f, ypkInfo.version);
f = new File(f, ypkInfo.md5 + ".ypk");
return f;
}
private static AuditIrpClient initIrpClient() {
EndpointConfig config = new EndpointConfig();
config.routerURI = GlobalConf.instance.doaConf.lhsAddress;
config.auditType = AuditType.None;
AuditIrpClient irpClient = new AuditIrpClient(GlobalConf.instance.doaConf.repoDoid, config);
return irpClient;
}
}

View File

@ -1,55 +1,34 @@
package org.bdware.server.doip; package org.bdware.server.doip;
import com.google.gson.*; import com.google.gson.JsonArray;
import com.google.gson.JsonElement;
import com.google.gson.JsonObject;
import com.google.gson.JsonPrimitive;
import io.netty.channel.ChannelHandler; import io.netty.channel.ChannelHandler;
import org.apache.logging.log4j.LogManager; import org.bdware.doip.core.doipMessage.DoipMessage;
import org.apache.logging.log4j.Logger; import org.bdware.doip.core.doipMessage.DoipResponseCode;
import org.bdware.doip.audit.server.DefaultRepoHandlerInjector; import org.bdware.doip.core.model.digitalObject.DigitalObject;
import org.bdware.doip.codec.digitalObject.DigitalObject; import org.bdware.doip.core.model.digitalObject.DoType;
import org.bdware.doip.codec.digitalObject.DoType; import org.bdware.doip.core.model.digitalObject.Element;
import org.bdware.doip.codec.doipMessage.DoipMessage; import org.bdware.doip.core.model.operations.BasicOperations;
import org.bdware.doip.codec.doipMessage.DoipMessageFactory; import org.bdware.doip.endpoint.doipServer.DoipServiceInfo;
import org.bdware.doip.codec.doipMessage.DoipResponseCode; import org.bdware.doip.endpoint.doipServer.Op;
import org.bdware.doip.codec.operations.BasicOperations; import org.bdware.doip.endpoint.doipServer.RepositoryHandlerBase;
import org.bdware.doip.endpoint.server.DoipServiceInfo;
import org.bdware.doip.endpoint.server.Op;
import org.bdware.doip.endpoint.server.RepositoryHandlerBase;
import org.bdware.irp.stateinfo.StateInfoBase;
import org.bdware.sc.ContractClient; import org.bdware.sc.ContractClient;
import org.bdware.sc.ContractMeta;
import org.bdware.sc.ContractStatusEnum;
import org.bdware.sc.bean.Contract;
import org.bdware.sc.bean.ContractExecType;
import org.bdware.sc.bean.ContractRequest; import org.bdware.sc.bean.ContractRequest;
import org.bdware.sc.bean.FunctionDesp; import org.bdware.sc.bean.FunctionDesp;
import org.bdware.sc.conn.ResultCallback; import org.bdware.sc.conn.ResultCallback;
import org.bdware.sc.db.CMTables;
import org.bdware.sc.db.KeyValueDBUtil;
import org.bdware.sc.util.JsonUtil; import org.bdware.sc.util.JsonUtil;
import org.bdware.server.GlobalConf;
import org.bdware.server.action.CMActions; import org.bdware.server.action.CMActions;
import org.zz.gmhelper.SM2KeyPair;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.PrintStream;
import java.util.ArrayList; import java.util.ArrayList;
import java.util.List; import java.util.List;
import static org.bdware.server.doip.ContractRepositoryMain.currentIrpClient;
@ChannelHandler.Sharable @ChannelHandler.Sharable
public class ContractRepositoryHandler extends RepositoryHandlerBase public class ContractRepositoryHandler extends RepositoryHandlerBase {
implements DefaultRepoHandlerInjector {
BCOManager bcoManager;
static Logger LOGGER = LogManager.getLogger(ContractRepositoryHandler.class);
public ContractRepositoryHandler(DoipServiceInfo info) { public ContractRepositoryHandler(DoipServiceInfo info) {
super(info); super(info);
GlobalConf.DOAConf doaConf = GlobalConf.instance.doaConf;
String bcoDir = GlobalConf.instance.bcoDir;
bcoManager = new BCOManager(doaConf.repoDoid, new File(bcoDir), doaConf.lhsAddress,
GlobalConf.instance.keyPair);
} }
@Override @Override
@ -59,11 +38,6 @@ public class ContractRepositoryHandler extends RepositoryHandlerBase
@Override @Override
public DoipMessage handleListOps(DoipMessage doipMessage) { public DoipMessage handleListOps(DoipMessage doipMessage) {
if (!GlobalConf.instance.doaConf.repoDoid.equals(doipMessage.header.parameters.id)) {
return replyStringWithStatus(doipMessage,
"unsupported doid:" + doipMessage.header.parameters.id,
DoipResponseCode.DoNotFound);
}
JsonArray ops = new JsonArray(); JsonArray ops = new JsonArray();
ops.add(BasicOperations.Hello.getName()); ops.add(BasicOperations.Hello.getName());
ops.add("call"); ops.add("call");
@ -72,126 +46,7 @@ public class ContractRepositoryHandler extends RepositoryHandlerBase
@Override @Override
public DoipMessage handleCreate(DoipMessage doipMessage) { public DoipMessage handleCreate(DoipMessage doipMessage) {
if (!GlobalConf.instance.doaConf.repoDoid.equals(doipMessage.header.parameters.id)) { return replyStringWithStatus(doipMessage, "not supported yet", DoipResponseCode.Declined);
return replyStringWithStatus(doipMessage,
"unsupported doid:" + doipMessage.header.parameters.id,
DoipResponseCode.DoNotFound);
}
// TODD 验证签名完事后进入
if (doipMessage.credential != null && doipMessage.credential.getSigner() != null) {
String permissions = KeyValueDBUtil.instance.getValue(CMTables.NodeRole.toString(),
doipMessage.credential.getSigner());
if (!permissions.contains("ContractInstanceManager")) {
return replyStringWithStatus(doipMessage, "permission denied, role:" + permissions,
DoipResponseCode.Declined);
}
}
DigitalObject digitalObject = null;
try {
digitalObject = doipMessage.body.getDataAsDigitalObject();
digitalObject.attributes.remove("verifiedPubKey");
} catch (Exception e) {
ByteArrayOutputStream bo = new ByteArrayOutputStream();
e.printStackTrace(new PrintStream(bo));
return replyStringWithStatus(doipMessage, "exception:" + new String(bo.toByteArray()),
DoipResponseCode.Invalid);
}
digitalObject.attributes.addProperty("owner", doipMessage.credential.getSigner());
try {
String result = startUsingJsonObject(digitalObject.attributes);
// Please note startContractByYPK is invoked in sync mode method.
return replyStringWithStatus(doipMessage, result, DoipResponseCode.Success);
} catch (Exception e) {
return replyStringWithStatus(doipMessage, e.getMessage(),
DoipResponseCode.MoreThanOneErrors);
}
}
public String startUsingJsonObject(JsonObject attributes) {
LOGGER.info("create BDO, bCcoId:" + attributes.get("bcoId").getAsString());
String path = null;
if (attributes.has("bcoId"))
path = bcoManager.download(attributes.get("bcoId").getAsString());
if (path == null) {
throw new IllegalArgumentException(
"exception, failed to locate bcoId:" + attributes.get("bcoId").getAsString());
}
attributes.addProperty("path", path);
Contract c = new Contract();
if (attributes.has("contractExecType"))
c.setType(ContractExecType.valueOf(attributes.get("contractExecType").getAsString()));
else
c.setType(ContractExecType.Sole);
if (attributes.has("shardingId"))
c.setShardingId(Integer.valueOf(attributes.get("shardingId").getAsString()));
else
c.setShardingId(-1);
c.setScript(path);
c.setOwner(attributes.get("owner").getAsString());
if (attributes.has("createParam")) {
c.setCreateParam(attributes.get("createParam"));
}
SM2KeyPair sm2Key = null;
if (attributes.has("sm2KeyPair"))
sm2Key = SM2KeyPair.fromJson(attributes.get("sm2KeyPair").getAsJsonObject().toString());
if (sm2Key == null)
CMActions.manager.allocateKeyIfNotExists(c);
else {
c.setKey(sm2Key.getPrivateKeyStr());
c.setPublicKey(sm2Key.getPublicKeyStr());
String contractID = String.valueOf(sm2Key.getPublicKeyStr().hashCode());
c.setID(contractID); // contractID是根据hash算出来的
}
String result = CMActions.manager.startContract(c);
registerBDOID(c.getID(), c.getPublicKey(), attributes.get("bcoId").getAsString(), result);
return result;
}
private void registerBDOID(String contractID, String contractPubKey, String bcoId,
String startResult) {
try {
JsonObject startResultJO = JsonParser.parseString(startResult).getAsJsonObject();
if (!startResultJO.get("status").getAsString().equals("Success"))
return;
int doipPort = 0;
if (startResultJO.has("doipStartPort"))
doipPort = startResultJO.get("doipStartPort").getAsInt();
if (startResultJO.has("doipListenPort"))
doipPort = startResultJO.get("doipListenPort").getAsInt();
StateInfoBase base = new StateInfoBase();
String repoId = GlobalConf.instance.doaConf.repoDoid;
String uri = GlobalConf.instance.doaConf.doipAddress;
int lastPos = uri.lastIndexOf(":");
base.identifier = repoId + "/" + contractID;
base.handleValues = new JsonObject();
base.handleValues.addProperty("bdwType", "BDO");
base.handleValues.addProperty("bcoId", bcoId);
base.handleValues.addProperty("repoId", repoId);
base.handleValues.addProperty("date", System.currentTimeMillis());
if (doipPort > 0) {
base.handleValues.addProperty("address", uri.substring(0, lastPos + 1) + doipPort);
base.handleValues.addProperty("version", "2.1");
base.handleValues.addProperty("protocol", "DOIP");
}
base.handleValues.addProperty("pubKey", contractPubKey);
StateInfoBase oldBase = currentIrpClient.resolve(base.identifier, false);
String registerResult = null;
LOGGER.info("base:" + oldBase == null ? "NULL" : JsonUtil.toPrettyJson(oldBase));
if (oldBase == null)
registerResult = currentIrpClient.register(base);
else
registerResult = currentIrpClient.reRegister(base);
// LOGGER.info("TORegister:" + new
// GsonBuilder().setPrettyPrinting().create().toJson(base));
LOGGER.info(base.identifier + " register result:" + registerResult);
} catch (Exception e) {
e.printStackTrace();
}
// irp
} }
@Override @Override
@ -201,65 +56,36 @@ public class ContractRepositoryHandler extends RepositoryHandlerBase
@Override @Override
public DoipMessage handleDelete(DoipMessage doipMessage) { public DoipMessage handleDelete(DoipMessage doipMessage) {
String id = doipMessage.header.parameters.attributes.get("elementId").getAsString(); return replyStringWithStatus(doipMessage, "not supported yet", DoipResponseCode.Declined);
id = id.replaceAll(".*/", "");
LOGGER.info("handleDelete:" + id);
// TODO judge whethere the do exists
ContractMeta meta = CMActions.manager.statusRecorder.getContractMeta(id);
if (meta == null) {
return replyStringWithStatus(doipMessage, "can't locate do",
DoipResponseCode.DoNotFound);
}
if (meta.getStatus() == ContractStatusEnum.KILLED) {
return replyStringWithStatus(doipMessage, "already deleted!",
DoipResponseCode.Declined);
}
DoipMessage[] content = new DoipMessage[1];
JsonObject jo = new JsonObject();
jo.addProperty("action", "killContractProcess");
String result = CMActions.manager.stopContract(meta.getID());
return replyStringWithStatus(doipMessage, result, DoipResponseCode.Success);
} }
@Override @Override
public DoipMessage handleRetrieve(DoipMessage doipMessage) { public DoipMessage handleRetrieve(DoipMessage doipMessage) {
if (doipMessage.header.parameters.id.equals(GlobalConf.instance.doaConf.repoDoid)) {
if (doipMessage.header.parameters.attributes == null
|| !doipMessage.header.parameters.attributes.has("element"))
return retrieveList(doipMessage);
else
return retrieveBDO(doipMessage,
doipMessage.header.parameters.attributes.get("element").getAsString());
} else
return replyStringWithStatus(doipMessage, "no such do", DoipResponseCode.Declined);
}
private DoipMessage retrieveBDO(DoipMessage doipMessage, String idOrName) {
ContractClient client = null; ContractClient client = null;
try { try {
client = CMActions.manager.getContractClientByDoi(idOrName); client = CMActions.manager.getContractClientByDoi(doipMessage.header.parameters.id);
} catch (Exception e) { } catch (Exception e) {
} }
if (client == null) { if (client == null) {
String doid = idOrName; String doid = doipMessage.header.parameters.id;
int off = doid.lastIndexOf("/"); int off = doid.lastIndexOf("/");
if (off > 0) if (off > 0)
doid = doid.substring(off + 1); doid = doid.substring(off + 1);
client = CMActions.manager.getContractClientByDoi(doid); client = CMActions.manager.getContractClientByDoi(doid);
} }
if (client == null) { if (client == null) {
return replyStringWithStatus(doipMessage, "BDO instance not exist!", return replyStringWithStatus(
DoipResponseCode.DoNotFound); doipMessage, "Contract instance not exist!", DoipResponseCode.DoNotFound);
} }
byte[] data = doipMessage.body.getEncodedData(); byte[] data = doipMessage.body.getEncodedData();
if (data == null || data.length == 0) { if (data == null || data.length == 0) {
JsonObject contractDO = contract2DigitalObject(client); DigitalObject contractDO = contract2DigitalObject(client);
return replyString(doipMessage, contractDO.toString()); return replyDO(doipMessage, contractDO);
} else { } else {
JsonObject jo = JsonUtil.parseStringAsJsonObject(new String(data)); JsonObject jo = JsonUtil.parseStringAsJsonObject(new String(data));
List<JsonElement> result = new ArrayList<>(); List<JsonElement> result = new ArrayList<>();
jo.addProperty("bdoSuffix", client.contractMeta.getID()); jo.addProperty("contractID", client.contractMeta.getID());
CMActions.executeContractInternal(jo, new ResultCallback() { CMActions.executeContractInternal(jo, new ResultCallback() {
@Override @Override
public void onResult(JsonObject str) { public void onResult(JsonObject str) {
@ -286,8 +112,7 @@ public class ContractRepositoryHandler extends RepositoryHandlerBase
result.add(new JsonPrimitive("Timeout!")); result.add(new JsonPrimitive("Timeout!"));
retStatus = DoipResponseCode.MoreThanOneErrors; retStatus = DoipResponseCode.MoreThanOneErrors;
} }
DigitalObject digitalObject = DigitalObject digitalObject = new DigitalObject(doipMessage.header.parameters.id, DoType.DO);
new DigitalObject(doipMessage.header.parameters.id, DoType.DO);
digitalObject.addAttribute("status", retStatus.getName()); digitalObject.addAttribute("status", retStatus.getName());
digitalObject.addAttribute("result", result.get(0)); digitalObject.addAttribute("result", result.get(0));
@ -295,57 +120,40 @@ public class ContractRepositoryHandler extends RepositoryHandlerBase
} }
} }
private DoipMessage retrieveList(DoipMessage message) { private DigitalObject contract2DigitalObject(ContractClient contractClient) {
JsonArray listDO = new JsonArray(); DigitalObject contractDO = new DigitalObject(contractClient.getContractDOI(), DoType.DO);
for (String key : CMActions.manager.statusRecorder.getStatus().keySet()) { contractDO.addAttribute("contractName", contractClient.getContractName());
ContractClient contractClient = CMActions.manager.getContractClientByDoi(key); // contractDO.addAttribute("script",contract.contract.getScriptStr());
if (contractClient != null) { contractDO.addAttribute("owner", contractClient.contractMeta.contract.getOwner());
JsonObject ele = new JsonObject();
ele.addProperty("suffix", contractClient.getContractID());
ele.addProperty("bdoName", contractClient.contractMeta.getName());
ele.addProperty("status", contractClient.contractMeta.getStatus().toString());
listDO.add(ele);
}
}
return replyString(message, listDO.toString());
}
private JsonObject contract2DigitalObject(ContractClient contractClient) {
JsonObject contractDO = new JsonObject();
contractDO.addProperty("suffix", contractClient.getContractID());
contractDO.addProperty("bdoName", contractClient.getContractName());
contractDO.addProperty("owner", contractClient.contractMeta.contract.getOwner());
JsonArray operations = new JsonArray();
contractDO.add("operations", operations);
for (FunctionDesp f : contractClient.getExportedFunctions()) { for (FunctionDesp f : contractClient.getExportedFunctions()) {
JsonObject jo = new JsonObject(); Element fe = new Element(f.functionName, "function");
jo.addProperty("opeationName", f.functionName); fe.setAttribute("annotation", JsonUtil.toJson(f.annotations));
jo.add("annotation", JsonUtil.parseObject(f.annotations)); contractDO.addElements(fe);
operations.add(jo);
} }
return contractDO; return contractDO;
} }
@Op(op = BasicOperations.Extension, name = "call") @Op(op = BasicOperations.Extension, name = "call")
public DoipMessage handleCall(DoipMessage doipMessage) { public DoipMessage handleCall(DoipMessage doipMessage) {
ContractClient cc = ContractClient cc = CMActions.manager.getContractClientByDoi(doipMessage.header.parameters.id);
CMActions.manager.getContractClientByDoi(doipMessage.header.parameters.id);
if (cc == null) if (cc == null)
return replyStringWithStatus(doipMessage, "Contract instance not exist!", return replyStringWithStatus(
DoipResponseCode.DoNotFound); doipMessage, "Contract instance not exist!", DoipResponseCode.DoNotFound);
// todo transform doipMessage to args // todo transform doipMessage to args
JsonObject args = doipMessage.header.parameters.attributes; JsonObject args = doipMessage.header.parameters.attributes;
ContractRequest cr = new ContractRequest(); ContractRequest cr = new ContractRequest();
cr.setContractID(cc.getContractID()); cr.setContractID(cc.getContractID());
cr.setContractDOI(doipMessage.header.parameters.id);
if (args.has("withDynamicAnalysis")) if (args.has("withDynamicAnalysis"))
cr.withDynamicAnalysis = args.get("withDynamicAnalysis").getAsBoolean(); cr.withDynamicAnalysis = args.get("withDynamicAnalysis").getAsBoolean();
if (args.has("withEvaluatesAnalysis")) if (args.has("withEvaluatesAnalysis"))
cr.withEvaluatesAnalysis = args.get("withEvaluatesAnalysis").getAsBoolean(); cr.withEvaluatesAnalysis = args.get("withEvaluatesAnalysis").getAsBoolean();
if (args.get("elementID") == null) if (args.get("elementID") == null)
return replyStringWithStatus(doipMessage, "missing elementID", return replyStringWithStatus(
DoipResponseCode.Invalid); doipMessage, "missing elementID", DoipResponseCode.Invalid);
cr.setAction(args.get("elementID").getAsString()); cr.setAction(args.get("elementID").getAsString());
if (doipMessage.body.getEncodedData() != null) if (doipMessage.body.getEncodedData() != null)
@ -355,8 +163,7 @@ public class ContractRepositoryHandler extends RepositoryHandlerBase
cr.setRequesterDOI(doipMessage.credential.getSigner()); cr.setRequesterDOI(doipMessage.credential.getSigner());
String reqID; String reqID;
if (args.has("requestID")) if (args.has("requestID")) reqID = args.get("requestID").getAsString();
reqID = args.get("requestID").getAsString();
else { else {
reqID = System.currentTimeMillis() + "_" + (int) (Math.random() * 1000); reqID = System.currentTimeMillis() + "_" + (int) (Math.random() * 1000);
args.addProperty("requestID", reqID); args.addProperty("requestID", reqID);
@ -365,43 +172,11 @@ public class ContractRepositoryHandler extends RepositoryHandlerBase
String resp = CMActions.manager.execute(cr, null); String resp = CMActions.manager.execute(cr, null);
// StringContainer sc = new StringContainer(); // StringContainer sc = new StringContainer();
// SyncContainer sync = new SyncContainer(sc); // SyncContainer sync = new SyncContainer(sc);
return replyString(doipMessage, resp); return replyString(doipMessage, resp);
} }
@Override
public void injectCreate(DoipMessage request, DoipMessageFactory.DoipMessageBuilder builder) {
builder.setDoipMessage(handleCreate(request));
}
@Override
public void injectHello(DoipMessage request, DoipMessageFactory.DoipMessageBuilder builder) {
builder.setDoipMessage(handleHello(request));
}
@Override
public void injectListOps(DoipMessage doipMessage,
DoipMessageFactory.DoipMessageBuilder builder) {
builder.setDoipMessage(handleListOps(doipMessage));
}
@Override
public void injectUpdate(DoipMessage request, DoipMessageFactory.DoipMessageBuilder builder) {
// use default behavior
}
@Override
public void injectRetrieve(DoipMessage doipMessage,
DoipMessageFactory.DoipMessageBuilder builder) {
builder.setDoipMessage(handleRetrieve(doipMessage));
}
@Override
public void injectDelete(DoipMessage doipMessage,
DoipMessageFactory.DoipMessageBuilder builder) {
builder.setDoipMessage(handleDelete(doipMessage));
}
} }

View File

@ -1,118 +1,50 @@
package org.bdware.server.doip; package org.bdware.server.doip;
import com.google.gson.Gson; import com.nimbusds.jose.jwk.JWK;
import io.netty.channel.ChannelHandlerContext;
import org.apache.logging.log4j.LogManager; import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger; import org.apache.logging.log4j.Logger;
import org.bdware.doip.audit.EndpointConfig; import org.bdware.doip.core.crypto.GlobalCertifications;
import org.bdware.doip.audit.client.AuditIrpClient; import org.bdware.doip.core.doipMessage.DoipMessageFormat;
import org.bdware.doip.audit.server.AuditDoipServer; import org.bdware.doip.core.utils.GlobalConfigurations;
import org.bdware.doip.audit.writer.AuditType; import org.bdware.doip.endpoint.doipServer.DoipListenerInfo;
import org.bdware.doip.codec.doipMessage.DoipMessage; import org.bdware.doip.endpoint.doipServer.DoipServerImpl;
import org.bdware.doip.codec.doipMessage.DoipMessageFactory; import org.bdware.doip.endpoint.doipServer.DoipServiceInfo;
import org.bdware.doip.codec.doipMessage.DoipResponseCode; import org.bdware.server.DOAConf;
import org.bdware.doip.encrypt.SM2Signer;
import org.bdware.doip.endpoint.server.DoipListenerConfig;
import org.bdware.doip.endpoint.server.DoipRequestHandler;
import org.bdware.doip.endpoint.server.DoipServiceInfo;
import org.bdware.sc.ContractMeta;
import org.bdware.server.GlobalConf; import org.bdware.server.GlobalConf;
import org.bdware.server.action.CMActions;
import org.zz.gmhelper.SM2KeyPair;
import java.util.ArrayList; import java.util.ArrayList;
import java.util.List; import java.util.List;
public class ContractRepositoryMain { public class ContractRepositoryMain {
private static final Logger LOGGER = LogManager.getLogger(ContractRepositoryMain.class); private static final Logger LOGGER = LogManager.getLogger(ContractRepositoryMain.class);
static AuditDoipServer currentServer; static DoipServerImpl currentServer;
static LocalDoipFrowarder forwarder;
static final String repoType = "BDRepo";
public static AuditIrpClient currentIrpClient;
public static ContractRepositoryHandler currentHandler;
public static void start() { public static void start() {
try { try {
LOGGER.info("DOIPServer, start" + new Gson().toJson(GlobalConf.instance.doaConf)); String[] ipAndPort = GlobalConf.instance.masterAddress.split(":");
String url = GlobalConf.instance.doaConf.doipAddress; String url = String.format("tcp://%s:%d", ipAndPort[0], Integer.valueOf(ipAndPort[1]) + 1);
forwarder = new LocalDoipFrowarder(); String doid = DOAConf.repoDoid;
if (url == null || GlobalConf.instance.doaConf.repoDoid.isEmpty()) { LOGGER.info("DOIPServer start:" + url);
LOGGER.warn("missing args, failed to start! url:" + url + " doid:" if (url == null || doid == null) {
+ GlobalConf.instance.doaConf.repoDoid); LOGGER.warn("missing args, failed to start! url:" + url + " doid:" + doid);
return; return;
} }
if (currentServer != null) { if (currentServer != null) {
currentServer.stop(); currentServer.stop();
} }
List<DoipListenerConfig> infos = new ArrayList<>();
infos.add(new DoipListenerConfig(url, "2.1"));
DoipServiceInfo info = new DoipServiceInfo(GlobalConf.instance.doaConf.repoDoid,
GlobalConf.instance.keyPair.getPublicKeyStr(), repoType, infos);
EndpointConfig config = new EndpointConfig();
config.publicKey = GlobalConf.instance.keyPair.getPublicKeyStr();
config.privateKey = GlobalConf.instance.keyPair.getPrivateKeyStr();
config.auditType = AuditType.None;
config.routerURI = GlobalConf.instance.doaConf.lhsAddress;
config.repoName = GlobalConf.instance.doaConf.repoName;
currentIrpClient = new AuditIrpClient(config);
currentServer = new AuditDoipServer(config, info);
currentHandler = new ContractRepositoryHandler(info);
currentServer.setRepositoryHandler(currentHandler);
DoipRequestHandler requestCallback = currentServer.getRequestCallback();
SM2Signer signer = new SM2Signer(SM2KeyPair.fromJson(new Gson().toJson(config)));
DelegateDoipHandler delegateHandler = new DelegateDoipHandler(requestCallback) {
@Override
protected DoipMessage delegateMessage(ChannelHandlerContext context,
DoipMessage message) {
DoipMessageFactory.DoipMessageBuilder builder =
new DoipMessageFactory.DoipMessageBuilder();
builder.createResponse(DoipResponseCode.DelegateRequired, message);
String id = message.header.parameters.id;
id = id.replaceAll(".*/", "");
ContractMeta meta = CMActions.manager.statusRecorder.getContractMeta(id);
if (enableDelegate(meta)) {
LOGGER.info("delegate:" + message.requestID + " --> doipPort:"
+ meta.contract.getDoipPort());
// if port is near cmhttp server port
builder.addAttributes("port", meta.contract.getDoipPort());
DoipMessage ret;
ret = builder.create();
if (message.credential != null && message.credential.getSigner() != null) {
signer.signMessage(ret);
}
return ret;
} else {
LOGGER.info("forward:" + message.requestID + " --> doipPort:"
+ meta.contract.getDoipPort());
return forwarder.forward(meta, message);
}
} List<DoipListenerInfo> infos = new ArrayList<>();
infos.add(new DoipListenerInfo(url, "2.1", DoipMessageFormat.PACKET));
@Override GlobalCertifications.jwKeyPair = JWK.parse("{\"kty\":\"EC\",\"d\":\"wMrGJjk877bKQ_AAvdb8DM1XpUFo6POSLYDXid6AfBw\",\"use\":\"sig\",\"crv\":\"P-256\",\"kid\":\"AIBD\\/dou.ADMIN\",\"x\":\"N0TydMwdnvkyHrXVh1zfc9_7DV6tRqfCGElhywzXJYo\",\"y\":\"rX5pGGML9efP2r8hoMSwxaR9gwVHmqaldsG-yfE_eUI\"}");
public boolean accept(ChannelHandlerContext context, DoipMessage message) { GlobalConfigurations.userID = GlobalCertifications.jwKeyPair.getKeyID();
String id = message.header.parameters.id; DoipServiceInfo info = new DoipServiceInfo(doid, GlobalConfigurations.userID, "ContractRepo", infos);
if (id != null) { currentServer = new DoipServerImpl(info);
id = id.replaceAll(".*/", ""); currentServer.setRepositoryHandler(new ContractRepositoryHandler(info));
ContractMeta meta = CMActions.manager.statusRecorder.getContractMeta(id);
if (meta != null)
return true;
}
return false;
}
};
currentServer.setRequestCallback(delegateHandler);
currentServer.start(); currentServer.start();
} catch (Exception e) { } catch (Exception e) {
e.printStackTrace(); e.printStackTrace();
LOGGER.warn("load doip config exception!"); LOGGER.warn("load doip config exception!");
} }
}
private static boolean enableDelegate(ContractMeta meta) {
int port = meta.contract.getDoipPort();
int delta = Integer.valueOf(GlobalConf.instance.ipPort.split(":")[1]) - port;
return Math.abs(delta) < 200;
} }
} }

View File

@ -0,0 +1,5 @@
package org.bdware.server.doip;
public class ContractRepositoryServer {
}

View File

@ -1,25 +0,0 @@
package org.bdware.server.doip;
import io.netty.channel.ChannelHandlerContext;
import org.bdware.doip.codec.doipMessage.DoipMessage;
import org.bdware.doip.endpoint.server.DoipRequestHandler;
public abstract class DelegateDoipHandler implements DoipRequestHandler {
private final DoipRequestHandler original;
public DelegateDoipHandler(DoipRequestHandler original) {
this.original = original;
}
public DoipMessage onRequest(ChannelHandlerContext context, DoipMessage doipMessage) {
if (accept(context, doipMessage)) {
return delegateMessage(context, doipMessage);
} else
return original.onRequest(context, doipMessage);
}
protected abstract DoipMessage delegateMessage(ChannelHandlerContext context,
DoipMessage message);
public abstract boolean accept(ChannelHandlerContext context, DoipMessage message);
}

View File

@ -1,61 +0,0 @@
package org.bdware.server.doip;
import org.bdware.doip.codec.doipMessage.DoipMessage;
import org.bdware.doip.codec.doipMessage.DoipMessageFactory;
import org.bdware.doip.codec.doipMessage.DoipResponseCode;
import org.bdware.doip.endpoint.client.ClientConfig;
import org.bdware.doip.endpoint.client.DoipClientImpl;
import org.bdware.doip.endpoint.client.DoipMessageCallback;
import org.bdware.sc.ContractMeta;
import java.io.ByteArrayOutputStream;
import java.io.PrintStream;
import java.util.HashMap;
import java.util.Map;
public class LocalDoipFrowarder {
Map<Integer, DoipClientImpl> connections;
public LocalDoipFrowarder() {
connections = new HashMap<>();
}
public DoipMessage forward(ContractMeta meta, DoipMessage message) {
DoipClientImpl connection;
try {
if (connections.containsKey(meta.contract.getDoipPort())) {
connection = connections.get(meta.contract.getDoipPort());
} else {
connection = new DoipClientImpl();
connection.connect(
ClientConfig.fromUrl("tcp://127.0.0.1:" + meta.contract.getDoipPort()));
connections.put(meta.contract.getDoipPort(), connection);
}
if (!connection.isConnected())
connection.reconnect();
DoipMessage[] result = new DoipMessage[1];
connection.sendRawMessage(message, new DoipMessageCallback() {
@Override
public void onResult(DoipMessage msg) {
synchronized (result) {
result[0] = msg;
result.notify();
}
}
});
synchronized (result) {
if (result[0] == null)
result.wait(30000L);
}
return result[0];
} catch (Exception e) {
ByteArrayOutputStream bo = new ByteArrayOutputStream();
e.printStackTrace(new PrintStream(bo));
DoipMessageFactory.DoipMessageBuilder builder =
new DoipMessageFactory.DoipMessageBuilder();
builder.createResponse(DoipResponseCode.UnKnownError, message);
builder.setBody(bo.toByteArray());
return builder.create();
}
}
}

View File

@ -1,12 +0,0 @@
package org.bdware.server.executor;
import org.bdware.sc.conn.ResultCallback;
public interface Context {
public String[] getMembers(String contractID);
public void sendToAgent(String pubkey, String content);
public void sleepWithTimeout(final String requestID, ResultCallback cb, int timeOut);
}

View File

@ -1,378 +1,375 @@
// package org.bdware.server.executor.consistency; package org.bdware.server.executor.consistency;
//
// import com.google.gson.JsonObject; import com.google.gson.JsonObject;
// import com.google.gson.JsonParser; import com.google.gson.JsonParser;
// import com.google.gson.JsonPrimitive; import com.google.gson.JsonPrimitive;
// import org.apache.logging.log4j.LogManager; import org.apache.logging.log4j.LogManager;
// import org.apache.logging.log4j.Logger; import org.apache.logging.log4j.Logger;
// import org.bdware.sc.ComponedContractResult; import org.bdware.sc.ComponedContractResult;
// import org.bdware.sc.ContractResult; import org.bdware.sc.ContractResult;
// import org.bdware.sc.bean.ContractRequest; import org.bdware.sc.bean.ContractRequest;
// import org.bdware.sc.conn.Node; import org.bdware.sc.conn.Node;
// import org.bdware.sc.conn.OnHashCallback; import org.bdware.sc.conn.OnHashCallback;
// import org.bdware.sc.conn.ResultCallback; import org.bdware.sc.conn.ResultCallback;
// import org.bdware.sc.consistency.Committer; import org.bdware.sc.consistency.Committer;
// import org.bdware.sc.consistency.pbft.PBFTAlgorithm; import org.bdware.sc.consistency.pbft.PBFTAlgorithm;
// import org.bdware.sc.consistency.pbft.PBFTMember; import org.bdware.sc.consistency.pbft.PBFTMember;
// import org.bdware.sc.consistency.pbft.PBFTMessage; import org.bdware.sc.consistency.pbft.PBFTMessage;
// import org.bdware.sc.consistency.pbft.PBFTType; import org.bdware.sc.consistency.pbft.PBFTType;
// import org.bdware.sc.units.*; import org.bdware.sc.units.*;
// import org.bdware.sc.util.JsonUtil; import org.bdware.sc.util.JsonUtil;
// import org.bdware.server.GlobalConf; import org.bdware.server.GlobalConf;
// import org.bdware.server.action.CMActions; import org.bdware.server.action.CMActions;
// import org.bdware.server.action.p2p.MasterServerRecoverMechAction; import org.bdware.server.action.p2p.MasterServerRecoverMechAction;
// import org.bdware.server.action.p2p.MasterServerTCPAction; import org.bdware.server.action.p2p.MasterServerTCPAction;
// import org.bdware.server.trustedmodel.ContractCluster; import org.bdware.server.trustedmodel.ContractCluster;
// import org.bdware.server.trustedmodel.ContractExecutor; import org.bdware.server.trustedmodel.ContractExecutor;
// import org.bdware.server.trustedmodel.MultiReqSeq; import org.bdware.server.trustedmodel.MultiReqSeq;
// import org.bdware.server.trustedmodel.ResultCollector; import org.bdware.server.trustedmodel.ResultCollector;
// import org.bdware.units.NetworkManager; import org.bdware.units.NetworkManager;
// import org.zz.gmhelper.SM2KeyPair; import org.zz.gmhelper.SM2KeyPair;
//
// import java.util.*; import java.util.*;
// import java.util.concurrent.ConcurrentHashMap; import java.util.concurrent.ConcurrentHashMap;
// import java.util.concurrent.atomic.AtomicInteger; import java.util.concurrent.atomic.AtomicInteger;
//
//// TODO 追赶差下的调用 //TODO 追赶差下的调用
// public class PBFTExecutor implements ContractExecutor { public class PBFTExecutor implements ContractExecutor {
// private static final Logger LOGGER = LogManager.getLogger(PBFTExecutor.class); private static final Logger LOGGER = LogManager.getLogger(PBFTExecutor.class);
// final Object lock = new Object(); final Object lock = new Object();
// private final List<PubKeyNode> members; private final List<PubKeyNode> members;
// int resultCount; int resultCount;
//
// AtomicInteger request_index = new AtomicInteger(0); AtomicInteger request_index = new AtomicInteger(0);
// // key为requestIDvalue为其seq // key为requestIDvalue为其seq
// Map<String, MultiReqSeq> seqMap = new ConcurrentHashMap<>(); Map<String, MultiReqSeq> seqMap = new ConcurrentHashMap<>();
// Map<String, ResultCache> resultCache = new ConcurrentHashMap<>(); Map<String, ResultCache> resultCache = new ConcurrentHashMap<>();
// // MultiPointContractInfo info; // MultiPointContractInfo info;
// String contractID; String contractID;
// PBFTAlgorithm pbft; PBFTAlgorithm pbft;
// ContractCluster contractCluster; ContractCluster contractCluster;
// boolean isMaster; boolean isMaster;
//
// public PBFTExecutor( public PBFTExecutor(
// int c, String con_id, final String masterPubkey, String[] members) { int c, String con_id, final String masterPubkey, String[] members) {
// resultCount = c; resultCount = c;
// contractID = con_id; contractID = con_id;
// this.members = new ArrayList<>(); this.members = new ArrayList<>();
// isMaster = GlobalConf.getNodeID().equals(masterPubkey); isMaster = GlobalConf.getNodeID().equals(masterPubkey);
// pbft = new PBFTAlgorithm(isMaster); pbft = new PBFTAlgorithm(isMaster);
// int count = 0; int count = 0;
// for (String mem : members) { for (String mem : members) {
// PubKeyNode pubkeyNode = new PubKeyNode(); PubKeyNode pubkeyNode = new PubKeyNode();
// pubkeyNode.pubkey = mem; pubkeyNode.pubkey = mem;
// PBFTMember pbftMember = new PBFTMember(); PBFTMember pbftMember = new PBFTMember();
// pbftMember.isMaster = mem.equals(masterPubkey); pbftMember.isMaster = mem.equals(masterPubkey);
// pbft.addMember(pubkeyNode, pbftMember); pbft.addMember(pubkeyNode, pbftMember);
// this.members.add(pubkeyNode); this.members.add(pubkeyNode);
// if (GlobalConf.getNodeID().equals(mem)) { if (GlobalConf.getNodeID().equals(mem)) {
// pbft.setSendID(count); pbft.setSendID(count);
// } }
// count++; count++;
// } }
// contractCluster = new ContractCluster(contractID, this.members); contractCluster = new ContractCluster(contractID, this.members);
// pbft.setConnection(contractCluster); pbft.setConnection(contractCluster);
// final MultiContractMeta cei = final MultiContractMeta cei = CMActions.manager.multiContractRecorder.getMultiContractMeta(contractID);
// CMActions.manager.multiContractRecorder.getMultiContractMeta(contractID); pbft.setCommitter(new Committer() {
// pbft.setCommitter(new Committer() { @Override
// @Override public void onCommit(ContractRequest data) {
// public void onCommit(ContractRequest data) { ResultCallback ret = null;
// ResultCallback ret = null; final long startTime = System.currentTimeMillis();
// final long startTime = System.currentTimeMillis(); ret = new ResultCallback() {
// ret = new ResultCallback() { @Override
// @Override public void onResult(String str) {
// public void onResult(String str) { Map<String, String> ret = new HashMap<>();
// Map<String, String> ret = new HashMap<>(); ret.put("action", "receiveTrustfullyResult");
// ret.put("action", "receiveTrustfullyResult"); SM2KeyPair keyPair = GlobalConf.instance.keyPair;
// SM2KeyPair keyPair = GlobalConf.instance.keyPair; ret.put("nodeID", keyPair.getPublicKeyStr());
// ret.put("nodeID", keyPair.getPublicKeyStr()); ret.put("responseID", data.getRequestID());
// ret.put("responseID", data.getRequestID()); ret.put("executeTime", (System.currentTimeMillis() - startTime) + "");
// ret.put("executeTime", (System.currentTimeMillis() - startTime) + ""); ret.put("data", str);
// ret.put("data", str); cei.setLastExeSeq(data.seq);
// cei.setLastExeSeq(data.seq); NetworkManager.instance.sendToAgent(masterPubkey, JsonUtil.toJson(ret));
// NetworkManager.instance.sendToAgent(masterPubkey, JsonUtil.toJson(ret)); }
// } };
// }; CMActions.manager.executeLocallyAsync(data, ret, null);
// CMActions.manager.executeLocallyAsync(data, ret, null); }
// } });
// }); }
// }
// public void onSyncMessage(Node node, byte[] data) {
// public void onSyncMessage(Node node, byte[] data) {
// pbft.onMessage(node, data);
// pbft.onMessage(node, data); }
// }
// public void setSeq(int seq) {
// public void setSeq(int seq) { request_index = new AtomicInteger(seq);
// request_index = new AtomicInteger(seq); pbft.setAtomSeq(request_index.get());
// pbft.setAtomSeq(request_index.get()); }
// }
// public ResultCallback createResultCallback(
// public ResultCallback createResultCallback( final String requestID,
// final String requestID, final ResultCallback originalCb,
// final ResultCallback originalCb, final int count,
// final int count, final int request_seq,
// final int request_seq, final String contractID) {
// final String contractID) { ComponedContractResult componedContractResult = new ComponedContractResult(count);
// ComponedContractResult componedContractResult = new ComponedContractResult(count); // TODO 加对应的超时
// // TODO 加对应的超时 return new ResultCollector(
// return new ResultCollector( requestID, new ResultMerger(originalCb, count, request_seq, contractID), count);
// requestID, new ResultMerger(originalCb, count, request_seq, contractID), count); }
// }
// public void sendRequest(String id, ContractRequest req, ResultCallback collector) {
// public void sendRequest(String id, ContractRequest req, ResultCallback collector) { // Map<String, Object> reqStr = new HashMap<>();
//// Map<String, Object> reqStr = new HashMap<>(); // reqStr.put("uniReqID", id);
//// reqStr.put("uniReqID", id); // reqStr.put("data", req);
//// reqStr.put("data", req); // reqStr.put("action", "executeContractLocally");
//// reqStr.put("action", "executeContractLocally"); ContractRequest cr2 = ContractRequest.parse(req.toByte());
// ContractRequest cr2 = ContractRequest.parse(req.toByte()); cr2.setRequestID(id);
// cr2.setRequestID(id); PBFTMessage request = new PBFTMessage();
// PBFTMessage request = new PBFTMessage(); request.setOrder(req.seq);
// request.setOrder(req.seq); request.setType(PBFTType.Request);
// request.setType(PBFTType.Request); request.setContent(cr2.toByte());
// request.setContent(cr2.toByte()); for (PubKeyNode node : members) {
// for (PubKeyNode node : members) { if (!NetworkManager.instance.hasAgentConnection(node.pubkey)) {
// if (!NetworkManager.instance.hasAgentConnection(node.pubkey)) { LOGGER.warn("cmNode " + node.pubkey.substring(0, 5) + " is null");
// LOGGER.warn("cmNode " + node.pubkey.substring(0, 5) + " is null"); collector.onResult(
// collector.onResult( "{\"status\":\"Error\",\"result\":\"node offline\","
// "{\"status\":\"Error\",\"result\":\"node offline\"," + "\"nodeID\":\""
// + "\"nodeID\":\"" + node
// + node + "\","
// + "\"," + "\"action\":\"onExecuteContractTrustfully\"}");
// + "\"action\":\"onExecuteContractTrustfully\"}"); // } else if (MasterServerRecoverMechAction.recoverStatus.get(node).get(contractID)
//// } else if (MasterServerRecoverMechAction.recoverStatus.get(node).get(contractID) // != RecoverFlag.Fine) {
//// != RecoverFlag.Fine) { // collector.onResult(
//// collector.onResult( // "{\"status\":\"Error\",\"result\":\"node recovering\","
//// "{\"status\":\"Error\",\"result\":\"node recovering\"," // + "\"nodeID\":\""
//// + "\"nodeID\":\"" // + node
//// + node // + "\","
//// + "\"," // + "\"action\":\"onExecuteContractTrustfully\"}");
//// + "\"action\":\"onExecuteContractTrustfully\"}"); // contractCluster.sendMessage(node, request.getBytes());
//// contractCluster.sendMessage(node, request.getBytes()); } else {
// } else { contractCluster.sendMessage(node, request.getBytes());
// contractCluster.sendMessage(node, request.getBytes()); }
// } }
// } // master负责缓存请求
// // master负责缓存请求 if (!MasterServerTCPAction.requestCache.containsKey(contractID)) {
// if (!MasterServerTCPAction.requestCache.containsKey(contractID)) { MasterServerTCPAction.requestCache.put(contractID, new RequestCache());
// MasterServerTCPAction.requestCache.put(contractID, new RequestCache()); }
// } // TODO 多调多统一个seq的有多个请求这个需要改
// // TODO 多调多统一个seq的有多个请求这个需要改 String[] nodes =
// String[] nodes = CMActions.manager.multiContractRecorder.getMultiContractMeta(contractID).getMembers();
// CMActions.manager.multiContractRecorder.getMultiContractMeta(contractID).getMembers(); LOGGER.info("cluster size=" + nodes.length + " contract " + req.getContractID());
// LOGGER.info("cluster size=" + nodes.length + " contract " + req.getContractID()); LOGGER.debug("contract " + req.getContractID() + " cluster: " + JsonUtil.toJson(nodes));
// LOGGER.debug("contract " + req.getContractID() + " cluster: " + JsonUtil.toJson(nodes));
// }
// }
//
// public boolean checkCurNodeNumValid() {
// public boolean checkCurNodeNumValid() { return true;
// return true; }
// }
// @Override
// @Override public void execute(String requestID, ContractRequest req, ResultCallback rc, OnHashCallback hcb) {
// public void execute(String requestID, ContractRequest req, ResultCallback rc, OnHashCallback hcb) LOGGER.debug(JsonUtil.toJson(req));
// { MultiContractMeta meta = CMActions.manager.multiContractRecorder.getMultiContractMeta(req.getContractID());
// LOGGER.debug(JsonUtil.toJson(req)); if (meta == null || !meta.isMaster()) {
// MultiContractMeta meta = CMActions.manager.executeContractOnOtherNodes(req, rc);
// CMActions.manager.multiContractRecorder.getMultiContractMeta(req.getContractID()); return;
// if (meta == null || !meta.isMaster()) { }
// CMActions.manager.executeContractOnOtherNodes(req, rc); req.setContractID(CMActions.manager.getContractIDByName(req.getContractID()));
// return;
// } // 三个相同requestID进来的时候会有冲突
// req.setContractID(CMActions.manager.getContractIDByName(req.getContractID())); // 仅在此处有冲突么
// // 这里是从MasterServer->MasterClient请求的是"executeContractLocally"
// // 三个相同requestID进来的时候会有冲突
// // 仅在此处有冲突么 // 如果是多点合约的请求A1A2A3的序号应该一致不能分配一个新的seq根据requestID判断是否不需要重新分配一个序号
// // 这里是从MasterServer->MasterClient请求的是"executeContractLocally" //TODO seqMap memory leak
// //TODO
// // 如果是多点合约的请求A1A2A3的序号应该一致不能分配一个新的seq根据requestID判断是否不需要重新分配一个序号 //TODO
// //TODO seqMap memory leak if (null != requestID && requestID.endsWith("_mul")) {
// //TODO synchronized (lock) {
// //TODO if (seqMap.containsKey(requestID)) {
// if (null != requestID && requestID.endsWith("_mul")) { req.seq = seqMap.get(requestID).seq;
// synchronized (lock) { } else {
// if (seqMap.containsKey(requestID)) { req.seq = request_index.getAndIncrement();
// req.seq = seqMap.get(requestID).seq; seqMap.put(requestID, new MultiReqSeq(req.seq));
// } else { }
// req.seq = request_index.getAndIncrement(); }
// seqMap.put(requestID, new MultiReqSeq(req.seq)); } else {
// } req.seq = request_index.getAndIncrement();
// } }
// } else { req.needSeq = true;
// req.seq = request_index.getAndIncrement(); String id =
// } System.currentTimeMillis() + "_" + (int) (Math.random() * 1000000) + "_" + req.seq;
// req.needSeq = true; LOGGER.info("execute receive requestID=" + requestID + " msgID=" + id);
// String id =
// System.currentTimeMillis() + "_" + (int) (Math.random() * 1000000) + "_" + req.seq; if (checkCurNodeNumValid()) {
// LOGGER.info("execute receive requestID=" + requestID + " msgID=" + id); LOGGER.debug("checkCurNodeNumValid=true");
// ResultCallback collector =
// if (checkCurNodeNumValid()) { createResultCallback(id, rc, resultCount, req.seq, req.getContractID());
// LOGGER.debug("checkCurNodeNumValid=true"); MasterServerTCPAction.sync.sleep(id, collector);
// ResultCallback collector = LOGGER.info("requestID=" + requestID + " master broadcasts request " + req.seq);
// createResultCallback(id, rc, resultCount, req.seq, req.getContractID()); sendRequest(id, req, collector);
// MasterServerTCPAction.sync.sleep(id, collector); } else {
// LOGGER.info("requestID=" + requestID + " master broadcasts request " + req.seq); LOGGER.debug("invalidNodeNumOnResult");
// sendRequest(id, req, collector); request_index.getAndDecrement();
// } else { ContractResult finalResult =
// LOGGER.debug("invalidNodeNumOnResult"); new ContractResult(
// request_index.getAndDecrement(); ContractResult.Status.Error,
// ContractResult finalResult = new JsonPrimitive("node number unavailable, request refused."));
// new ContractResult( rc.onResult(JsonUtil.toJson(finalResult));
// ContractResult.Status.Error, }
// new JsonPrimitive("node number unavailable, request refused."));
// rc.onResult(JsonUtil.toJson(finalResult)); // }
// }
// /* // 三个相同requestID进来的时候会有冲突
// // } // 仅在此处有冲突么
// // 这里是从MasterServer->MasterClient请求的是"executeContractLocally"
// /* // 三个相同requestID进来的时候会有冲突 req.seq = request_index.getAndIncrement();
// // 仅在此处有冲突么 req.needSeq = true;
// // 这里是从MasterServer->MasterClient请求的是"executeContractLocally" ResultCallback collector = createResultCallback(id, rc, resultCount, req.getContractID());
// req.seq = request_index.getAndIncrement(); MasterServerTCPAction.sync.sleep(id, collector);
// req.needSeq = true; sendRequest(id, req, collector);*/
// ResultCallback collector = createResultCallback(id, rc, resultCount, req.getContractID()); }
// MasterServerTCPAction.sync.sleep(id, collector);
// sendRequest(id, req, collector);*/ // 清理缓存的多点合约请求序号
// } public void clearCache() {
// final long time = System.currentTimeMillis() - 30000L;
// // 清理缓存的多点合约请求序号 seqMap.entrySet()
// public void clearCache() { .removeIf(
// final long time = System.currentTimeMillis() - 30000L; entry -> {
// seqMap.entrySet() MultiReqSeq cache = entry.getValue();
// .removeIf( if (null == cache) {
// entry -> { return true;
// MultiReqSeq cache = entry.getValue(); }
// if (null == cache) { return cache.startTime < time;
// return true; });
// } }
// return cache.startTime < time;
// }); public static class ResultMerger extends ResultCallback {
// } ComponedContractResult componedContractResult;
// AtomicInteger order;
// public static class ResultMerger extends ResultCallback { String contractID;
// ComponedContractResult componedContractResult; int count;
// AtomicInteger order; int request_seq;
// String contractID; ResultCallback originalCallback;
// int count; Set<String> nodeIDs = new HashSet<>(); // 已收到返回结果的节点
// int request_seq;
// ResultCallback originalCallback; ResultMerger(
// Set<String> nodeIDs = new HashSet<>(); // 已收到返回结果的节点 final ResultCallback originalCb,
// final int count,
// ResultMerger( final int request_seq,
// final ResultCallback originalCb, final String contractID) {
// final int count, originalCallback = originalCb;
// final int request_seq, this.count = count;
// final String contractID) { this.request_seq = request_seq;
// originalCallback = originalCb; this.contractID = contractID;
// this.count = count; componedContractResult = new ComponedContractResult(count);
// this.request_seq = request_seq; order = new AtomicInteger(0);
// this.contractID = contractID; }
// componedContractResult = new ComponedContractResult(count);
// order = new AtomicInteger(0); public String getContractID() {
// } return contractID;
// }
// public String getContractID() {
// return contractID; public String getInfo() {
// } return "contractID="
// + contractID
// public String getInfo() { + " 收到第 "
// return "contractID=" + order
// + contractID + " 个节点回复 : "
// + " 收到第 " + " order="
// + order + order
// + " 个节点回复 : " + " count="
// + " order=" + count
// + order + " ";
// + " count=" }
// + count
// + " "; @Override
// } public void onResult(String str) {
// // TODO 必须在这里聚合
// @Override // str的data是个ContractResult
// public void onResult(String str) { // 在这儿也是返回个ContractResult
// // TODO 必须在这里聚合 try {
// // str的data是个ContractResult LOGGER.debug("a result of contract" + contractID + ": " + str);
// // 在这儿也是返回个ContractResult JsonObject obj = JsonParser.parseString(str).getAsJsonObject();
// try { if (obj.has("nodeID")) {
// LOGGER.debug("a result of contract" + contractID + ": " + str); String id = obj.get("nodeID").getAsString();
// JsonObject obj = JsonParser.parseString(str).getAsJsonObject(); if (nodeIDs.contains(id)) {
// if (obj.has("nodeID")) { LOGGER.debug(
// String id = obj.get("nodeID").getAsString(); "ignored result because the result of node "
// if (nodeIDs.contains(id)) { + id.substring(0, 5)
// LOGGER.debug( + " has been received");
// "ignored result because the result of node " return;
// + id.substring(0, 5) }
// + " has been received"); nodeIDs.add(id);
// return; }
// }
// nodeIDs.add(id); LOGGER.debug(
// } String.format(
// "contractID=%s received=%s order=%d count=%d",
// LOGGER.debug( contractID, str, order.get(), count));
// String.format( componedContractResult.add(obj);
// "contractID=%s received=%s order=%d count=%d", // 收集到所有结果
// contractID, str, order.get(), count)); if (order.incrementAndGet() == count) {
// componedContractResult.add(obj); ContractResult finalResult = componedContractResult.figureFinalResult();
// // 收集到所有结果 finalResult.needSeq = true;
// if (order.incrementAndGet() == count) { finalResult.seq = request_seq;
// ContractResult finalResult = componedContractResult.figureFinalResult();
// finalResult.needSeq = true; // if (null == finalResult) {
// finalResult.seq = request_seq; // finalResult =
// // new ContractResult(
// // if (null == finalResult) { // ContractResult.Status.Exception,
// // finalResult = // new JsonPrimitive(
// // new ContractResult( // "no nore than half of the
// // ContractResult.Status.Exception, // consistent result"));
// // new JsonPrimitive( // originalCallback.onResult(new
// // "no nore than half of the // Gson().toJson(finalResult));
// // consistent result")); // } else {
// // originalCallback.onResult(new originalCallback.onResult(JsonUtil.toJson(finalResult));
// // Gson().toJson(finalResult)); // }
// // } else { LOGGER.debug(
// originalCallback.onResult(JsonUtil.toJson(finalResult)); String.format(
// // } "%d results are the same: %s",
// LOGGER.debug( finalResult.size, finalResult.result));
// String.format(
// "%d results are the same: %s", // 集群中事务序号+1
// finalResult.size, finalResult.result)); CMActions.manager.multiContractRecorder
// .getMultiContractMeta(contractID)
// // 集群中事务序号+1 .nextSeqAtMaster();
// CMActions.manager.multiContractRecorder
// .getMultiContractMeta(contractID) // recover其中无状态合约CP出错无需恢复
// .nextSeqAtMaster(); Set<String> nodesID = componedContractResult.getProblemNodes();
// if (null == nodesID || nodesID.isEmpty()) {
// // recover其中无状态合约CP出错无需恢复 return;
// Set<String> nodesID = componedContractResult.getProblemNodes(); }
// if (null == nodesID || nodesID.isEmpty()) { for (String nodeID : nodesID) {
// return; LOGGER.warn("node fails! " + nodeID);
// } if (MasterServerRecoverMechAction.recoverStatus.get(nodeID).get(contractID)
// for (String nodeID : nodesID) { == RecoverFlag.Fine) {
// LOGGER.warn("node fails! " + nodeID); MasterServerRecoverMechAction.recoverStatus
// if (MasterServerRecoverMechAction.recoverStatus.get(nodeID).get(contractID) .get(nodeID)
// == RecoverFlag.Fine) { .put(contractID, RecoverFlag.ToRecover);
// MasterServerRecoverMechAction.recoverStatus }
// .get(nodeID) }
// .put(contractID, RecoverFlag.ToRecover); for (String nodeID : nodesID) {
// } if (MasterServerRecoverMechAction.recoverStatus.get(nodeID).get(contractID)
// } == RecoverFlag.ToRecover) {
// for (String nodeID : nodesID) { LOGGER.warn("node in recover " + nodeID);
// if (MasterServerRecoverMechAction.recoverStatus.get(nodeID).get(contractID)
// == RecoverFlag.ToRecover) { // 因为该节点结果有误所以即时是stableMode也认为trans记录不可信
// LOGGER.warn("node in recover " + nodeID); // 直接通过load别的节点来恢复
// MasterServerRecoverMechAction.restartContractFromCommonMode(
// // 因为该节点结果有误所以即时是stableMode也认为trans记录不可信 nodeID, contractID);
// // 直接通过load别的节点来恢复 }
// MasterServerRecoverMechAction.restartContractFromCommonMode( }
// nodeID, contractID); }
// } // clearCache();
// } } catch (Exception e) {
// } e.printStackTrace();
// // clearCache(); LOGGER.warn("result exception!");
// } catch (Exception e) { }
// e.printStackTrace(); }
// LOGGER.warn("result exception!"); }
// } }
// }
// }
// }

View File

@ -40,10 +40,11 @@ public class RequestAllExecutor implements ContractExecutor {
// key为requestIDvalue为其seq // key为requestIDvalue为其seq
Map<String, MultiReqSeq> seqMap = new ConcurrentHashMap<>(); Map<String, MultiReqSeq> seqMap = new ConcurrentHashMap<>();
Map<String, ResultCache> resultCache = new ConcurrentHashMap<>(); Map<String, ResultCache> resultCache = new ConcurrentHashMap<>();
// MultiPointContractInfo info; // MultiPointContractInfo info;
String contractID; String contractID;
public RequestAllExecutor(ContractExecType t, int c, String con_id) { public RequestAllExecutor(
ContractExecType t, int c, String con_id) {
type = t; type = t;
resultCount = c; resultCount = c;
contractID = con_id; contractID = con_id;
@ -53,13 +54,16 @@ public class RequestAllExecutor implements ContractExecutor {
request_index = new AtomicInteger(seq); request_index = new AtomicInteger(seq);
} }
public ResultCallback createResultCallback(final String requestID, public ResultCallback createResultCallback(
final ResultCallback originalCb, final int count, final int request_seq, final String requestID,
final ResultCallback originalCb,
final int count,
final int request_seq,
final String contractID) { final String contractID) {
ComponedContractResult componedContractResult = new ComponedContractResult(count); ComponedContractResult componedContractResult = new ComponedContractResult(count);
// TODO 加对应的超时 // TODO 加对应的超时
return new ResultCollector(requestID, return new ResultCollector(
new ResultMerger(originalCb, count, request_seq, contractID), count); requestID, new ResultMerger(originalCb, count, request_seq, contractID), count);
} }
public void sendRequest(String id, ContractRequest req, ResultCallback collector) { public void sendRequest(String id, ContractRequest req, ResultCallback collector) {
@ -78,8 +82,8 @@ public class RequestAllExecutor implements ContractExecutor {
LOGGER.debug(JsonUtil.toJson(req)); LOGGER.debug(JsonUtil.toJson(req));
String[] nodes = CMActions.manager.multiContractRecorder.getMultiContractMeta(contractID) String[] nodes =
.getMembers(); CMActions.manager.multiContractRecorder.getMultiContractMeta(contractID).getMembers();
LOGGER.info("cluster size=" + nodes.length + " contract " + req.getContractID()); LOGGER.info("cluster size=" + nodes.length + " contract " + req.getContractID());
LOGGER.debug("contract " + req.getContractID() + " cluster: " + JsonUtil.toJson(nodes)); LOGGER.debug("contract " + req.getContractID() + " cluster: " + JsonUtil.toJson(nodes));
for (String node : nodes) { for (String node : nodes) {
@ -87,13 +91,19 @@ public class RequestAllExecutor implements ContractExecutor {
if (!NetworkManager.instance.hasAgentConnection(node)) { if (!NetworkManager.instance.hasAgentConnection(node)) {
LOGGER.warn("cmNode " + node.substring(0, 5) + " is null"); LOGGER.warn("cmNode " + node.substring(0, 5) + " is null");
collector.onResult( collector.onResult(
"{\"status\":\"Error\",\"result\":\"node offline\"," + "\"nodeID\":\"" "{\"status\":\"Error\",\"result\":\"node offline\","
+ node + "\"," + "\"action\":\"onExecuteContractTrustfully\"}"); + "\"nodeID\":\""
} else if (MasterServerRecoverMechAction.recoverStatus.get(node) + node
.get(contractID) != RecoverFlag.Fine) { + "\","
+ "\"action\":\"onExecuteContractTrustfully\"}");
} else if (MasterServerRecoverMechAction.recoverStatus.get(node).get(contractID)
!= RecoverFlag.Fine) {
collector.onResult( collector.onResult(
"{\"status\":\"Error\",\"result\":\"node recovering\"," + "\"nodeID\":\"" "{\"status\":\"Error\",\"result\":\"node recovering\","
+ node + "\"," + "\"action\":\"onExecuteContractTrustfully\"}"); + "\"nodeID\":\""
+ node
+ "\","
+ "\"action\":\"onExecuteContractTrustfully\"}");
NetworkManager.instance.sendToAgent(node, sendStr); NetworkManager.instance.sendToAgent(node, sendStr);
} else { } else {
LOGGER.info("send request to cmNode " + node.substring(0, 5)); LOGGER.info("send request to cmNode " + node.substring(0, 5));
@ -103,17 +113,16 @@ public class RequestAllExecutor implements ContractExecutor {
} }
public boolean checkCurNodeNumValid() { public boolean checkCurNodeNumValid() {
String[] nodes = CMActions.manager.multiContractRecorder.getMultiContractMeta(contractID) String[] nodes =
.getMembers(); CMActions.manager.multiContractRecorder.getMultiContractMeta(contractID).getMembers();
int validNode = 0; int validNode = 0;
Map<String, String> mapResult = new HashMap<>(); Map<String, String> mapResult = new HashMap<>();
for (String node : nodes) { for (String node : nodes) {
mapResult.put(node.substring(0, 5), mapResult.put(node.substring(0, 5), String.format("%s %s", NetworkManager.instance.hasAgentConnection(node) + "",
String.format("%s %s", NetworkManager.instance.hasAgentConnection(node) + "", MasterServerRecoverMechAction.recoverStatus.get(node).get(contractID)));
MasterServerRecoverMechAction.recoverStatus.get(node).get(contractID)));
if (NetworkManager.instance.hasAgentConnection(node) if (NetworkManager.instance.hasAgentConnection(node)
&& MasterServerRecoverMechAction.recoverStatus.get(node) && MasterServerRecoverMechAction.recoverStatus.get(node).get(contractID)
.get(contractID) == RecoverFlag.Fine) { == RecoverFlag.Fine) {
validNode++; validNode++;
} }
} }
@ -127,11 +136,9 @@ public class RequestAllExecutor implements ContractExecutor {
} }
@Override @Override
public void execute(String requestID, ContractRequest req, ResultCallback rc, public void execute(String requestID, ContractRequest req, ResultCallback rc, OnHashCallback hcb) {
OnHashCallback hcb) {
LOGGER.debug(JsonUtil.toJson(req)); LOGGER.debug(JsonUtil.toJson(req));
MultiContractMeta meta = MultiContractMeta meta = CMActions.manager.multiContractRecorder.getMultiContractMeta(req.getContractID());
CMActions.manager.multiContractRecorder.getMultiContractMeta(req.getContractID());
if (meta == null || !meta.isMaster()) { if (meta == null || !meta.isMaster()) {
CMActions.manager.executeContractOnOtherNodes(req, rc); CMActions.manager.executeContractOnOtherNodes(req, rc);
return; return;
@ -143,9 +150,9 @@ public class RequestAllExecutor implements ContractExecutor {
// 这里是从MasterServer->MasterClient请求的是"executeContractLocally" // 这里是从MasterServer->MasterClient请求的是"executeContractLocally"
// 如果是多点合约的请求A1A2A3的序号应该一致不能分配一个新的seq根据requestID判断是否不需要重新分配一个序号 // 如果是多点合约的请求A1A2A3的序号应该一致不能分配一个新的seq根据requestID判断是否不需要重新分配一个序号
// TODO seqMap memory leak //TODO seqMap memory leak
// TODO //TODO
// TODO //TODO
if (null != requestID && requestID.endsWith("_mul")) { if (null != requestID && requestID.endsWith("_mul")) {
synchronized (lock) { synchronized (lock) {
if (seqMap.containsKey(requestID)) { if (seqMap.containsKey(requestID)) {
@ -173,32 +180,37 @@ public class RequestAllExecutor implements ContractExecutor {
} else { } else {
LOGGER.debug("invalidNodeNumOnResult"); LOGGER.debug("invalidNodeNumOnResult");
request_index.getAndDecrement(); request_index.getAndDecrement();
ContractResult finalResult = new ContractResult(ContractResult.Status.Error, ContractResult finalResult =
new JsonPrimitive("node number unavailable, request refused.")); new ContractResult(
ContractResult.Status.Error,
new JsonPrimitive("node number unavailable, request refused."));
rc.onResult(JsonUtil.toJson(finalResult)); rc.onResult(JsonUtil.toJson(finalResult));
} }
// } // }
/* /* // 三个相同requestID进来的时候会有冲突
* // 三个相同requestID进来的时候会有冲突 // 仅在此处有冲突么 // // 仅在此处有冲突么
* 这里是从MasterServer->MasterClient请求的是"executeContractLocally" req.seq = // 这里是从MasterServer->MasterClient请求的是"executeContractLocally"
* request_index.getAndIncrement(); req.needSeq = true; ResultCallback collector = req.seq = request_index.getAndIncrement();
* createResultCallback(id, rc, resultCount, req.getContractID()); req.needSeq = true;
* MasterServerTCPAction.sync.sleep(id, collector); sendRequest(id, req, collector); ResultCallback collector = createResultCallback(id, rc, resultCount, req.getContractID());
*/ MasterServerTCPAction.sync.sleep(id, collector);
sendRequest(id, req, collector);*/
} }
// 清理缓存的多点合约请求序号 // 清理缓存的多点合约请求序号
public void clearCache() { public void clearCache() {
final long time = System.currentTimeMillis() - 30000L; final long time = System.currentTimeMillis() - 30000L;
seqMap.entrySet().removeIf(entry -> { seqMap.entrySet()
MultiReqSeq cache = entry.getValue(); .removeIf(
if (null == cache) { entry -> {
return true; MultiReqSeq cache = entry.getValue();
} if (null == cache) {
return cache.startTime < time; return true;
}); }
return cache.startTime < time;
});
} }
public static class ResultMerger extends ResultCallback { public static class ResultMerger extends ResultCallback {
@ -210,7 +222,10 @@ public class RequestAllExecutor implements ContractExecutor {
ResultCallback originalCallback; ResultCallback originalCallback;
Set<String> nodeIDs = new HashSet<>(); // 已收到返回结果的节点 Set<String> nodeIDs = new HashSet<>(); // 已收到返回结果的节点
ResultMerger(final ResultCallback originalCb, final int count, final int request_seq, ResultMerger(
final ResultCallback originalCb,
final int count,
final int request_seq,
final String contractID) { final String contractID) {
originalCallback = originalCb; originalCallback = originalCb;
this.count = count; this.count = count;
@ -225,8 +240,16 @@ public class RequestAllExecutor implements ContractExecutor {
} }
public String getInfo() { public String getInfo() {
return "contractID=" + contractID + " 收到第 " + order + " 个节点回复 : " + " order=" + order return "contractID="
+ " count=" + count + " "; + contractID
+ " 收到第 "
+ order
+ " 个节点回复 : "
+ " order="
+ order
+ " count="
+ count
+ " ";
} }
@Override @Override
@ -240,15 +263,19 @@ public class RequestAllExecutor implements ContractExecutor {
if (obj.has("nodeID")) { if (obj.has("nodeID")) {
String id = obj.get("nodeID").getAsString(); String id = obj.get("nodeID").getAsString();
if (nodeIDs.contains(id)) { if (nodeIDs.contains(id)) {
LOGGER.debug("ignored result because the result of node " LOGGER.debug(
+ id.substring(0, 5) + " has been received"); "ignored result because the result of node "
+ id.substring(0, 5)
+ " has been received");
return; return;
} }
nodeIDs.add(id); nodeIDs.add(id);
} }
LOGGER.debug(String.format("contractID=%s received=%s order=%d count=%d", LOGGER.debug(
contractID, str, order.get(), count)); String.format(
"contractID=%s received=%s order=%d count=%d",
contractID, str, order.get(), count));
componedContractResult.add(obj); componedContractResult.add(obj);
// 收集到所有结果 // 收集到所有结果
if (order.incrementAndGet() == count) { if (order.incrementAndGet() == count) {
@ -256,23 +283,26 @@ public class RequestAllExecutor implements ContractExecutor {
finalResult.needSeq = true; finalResult.needSeq = true;
finalResult.seq = request_seq; finalResult.seq = request_seq;
// if (null == finalResult) { // if (null == finalResult) {
// finalResult = // finalResult =
// new ContractResult( // new ContractResult(
// ContractResult.Status.Exception, // ContractResult.Status.Exception,
// new JsonPrimitive( // new JsonPrimitive(
// "no nore than half of the // "no nore than half of the
// consistent result")); // consistent result"));
// originalCallback.onResult(new // originalCallback.onResult(new
// Gson().toJson(finalResult)); // Gson().toJson(finalResult));
// } else { // } else {
originalCallback.onResult(JsonUtil.toJson(finalResult)); originalCallback.onResult(JsonUtil.toJson(finalResult));
// } // }
LOGGER.debug(String.format("%d results are the same: %s", finalResult.size, LOGGER.debug(
finalResult.result)); String.format(
"%d results are the same: %s",
finalResult.size, finalResult.result));
// 集群中事务序号+1 // 集群中事务序号+1
CMActions.manager.multiContractRecorder.getMultiContractMeta(contractID) CMActions.manager.multiContractRecorder
.getMultiContractMeta(contractID)
.nextSeqAtMaster(); .nextSeqAtMaster();
// recover其中无状态合约CP出错无需恢复 // recover其中无状态合约CP出错无需恢复
@ -282,25 +312,26 @@ public class RequestAllExecutor implements ContractExecutor {
} }
for (String nodeID : nodesID) { for (String nodeID : nodesID) {
LOGGER.warn("node fails! " + nodeID); LOGGER.warn("node fails! " + nodeID);
if (MasterServerRecoverMechAction.recoverStatus.get(nodeID) if (MasterServerRecoverMechAction.recoverStatus.get(nodeID).get(contractID)
.get(contractID) == RecoverFlag.Fine) { == RecoverFlag.Fine) {
MasterServerRecoverMechAction.recoverStatus.get(nodeID).put(contractID, MasterServerRecoverMechAction.recoverStatus
RecoverFlag.ToRecover); .get(nodeID)
.put(contractID, RecoverFlag.ToRecover);
} }
} }
for (String nodeID : nodesID) { for (String nodeID : nodesID) {
if (MasterServerRecoverMechAction.recoverStatus.get(nodeID) if (MasterServerRecoverMechAction.recoverStatus.get(nodeID).get(contractID)
.get(contractID) == RecoverFlag.ToRecover) { == RecoverFlag.ToRecover) {
LOGGER.warn("node in recover " + nodeID); LOGGER.warn("node in recover " + nodeID);
// 因为该节点结果有误所以即时是stableMode也认为trans记录不可信 // 因为该节点结果有误所以即时是stableMode也认为trans记录不可信
// 直接通过load别的节点来恢复 // 直接通过load别的节点来恢复
MasterServerRecoverMechAction.restartContractFromCommonMode(nodeID, MasterServerRecoverMechAction.restartContractFromCommonMode(
contractID); nodeID, contractID);
} }
} }
} }
// clearCache(); // clearCache();
} catch (Exception e) { } catch (Exception e) {
e.printStackTrace(); e.printStackTrace();
LOGGER.warn("result exception!"); LOGGER.warn("result exception!");

View File

@ -1,403 +1,400 @@
// package org.bdware.server.executor.unconsistency; package org.bdware.server.executor.unconsistency;
//
// import com.google.gson.JsonObject; import com.google.gson.JsonObject;
// import com.google.gson.JsonParser; import com.google.gson.JsonParser;
// import com.google.gson.JsonPrimitive; import com.google.gson.JsonPrimitive;
// import org.apache.logging.log4j.LogManager; import org.apache.logging.log4j.LogManager;
// import org.apache.logging.log4j.Logger; import org.apache.logging.log4j.Logger;
// import org.bdware.sc.ComponedContractResult; import org.bdware.sc.ComponedContractResult;
// import org.bdware.sc.ContractMeta; import org.bdware.sc.ContractMeta;
// import org.bdware.sc.ContractResult; import org.bdware.sc.ContractResult;
// import org.bdware.sc.bean.*; import org.bdware.sc.bean.*;
// import org.bdware.sc.conn.OnHashCallback; import org.bdware.sc.conn.OnHashCallback;
// import org.bdware.sc.conn.ResultCallback; import org.bdware.sc.conn.ResultCallback;
// import org.bdware.sc.units.MultiContractMeta; import org.bdware.sc.units.MultiContractMeta;
// import org.bdware.sc.units.RecoverFlag; import org.bdware.sc.units.RecoverFlag;
// import org.bdware.sc.units.RequestCache; import org.bdware.sc.units.RequestCache;
// import org.bdware.sc.units.ResultCache; import org.bdware.sc.units.ResultCache;
// import org.bdware.sc.util.JsonUtil; import org.bdware.sc.util.JsonUtil;
// import org.bdware.server.action.CMActions; import org.bdware.server.action.CMActions;
// import org.bdware.server.action.p2p.MasterServerRecoverMechAction; import org.bdware.server.action.p2p.MasterServerRecoverMechAction;
// import org.bdware.server.action.p2p.MasterServerTCPAction; import org.bdware.server.action.p2p.MasterServerTCPAction;
// import org.bdware.server.trustedmodel.ContractExecutor; import org.bdware.server.trustedmodel.ContractExecutor;
// import org.bdware.server.trustedmodel.MultiReqSeq; import org.bdware.server.trustedmodel.MultiReqSeq;
// import org.bdware.server.trustedmodel.ResultCollector; import org.bdware.server.trustedmodel.ResultCollector;
// import org.bdware.units.NetworkManager; import org.bdware.units.NetworkManager;
//
// import java.math.BigInteger; import java.math.BigInteger;
// import java.util.HashMap; import java.util.HashMap;
// import java.util.HashSet; import java.util.HashSet;
// import java.util.Map; import java.util.Map;
// import java.util.Set; import java.util.Set;
// import java.util.concurrent.ConcurrentHashMap; import java.util.concurrent.ConcurrentHashMap;
// import java.util.concurrent.atomic.AtomicInteger; import java.util.concurrent.atomic.AtomicInteger;
//
//// 改为MultiPointCooperationExecutor // 改为MultiPointCooperationExecutor
// public class MultiPointCooperationExecutor implements ContractExecutor { public class MultiPointCooperationExecutor implements ContractExecutor {
// private static final Logger LOGGER = LogManager.getLogger(MultiPointCooperationExecutor.class); private static final Logger LOGGER = LogManager.getLogger(MultiPointCooperationExecutor.class);
// final Object lock = new Object(); final Object lock = new Object();
// int resultCount; int resultCount;
// AtomicInteger request_index = new AtomicInteger(0); AtomicInteger request_index = new AtomicInteger(0);
// ContractExecType type; ContractExecType type;
// // key为requestIDvalue为其seq // key为requestIDvalue为其seq
// Map<String, MultiReqSeq> seqMap = new ConcurrentHashMap<>(); Map<String, MultiReqSeq> seqMap = new ConcurrentHashMap<>();
// Map<String, ResultCache> resultCache = new ConcurrentHashMap<>(); Map<String, ResultCache> resultCache = new ConcurrentHashMap<>();
// // MultiPointContractInfo info; // MultiPointContractInfo info;
// MultiContractMeta multiMeta; MultiContractMeta multiMeta;
// String contractID; String contractID;
//
// public MultiPointCooperationExecutor(ContractExecType t, int c, String con_id) { public MultiPointCooperationExecutor(ContractExecType t, int c, String con_id) {
// LOGGER.info("-- sharding executor---"); LOGGER.info("-- sharding executor---");
// type = t; type = t;
// resultCount = c; resultCount = c;
// contractID = con_id; contractID = con_id;
// multiMeta = CMActions.manager.multiContractRecorder.getMultiContractMeta(contractID); multiMeta = CMActions.manager.multiContractRecorder.getMultiContractMeta(contractID);
// } }
//
// public void setSeq(int seq) { public void setSeq(int seq) {
// request_index = new AtomicInteger(seq); request_index = new AtomicInteger(seq);
// } }
//
// public ResultCallback createResultCallback( public ResultCallback createResultCallback(
// final String requestID, final String requestID,
// final ResultCallback originalCb, final ResultCallback originalCb,
// final int count, final int count,
// final int request_seq, final int request_seq,
// final String contractID, JoinInfo joinInfo) { final String contractID, JoinInfo joinInfo) {
// // TODO 加对应的超时 // TODO 加对应的超时
// return new ResultCollector( return new ResultCollector(
// requestID, requestID,
// new MultiPointCooperationExecutor.ResultMerger(originalCb, count, request_seq, contractID, new MultiPointCooperationExecutor.ResultMerger(originalCb, count, request_seq, contractID, joinInfo),
// joinInfo), count); // 把count改成了1设置成获得1个响应就行
// count); // 把count改成了1设置成获得1个响应就行 }
// }
// public void sendRequest(String id, ContractRequest req, String[] nodes) {
// public void sendRequest(String id, ContractRequest req, String[] nodes) { Map<String, Object> reqStr = new HashMap<>();
// Map<String, Object> reqStr = new HashMap<>(); reqStr.put("uniReqID", id);
// reqStr.put("uniReqID", id); reqStr.put("data", req);
// reqStr.put("data", req); req.needSeq = false;
// req.needSeq = false; reqStr.put("action", "executeContractLocally");
// reqStr.put("action", "executeContractLocally"); String sendStr = JsonUtil.toJson(reqStr);
// String sendStr = JsonUtil.toJson(reqStr); // master负责缓存请求
// // master负责缓存请求 if (!MasterServerTCPAction.requestCache.containsKey(contractID)) {
// if (!MasterServerTCPAction.requestCache.containsKey(contractID)) { MasterServerTCPAction.requestCache.put(contractID, new RequestCache());
// MasterServerTCPAction.requestCache.put(contractID, new RequestCache()); }
// } // TODO 多调多统一个seq的有多个请求这个需要改
// // TODO 多调多统一个seq的有多个请求这个需要改 MasterServerTCPAction.requestCache.get(contractID).put(req.seq, sendStr);
// MasterServerTCPAction.requestCache.get(contractID).put(req.seq, sendStr); LOGGER.debug(JsonUtil.toJson(req));
// LOGGER.debug(JsonUtil.toJson(req)); LOGGER.info("node size = " + nodes.length);
// LOGGER.info("node size = " + nodes.length); LOGGER.debug("nodes:" + JsonUtil.toJson(nodes));
// LOGGER.debug("nodes:" + JsonUtil.toJson(nodes)); for (String node : nodes) {
// for (String node : nodes) { LOGGER.info(
// LOGGER.info( "[sendRequests] get cmNode "
// "[sendRequests] get cmNode " + node.substring(0, 5)
// + node.substring(0, 5) + " not null "
// + " not null " + "RequestAllExecutor 发送请求给 "
// + "RequestAllExecutor 发送请求给 " + node.substring(0, 5));
// + node.substring(0, 5)); NetworkManager.instance.sendToAgent(node, sendStr);
// NetworkManager.instance.sendToAgent(node, sendStr); }
// } }
// }
// private String[] getAccordingToRouteInfo(RouteInfo routeInfo, ContractRequest req, String[] members) {
// private String[] getAccordingToRouteInfo(RouteInfo routeInfo, ContractRequest req, String[] try {
// members) { int val;
// try { switch (routeInfo.useDefault) {
// int val; case byRequester:
// switch (routeInfo.useDefault) { val =
// case byRequester: new BigInteger(req.getRequester(), 16)
// val = .mod(new BigInteger("" + members.length))
// new BigInteger(req.getRequester(), 16) .intValue();
// .mod(new BigInteger("" + members.length)) while (val < 0) {
// .intValue(); val = val + members.length;
// while (val < 0) { }
// val = val + members.length; return new String[]{members[val]};
// } case byArgHash:
// return new String[]{members[val]}; val = req.getArg().hashCode();
// case byArgHash: val = val % members.length;
// val = req.getArg().hashCode(); while (val < 0) {
// val = val % members.length; val += members.length;
// while (val < 0) { }
// val += members.length; return new String[]{members[val]};
// } case byTarget:
// return new String[]{members[val]}; JsonObject jo = req.getArg().getAsJsonObject();
// case byTarget: val =
// JsonObject jo = req.getArg().getAsJsonObject(); new BigInteger(jo.get("target").getAsString(), 16)
// val = .mod(new BigInteger("" + members.length))
// new BigInteger(jo.get("target").getAsString(), 16) .intValue();
// .mod(new BigInteger("" + members.length)) while (val < 0) {
// .intValue(); val = val + members.length;
// while (val < 0) { }
// val = val + members.length; return new String[]{members[val]};
// } default:
// return new String[]{members[val]}; return members;
// default: }
// return members; } catch (Exception e) {
// } return members;
// } catch (Exception e) { }
// return members; }
// }
// } public boolean checkCurNodeNumValid() {
// LOGGER.info("checkCurNodeNumValid");
// public boolean checkCurNodeNumValid() { String[] nodes = multiMeta.getMembers();
// LOGGER.info("checkCurNodeNumValid"); // List<String> nodes = info.members;
// String[] nodes = multiMeta.getMembers(); int validNode = 0;
// // List<String> nodes = info.members; for (String node : nodes) {
// int validNode = 0; if (NetworkManager.instance.hasAgentConnection(node)
// for (String node : nodes) { && MasterServerRecoverMechAction.recoverStatus.get(node).get(contractID)
// if (NetworkManager.instance.hasAgentConnection(node) == RecoverFlag.Fine) {
// && MasterServerRecoverMechAction.recoverStatus.get(node).get(contractID) validNode++;
// == RecoverFlag.Fine) { }
// validNode++; }
// } int c = resultCount;
// } if (type == ContractExecType.Sharding) c = (int) Math.ceil((double) c / 2);
// int c = resultCount; LOGGER.info("c=" + c + " validNode=" + validNode);
// if (type == ContractExecType.Sharding) c = (int) Math.ceil((double) c / 2); return validNode >= c;
// LOGGER.info("c=" + c + " validNode=" + validNode); }
// return validNode >= c;
// } @Override
// public void execute(String requestID, ContractRequest req, ResultCallback rc, OnHashCallback hcb) {
// @Override LOGGER.info("[MultiPointCooperationExecutor] execute " + JsonUtil.toJson(req));
// public void execute(String requestID, ContractRequest req, ResultCallback rc, OnHashCallback hcb) // 获得action 函数名
// { LOGGER.info("action is : " + req.getAction());
// LOGGER.info("[MultiPointCooperationExecutor] execute " + JsonUtil.toJson(req)); req.setContractID(CMActions.manager.getContractIDByName(req.getContractID()));
// // 获得action 函数名 if (requestID != null && requestID.endsWith("_mul")) {
// LOGGER.info("action is : " + req.getAction()); synchronized (lock) {
// req.setContractID(CMActions.manager.getContractIDByName(req.getContractID())); if (seqMap.containsKey(requestID)) {
// if (requestID != null && requestID.endsWith("_mul")) { req.seq = seqMap.get(requestID).seq;
// synchronized (lock) { } else {
// if (seqMap.containsKey(requestID)) { req.seq = request_index.getAndIncrement();
// req.seq = seqMap.get(requestID).seq; seqMap.put(requestID, new MultiReqSeq(req.seq));
// } else { }
// req.seq = request_index.getAndIncrement(); }
// seqMap.put(requestID, new MultiReqSeq(req.seq)); } else {
// } req.seq = request_index.getAndIncrement();
// } }
// } else { req.needSeq = true;
// req.seq = request_index.getAndIncrement(); String id =
// } System.currentTimeMillis() + "_" + (int) (Math.random() * 1000000) + "_" + req.seq;
// req.needSeq = true; LOGGER.info("execute receive requestID= " + requestID + " msgID=" + id);
// String id = if (checkCurNodeNumValid()) { // 校验成功 current node num 合法
// System.currentTimeMillis() + "_" + (int) (Math.random() * 1000000) + "_" + req.seq; LOGGER.info("checkCurNodeNumValid true");
// LOGGER.info("execute receive requestID= " + requestID + " msgID=" + id); ContractMeta meta =
// if (checkCurNodeNumValid()) { // 校验成功 current node num 合法 CMActions.manager.statusRecorder.getContractMeta(req.getContractID());
// LOGGER.info("checkCurNodeNumValid true"); FunctionDesp fun = meta.getExportedFunction(req.getAction());
// ContractMeta meta = ResultCallback collector;
// CMActions.manager.statusRecorder.getContractMeta(req.getContractID()); // TODO @fanbo 下面的count 1要改应该是根据route的规则来
// FunctionDesp fun = meta.getExportedFunction(req.getAction()); //Count 根据join规则来
// ResultCallback collector; //nodes 根据route规则来
// // TODO @fanbo 下面的count 1要改应该是根据route的规则来 JoinInfo joinInfo = fun.joinInfo;
// //Count 根据join规则来 RouteInfo routeInfo = fun.routeInfo;
// //nodes 根据route规则来 int count = getJoinCount(joinInfo, contractID);
// JoinInfo joinInfo = fun.joinInfo; LOGGER.info("requestID=" + requestID + " join Count: " + count);
// RouteInfo routeInfo = fun.routeInfo;
// int count = getJoinCount(joinInfo, contractID); String[] members = multiMeta.getMembers();
// LOGGER.info("requestID=" + requestID + " join Count: " + count); String[] nodes = getAccordingToRouteInfo(routeInfo, req, members);
// if (nodes.length < count) {
// String[] members = multiMeta.getMembers(); count = nodes.length;
// String[] nodes = getAccordingToRouteInfo(routeInfo, req, members); }
// if (nodes.length < count) { collector =
// count = nodes.length; createResultCallback(id, rc, count, req.seq, req.getContractID(), joinInfo); // 初始化结果收集器
// } MasterServerTCPAction.sync.sleep(id, collector);
// collector = LOGGER.info("requestID=" + requestID + " master broadcasts request " + req.seq);
// createResultCallback(id, rc, count, req.seq, req.getContractID(), joinInfo); // 初始化结果收集器 sendRequest(id, req, nodes); // 发送请求
// MasterServerTCPAction.sync.sleep(id, collector); } else {
// LOGGER.info("requestID=" + requestID + " master broadcasts request " + req.seq); LOGGER.info("invalidNodeNumOnResult");
// sendRequest(id, req, nodes); // 发送请求 request_index.getAndDecrement();
// } else { ContractResult finalResult =
// LOGGER.info("invalidNodeNumOnResult"); new ContractResult(
// request_index.getAndDecrement(); ContractResult.Status.Error,
// ContractResult finalResult = new JsonPrimitive("node number unavailbale,request refused."));
// new ContractResult( rc.onResult(JsonUtil.toJson(finalResult));
// ContractResult.Status.Error, }
// new JsonPrimitive("node number unavailbale,request refused.")); }
// rc.onResult(JsonUtil.toJson(finalResult));
// } private int getJoinCount(JoinInfo joinInfo, String contractID) {
// } if (joinInfo == null) return resultCount;
// if (joinInfo.joinCount.isJsonPrimitive() && joinInfo.joinCount.getAsJsonPrimitive().isNumber()) {
// private int getJoinCount(JoinInfo joinInfo, String contractID) { return joinInfo.joinCount.getAsJsonPrimitive().getAsInt();
// if (joinInfo == null) return resultCount; }
// if (joinInfo.joinCount.isJsonPrimitive() && joinInfo.joinCount.getAsJsonPrimitive().isNumber()) { try {
// return joinInfo.joinCount.getAsJsonPrimitive().getAsInt(); ContractRequest cr = new ContractRequest();
// } cr.setContractID(contractID);
// try { cr.setAction(joinInfo.joinCount.getAsString());
// ContractRequest cr = new ContractRequest(); //TODO Arg需要好好设计一下
// cr.setContractID(contractID); //TODO 又好用又简单的那种设计
// cr.setAction(joinInfo.joinCount.getAsString()); //TODO
// //TODO Arg需要好好设计一下 cr.setArg("");
// //TODO 又好用又简单的那种设计 String result = CMActions.manager.executeLocally(cr, null);
// //TODO return JsonUtil.parseString(result).getAsJsonObject().get("result").getAsInt();
// cr.setArg(""); } catch (Exception e) {
// String result = CMActions.manager.executeLocally(cr, null); e.printStackTrace();
// return JsonUtil.parseString(result).getAsJsonObject().get("result").getAsInt(); return 1;
// } catch (Exception e) { }
// e.printStackTrace(); }
// return 1;
// } // 清理缓存的多点合约请求序号
// } public void clearCache() {
// final long time = System.currentTimeMillis() - 30000L;
// // 清理缓存的多点合约请求序号 seqMap.entrySet()
// public void clearCache() { .removeIf(
// final long time = System.currentTimeMillis() - 30000L; entry -> {
// seqMap.entrySet() MultiReqSeq cache = entry.getValue();
// .removeIf( if (null == cache) {
// entry -> { return true;
// MultiReqSeq cache = entry.getValue(); }
// if (null == cache) { return cache.startTime < time;
// return true; });
// } }
// return cache.startTime < time;
// }); public static class ResultMerger extends ResultCallback {
// } ComponedContractResult componedContractResult;
// AtomicInteger order;
// public static class ResultMerger extends ResultCallback { String contractID;
// ComponedContractResult componedContractResult; int count; // 记录有多少个节点
// AtomicInteger order; int request_seq;
// String contractID; ResultCallback originalCallback;
// int count; // 记录有多少个节点 Set<String> nodeIDs = new HashSet<>(); // 已收到返回结果的节点
// int request_seq; JoinInfo joinInfo;
// ResultCallback originalCallback;
// Set<String> nodeIDs = new HashSet<>(); // 已收到返回结果的节点 ResultMerger(
// JoinInfo joinInfo; final ResultCallback originalCb,
// final int count,
// ResultMerger( final int request_seq,
// final ResultCallback originalCb, final String contractID,
// final int count, final JoinInfo joinInfo) {
// final int request_seq, originalCallback = originalCb;
// final String contractID, this.count = count;
// final JoinInfo joinInfo) { this.request_seq = request_seq;
// originalCallback = originalCb; this.contractID = contractID;
// this.count = count; componedContractResult = new ComponedContractResult(count);
// this.request_seq = request_seq; order = new AtomicInteger(0);
// this.contractID = contractID; this.joinInfo = joinInfo;
// componedContractResult = new ComponedContractResult(count); }
// order = new AtomicInteger(0);
// this.joinInfo = joinInfo; public String getInfo() {
// } return "contractID="
// + contractID
// public String getInfo() { + " 收到第 "
// return "contractID=" + order
// + contractID + " 个节点回复 : "
// + " 收到第 " + " order="
// + order + order
// + " 个节点回复 : " + " count="
// + " order=" + count
// + order + " ";
// + " count=" }
// + count
// + " "; @Override
// } public void onResult(String str) {
// // TODO 必须在这里聚合
// @Override // str的data是个ContractResult
// public void onResult(String str) { // 在这儿也是返回个ContractResult
// // TODO 必须在这里聚合 try {
// // str的data是个ContractResult LOGGER.info(str);
// // 在这儿也是返回个ContractResult JsonObject obj = JsonParser.parseString(str).getAsJsonObject();
// try { String id = obj.get("nodeID").getAsString();
// LOGGER.info(str); if (nodeIDs.contains(id)) {
// JsonObject obj = JsonParser.parseString(str).getAsJsonObject(); LOGGER.info("已经收到节点 " + id.substring(0, 5) + " 的结果,该结果被忽略");
// String id = obj.get("nodeID").getAsString(); return;
// if (nodeIDs.contains(id)) { }
// LOGGER.info("已经收到节点 " + id.substring(0, 5) + " 的结果,该结果被忽略"); nodeIDs.add(id);
// return; LOGGER.info(
// } "contractID="
// nodeIDs.add(id); + contractID
// LOGGER.info( + " 收到第 "
// "contractID=" + order
// + contractID + " 个节点回复 : "
// + " 收到第 " + str
// + order + " order="
// + " 个节点回复 : " + order
// + str + " count="
// + " order=" + count);
// + order componedContractResult.add(obj);
// + " count=" // 收集到所有结果
// + count); if (order.incrementAndGet() == count) {
// componedContractResult.add(obj); ContractResult finalResult = componedContractResult.mergeFinalResult();
// // 收集到所有结果
// if (order.incrementAndGet() == count) { finalResult.needSeq = true;
// ContractResult finalResult = componedContractResult.mergeFinalResult(); finalResult.seq = request_seq;
//
// finalResult.needSeq = true; // if (null == finalResult) {
// finalResult.seq = request_seq; // finalResult =
// // new ContractResult(
// // if (null == finalResult) { // ContractResult.Status.Exception,
// // finalResult = // new JsonPrimitive(
// // new ContractResult( // "no nore than half of the
// // ContractResult.Status.Exception, // consistent result"));
// // new JsonPrimitive( // originalCallback.onResult(new
// // "no nore than half of the // Gson().toJson(finalResult));
// // consistent result")); // } else {
// // originalCallback.onResult(new if (joinInfo != null) {
// // Gson().toJson(finalResult)); handleJoinInfo(finalResult, joinInfo);
// // } else { }
// if (joinInfo != null) { originalCallback.onResult(JsonUtil.toJson(finalResult));
// handleJoinInfo(finalResult, joinInfo); // }
// } LOGGER.info(
// originalCallback.onResult(JsonUtil.toJson(finalResult)); "本次执行最终结果为 " + finalResult.size + "个节点合并的,结果为 " + finalResult.result);
// // }
// LOGGER.info( // 集群中事务序号+1
// "本次执行最终结果为 " + finalResult.size + "个节点合并的,结果为 " + finalResult.result); // MasterServerTCPAction.contractID2Members.get(contractID).nextSeq();
// CMActions.manager
// // 集群中事务序号+1 .multiContractRecorder
// // MasterServerTCPAction.contractID2Members.get(contractID).nextSeq(); .getMultiContractMeta(contractID)
// CMActions.manager .nextSeqAtMaster();
// .multiContractRecorder // recover其中无状态合约CP出错无需恢复
// .getMultiContractMeta(contractID) Set<String> nodesID = componedContractResult.getProblemNodes();
// .nextSeqAtMaster(); if (null == nodesID || nodesID.isEmpty()) {
// // recover其中无状态合约CP出错无需恢复 return;
// Set<String> nodesID = componedContractResult.getProblemNodes(); }
// if (null == nodesID || nodesID.isEmpty()) { for (String nodeID : nodesID) {
// return; LOGGER.info("结果出现问题的节点有:" + nodeID);
// } if (MasterServerRecoverMechAction.recoverStatus.get(nodeID).get(contractID)
// for (String nodeID : nodesID) { == RecoverFlag.Fine) {
// LOGGER.info("结果出现问题的节点有:" + nodeID); MasterServerRecoverMechAction.recoverStatus
// if (MasterServerRecoverMechAction.recoverStatus.get(nodeID).get(contractID) .get(nodeID)
// == RecoverFlag.Fine) { .put(contractID, RecoverFlag.ToRecover);
// MasterServerRecoverMechAction.recoverStatus }
// .get(nodeID) }
// .put(contractID, RecoverFlag.ToRecover); for (String nodeID : nodesID) {
// } if (MasterServerRecoverMechAction.recoverStatus.get(nodeID).get(contractID)
// } == RecoverFlag.ToRecover) {
// for (String nodeID : nodesID) { LOGGER.info("问题节点开始恢复:" + nodeID);
// if (MasterServerRecoverMechAction.recoverStatus.get(nodeID).get(contractID)
// == RecoverFlag.ToRecover) { // 因为该节点结果有误所以即时是stableMode也认为trans记录不可信
// LOGGER.info("问题节点开始恢复:" + nodeID); // 直接通过load别的节点来恢复
// MasterServerRecoverMechAction.restartContractFromCommonMode(
// // 因为该节点结果有误所以即时是stableMode也认为trans记录不可信 nodeID, contractID);
// // 直接通过load别的节点来恢复 }
// MasterServerRecoverMechAction.restartContractFromCommonMode( }
// nodeID, contractID); }
// } // clearCache();
// } } catch (Exception e) {
// } e.printStackTrace();
// // clearCache(); LOGGER.info("本次执行最终结果为有异常");
// } catch (Exception e) { }
// e.printStackTrace(); }
// LOGGER.info("本次执行最终结果为有异常");
// } private void handleJoinInfo(ContractResult finalResult, JoinInfo joinInfo) {
// } JsonObject jo = finalResult.result.getAsJsonObject();
// if (joinInfo != null && joinInfo.joinRule != null) {
// private void handleJoinInfo(ContractResult finalResult, JoinInfo joinInfo) { //TODO 不应该是double 类型
// JsonObject jo = finalResult.result.getAsJsonObject(); switch (joinInfo.joinRule) {
// if (joinInfo != null && joinInfo.joinRule != null) { case "add":
// //TODO 不应该是double 类型 double val = 0;
// switch (joinInfo.joinRule) { for (String key : jo.keySet()) {
// case "add": val += jo.get(key).getAsDouble();
// double val = 0; }
// for (String key : jo.keySet()) { finalResult.result = new JsonPrimitive(val);
// val += jo.get(key).getAsDouble(); break;
// } case "multiply":
// finalResult.result = new JsonPrimitive(val); val = 1;
// break; for (String key : jo.keySet()) {
// case "multiply": val *= jo.get(key).getAsDouble();
// val = 1; }
// for (String key : jo.keySet()) { finalResult.result = new JsonPrimitive(val);
// val *= jo.get(key).getAsDouble(); break;
// } }
// finalResult.result = new JsonPrimitive(val); }
// break; }
// } }
// } }
// }
// }
// }

View File

@ -1,70 +1,68 @@
// package org.bdware.server.executor.unconsistency; package org.bdware.server.executor.unconsistency;
//
// import com.google.gson.JsonObject; import com.google.gson.JsonObject;
// import com.google.gson.JsonParser; import com.google.gson.JsonParser;
// import org.apache.logging.log4j.LogManager; import org.apache.logging.log4j.LogManager;
// import org.apache.logging.log4j.Logger; import org.apache.logging.log4j.Logger;
// import org.bdware.sc.bean.ContractRequest; import org.bdware.sc.bean.ContractRequest;
// import org.bdware.sc.conn.OnHashCallback; import org.bdware.sc.conn.OnHashCallback;
// import org.bdware.sc.conn.ResultCallback; import org.bdware.sc.conn.ResultCallback;
// import org.bdware.sc.util.JsonUtil; import org.bdware.sc.util.JsonUtil;
// import org.bdware.server.ControllerManager; import org.bdware.server.ControllerManager;
// import org.bdware.server.action.CMActions; import org.bdware.server.action.CMActions;
// import org.bdware.server.action.p2p.MasterServerTCPAction; import org.bdware.server.action.p2p.MasterServerTCPAction;
// import org.bdware.server.trustedmodel.ContractExecutor; import org.bdware.server.trustedmodel.ContractExecutor;
// import org.bdware.server.trustedmodel.AgentManager; import org.bdware.server.trustedmodel.AgentManager;
// import org.bdware.units.NetworkManager; import org.bdware.units.NetworkManager;
//
// import java.util.HashMap; import java.util.HashMap;
// import java.util.Map; import java.util.Map;
// import java.util.concurrent.atomic.AtomicInteger; import java.util.concurrent.atomic.AtomicInteger;
//
// public class RequestOnceExecutor implements ContractExecutor { public class RequestOnceExecutor implements ContractExecutor {
// private static final Logger LOGGER = LogManager.getLogger(RequestOnceExecutor.class); private static final Logger LOGGER = LogManager.getLogger(RequestOnceExecutor.class);
// String contractID; String contractID;
// AtomicInteger order = new AtomicInteger(0); AtomicInteger order = new AtomicInteger(0);
//
// public RequestOnceExecutor(String contractID) { public RequestOnceExecutor(String contractID) {
// this.contractID = contractID; this.contractID = contractID;
// } }
//
// @Override @Override
// public void execute(String requestID, ContractRequest req, ResultCallback rc, OnHashCallback hcb) public void execute(String requestID, ContractRequest req, ResultCallback rc, OnHashCallback hcb) {
// { ResultCallback cb =
// ResultCallback cb = new ResultCallback() {
// new ResultCallback() { @Override
// @Override public void onResult(String str) {
// public void onResult(String str) { LOGGER.debug(str);
// LOGGER.debug(str); JsonObject jo = JsonParser.parseString(str).getAsJsonObject();
// JsonObject jo = JsonParser.parseString(str).getAsJsonObject(); JsonObject result =
// JsonObject result = JsonParser.parseString(jo.get("data").getAsString())
// JsonParser.parseString(jo.get("data").getAsString()) .getAsJsonObject();
// .getAsJsonObject(); for (String key : result.keySet()) jo.add(key, result.get(key));
// for (String key : result.keySet()) jo.add(key, result.get(key)); jo.remove("action");
// jo.remove("action"); jo.addProperty("action", "onExecuteResult");
// jo.addProperty("action", "onExecuteResult"); LOGGER.debug(jo.toString());
// LOGGER.debug(jo.toString()); rc.onResult(jo.toString());
// rc.onResult(jo.toString()); }
// } };
// }; MasterServerTCPAction.sync.sleep(requestID, cb);
// MasterServerTCPAction.sync.sleep(requestID, cb); String[] members = CMActions.manager.multiContractRecorder.getMultiContractMeta(contractID).getMembers();
// String[] members = for (int i = 0; i < members.length; i++) {
// CMActions.manager.multiContractRecorder.getMultiContractMeta(contractID).getMembers(); LOGGER.info("[members]:" + members.length);
// for (int i = 0; i < members.length; i++) { int size = members.length;
// LOGGER.info("[members]:" + members.length); String nodeID = members[order.incrementAndGet() % size];
// int size = members.length; //ADD Connect
// String nodeID = members[order.incrementAndGet() % size]; Map<String, Object> obj = new HashMap<>();
// //ADD Connect obj.put("action", "executeContractLocally");
// Map<String, Object> obj = new HashMap<>(); obj.put("requestID",requestID);
// obj.put("action", "executeContractLocally"); obj.put("data", req);
// obj.put("requestID",requestID); obj.put("uniReqID", requestID);
// obj.put("data", req); NetworkManager.instance.sendToAgent(nodeID,JsonUtil.toJson(obj));
// obj.put("uniReqID", requestID); return;
// NetworkManager.instance.sendToAgent(nodeID,JsonUtil.toJson(obj)); }
// return; rc.onResult(
// } "{\"status\":\"Error\",\"result\":\"all nodes "
// rc.onResult( + " offline\",\"action\":\"onExecuteContract\"}");
// "{\"status\":\"Error\",\"result\":\"all nodes " }
// + " offline\",\"action\":\"onExecuteContract\"}"); }
// }
// }

View File

@ -1,86 +1,83 @@
// package org.bdware.server.executor.unconsistency; package org.bdware.server.executor.unconsistency;
//
// import com.google.gson.JsonObject; import com.google.gson.JsonObject;
// import com.google.gson.JsonParser; import com.google.gson.JsonParser;
// import org.apache.logging.log4j.LogManager; import org.apache.logging.log4j.LogManager;
// import org.apache.logging.log4j.Logger; import org.apache.logging.log4j.Logger;
// import org.bdware.sc.ContractResult; import org.bdware.sc.ContractResult;
// import org.bdware.sc.bean.ContractRequest; import org.bdware.sc.bean.ContractRequest;
// import org.bdware.sc.conn.OnHashCallback; import org.bdware.sc.conn.OnHashCallback;
// import org.bdware.sc.conn.ResultCallback; import org.bdware.sc.conn.ResultCallback;
// import org.bdware.sc.util.JsonUtil; import org.bdware.sc.util.JsonUtil;
// import org.bdware.server.action.CMActions; import org.bdware.server.action.CMActions;
// import org.bdware.server.action.p2p.MasterServerTCPAction; import org.bdware.server.action.p2p.MasterServerTCPAction;
// import org.bdware.server.trustedmodel.ContractExecutor; import org.bdware.server.trustedmodel.ContractExecutor;
// import org.bdware.units.NetworkManager; import org.bdware.units.NetworkManager;
//
// import java.util.HashMap; import java.util.HashMap;
// import java.util.Map; import java.util.Map;
// import java.util.concurrent.atomic.AtomicInteger; import java.util.concurrent.atomic.AtomicInteger;
//
// public class ResponseOnceExecutor implements ContractExecutor { public class ResponseOnceExecutor implements ContractExecutor {
// private static final Logger LOGGER = LogManager.getLogger(ResponseOnceExecutor.class); private static final Logger LOGGER = LogManager.getLogger(ResponseOnceExecutor.class);
// private final String contractID; private final String contractID;
// AtomicInteger order = new AtomicInteger(0); AtomicInteger order = new AtomicInteger(0);
//
// public ResponseOnceExecutor(String contractID) { public ResponseOnceExecutor(String contractID) {
// this.contractID = contractID; this.contractID = contractID;
// } }
//
// @Override @Override
// public void execute(String requestID, ContractRequest req, ResultCallback rc, OnHashCallback hcb) public void execute(String requestID, ContractRequest req, ResultCallback rc, OnHashCallback hcb) {
// { executeInternal(requestID, rc, req, 2);
// executeInternal(requestID, rc, req, 2); }
// }
// private void executeInternal(
// private void executeInternal( String requestID, ResultCallback rc, ContractRequest req, int count) {
// String requestID, ResultCallback rc, ContractRequest req, int count) { // String contractID = req.getContractID();
// // String contractID = req.getContractID(); // TODO 标注失效节点是否选择重新迁移
// // TODO 标注失效节点是否选择重新迁移 ResultCallback cb =
// ResultCallback cb = new ResultCallback() {
// new ResultCallback() { @Override
// @Override public void onResult(String str) {
// public void onResult(String str) { LOGGER.debug(str);
// LOGGER.debug(str); JsonObject jo = JsonParser.parseString(str).getAsJsonObject();
// JsonObject jo = JsonParser.parseString(str).getAsJsonObject(); jo.remove("action");
// jo.remove("action"); jo.addProperty("action", "onExecuteResult");
// jo.addProperty("action", "onExecuteResult"); LOGGER.debug(jo.toString());
// LOGGER.debug(jo.toString()); if (jo.has("data")) {
// if (jo.has("data")) { String data = jo.get("data").getAsString();
// String data = jo.get("data").getAsString(); ContractResult cr = JsonUtil.fromJson(data, ContractResult.class);
// ContractResult cr = JsonUtil.fromJson(data, ContractResult.class); if (cr.status != ContractResult.Status.Success && count > 0) {
// if (cr.status != ContractResult.Status.Success && count > 0) { executeInternal(requestID, rc, req, count - 1);
// executeInternal(requestID, rc, req, count - 1); } else rc.onResult(jo.toString());
// } else rc.onResult(jo.toString()); } else {
// } else { JsonObject jo2 = new JsonObject();
// JsonObject jo2 = new JsonObject(); jo2.addProperty("action", "onExecuteResult");
// jo2.addProperty("action", "onExecuteResult"); jo.remove("action");
// jo.remove("action"); jo2.addProperty("data", jo.toString());
// jo2.addProperty("data", jo.toString()); rc.onResult(jo2.toString());
// rc.onResult(jo2.toString()); }
// } }
// } };
// }; MasterServerTCPAction.sync.sleepWithTimeout(requestID, cb, 5);
// MasterServerTCPAction.sync.sleepWithTimeout(requestID, cb, 5); if (!sendOnce(requestID, req))
// if (!sendOnce(requestID, req)) rc.onResult(
// rc.onResult( "{\"status\":\"Error\",\"data\":\"{\\\"status\\\":\\\"Error\\\",\\\"result\\\":\\\"all nodes offline\\\"}\",\"action\":\"onExecuteContract\"}");
// "{\"status\":\"Error\",\"data\":\"{\\\"status\\\":\\\"Error\\\",\\\"result\\\":\\\"all nodes }
// offline\\\"}\",\"action\":\"onExecuteContract\"}");
// } private boolean sendOnce(String requestID, ContractRequest req) {
// String[] members = CMActions.manager.multiContractRecorder.getMultiContractMeta(contractID).getMembers();
// private boolean sendOnce(String requestID, ContractRequest req) { for (int i = 0; i < members.length; i++) {
// String[] members = int size = members.length;
// CMActions.manager.multiContractRecorder.getMultiContractMeta(contractID).getMembers(); String nodeID = members[order.incrementAndGet() % size];
// for (int i = 0; i < members.length; i++) { Map<String, Object> obj = new HashMap<>();
// int size = members.length; obj.put("action", "executeContractLocally");
// String nodeID = members[order.incrementAndGet() % size]; obj.put("data", req);
// Map<String, Object> obj = new HashMap<>(); obj.put("uniReqID", requestID);
// obj.put("action", "executeContractLocally"); NetworkManager.instance.sendToAgent(nodeID, JsonUtil.toJson(obj));
// obj.put("data", req); return true;
// obj.put("uniReqID", requestID); }
// NetworkManager.instance.sendToAgent(nodeID, JsonUtil.toJson(obj)); return false;
// return true; }
// } }
// return false;
// }
// }

View File

@ -33,30 +33,30 @@ public class _UNUSED_RouteEnabledExecutor implements ContractExecutor {
} }
@Override @Override
public void execute(String requestID, ContractRequest req, ResultCallback rc, public void execute(String requestID, ContractRequest req, ResultCallback rc, OnHashCallback hashCallback) {
OnHashCallback hashCallback) {
executeInternal(requestID, rc, req, 2); executeInternal(requestID, rc, req, 2);
} }
private void executeInternal(String requestID, ResultCallback rc, ContractRequest req, private void executeInternal(
int count) { String requestID, ResultCallback rc, ContractRequest req, int count) {
// String contractID = req.getContractID(); // String contractID = req.getContractID();
// TODO 标注失效节点是否选择重新迁移 // TODO 标注失效节点是否选择重新迁移
ResultCallback cb = new ResultCallback() { ResultCallback cb =
@Override new ResultCallback() {
public void onResult(String str) { @Override
LOGGER.debug(str); public void onResult(String str) {
JsonObject jo = JsonParser.parseString(str).getAsJsonObject(); LOGGER.debug(str);
JsonObject result = JsonObject jo = JsonParser.parseString(str).getAsJsonObject();
JsonParser.parseString(jo.get("data").getAsString()).getAsJsonObject(); JsonObject result =
for (String key : result.keySet()) JsonParser.parseString(jo.get("data").getAsString())
jo.add(key, result.get(key)); .getAsJsonObject();
jo.remove("action"); for (String key : result.keySet()) jo.add(key, result.get(key));
jo.addProperty("action", "onExecuteResult"); jo.remove("action");
LOGGER.debug(jo.toString()); jo.addProperty("action", "onExecuteResult");
rc.onResult(jo.toString()); LOGGER.debug(jo.toString());
} rc.onResult(jo.toString());
}; }
};
MasterServerTCPAction.sync.sleepWithTimeout(requestID, cb, 5); MasterServerTCPAction.sync.sleepWithTimeout(requestID, cb, 5);
if (!send(requestID, req)) if (!send(requestID, req))
rc.onResult( rc.onResult(
@ -69,8 +69,7 @@ public class _UNUSED_RouteEnabledExecutor implements ContractExecutor {
req.getArg(); req.getArg();
req.getRequester(); req.getRequester();
req.getAction(); req.getAction();
MultiContractMeta mMeta = MultiContractMeta mMeta = CMActions.manager.multiContractRecorder.getMultiContractMeta(meta.getID());
CMActions.manager.multiContractRecorder.getMultiContractMeta(meta.getID());
FunctionDesp desp = meta.getExportedFunction(req.getAction()); FunctionDesp desp = meta.getExportedFunction(req.getAction());
RouteInfo info = desp.getRoute(); RouteInfo info = desp.getRoute();
@ -78,8 +77,10 @@ public class _UNUSED_RouteEnabledExecutor implements ContractExecutor {
if (info != null && info.useDefault != null) { if (info != null && info.useDefault != null) {
switch (info.useDefault) { switch (info.useDefault) {
case byRequester: case byRequester:
hash = new BigInteger(req.getRequester(), 16) hash =
.mod(BigInteger.valueOf(mMeta.getMembers().length)).intValue(); new BigInteger(req.getRequester(), 16)
.mod(BigInteger.valueOf(mMeta.getMembers().length))
.intValue();
break; break;
case byArgHash: case byArgHash:
hash = req.getArg().hashCode(); hash = req.getArg().hashCode();
@ -87,15 +88,13 @@ public class _UNUSED_RouteEnabledExecutor implements ContractExecutor {
} }
} }
String[] members = CMActions.manager.multiContractRecorder.getMultiContractMeta(contractID) String[] members =
.getMembers(); CMActions.manager.multiContractRecorder.getMultiContractMeta(contractID).getMembers();
String nodeID; String nodeID;
for (int i = 0; i < members.length; i++) { for (int i = 0; i < members.length; i++) {
int size = members.length; int size = members.length;
if (hash != -1) if (hash != -1) nodeID = members[hash % size];
nodeID = members[hash % size]; else nodeID = members[order.incrementAndGet() % size];
else
nodeID = members[order.incrementAndGet() % size];
Map<String, Object> obj = new HashMap<>(); Map<String, Object> obj = new HashMap<>();
obj.put("action", "executeContractLocally"); obj.put("action", "executeContractLocally");
obj.put("data", req); obj.put("data", req);

View File

@ -30,6 +30,7 @@ import java.io.UnsupportedEncodingException;
import java.net.URLDecoder; import java.net.URLDecoder;
import java.nio.charset.StandardCharsets; import java.nio.charset.StandardCharsets;
import java.util.HashMap; import java.util.HashMap;
import java.util.List;
import java.util.Map; import java.util.Map;
import static io.netty.handler.codec.http.HttpResponseStatus.OK; import static io.netty.handler.codec.http.HttpResponseStatus.OK;
@ -44,8 +45,11 @@ public class CMHttpHandler extends SimpleChannelInboundHandler<HttpObject> {
URIHandler uriHandlers; URIHandler uriHandlers;
public CMHttpHandler() { public CMHttpHandler() {
FileFilter fileFilter = pathname -> !pathname.getName().equals("CenterPortal.html") FileFilter fileFilter =
&& !pathname.getAbsolutePath().contains(".."); // TODO 路径判断过滤下载任意文件 pathname ->
!pathname.getName().equals("CenterPortal.html")
&& !pathname.getAbsolutePath()
.contains(".."); // TODO 路径判断过滤下载任意文件
HttpFileHandleAdapter ideFileService = new HttpFileHandleAdapter( HttpFileHandleAdapter ideFileService = new HttpFileHandleAdapter(
new File("./WebContent/ide/").getAbsolutePath(), fileFilter) { new File("./WebContent/ide/").getAbsolutePath(), fileFilter) {
@URIPath({"/"}) @URIPath({"/"})
@ -54,59 +58,68 @@ public class CMHttpHandler extends SimpleChannelInboundHandler<HttpObject> {
channelRead0(ctx, request); channelRead0(ctx, request);
} }
}; };
HttpFileHandleAdapter otherFileService = HttpFileHandleAdapter otherFileService = new HttpFileHandleAdapter(
new HttpFileHandleAdapter(new File("./WebContent/").getAbsolutePath(), fileFilter) { new File("./WebContent/").getAbsolutePath(), fileFilter) {
@URIPath({"/client/", "/doc/", "/blog/"}) @URIPath({"/client/", "/doc/"})
private void handleFile(ChannelHandlerContext ctx, FullHttpRequest request) private void handleFile(ChannelHandlerContext ctx, FullHttpRequest request)
throws Exception { throws Exception {
channelRead0(ctx, request); channelRead0(ctx, request);
}
};
UserManagerAction userManagerAction = new UserManagerAction(null);
MasterWSAction masterWSAction = new MasterWSAction(null);
actionExecutor = new ActionExecutor<ResultCallback, JsonObject>(
ContractManagerFrameHandler.executorService, new CMActions(),
ManagerActions.instance, new FileActions(null), userManagerAction, masterWSAction,
GRPCPool.instance, new HttpFileAction(), new BDIndexerAction(),
LedgerActions.instance, new CMLogAction(), new TemporyTestAction()) {
@Override
public boolean checkPermission(Action a, JsonObject arg, long per) {
boolean flag = a.httpAccess();
long val = a.userPermission(); // 使用者必须达到的permission
if (val == 0) {
return true;
}
long permission = arg.get("permission").getAsLong();
boolean flag2 = false; // 启动http权限后应改为false
String status = "refuse";
String action = arg.get("action").getAsString();
if (val == 0) {
flag2 = true;
} else if ((permission & val) == val) {
System.out.print((permission & val));
flag2 = true;
}
if (flag && flag2) {
status = "accept";
}
String pubkey = "anonymity";
if (arg.has("pubKey")) {
pubkey = arg.get("pubKey").getAsString();
}
TimeDBUtil.instance.put(CMTables.LocalNodeLogDB.toString(), String.format(
"{\"action\":\"%s\",\"pubKey\":\"%s\",\"status\":\"%s\",\"date\":%d}",
action, pubkey, status, System.currentTimeMillis()));
return flag && flag2;
} }
}; };
if (wsPluginActions != null) actionExecutor =
for (String str : wsPluginActions) { new ActionExecutor<ResultCallback, JsonObject>(
Object obj = createInstanceByClzName(str); ContractManagerFrameHandler.executorService,
actionExecutor.appendHandler(obj); new CMActions(),
} ManagerActions.instance,
GRPCPool.instance,
new HttpFileAction(),
new BDIndexerAction(),
LedgerActions.instance,
new CMLogAction(),
new TemporyTestAction()) {
@Override
public boolean checkPermission(Action a, JsonObject arg, long per) {
boolean flag = a.httpAccess();
long val = a.userPermission(); // 使用者必须达到的permission
if (val == 0) {
return true;
}
long permission = arg.get("permission").getAsLong();
boolean flag2 = false; // 启动http权限后应改为false
String status = "refuse";
String action = arg.get("action").getAsString();
if (val == 0) {
flag2 = true;
} else if ((permission & val) == val) {
System.out.print((permission & val));
flag2 = true;
}
if (flag && flag2) {
status = "accept";
}
String pubkey = "anonymity";
if (arg.has("pubKey")) {
pubkey = arg.get("pubKey").getAsString();
}
TimeDBUtil.instance.put(
CMTables.LocalNodeLogDB.toString(),
String.format(
"{\"action\":\"%s\",\"pubKey\":\"%s\",\"status\":\"%s\",\"date\":%d}",
action,
pubkey,
status,
System.currentTimeMillis()));
return flag && flag2;
}
};
for (String str : wsPluginActions) {
Object obj = createInstanceByClzName(str);
actionExecutor.appendHandler(obj);
}
uriHandlers = new URIHandler(); uriHandlers = new URIHandler();
DOIPOverHttpHandler doipOverHttpHandler = new DOIPOverHttpHandler(); DOIPOverHttpHandler doipOverHttpHandler = new DOIPOverHttpHandler();
@ -150,57 +163,89 @@ public class CMHttpHandler extends SimpleChannelInboundHandler<HttpObject> {
@URIPath(method = HttpMethod.OPTIONS) @URIPath(method = HttpMethod.OPTIONS)
public void crossOrigin(ChannelHandlerContext ctx, FullHttpRequest request) { public void crossOrigin(ChannelHandlerContext ctx, FullHttpRequest request) {
DefaultFullHttpResponse fullResponse = new DefaultFullHttpResponse( DefaultFullHttpResponse fullResponse =
request.protocolVersion(), OK, Unpooled.wrappedBuffer("success".getBytes())); new DefaultFullHttpResponse(
request.protocolVersion(),
OK,
Unpooled.wrappedBuffer("success".getBytes()));
fullResponse.headers().remove("Access-Control-Allow-Origin"); fullResponse.headers().remove("Access-Control-Allow-Origin");
fullResponse.headers().remove("Access-Control-Allow-Headers"); fullResponse.headers().remove("Access-Control-Allow-Headers");
fullResponse.headers().add("Access-Control-Allow-Origin", "*"); fullResponse.headers().add("Access-Control-Allow-Origin", "*");
fullResponse.headers().add("Access-Control-Allow-Methods", "*"); fullResponse
fullResponse.headers().add("Access-Control-Allow-Headers", .headers()
"Content-Type, Cookie, Accept-Encoding, User-Agent, Host, Referer, " .add("Access-Control-Allow-Headers",
+ "X-Requested-With, Accept, Accept-Language, Cache-Control, Connection"); "Content-Type, Cookie, Accept-Encoding, User-Agent, Host, Referer, " +
"X-Requested-With, Accept, Accept-Language, Cache-Control, Connection");
ChannelFuture f = ctx.write(fullResponse); ChannelFuture f = ctx.write(fullResponse);
f.addListener(ChannelFutureListener.CLOSE); f.addListener(ChannelFutureListener.CLOSE);
LOGGER.info("[OOOOOOOOption] received!"); LOGGER.info("[OOOOOOOOption] received!");
} }
@URIPath({"/SCIDE/CMManager", "/SCIDE/SCManager", "/BDO"}) @URIPath({"/SCIDE/CMManager", "/SCIDE/SCManager"})
public void handleHttpGet(ChannelHandlerContext ctx, FullHttpRequest msg) throws Exception { public void handleHttpGet(ChannelHandlerContext ctx, FullHttpRequest msg) throws Exception {
JsonObject transformedParam = QueryStringDecoder decoderQuery = new QueryStringDecoder(msg.uri());
ArgParser.parseGetAndVerify(msg, new ArgParser.VerifiedCallback() { Map<String, List<String>> parameters = decoderQuery.parameters();
@Override JsonObject transformedParam = new JsonObject();
public void onResult(boolean verified, JsonObject transformedParam) { for (String key : parameters.keySet()) {
LOGGER.info("verify signature: " + verified + " " List<String> val = parameters.get(key);
+ transformedParam.toString()); if (null != val) {
if (verified) { transformedParam.addProperty(key, val.get(0));
// 查permission }
String pubkey = transformedParam.get("pubKey").getAsString(); }
String ret = KeyValueDBUtil.instance
.getValue(CMTables.NodeRole.toString(), pubkey); // 匿名用户权限为0
long permission; transformedParam.addProperty("permission", 0);
if (ret != null && ret.length() > 0) { transformedParam.remove("verifiedPubKey");
permission = 0x86000d41L | Role.compoundValue(ret.split(","));
} else { // 验签 有pubKey就必须有sign
assert ret != null; String uri = URLDecoder.decode(msg.uri(), "UTF-8").split("\\?")[1];
permission = Role.compoundValue(ret.split(",")); if (transformedParam.has("pubKey")) {
} int index = uri.lastIndexOf('&');
transformedParam.addProperty("permission", permission); String str = uri.substring(0, index);
LOGGER.info("user permission: " + permission); LOGGER.info("before verifying: " + str);
transformedParam.addProperty("verifiedPubKey", boolean verify = false;
transformedParam.get("pubKey").getAsString()); try {
} verify =
} SM2Util.plainStrVerify(
}); transformedParam.get("pubKey").getAsString(),
str,
transformedParam.get("sign").getAsString());
} catch (Exception e) {
LOGGER.error(e.getMessage());
LOGGER.debug(ExceptionUtil.exceptionToString(e));
}
LOGGER.info("verify signature: " + verify);
if (verify) {
// 查permission
String pubkey = transformedParam.get("pubKey").getAsString();
String ret = KeyValueDBUtil.instance.getValue(CMTables.NodeRole.toString(), pubkey);
long permission;
if (ret != null && ret.length() > 0) {
permission = 0x86000d41L | Role.compoundValue(ret.split(","));
} else {
assert ret != null;
permission = Role.compoundValue(ret.split(","));
}
transformedParam.addProperty("permission", permission);
LOGGER.info("user permission: " + permission);
transformedParam.addProperty(
"verifiedPubKey", transformedParam.get("pubKey").getAsString());
}
}
handleReq(transformedParam, ctx, msg); handleReq(transformedParam, ctx, msg);
} }
@URIPath(method = HttpMethod.POST, value = {"/SCIDE/CMManager", "/SCIDE/SCManager", "/BDO"}) @URIPath(
method = HttpMethod.POST,
value = {"/SCIDE/CMManager", "/SCIDE/SCManager"})
public void handleHttpPost(ChannelHandlerContext ctx, FullHttpRequest msg) public void handleHttpPost(ChannelHandlerContext ctx, FullHttpRequest msg)
throws UnsupportedEncodingException { throws UnsupportedEncodingException {
// http请求中规定签名必须是最后一个且公钥名必须为pubKey否则验签失败 // http请求中规定签名必须是最后一个且公钥名必须为pubKey否则验签失败
// 倒数第二个参数是pubKey倒数第一个参数是sign // 倒数第二个参数是pubKey倒数第一个参数是sign
// 有pubKey就必须签名 // 有pubKey就必须签名
String uri = URLDecoder.decode(msg.uri(), "UTF-8"); String uri = URLDecoder.decode(msg.uri(), "UTF-8");
LOGGER.info("handle " + uri);
ByteBuf content = msg.content(); ByteBuf content = msg.content();
byte[] reqContent = new byte[content.readableBytes()]; byte[] reqContent = new byte[content.readableBytes()];
content.readBytes(reqContent); content.readBytes(reqContent);
@ -222,8 +267,11 @@ public class CMHttpHandler extends SimpleChannelInboundHandler<HttpObject> {
String str = "action:" + action; String str = "action:" + action;
boolean verify = false; boolean verify = false;
try { try {
verify = SM2Util.plainStrVerify(map.get("pubKey").getAsString(), str, verify =
map.get("sign").getAsString()); SM2Util.plainStrVerify(
map.get("pubKey").getAsString(),
str,
map.get("sign").getAsString());
} catch (Exception e) { } catch (Exception e) {
LOGGER.error(e.getMessage()); LOGGER.error(e.getMessage());
LOGGER.debug(ExceptionUtil.exceptionToString(e)); LOGGER.debug(ExceptionUtil.exceptionToString(e));
@ -256,13 +304,10 @@ public class CMHttpHandler extends SimpleChannelInboundHandler<HttpObject> {
if (!map.has("action")) { if (!map.has("action")) {
LOGGER.error("no action in map!"); LOGGER.error("no action in map!");
ret = UNSUPPORTED_ACTION.getBytes(); ret = UNSUPPORTED_ACTION.getBytes();
DefaultFullHttpResponse response = new DefaultFullHttpResponse(HttpVersion.HTTP_1_1, DefaultFullHttpResponse response =
OK, Unpooled.wrappedBuffer(ret)); new DefaultFullHttpResponse(
response.headers().add("Access-Control-Allow-Origin", "*"); HttpVersion.HTTP_1_1, OK, Unpooled.wrappedBuffer(ret));
response.headers().add("Access-Control-Allow-Methods", "*");
ChannelFuture f = ctx.write(response); ChannelFuture f = ctx.write(response);
response.headers().add("Access-Control-Allow-Origin", "*");
response.headers().add("Access-Control-Allow-Methods", "*");
f.addListener(ChannelFutureListener.CLOSE); f.addListener(ChannelFutureListener.CLOSE);
return; return;
} else { } else {
@ -272,46 +317,34 @@ public class CMHttpHandler extends SimpleChannelInboundHandler<HttpObject> {
HttpResultCallback cb; HttpResultCallback cb;
if (action.equals("downloadContract")) { if (action.equals("downloadContract")) {
cb = new FileDownloaderCallback(ctx, req); cb = new FileDownloaderCallback(ctx, req);
} else if (action.equals("distributeContract")) {
cb = new HttpServerSentEventResultCallback(ctx, null);
cb.addHeader("Access-Control-Allow-Origin", "*");
cb.addHeader("Access-Control-Allow-Methods", "*");
cb.addHeader("Content-Type", "text/event-stream");
cb.addHeader("Cache-Control", "no-cache, no-store, max-age=0, must-revalidate");
cb.addHeader("Transfer-Encoding", "chunked");
((HttpServerSentEventResultCallback) cb).writeInitialHead();
} else if (map.has("callback")) { } else if (map.has("callback")) {
cb = new HttpResultCallback(ctx, map.get("callback").getAsString()); cb = new HttpResultCallback(ctx, map.get("callback").getAsString());
cb.addHeader("Access-Control-Allow-Origin", "*");
cb.addHeader("Access-Control-Allow-Methods", "*");
cb.addHeader("Content-Type", "application/json"); cb.addHeader("Content-Type", "application/json");
} else { } else {
cb = new HttpResultCallback(ctx, null); cb = new HttpResultCallback(ctx, null);
cb.addHeader("Content-Type", "application/json"); cb.addHeader("Content-Type", "application/json");
cb.addHeader("Access-Control-Allow-Origin", "*");
cb.addHeader("Access-Control-Allow-Methods", "*");
} }
if (map.get("action").getAsString().equals("downloadUUID")) { if (map.get("action").getAsString().equals("downloadUUID")) {
cb.addHeader("Access-Control-Allow-Origin", "*");
cb.addHeader("Access-Control-Allow-Methods", "*");
cb.addHeader("content-disposition", "attachment;filename=encodeduuid.key"); cb.addHeader("content-disposition", "attachment;filename=encodeduuid.key");
} }
actionExecutor.handle(action, map, cb); actionExecutor.handle(action, map, cb);
} }
} catch (IllegalArgumentException e) { } catch (IllegalArgumentException e) {
DefaultFullHttpResponse response = new DefaultFullHttpResponse(HttpVersion.HTTP_1_1, OK, DefaultFullHttpResponse response =
Unpooled.wrappedBuffer(e.getMessage().getBytes())); new DefaultFullHttpResponse(
response.headers().add("Access-Control-Allow-Origin", "*"); HttpVersion.HTTP_1_1,
response.headers().add("Access-Control-Allow-Methods", "*"); OK,
Unpooled.wrappedBuffer(e.getMessage().getBytes()));
ChannelFuture f = ctx.write(response); ChannelFuture f = ctx.write(response);
f.addListener(ChannelFutureListener.CLOSE); f.addListener(ChannelFutureListener.CLOSE);
} catch (Exception e) { } catch (Exception e) {
Map<String, String> ret = new HashMap<>(); Map<String, String> ret = new HashMap<>();
ret.put("msg", ExceptionUtil.exceptionToString(e)); ret.put("msg", ExceptionUtil.exceptionToString(e));
DefaultFullHttpResponse response = new DefaultFullHttpResponse(HttpVersion.HTTP_1_1, OK, DefaultFullHttpResponse response =
Unpooled.wrappedBuffer(JsonUtil.toJson(ret).getBytes())); new DefaultFullHttpResponse(
response.headers().add("Access-Control-Allow-Origin", "*"); HttpVersion.HTTP_1_1,
response.headers().add("Access-Control-Allow-Methods", "*"); OK,
Unpooled.wrappedBuffer(JsonUtil.toJson(ret).getBytes()));
ChannelFuture f = ctx.write(response); ChannelFuture f = ctx.write(response);
f.addListener(ChannelFutureListener.CLOSE); f.addListener(ChannelFutureListener.CLOSE);
} }
@ -319,11 +352,9 @@ public class CMHttpHandler extends SimpleChannelInboundHandler<HttpObject> {
@Override @Override
public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) { public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) {
LOGGER.warn("catch exception in " + parseCtx2String(ctx) + ": " LOGGER.warn("catch exception in " + parseCtx2String(ctx) + ": " + cause.getClass().getSimpleName());
+ cause.getClass().getSimpleName());
LOGGER.debug(ExceptionUtil.exceptionToString(cause)); LOGGER.debug(ExceptionUtil.exceptionToString(cause));
cause.printStackTrace(); // ctx.close();
// ctx.close();
} }
private String parseCtx2String(ChannelHandlerContext ctx) { private String parseCtx2String(ChannelHandlerContext ctx) {

View File

@ -1,6 +1,5 @@
package org.bdware.server.http; package org.bdware.server.http;
import com.google.gson.Gson;
import com.google.gson.JsonObject; import com.google.gson.JsonObject;
import io.netty.buffer.Unpooled; import io.netty.buffer.Unpooled;
import io.netty.channel.ChannelFuture; import io.netty.channel.ChannelFuture;
@ -14,7 +13,6 @@ import io.netty.util.concurrent.GenericFutureListener;
import org.apache.logging.log4j.LogManager; import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger; import org.apache.logging.log4j.Logger;
import org.bdware.sc.ContractMeta; import org.bdware.sc.ContractMeta;
import org.bdware.sc.YPKResourceManager;
import org.bdware.sc.conn.ResultCallback; import org.bdware.sc.conn.ResultCallback;
import org.bdware.sc.util.JsonUtil; import org.bdware.sc.util.JsonUtil;
import org.bdware.server.action.CMActions; import org.bdware.server.action.CMActions;
@ -22,7 +20,11 @@ import org.zz.gmhelper.SM2Util;
import java.io.*; import java.io.*;
import java.net.URLDecoder; import java.net.URLDecoder;
import java.util.*; import java.util.EnumSet;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.zip.ZipEntry;
import java.util.zip.ZipFile; import java.util.zip.ZipFile;
import static io.netty.handler.codec.http.HttpVersion.HTTP_1_1; import static io.netty.handler.codec.http.HttpVersion.HTTP_1_1;
@ -30,39 +32,6 @@ import static io.netty.handler.codec.http.HttpVersion.HTTP_1_1;
public class DOIPOverHttpHandler { public class DOIPOverHttpHandler {
private static final Logger LOGGER = LogManager.getLogger(DOIPOverHttpHandler.class); private static final Logger LOGGER = LogManager.getLogger(DOIPOverHttpHandler.class);
Map<String, ZipFile> zipFilePool = new HashMap<>(); Map<String, ZipFile> zipFilePool = new HashMap<>();
Map<String, Long> lastVisit = new HashMap<>();
Map<String, Long> lastModified = new HashMap<>();
public synchronized void pruneZipPool() {
Set<String> toPrune = new HashSet<>();
long current = System.currentTimeMillis();
for (String str : zipFilePool.keySet()) {
Long last = lastVisit.get(str);
if (last != null && current - last > 30L * 24L * 3600L * 1000L) {
toPrune.add(str);
}
}
for (String str : toPrune) {
try {
ZipFile zf = zipFilePool.get(str);
zipFilePool.remove(str);
lastVisit.remove(str);
lastModified.remove(str);
zf.close();
} catch (Exception e) {
e.printStackTrace();
}
}
}
@URIPath({"/HTTPStat/"})
public void getHTTPStat(ChannelHandlerContext ctx, FullHttpRequest request) {
FullHttpResponse response =
new DefaultFullHttpResponse(HTTP_1_1, HttpResponseStatus.OK, Unpooled.wrappedBuffer(
new Gson().toJson(DOIPOverHttpStatics.httpRecords).getBytes()));
response.headers().set(HttpHeaderNames.CONTENT_TYPE, "text/plain; charset=UTF-8");
ctx.writeAndFlush(response).addListener(ChannelFutureListener.CLOSE);
}
@URIPath({"/contracts/", "/DOIP/"}) @URIPath({"/contracts/", "/DOIP/"})
public void mockDOIP(ChannelHandlerContext ctx, FullHttpRequest request) { public void mockDOIP(ChannelHandlerContext ctx, FullHttpRequest request) {
@ -72,27 +41,32 @@ public class DOIPOverHttpHandler {
String ops = arg.get("operation").getAsString(); String ops = arg.get("operation").getAsString();
Operations defaultOp = Operations.parse(ops); Operations defaultOp = Operations.parse(ops);
if (defaultOp == null) { if (defaultOp == null) {
CMActions.executeContractInternal(arg, new ResultCallback() { CMActions.executeContractInternal(
@Override arg,
public void onResult(String str) { new ResultCallback() {
FullHttpResponse response = new DefaultFullHttpResponse(HTTP_1_1, @Override
HttpResponseStatus.OK, Unpooled.wrappedBuffer(str.getBytes())); public void onResult(String str) {
response.headers().set(HttpHeaderNames.CONTENT_TYPE, FullHttpResponse response =
"text/plain; charset=UTF-8"); new DefaultFullHttpResponse(
ctx.writeAndFlush(response).addListener(ChannelFutureListener.CLOSE); HTTP_1_1,
} HttpResponseStatus.OK,
}, null); Unpooled.wrappedBuffer(str.getBytes()));
response.headers()
.set(
HttpHeaderNames.CONTENT_TYPE,
"text/plain; charset=UTF-8");
ctx.writeAndFlush(response)
.addListener(ChannelFutureListener.CLOSE);
}
},
null);
} else { } else {
switch (defaultOp) { switch (defaultOp) {
case ListOps: case ListOps:
sendListContractProcess(arg, ctx); sendListContractProcess(arg, ctx);
return; return;
case Retrieve: case Retrieve:
if (arg.has("__public") && arg.get("__public").getAsBoolean()) { sendAssets(arg, ctx);
sendPublicFiles(arg, ctx);
} else {
sendAssets(arg, ctx);
}
return; return;
case RetrieveYPK: case RetrieveYPK:
sendYpk(arg, ctx, request); sendYpk(arg, ctx, request);
@ -106,8 +80,11 @@ public class DOIPOverHttpHandler {
e.printStackTrace(); e.printStackTrace();
ByteArrayOutputStream bo = new ByteArrayOutputStream(); ByteArrayOutputStream bo = new ByteArrayOutputStream();
e.printStackTrace(new PrintStream(bo)); e.printStackTrace(new PrintStream(bo));
FullHttpResponse response = new DefaultFullHttpResponse(HTTP_1_1, HttpResponseStatus.OK, FullHttpResponse response =
Unpooled.wrappedBuffer(bo.toByteArray())); new DefaultFullHttpResponse(
HTTP_1_1,
HttpResponseStatus.OK,
Unpooled.wrappedBuffer(bo.toByteArray()));
response.headers().set(HttpHeaderNames.CONTENT_TYPE, "text/plain; charset=UTF-8"); response.headers().set(HttpHeaderNames.CONTENT_TYPE, "text/plain; charset=UTF-8");
ctx.writeAndFlush(response).addListener(ChannelFutureListener.CLOSE); ctx.writeAndFlush(response).addListener(ChannelFutureListener.CLOSE);
} }
@ -116,18 +93,22 @@ public class DOIPOverHttpHandler {
private void sendListContractProcess(JsonObject arg, ChannelHandlerContext ctx) { private void sendListContractProcess(JsonObject arg, ChannelHandlerContext ctx) {
JsonObject ret = new JsonObject(); JsonObject ret = new JsonObject();
ret.addProperty("action", "onListOps"); ret.addProperty("action", "onListOps");
ret.addProperty("data", ret.addProperty(
CMActions.manager.listTheContracts(arg.get("contractID").getAsString())); "data", CMActions.manager.listTheContracts(arg.get("contractID").getAsString()));
FullHttpResponse response = new DefaultFullHttpResponse(HTTP_1_1, HttpResponseStatus.OK, FullHttpResponse response =
Unpooled.wrappedBuffer(JsonUtil.toJson(ret).getBytes())); new DefaultFullHttpResponse(
HTTP_1_1,
HttpResponseStatus.OK,
Unpooled.wrappedBuffer(JsonUtil.toJson(ret).getBytes()));
response.headers().set(HttpHeaderNames.CONTENT_TYPE, "text/plain; charset=UTF-8"); response.headers().set(HttpHeaderNames.CONTENT_TYPE, "text/plain; charset=UTF-8");
ctx.writeAndFlush(response).addListener(ChannelFutureListener.CLOSE); ctx.writeAndFlush(response).addListener(ChannelFutureListener.CLOSE);
} }
private void sendYpk(JsonObject arg, ChannelHandlerContext ctx, FullHttpRequest request) private void sendYpk(JsonObject arg, ChannelHandlerContext ctx, FullHttpRequest request)
throws IOException { throws IOException {
ContractMeta meta = CMActions.manager.statusRecorder ContractMeta meta =
.getContractMeta(arg.get("contractID").getAsString()); CMActions.manager.statusRecorder.getContractMeta(
arg.get("contractID").getAsString());
if (meta == null) { if (meta == null) {
HttpFileHandleAdapter.sendError(ctx, HttpResponseStatus.NOT_FOUND); HttpFileHandleAdapter.sendError(ctx, HttpResponseStatus.NOT_FOUND);
return; return;
@ -161,115 +142,44 @@ public class DOIPOverHttpHandler {
return; return;
} }
private void sendPublicFiles(JsonObject arg, ChannelHandlerContext ctx) throws Exception { // TODO @杨环宇 把zipFilePool用起来做一个延迟关闭的东西避免频繁打开文件的操作
ContractMeta meta = CMActions.manager.statusRecorder
.getContractMeta(arg.get("contractID").getAsString());
if (meta == null) {
HttpFileHandleAdapter.sendError(ctx, HttpResponseStatus.NOT_FOUND);
return;
}
String path = arg.get("argument").getAsString();
File dir = new File("./ContractDB", meta.getName());
File toSend = new File(dir, path);
FileInputStream fin;
try {
if (!toSend.exists() || toSend.isDirectory()) {
HttpFileHandleAdapter.sendError(ctx, HttpResponseStatus.NOT_FOUND);
return;
} else
fin = new FileInputStream(toSend);
} catch (Exception e) {
HttpFileHandleAdapter.sendError(ctx, HttpResponseStatus.NOT_FOUND);
return;
}
HttpResponse response = new DefaultHttpResponse(HTTP_1_1, HttpResponseStatus.OK);
HttpFileHandleAdapter.appendContentType(path, response.headers());
ctx.write(response);
ChannelFuture future = ctx.writeAndFlush(new ChunkedStream(fin));
future.addListener(new GenericFutureListener<Future<? super Void>>() {
@Override
public void operationComplete(Future<? super Void> arg0) throws Exception {
ctx.writeAndFlush(LastHttpContent.EMPTY_LAST_CONTENT);
fin.close();
}
});
// 写入文件尾部
future.addListener(ChannelFutureListener.CLOSE);
return;
}
private void sendAssets(JsonObject arg, ChannelHandlerContext ctx) throws Exception { private void sendAssets(JsonObject arg, ChannelHandlerContext ctx) throws Exception {
ContractMeta meta = CMActions.manager.statusRecorder
.getContractMeta(arg.get("contractID").getAsString()); ContractMeta meta =
CMActions.manager.statusRecorder.getContractMeta(
arg.get("contractID").getAsString());
if (meta == null) { if (meta == null) {
HttpFileHandleAdapter.sendError(ctx, HttpResponseStatus.NOT_FOUND); HttpFileHandleAdapter.sendError(ctx, HttpResponseStatus.NOT_FOUND);
return; return;
} }
String path = arg.get("argument").getAsString(); String path = arg.get("argument").getAsString();
String dir = YPKResourceManager.getUnzipDir(meta.contract); ZipFile zipFile = new ZipFile(new File(meta.contract.getScriptStr()));
File toSend = new File(dir, path); ZipEntry zipEntry = zipFile.getEntry(path);
if (!toSend.exists()) {
if (YPKResourceManager.existYPK(meta.contract)) { if (zipEntry == null) {
YPKResourceManager.unzipYPK(meta.contract); HttpFileHandleAdapter.sendError(ctx, HttpResponseStatus.NOT_FOUND);
} else { return;
HttpFileHandleAdapter.sendError(ctx, HttpResponseStatus.NOT_FOUND);
return;
}
} }
InputStream in = YPKResourceManager.getCachedStream(meta.contract, path); InputStream in = zipFile.getInputStream(zipEntry);
DOIPOverHttpStatics.Records httpRecords = new DOIPOverHttpStatics.Records();
httpRecords.start = System.currentTimeMillis();
httpRecords.url = path;
DOIPOverHttpStatics.httpRecords.add(httpRecords);
HttpResponse response = new DefaultHttpResponse(HTTP_1_1, HttpResponseStatus.OK); HttpResponse response = new DefaultHttpResponse(HTTP_1_1, HttpResponseStatus.OK);
HttpFileHandleAdapter.appendContentType(path, response.headers()); HttpFileHandleAdapter.appendContentType(path, response.headers());
// HttpHeaders headers = response.headers();
// headers.set(HttpHeaderNames.CACHE_CONTROL, "public, max-age=2592000");
ctx.write(response); ctx.write(response);
ChannelFuture future = ctx.writeAndFlush(new ChunkedStream(in)); ChannelFuture future = ctx.writeAndFlush(new ChunkedStream(in));
future.addListener(new GenericFutureListener<Future<? super Void>>() { future.addListener(
@Override new GenericFutureListener<Future<? super Void>>() {
public void operationComplete(Future<? super Void> arg0) throws Exception { @Override
ctx.writeAndFlush(LastHttpContent.EMPTY_LAST_CONTENT); public void operationComplete(Future<? super Void> arg0) throws Exception {
in.close(); ctx.writeAndFlush(LastHttpContent.EMPTY_LAST_CONTENT);
httpRecords.end = System.currentTimeMillis(); zipFile.close();
httpRecords.dur = httpRecords.end - httpRecords.start; }
ctx.close(); });
}
});
// 写入文件尾部 // 写入文件尾部
future.addListener(ChannelFutureListener.CLOSE); future.addListener(ChannelFutureListener.CLOSE);
return; return;
} }
private synchronized ZipFile getZipFileFromPool(String scriptStr) throws Exception {
try {
ZipFile cachedFile = zipFilePool.get(scriptStr);
if (cachedFile == null) {
File f = new File(scriptStr);
cachedFile = new ZipFile(f);
zipFilePool.put(scriptStr, cachedFile);
lastModified.put(scriptStr, f.lastModified());
} else {
File f = new File(scriptStr);
if (lastModified.get(scriptStr) != f.lastModified()) {
cachedFile.close();
cachedFile = new ZipFile(f);
zipFilePool.put(scriptStr, cachedFile);
lastModified.put(scriptStr, f.lastModified());
}
}
lastVisit.put(scriptStr, System.currentTimeMillis());
return cachedFile;
} catch (Exception e) {
e.printStackTrace();
}
return new ZipFile(new File(scriptStr));
}
private void injectExtraArgs(JsonObject transformedParam, String fulluri) { private void injectExtraArgs(JsonObject transformedParam, String fulluri) {
String[] data = fulluri.split("/"); String[] data = fulluri.split("/");
String contractIDOrName = data[2]; String contractIDOrName = data[2];
String uris[] = URLDecoder.decode(fulluri).split("\\?"); String uris[] = URLDecoder.decode(fulluri).split("\\?");
@ -277,40 +187,34 @@ public class DOIPOverHttpHandler {
if (uri != null && transformedParam.has("pubKey")) { if (uri != null && transformedParam.has("pubKey")) {
int index = fulluri.lastIndexOf('&'); int index = fulluri.lastIndexOf('&');
String str = fulluri; String str = fulluri;
if (index > 0) if (index > 0) str = fulluri.substring(0, index);
str = fulluri.substring(0, index);
LOGGER.info("[mockDOIP] before verify:" + str); LOGGER.info("[mockDOIP] before verify:" + str);
boolean verify = false; boolean verify = false;
try { try {
verify = SM2Util.plainStrVerify(transformedParam.get("pubKey").getAsString(), str, verify =
transformedParam.get("sign").getAsString()); SM2Util.plainStrVerify(
transformedParam.get("pubKey").getAsString(),
str,
transformedParam.get("sign").getAsString());
} catch (Exception e) { } catch (Exception e) {
e.printStackTrace(); e.printStackTrace();
} }
if (verify) { if (verify) {
transformedParam.addProperty("verifiedPubKey", transformedParam.addProperty(
transformedParam.get("pubKey").getAsString()); "verifiedPubKey", transformedParam.get("pubKey").getAsString());
} else } else transformedParam.remove("verifiedPubKey");
transformedParam.remove("verifiedPubKey");
} }
transformedParam.addProperty("contractID", data[2].replaceAll("\\?.*$", "")); transformedParam.addProperty("contractID", data[2].replaceAll("\\?.*$", ""));
if (data.length > 3) { if (data.length > 3) {
String assetPath = data[3]; String assetPath = data[3];
transformedParam.remove("__public"); if (assetPath.equals("assets")) {
if (assetPath.equals("assets") && !fulluri.contains("..")) {
transformedParam.addProperty("operation", Operations.Retrieve.val); transformedParam.addProperty("operation", Operations.Retrieve.val);
int index = data[0].length() + data[1].length() + data[2].length() + 2; int index = data[0].length() + data[1].length() + data[2].length() + 2;
String path = fulluri.substring(index); String path = fulluri.substring(index);
path = path.replaceAll("\\?.*$", ""); path = path.replaceAll("\\?.*$", "");
if (path.equals("/assets/")) if (path.equals("/assets/"))
path += "index.html"; path+="index.html";
transformedParam.addProperty("argument", path); transformedParam.addProperty("argument", path);
} else if (assetPath.equals("public") && !fulluri.contains("..")) {
transformedParam.addProperty("operation", Operations.Retrieve.val);
int index = data[0].length() + data[1].length() + data[2].length() + 2;
String path = fulluri.substring(index);
transformedParam.addProperty("argument", path);
transformedParam.addProperty("__public", true);
} }
if (assetPath.startsWith("ypk?")) { if (assetPath.startsWith("ypk?")) {
transformedParam.addProperty("operation", Operations.RetrieveYPK.val); transformedParam.addProperty("operation", Operations.RetrieveYPK.val);
@ -326,19 +230,22 @@ public class DOIPOverHttpHandler {
JsonObject transformedParam = new JsonObject(); JsonObject transformedParam = new JsonObject();
for (String key : parameters.keySet()) { for (String key : parameters.keySet()) {
List<String> val = parameters.get(key); List<String> val = parameters.get(key);
if (val != null) if (val != null) transformedParam.addProperty(key, val.get(0));
transformedParam.addProperty(key, val.get(0));
} }
return transformedParam; return transformedParam;
} }
enum Operations { enum Operations {
Hello("0.DOIP/Op.Hello"), ListOps("0.DOIP/Op.ListOperations"), Retrieve( Hello("0.DOIP/Op.Hello"),
"0.DOIP/Op.Retrieve"), RetrieveYPK("86.BDWare/Op.RetrieveYPK"), Create( ListOps("0.DOIP/Op.ListOperations"),
"0.DOIP/Op.Create"), Update("0.DOIP/Op.Update"), Delete( Retrieve("0.DOIP/Op.Retrieve"),
"0.DOIP/Op.Delete"), Search("0.DOIP/Op.Search"), Extension( RetrieveYPK("86.BDWare/Op.RetrieveYPK"),
"0.DOIP/Op.Extension"), Unknown("0.DOIP/Op.Unknown"); Create("0.DOIP/Op.Create"),
Update("0.DOIP/Op.Update"),
Delete("0.DOIP/Op.Delete"),
Search("0.DOIP/Op.Search"),
Extension("0.DOIP/Op.Extension"),
Unknown("0.DOIP/Op.Unknown");
private final String val; private final String val;
Operations(String s) { Operations(String s) {
@ -347,8 +254,7 @@ public class DOIPOverHttpHandler {
public static Operations parse(String str) { public static Operations parse(String str) {
for (Operations ops : EnumSet.allOf(Operations.class)) { for (Operations ops : EnumSet.allOf(Operations.class)) {
if (ops.val.equals(str)) if (ops.val.equals(str)) return ops;
return ops;
} }
return null; return null;
} }

View File

@ -1,15 +0,0 @@
package org.bdware.server.http;
import java.util.ArrayList;
import java.util.List;
public class DOIPOverHttpStatics {
public static List<Records> httpRecords = new ArrayList<Records>();
static class Records {
long start;
long end;
long dur;
String url;
}
}

View File

@ -12,7 +12,6 @@ import org.bdware.sc.conn.ByteUtil;
import org.bdware.sc.conn.ResultCallback; import org.bdware.sc.conn.ResultCallback;
import org.bdware.sc.db.CMTables; import org.bdware.sc.db.CMTables;
import org.bdware.sc.db.KeyValueDBUtil; import org.bdware.sc.db.KeyValueDBUtil;
import org.bdware.sc.event.REvent;
import org.bdware.sc.units.MultiContractMeta; import org.bdware.sc.units.MultiContractMeta;
import org.bdware.sc.util.JsonUtil; import org.bdware.sc.util.JsonUtil;
import org.bdware.server.GlobalConf; import org.bdware.server.GlobalConf;
@ -41,17 +40,17 @@ public class NodeCenterClientController implements NodeCenterConn {
private static final Logger LOGGER = LogManager.getLogger(NodeCenterClientController.class); private static final Logger LOGGER = LogManager.getLogger(NodeCenterClientController.class);
public static SyncResult sync = new SyncResult(); public static SyncResult sync = new SyncResult();
private static boolean startCheck = false; private static boolean startCheck = false;
private final Map<String, FileOutputStream> fileMap;
private final NetNeighbors neighbors; private final NetNeighbors neighbors;
public Map<String, ResultCallback> distributeReqMap = new ConcurrentHashMap<>(); public Map<String, ResultCallback> distributeReqMap = new ConcurrentHashMap<>();
// public NodeCenterClientController cmClientController; // public NodeCenterClientController cmClientController;
String nodeID; String nodeID;
NodeCenterClientHandler handler; NodeCenterClientHandler handler;
// 合约contractIDmaster的公钥 // 合约contractIDmaster的公钥
Map<String, String> contractID2PubKey = new ConcurrentHashMap<>(); Map<String, String> contractID2PubKey = new ConcurrentHashMap<>();
Deque<JsonObject> receiveQueue = new ArrayDeque<>();
ReceiveFileThread receiveFileThread = new ReceiveFileThread();
public NodeCenterClientController(String nodeID) { public NodeCenterClientController(String nodeID) {
this.fileMap = new HashMap<>();
this.nodeID = nodeID; this.nodeID = nodeID;
this.neighbors = new NetNeighbors(); this.neighbors = new NetNeighbors();
} }
@ -123,8 +122,11 @@ public class NodeCenterClientController implements NodeCenterConn {
setNodeID.put("id", keyPair.getPublicKeyStr()); setNodeID.put("id", keyPair.getPublicKeyStr());
String signature = "no signature"; String signature = "no signature";
try { try {
byte[] sig = SM2Util.sign(keyPair.getPrivateKeyParameter(), byte[] sig =
(keyPair.getPublicKeyStr() + json.get("session").getAsString()).getBytes()); SM2Util.sign(
keyPair.getPrivateKeyParameter(),
(keyPair.getPublicKeyStr() + json.get("session").getAsString())
.getBytes());
signature = ByteUtils.toHexString(sig); signature = ByteUtils.toHexString(sig);
} catch (Exception e) { } catch (Exception e) {
e.printStackTrace(); e.printStackTrace();
@ -133,8 +135,7 @@ public class NodeCenterClientController implements NodeCenterConn {
setNodeID.put("nodeName", GlobalConf.instance.name); setNodeID.put("nodeName", GlobalConf.instance.name);
setNodeID.put("peerID", GlobalConf.instance.peerID); setNodeID.put("peerID", GlobalConf.instance.peerID);
setNodeID.put("ipPort", GlobalConf.instance.ipPort); setNodeID.put("ipPort", GlobalConf.instance.ipPort);
setNodeID.put("masterAddress", GlobalConf.instance.ipPort); setNodeID.put("masterAddress", GlobalConf.instance.masterAddress);
// setNodeID.put("masterAddress", GlobalConf.instance.masterAddress);
sendMsg(JsonUtil.toJson(setNodeID)); sendMsg(JsonUtil.toJson(setNodeID));
} }
@ -146,8 +147,8 @@ public class NodeCenterClientController implements NodeCenterConn {
@Action @Action
public void syncPong(JsonObject json, ResultCallback resultCallback) { public void syncPong(JsonObject json, ResultCallback resultCallback) {
sync.wakeUp(json.get("requestID").getAsString(), sync.wakeUp(
"{\"status\":\"Success\",\"result\":\"a\"}"); json.get("requestID").getAsString(), "{\"status\":\"Success\",\"result\":\"a\"}");
} }
public boolean syncPing() { public boolean syncPing() {
@ -170,9 +171,12 @@ public class NodeCenterClientController implements NodeCenterConn {
} }
public void listCMInfo() { public void listCMInfo() {
sendMsg("{\"action\":\"listCMInfo\",\"pubKey\":\"" sendMsg(
+ KeyValueDBUtil.instance.getValue(CMTables.ConfigDB.toString(), "pubKey") "{\"action\":\"listCMInfo\",\"pubKey\":\""
+ "\",\"requestID\":\"" + System.currentTimeMillis() + "\"}"); + KeyValueDBUtil.instance.getValue(CMTables.ConfigDB.toString(), "pubKey")
+ "\",\"requestID\":\""
+ System.currentTimeMillis()
+ "\"}");
} }
@Action @Action
@ -204,9 +208,8 @@ public class NodeCenterClientController implements NodeCenterConn {
public void updateNonMasters(JsonObject jo, ResultCallback cb) { public void updateNonMasters(JsonObject jo, ResultCallback cb) {
String[] contracts = jo.get("contracts").getAsString().split(","); String[] contracts = jo.get("contracts").getAsString().split(",");
for (String id : contracts) { for (String id : contracts) {
if (null != CMActions.manager.setContractIsMaster(id, String.valueOf(false))) { LOGGER.info("旧的master设置合约 " + id + " 自己不再是master");
LOGGER.warn("master of contract " + id + " changes"); CMActions.manager.setContractIsMaster(id, false + "");
}
} }
} }
@ -221,14 +224,6 @@ public class NodeCenterClientController implements NodeCenterConn {
LOGGER.info("update " + info.size() + " contracts in node center"); LOGGER.info("update " + info.size() + " contracts in node center");
} }
@Action(async = true)
public void publishEventFromCenter(JsonObject jo, ResultCallback rcb) {
if (jo.has("event")) {
CMActions.manager
.deliverEvent(JsonUtil.fromJson(jo.get("event").getAsString(), REvent.class));
}
}
@Action(async = true) @Action(async = true)
public void requestReadMe(JsonObject jo, ResultCallback cb) throws IOException { public void requestReadMe(JsonObject jo, ResultCallback cb) throws IOException {
JsonObject resp = new JsonObject(); JsonObject resp = new JsonObject();
@ -242,6 +237,7 @@ public class NodeCenterClientController implements NodeCenterConn {
resp.addProperty("pubkey", meta.contract.getPublicKey()); resp.addProperty("pubkey", meta.contract.getPublicKey());
resp.addProperty("name", meta.getName()); resp.addProperty("name", meta.getName());
resp.addProperty("buildTime", meta.contract.getBuildTime()); resp.addProperty("buildTime", meta.contract.getBuildTime());
resp.addProperty("doi", meta.contract.getDOI());
ZipFile zipFile = new ZipFile(new File(meta.contract.getScriptStr())); ZipFile zipFile = new ZipFile(new File(meta.contract.getScriptStr()));
ZipEntry zipEntry = zipFile.getEntry("/assets/README.md"); ZipEntry zipEntry = zipFile.getEntry("/assets/README.md");
if (null == zipEntry) { if (null == zipEntry) {
@ -252,7 +248,7 @@ public class NodeCenterClientController implements NodeCenterConn {
InputStream in = zipFile.getInputStream(zipEntry); InputStream in = zipFile.getInputStream(zipEntry);
ByteArrayOutputStream bo = new ByteArrayOutputStream(); ByteArrayOutputStream bo = new ByteArrayOutputStream();
byte[] buff = new byte[1024]; byte[] buff = new byte[1024];
for (int k; (k = in.read(buff)) > 0;) { for (int k; (k = in.read(buff)) > 0; ) {
bo.write(buff, 0, k); bo.write(buff, 0, k);
} }
resp.addProperty("readmeStr", bo.toString()); resp.addProperty("readmeStr", bo.toString());
@ -273,18 +269,15 @@ public class NodeCenterClientController implements NodeCenterConn {
String requestID = jo.get("requestID").getAsString(); String requestID = jo.get("requestID").getAsString();
String requesterNodeID = jo.get("requesterNodeID").getAsString(); String requesterNodeID = jo.get("requesterNodeID").getAsString();
String crStr = jo.get("contractRequest").getAsString(); String crStr = jo.get("contractRequest").getAsString();
CMActions.manager.executeLocallyAsync(JsonUtil.fromJson(crStr, ContractRequest.class), String cr =
new ResultCallback() { CMActions.manager.executeLocally(
@Override JsonUtil.fromJson(crStr, ContractRequest.class), null);
public void onResult(String str) { JsonObject ret = new JsonObject();
JsonObject ret = new JsonObject(); ret.addProperty("action", "onReceiveContractExecution");
ret.addProperty("action", "onReceiveContractExecution"); ret.addProperty("requestID", requestID);
ret.addProperty("requestID", requestID); ret.addProperty("requesterNodeID", requesterNodeID);
ret.addProperty("requesterNodeID", requesterNodeID); ret.addProperty("contractResult", cr);
ret.addProperty("contractResult", str); sendMsg(JsonUtil.toJson(ret));
sendMsg(JsonUtil.toJson(ret));
}
}, null);
} }
@Action(async = true) @Action(async = true)
@ -337,8 +330,8 @@ public class NodeCenterClientController implements NodeCenterConn {
@Override @Override
public String routeContract(String contractID) { public String routeContract(String contractID) {
LOGGER.debug("[CMClientController] routeContract : " + contractID); LOGGER.info("[CMClientController] routeContract : " + contractID);
LOGGER.debug("contractID2Pubkey.contractsKey=" + contractID2PubKey.containsKey(contractID)); LOGGER.info("contractID2Pubkey.contractsKey=" + contractID2PubKey.containsKey(contractID));
// TODO RouteContract是不是IRP协议/DOIP协议 // TODO RouteContract是不是IRP协议/DOIP协议
if (contractID2PubKey.containsKey(contractID)) { if (contractID2PubKey.containsKey(contractID)) {
return contractID2PubKey.get(contractID); return contractID2PubKey.get(contractID);
@ -354,15 +347,15 @@ public class NodeCenterClientController implements NodeCenterConn {
String requestID = System.currentTimeMillis() + "_" + (int) (Math.random() * 100000); String requestID = System.currentTimeMillis() + "_" + (int) (Math.random() * 100000);
req.put("requestID", requestID); req.put("requestID", requestID);
sendMsg(JsonUtil.toJson(req)); sendMsg(JsonUtil.toJson(req));
// TODO use async instead? //TODO use async instead?
ContractResult cr = sync.syncSleep(requestID); ContractResult cr = sync.syncSleep(requestID);
LOGGER.debug("result: " + JsonUtil.toJson(cr)); LOGGER.debug("result: " + JsonUtil.toJson(cr));
LOGGER.info("node " + pubKey + " succeed!"); LOGGER.info("node " + pubKey + " succeed!");
if (!cr.result.equals(JsonNull.INSTANCE)) { if (!cr.result.equals(JsonNull.INSTANCE)) {
try { try {
JsonObject jo = cr.result.getAsJsonObject(); JsonObject jo = cr.result.getAsJsonObject();
NetworkManager.instance.updateAgentRouter(jo.get("pubKey").getAsString(), NetworkManager.instance.updateAgentRouter(
jo.get("masterAddress").getAsString()); jo.get("pubKey").getAsString(), jo.get("masterAddress").getAsString());
NetworkManager.instance.connectToAgent(jo.get("pubKey").getAsString(), null); NetworkManager.instance.connectToAgent(jo.get("pubKey").getAsString(), null);
return "success"; return "success";
} catch (Exception e) { } catch (Exception e) {
@ -386,17 +379,18 @@ public class NodeCenterClientController implements NodeCenterConn {
if (!cr.result.equals(JsonNull.INSTANCE)) { if (!cr.result.equals(JsonNull.INSTANCE)) {
try { try {
JsonObject jo = cr.result.getAsJsonObject(); JsonObject jo = cr.result.getAsJsonObject();
NetworkManager.instance.updateAgentRouter(jo.get("pubKey").getAsString(), NetworkManager.instance.updateAgentRouter(
jo.get("masterAddress").getAsString()); jo.get("pubKey").getAsString(), jo.get("masterAddress").getAsString());
NetworkManager.instance.connectToAgent(jo.get("pubKey").getAsString(), null); NetworkManager.instance.connectToAgent(jo.get("pubKey").getAsString(), null);
LOGGER.info(String.format("the master of contract %s: pubKey=%s address=%s", LOGGER.info(
contractID, jo.get("pubKey").getAsString(), String.format("the master of contract %s: pubKey=%s address=%s",
jo.get("masterAddress").getAsString())); contractID,
jo.get("pubKey").getAsString(),
jo.get("masterAddress").getAsString()));
contractID2PubKey.put(contractID, jo.get("pubKey").getAsString()); contractID2PubKey.put(contractID, jo.get("pubKey").getAsString());
return jo.get("pubKey").getAsString(); return jo.get("pubKey").getAsString();
} catch (Exception e) { } catch (Exception e) {
LOGGER.warn( LOGGER.warn("the master of contract " + contractID + " is null! " + e.getMessage());
"the master of contract " + contractID + " is null! " + e.getMessage());
} }
} }
} catch (Exception e) { } catch (Exception e) {
@ -415,8 +409,8 @@ public class NodeCenterClientController implements NodeCenterConn {
return; return;
} }
startCheck = true; startCheck = true;
for (MultiContractMeta meta : CMActions.manager.multiContractRecorder.getStatus() for (MultiContractMeta meta :
.values()) { CMActions.manager.multiContractRecorder.getStatus().values()) {
String contractID = meta.getContractID(); String contractID = meta.getContractID();
LOGGER.info("check master of contract " + contractID); LOGGER.info("check master of contract " + contractID);
ContractMeta cmeta = CMActions.manager.statusRecorder.getContractMeta(meta.getID()); ContractMeta cmeta = CMActions.manager.statusRecorder.getContractMeta(meta.getID());
@ -430,21 +424,20 @@ public class NodeCenterClientController implements NodeCenterConn {
// 该合约可能在这个节点崩溃期间已经被终止不存在了这个节点不用恢复这个合约了直接从数据库中删除 // 该合约可能在这个节点崩溃期间已经被终止不存在了这个节点不用恢复这个合约了直接从数据库中删除
LOGGER.info("该合约在集群已经不存在!"); LOGGER.info("该合约在集群已经不存在!");
KeyValueDBUtil.instance.delete(CMTables.UnitContracts.toString(), contractID); KeyValueDBUtil.instance.delete(CMTables.UnitContracts.toString(), contractID);
if (KeyValueDBUtil.instance.containsKey(CMTables.CheckPointLastHash.toString(), if (KeyValueDBUtil.instance.containsKey(
contractID)) { CMTables.CheckPointLastHash.toString(), contractID)) {
KeyValueDBUtil.instance.delete(CMTables.CheckPointLastHash.toString(), KeyValueDBUtil.instance.delete(
contractID); CMTables.CheckPointLastHash.toString(), contractID);
} }
if (KeyValueDBUtil.instance.containsKey(CMTables.LastExeSeq.toString(), if (KeyValueDBUtil.instance.containsKey(
contractID)) { CMTables.LastExeSeq.toString(), contractID)) {
KeyValueDBUtil.instance.delete(CMTables.LastExeSeq.toString(), contractID); KeyValueDBUtil.instance.delete(CMTables.LastExeSeq.toString(), contractID);
} }
continue; continue;
} }
MasterClientRecoverMechAction.recoverSet.add(contractID); MasterClientRecoverMechAction.recoverSet.add(contractID);
LOGGER.info("queryUnitContractsID master为" + master.substring(0, 5) + " -> 合约id:" LOGGER.info("queryUnitContractsID master为" + master.substring(0, 5) + " -> 合约id:" + contractID);
+ contractID);
RecoverMechTimeRecorder.queryMasterFinish = System.currentTimeMillis(); RecoverMechTimeRecorder.queryMasterFinish = System.currentTimeMillis();
queryUnitContractsID2(contractID, master); queryUnitContractsID2(contractID, master);
} }
@ -485,7 +478,9 @@ public class NodeCenterClientController implements NodeCenterConn {
@Action(async = true) @Action(async = true)
public void requestLog(JsonObject json, ResultCallback rc) { public void requestLog(JsonObject json, ResultCallback rc) {
if (!json.has("requestID") || !json.has("contractID") || !json.has("offset") if (!json.has("requestID")
|| !json.has("contractID")
|| !json.has("offset")
|| !json.has("count")) { || !json.has("count")) {
LOGGER.debug( LOGGER.debug(
"[CMClientController] missing arguments, requestID / contractID / offset / count"); "[CMClientController] missing arguments, requestID / contractID / offset / count");
@ -523,20 +518,69 @@ public class NodeCenterClientController implements NodeCenterConn {
queryNCRepoDOI(json, result); queryNCRepoDOI(json, result);
} }
@Action(async = false) @Action(async = true)
public synchronized void receiveProject(JsonObject args, final ResultCallback rc) { public void receiveProject(JsonObject args, final ResultCallback rc) {
try { LOGGER.debug("position----7");
receiveQueue.add(args);
synchronized (receiveFileThread) { String fileName = args.get("fileName").getAsString();
receiveFileThread.notify(); boolean isAppend = args.get("isAppend").getAsBoolean();
boolean isDone = args.get("isDone").getAsBoolean();
boolean isPrivate = args.get("isPrivate").getAsBoolean();
LOGGER.debug(
String.format("isAppend=%b isDone=%b isPrivate=%b", isAppend, isDone, isPrivate));
String path = GlobalConf.instance.publicCompiledDir;
if (isPrivate && args.has("pubKey")) {
path = GlobalConf.instance.privateCompiledDir + "/" + args.get("pubKey").getAsString();
}
File dir = new File(path);
if (!dir.exists()) {
LOGGER.debug("mkdir " + dir.getAbsoluteFile() + ": " + dir.mkdirs());
}
FileOutputStream fout = null;
if (!isAppend) {
try {
fout = new FileOutputStream(new File(dir, fileName));
fileMap.put(fileName, fout);
} catch (FileNotFoundException e) {
e.printStackTrace();
}
} else {
fout = fileMap.get(fileName);
}
if (isDone) {
if (fout != null)
try {
fout.close();
fileMap.remove(fileName);
} catch (IOException e) {
e.printStackTrace();
}
LOGGER.debug("receive finish.");
Map<String, String> req = new HashMap<>();
req.put("action", "onReceiveProject");
req.put("requestID", args.get("requestID").getAsString());
req.put("nodeID", nodeID);
req.put("progress", "100");
rc.onResult(JsonUtil.toJson(req));
} else {
String data = args.get("data").getAsString();
byte[] byteData = ByteUtil.decodeBASE64(data);
try {
if (null != fout && null != byteData) {
fout.write(byteData);
}
} catch (IOException e) {
e.printStackTrace();
} }
} catch (Exception e) {
e.printStackTrace();
} }
} }
public void queryNCRepoDOI(JsonObject json, ResultCallback result) { public void queryNCRepoDOI(JsonObject json, ResultCallback result) {
LOGGER.debug("sendProject: position ---- 3");
String projectName = json.get("projectName").getAsString(); String projectName = json.get("projectName").getAsString();
LOGGER.debug("sendProject: position ---- 3\tprojectName=" + projectName);
String parPath = GlobalConf.instance.publicCompiledDir; String parPath = GlobalConf.instance.publicCompiledDir;
boolean isPrivate = false; boolean isPrivate = false;
if (json.has("isPrivate") && json.get("isPrivate").getAsBoolean()) { if (json.has("isPrivate") && json.get("isPrivate").getAsBoolean()) {
@ -557,11 +601,11 @@ public class NodeCenterClientController implements NodeCenterConn {
LOGGER.debug("tempZip = " + tempZip.getAbsolutePath()); LOGGER.debug("tempZip = " + tempZip.getAbsolutePath());
try { try {
FileInputStream fin = new FileInputStream(tempZip); FileInputStream fin = new FileInputStream(tempZip);
byte[] buff = new byte[500 * 1024]; byte[] buff = new byte[30 * 1024];
long total = tempZip.length(); long total = tempZip.length();
LOGGER.debug("temp length = " + total); LOGGER.debug("temp length = " + total);
long count = 0; long count = 0;
for (int len; (len = (fin.read(buff))) > 0;) { for (int len; (len = (fin.read(buff))) > 0; ) {
LOGGER.debug("read len = " + len); LOGGER.debug("read len = " + len);
req.put("data", ByteUtil.encodeBASE64(buff, len)); req.put("data", ByteUtil.encodeBASE64(buff, len));
count += len; count += len;
@ -625,8 +669,8 @@ public class NodeCenterClientController implements NodeCenterConn {
MasterElectTimeRecorder.slaveConnectFinish = System.currentTimeMillis(); MasterElectTimeRecorder.slaveConnectFinish = System.currentTimeMillis();
// 开启master恢复 // 开启master恢复
MasterServerRecoverMechAction.newMasterRecover(contractID, MasterServerRecoverMechAction.newMasterRecover(
json.get("members").getAsString(), onlineMembers); contractID, json.get("members").getAsString(), onlineMembers);
} }
private boolean waitForConnection(List<String> nodeNames) { private boolean waitForConnection(List<String> nodeNames) {
@ -646,8 +690,7 @@ public class NodeCenterClientController implements NodeCenterConn {
e.printStackTrace(); e.printStackTrace();
} }
} }
} else } else return true;
return true;
} }
return false; return false;
} }
@ -658,34 +701,18 @@ public class NodeCenterClientController implements NodeCenterConn {
} }
@Action(async = true) @Action(async = true)
public void onDistribute(JsonObject json, ResultCallback rc) throws IOException { public void onDistribute(JsonObject json, ResultCallback rc) {
if (json.has("over")) { if (json.has("over")) {
String distributeID = null; String distributeID = json.get("distributeID").getAsString();
if (json.has("distributeID"))
distributeID = json.get("distributeID").getAsString();
else
distributeID = json.get("responseID").getAsString();
ResultCallback to = distributeReqMap.get(distributeID); ResultCallback to = distributeReqMap.get(distributeID);
distributeReqMap.remove(distributeID); distributeReqMap.remove(distributeID);
to.onResult(json.get("content").getAsString()); to.onResult(json.get("content").getAsString());
if (to instanceof Closeable) {
((Closeable) to).close();
}
} else { } else {
String distributeID = json.get("distributeID").getAsString(); String distributeID = json.get("distributeID").getAsString();
distributeReqMap.get(distributeID).onResult(json.get("content").getAsString()); distributeReqMap.get(distributeID).onResult(json.get("content").getAsString());
} }
} }
@Action(async = true)
public void onDistributeYPK(JsonObject json, ResultCallback rc) {
try {
onDistribute(json, rc);
} catch (IOException e) {
e.printStackTrace();
}
}
@Action(async = true) @Action(async = true)
public void transferInstance(JsonObject jo, ResultCallback result) { public void transferInstance(JsonObject jo, ResultCallback result) {
LOGGER.info("transferInstance"); LOGGER.info("transferInstance");
@ -716,11 +743,13 @@ public class NodeCenterClientController implements NodeCenterConn {
public void NCStartElect(JsonObject jo, ResultCallback result) { public void NCStartElect(JsonObject jo, ResultCallback result) {
String conID = jo.get("contractID").getAsString(); String conID = jo.get("contractID").getAsString();
String uniNumber = null; String uniNumber = null;
if (jo.has("nuiNumber")) if (jo.has("nuiNumber")) uniNumber = jo.get("nuiNumber").getAsString();
uniNumber = jo.get("nuiNumber").getAsString();
ContractClient cc = CMActions.manager.getClient(conID); ContractClient cc = CMActions.manager.getClient(conID);
LOGGER.info("[CMClientController] NCStartElect : contractID=" + conID + " client==null:" LOGGER.info(
+ (null == cc)); "[CMClientController] NCStartElect : contractID="
+ conID
+ " client==null:"
+ (null == cc));
// 不是自己本地的合约 // 不是自己本地的合约
if (null == cc) { if (null == cc) {
@ -757,91 +786,4 @@ public class NodeCenterClientController implements NodeCenterConn {
} }
} }
} }
class ReceiveFileThread extends Thread {
private final Map<String, FileOutputStream> fileMap = new HashMap<>();
ReceiveFileThread() {
super();
this.start();
}
public void run() {
for (;;) {
if (receiveQueue.size() > 0) {
try {
JsonObject jo = receiveQueue.poll();
receiveProject(jo);
} catch (Exception e) {
e.printStackTrace();
}
} else {
synchronized (ReceiveFileThread.this) {
try {
this.wait();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
}
}
public void receiveProject(JsonObject args) {
String fileName = args.get("fileName").getAsString();
boolean isAppend = args.get("isAppend").getAsBoolean();
boolean isDone = args.get("isDone").getAsBoolean();
boolean isPrivate = args.get("isPrivate").getAsBoolean();
LOGGER.debug(String.format("isAppend=%b isDone=%b isPrivate=%b", isAppend, isDone,
isPrivate));
String path = GlobalConf.instance.publicCompiledDir;
if (isPrivate && args.has("pubKey")) {
path = GlobalConf.instance.privateCompiledDir + "/"
+ args.get("pubKey").getAsString();
}
File dir = new File(path);
if (!dir.exists()) {
LOGGER.debug("mkdir " + dir.getAbsoluteFile() + ": " + dir.mkdirs());
}
FileOutputStream fout = null;
if (!isAppend) {
try {
fout = new FileOutputStream(new File(dir, fileName));
fileMap.put(fileName, fout);
} catch (FileNotFoundException e) {
e.printStackTrace();
}
} else {
fout = fileMap.get(fileName);
}
if (isDone) {
if (fout != null)
try {
fout.close();
fileMap.remove(fileName);
} catch (IOException e) {
e.printStackTrace();
}
LOGGER.debug("receive finish.");
Map<String, String> req = new HashMap<>();
req.put("action", "onReceiveProject");
req.put("requestID", args.get("requestID").getAsString());
req.put("nodeID", nodeID);
req.put("progress", "100");
NetworkManager.instance.sendToNodeCenter(JsonUtil.toJson(req));
} else {
String data = args.get("data").getAsString();
byte[] byteData = ByteUtil.decodeBASE64(data);
try {
if (null != fout && null != byteData) {
fout.write(byteData);
}
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
} }

View File

@ -20,6 +20,7 @@ import java.io.ByteArrayInputStream;
import java.io.InputStreamReader; import java.io.InputStreamReader;
import java.util.HashMap; import java.util.HashMap;
import java.util.Map; import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;
import static org.bdware.server.CMHttpServer.pluginLoader; import static org.bdware.server.CMHttpServer.pluginLoader;
@ -30,7 +31,7 @@ public class NodeCenterClientHandler extends SimpleChannelInboundHandler<Object>
public boolean hasPermission; public boolean hasPermission;
private final NodeCenterClientController controller; private final NodeCenterClientController controller;
Channel channel; Channel channel;
// UDPTrustfulExecutor udpExecutor; // UDPTrustfulExecutor udpExecutor;
// RecoverMechExecutor recoverMechExecutor; // RecoverMechExecutor recoverMechExecutor;
ActionExecutor<ResultCallback, JsonObject> ae; ActionExecutor<ResultCallback, JsonObject> ae;
private boolean isConnected; private boolean isConnected;
@ -81,8 +82,8 @@ public class NodeCenterClientHandler extends SimpleChannelInboundHandler<Object>
} }
public synchronized void sendMsg(String msg) { public synchronized void sendMsg(String msg) {
// logger.debug("[CMClientHandler] sendMsg, TID:" + // logger.debug("[CMClientHandler] sendMsg, TID:" +
// Thread.currentThread().getId() + msg+" isActive:"+channel.isActive()+" // Thread.currentThread().getId() + msg+" isActive:"+channel.isActive()+"
// "+channel.isOpen()); // "+channel.isOpen());
ByteBuf buf = Unpooled.wrappedBuffer(msg.getBytes()); ByteBuf buf = Unpooled.wrappedBuffer(msg.getBytes());
channel.writeAndFlush(buf); channel.writeAndFlush(buf);
@ -99,16 +100,19 @@ public class NodeCenterClientHandler extends SimpleChannelInboundHandler<Object>
final JsonObject arg = final JsonObject arg =
JsonParser.parseReader(new InputStreamReader(new ByteArrayInputStream(bytes))) JsonParser.parseReader(new InputStreamReader(new ByteArrayInputStream(bytes)))
.getAsJsonObject(); .getAsJsonObject();
// logger.debug("[CMClient] receive:" + arg.toString()); // logger.debug("[CMClient] receive:" + arg.toString());
if (arg.has("action")) { if (arg.has("action")) {
final String action = arg.get("action").getAsString(); final String action = arg.get("action").getAsString();
ae.handle(action, arg, new ResultCallback() { ae.handle(
@Override action,
public void onResult(String str) { arg,
sendMsg(str); new ResultCallback() {
} @Override
}); public void onResult(String str) {
sendMsg(str);
}
});
} }
} catch (java.lang.IllegalArgumentException e) { } catch (java.lang.IllegalArgumentException e) {
@ -132,8 +136,7 @@ public class NodeCenterClientHandler extends SimpleChannelInboundHandler<Object>
public void close() { public void close() {
try { try {
isConnected = false; isConnected = false;
if (channel != null) if (channel != null) channel.close();
channel.close();
} catch (Exception e) { } catch (Exception e) {
e.printStackTrace(); e.printStackTrace();
} finally { } finally {

View File

@ -40,10 +40,16 @@ public class TCPClientFrameHandler extends SimpleChannelInboundHandler<Object> {
public TCPClientFrameHandler(String masterPubkey) { public TCPClientFrameHandler(String masterPubkey) {
master = masterPubkey; master = masterPubkey;
aliveCheckClientAction = new AliveCheckClientAction(masterPubkey); aliveCheckClientAction = new AliveCheckClientAction(masterPubkey);
ae = new ActionExecutor<>(executorService, aliveCheckClientAction, ae = new ActionExecutor<>(
new MasterClientTCPAction(), new MasterClientRecoverMechAction(), executorService,
MasterClientTransferAction.instance, new MasterServerRecoverMechAction(), aliveCheckClientAction,
new MasterServerTransferAction(), new MasterServerTCPAction(), new EventActions()); new MasterClientTCPAction(),
new MasterClientRecoverMechAction(),
MasterClientTransferAction.instance,
new MasterServerRecoverMechAction(),
new MasterServerTransferAction(),
new MasterServerTCPAction(),
new EventActions());
for (String str : clientToAgentPlugins) { for (String str : clientToAgentPlugins) {
Object obj = createInstanceByClzName(str); Object obj = createInstanceByClzName(str);
ae.appendHandler(obj); ae.appendHandler(obj);
@ -60,22 +66,21 @@ public class TCPClientFrameHandler extends SimpleChannelInboundHandler<Object> {
} }
// public void updateContractID2Client(String contract) { // public void updateContractID2Client(String contract) {
// // 如果该合约正在和旧的master保持连接 // // 如果该合约正在和旧的master保持连接
// if (MasterClientTCPAction.contractID2MasterInfo.containsKey(contract)) { // if (MasterClientTCPAction.contractID2MasterInfo.containsKey(contract)) {
// MasterClientTCPAction former = // MasterClientTCPAction former =
// MasterClientTCPAction.contractID2MasterInfo.get(contract); // MasterClientTCPAction.contractID2MasterInfo.get(contract);
// former.closeMaster(); // former.closeMaster();
// } // }
// //
// MasterClientTCPAction.contractID2MasterInfo.put(contract, actions); // MasterClientTCPAction.contractID2MasterInfo.put(contract, actions);
// } // }
public void close() { public void close() {
try { try {
aliveCheckClientAction.closeMaster(); aliveCheckClientAction.closeMaster();
if (channel != null) if (channel != null) channel.close();
channel.close();
} catch (Exception e) { } catch (Exception e) {
e.printStackTrace(); e.printStackTrace();
} finally { } finally {
@ -103,8 +108,7 @@ public class TCPClientFrameHandler extends SimpleChannelInboundHandler<Object> {
ByteBuf bb = (ByteBuf) frame; ByteBuf bb = (ByteBuf) frame;
JsonObject arg; JsonObject arg;
try { try {
arg = JsonUtil arg = JsonUtil.parseReaderAsJsonObject(new InputStreamReader(new ByteBufInputStream(bb)));
.parseReaderAsJsonObject(new InputStreamReader(new ByteBufInputStream(bb)));
} catch (Exception e) { } catch (Exception e) {
e.printStackTrace(); e.printStackTrace();
Response response = new Response(); Response response = new Response();
@ -115,6 +119,7 @@ public class TCPClientFrameHandler extends SimpleChannelInboundHandler<Object> {
} }
Response response; Response response;
try { try {
//LOGGER.info("====== TCPClientFrameHandler:" + arg.toString());
final String action = arg.get("action").getAsString(); final String action = arg.get("action").getAsString();
PubkeyResultCallback pc = new PubkeyResultCallback(master, new ResultCallback() { PubkeyResultCallback pc = new PubkeyResultCallback(master, new ResultCallback() {
@Override @Override
@ -122,7 +127,10 @@ public class TCPClientFrameHandler extends SimpleChannelInboundHandler<Object> {
sendMsg(ret); sendMsg(ret);
} }
}); });
ae.handle(action, arg, pc); ae.handle(
action,
arg, pc
);
} catch (IllegalArgumentException e) { } catch (IllegalArgumentException e) {
response = new Response(); response = new Response();
response.action = "onException"; response.action = "onException";
@ -138,9 +146,12 @@ public class TCPClientFrameHandler extends SimpleChannelInboundHandler<Object> {
StringBuilder ret = new StringBuilder(); StringBuilder ret = new StringBuilder();
int count = 0; int count = 0;
for (String s : strs) { for (String s : strs) {
if (s.contains("sun.reflect") || s.contains("java.lang.reflect") if (s.contains("sun.reflect")
|| s.contains("org.apache") || s.contains("java.util") || s.contains("java.lang.reflect")
|| s.contains("java.lang") || s.contains("io.netty")) { || s.contains("org.apache")
|| s.contains("java.util")
|| s.contains("java.lang")
|| s.contains("io.netty")) {
continue; continue;
} }
ret.append(s); ret.append(s);

View File

@ -31,44 +31,52 @@ public class TCPServerFrameHandler extends SimpleChannelInboundHandler<Object> {
public TCPServerFrameHandler() { public TCPServerFrameHandler() {
checkAction = new AliveCheckServerAction(this); checkAction = new AliveCheckServerAction(this);
ae = new ActionExecutor<ResultCallback, JsonObject>(executorService, checkAction, ae =
new MasterClientTCPAction(), new MasterClientRecoverMechAction(), new ActionExecutor<ResultCallback, JsonObject>(
MasterClientTransferAction.instance, new MasterServerRecoverMechAction(), executorService,
new MasterServerTransferAction(), new MasterServerTCPAction(), new EventActions()) { checkAction,
@Override new MasterClientTCPAction(),
public boolean checkPermission(Action a, final JsonObject args, long permission) { new MasterClientRecoverMechAction(),
return true; MasterClientTransferAction.instance,
// long val = a.userPermission(); new MasterServerRecoverMechAction(),
// new MasterServerTransferAction(),
// boolean flag; new MasterServerTCPAction(),
// String status = "refuse"; new EventActions()) {
// String action = args.get("action"); @Override
// public boolean checkPermission(
// if (val == 0) { Action a, final JsonObject args, long permission) {
// flag = true; return true;
// status = "accept"; // long val = a.userPermission();
// } else if ((permission & val) == val) { //
// flag = true; // boolean flag;
// status = "accept"; // String status = "refuse";
// } else { // String action = args.get("action");
// flag = false; //
// } // if (val == 0) {
// // flag = true;
// TimeDBUtil.instance.put( // status = "accept";
// NCTables.CMLog.toString(), // } else if ((permission & val) == val) {
// "{\"action\":\"" // flag = true;
// + action // status = "accept";
// + "\",\"pubKey\":\"" // } else {
// + pubKey // flag = false;
// + "\",\"status\":\"" // }
// + status //
// + "\",\"date\":" // TimeDBUtil.instance.put(
// + System.currentTimeMillis() // NCTables.CMLog.toString(),
// + "}"); // "{\"action\":\""
// // + action
// return flag; // + "\",\"pubKey\":\""
} // + pubKey
}; // + "\",\"status\":\""
// + status
// + "\",\"date\":"
// + System.currentTimeMillis()
// + "}");
//
// return flag;
}
};
} }
@ -90,9 +98,8 @@ public class TCPServerFrameHandler extends SimpleChannelInboundHandler<Object> {
ByteBuf bb = (ByteBuf) frame; ByteBuf bb = (ByteBuf) frame;
JsonObject arg; JsonObject arg;
try { try {
arg = JsonUtil arg = JsonUtil.parseReaderAsJsonObject(new InputStreamReader(new ByteBufInputStream(bb)));
.parseReaderAsJsonObject(new InputStreamReader(new ByteBufInputStream(bb))); // logger.info("[MasterServer] receive:" + arg.toString());
// logger.info("[MasterServer] receive:" + arg.toString());
} catch (Exception e) { } catch (Exception e) {
e.printStackTrace(); e.printStackTrace();
@ -107,14 +114,16 @@ public class TCPServerFrameHandler extends SimpleChannelInboundHandler<Object> {
final String action = arg.get("action").getAsString(); final String action = arg.get("action").getAsString();
PubkeyResultCallback pubkeyResultCallback = PubkeyResultCallback pubkeyResultCallback = new PubkeyResultCallback(checkAction.pubKey, new ResultCallback() {
new PubkeyResultCallback(checkAction.pubKey, new ResultCallback() { @Override
@Override public void onResult(String ret) {
public void onResult(String ret) { sendMsg(ret);
sendMsg(ret); }
} });
}); ae.handle(
ae.handle(action, arg, pubkeyResultCallback); action,
arg, pubkeyResultCallback
);
} catch (IllegalArgumentException e) { } catch (IllegalArgumentException e) {
response = new Response(); response = new Response();
@ -132,9 +141,12 @@ public class TCPServerFrameHandler extends SimpleChannelInboundHandler<Object> {
StringBuilder ret = new StringBuilder(); StringBuilder ret = new StringBuilder();
int count = 0; int count = 0;
for (String s : strs) { for (String s : strs) {
if (s.contains("sun.reflect") || s.contains("java.lang.reflect") if (s.contains("sun.reflect")
|| s.contains("org.apache") || s.contains("java.util") || s.contains("java.lang.reflect")
|| s.contains("java.lang") || s.contains("io.netty")) { || s.contains("org.apache")
|| s.contains("java.util")
|| s.contains("java.lang")
|| s.contains("io.netty")) {
continue; continue;
} }
ret.append(s); ret.append(s);

View File

@ -33,24 +33,28 @@ public class AgentManager implements AgentPeerManagerIntf {
@Override @Override
public void executeByOtherNodeAsync(String pubKey, ContractRequest c, ResultCallback cb) { public void executeByOtherNodeAsync(String pubKey, ContractRequest c, ResultCallback cb) {
LOGGER.debug(pubKey + " " + c.getRequestID() + " " + c.getContractID() + " cb:" + cb); LOGGER.error(pubKey + " " + c.getRequestID() + " " + c.getContractID() + " cb:" + cb);
int maxMasterProxyLoad = CongestionControl.masterProxyLoad.incrementAndGet(); int maxMasterProxyLoad = CongestionControl.masterProxyLoad.incrementAndGet();
if (maxMasterProxyLoad > CongestionControl.maxMasterProxyLoad) if (maxMasterProxyLoad > CongestionControl.maxMasterProxyLoad)
CongestionControl.maxMasterProxyLoad = maxMasterProxyLoad; CongestionControl.maxMasterProxyLoad = maxMasterProxyLoad;
if (CongestionControl.slaveControl()) { if (CongestionControl.slaveControl()) {
ContractResult cr = new ContractResult(ContractResult.Status.Error, ContractResult cr =
new JsonPrimitive("canceled because of queue too long")); new ContractResult(
ContractResult.Status.Error,
new JsonPrimitive("canceled because of queue too long"));
cb.onResult(JsonUtil.parseObjectAsJsonObject(cr)); cb.onResult(JsonUtil.parseObjectAsJsonObject(cr));
CongestionControl.masterProxyLoad.decrementAndGet(); CongestionControl.masterProxyLoad.decrementAndGet();
return; return;
} }
MasterServerTCPAction.sync.sleep(c.getRequestID(), new ResultCallback() { MasterServerTCPAction.sync.sleep(
@Override c.getRequestID(),
public void onResult(String str) { new ResultCallback() {
cb.onResult(JsonUtil.parseStringAsJsonObject(str)); @Override
CongestionControl.masterProxyLoad.decrementAndGet(); public void onResult(String str) {
} cb.onResult(JsonUtil.parseStringAsJsonObject(str));
}); CongestionControl.masterProxyLoad.decrementAndGet();
}
});
Map<String, Object> req = new HashMap<>(); Map<String, Object> req = new HashMap<>();
req.put("action", "requestContractExecutionServer"); req.put("action", "requestContractExecutionServer");
req.put("requestID", c.getRequestID()); req.put("requestID", c.getRequestID());
@ -89,8 +93,8 @@ public class AgentManager implements AgentPeerManagerIntf {
@Override @Override
public void transferToOtherNode(String pubKey, String contractID) { public void transferToOtherNode(String pubKey, String contractID) {
// TODO 问题1合约的ypk或者script怎么获取ypk如果是包含私有路径的可以在Contract中设置一个字段启动的时候写入吗 目前认为这个从前端传入 // TODO 问题1合约的ypk或者script怎么获取ypk如果是包含私有路径的可以在Contract中设置一个字段启动的时候写入吗 目前认为这个从前端传入
// TODO 问题2 转移过程中进度返回给哪个前端显示需要显示吗 // TODO 问题2 转移过程中进度返回给哪个前端显示需要显示吗
LOGGER.info("transferToOtherNode : pubKey=" + pubKey + " contractID=" + contractID); LOGGER.info("transferToOtherNode : pubKey=" + pubKey + " contractID=" + contractID);
ContractMeta meta = CMActions.manager.statusRecorder.getContractMeta(contractID); ContractMeta meta = CMActions.manager.statusRecorder.getContractMeta(contractID);
MasterClientTransferAction.instance.transferInstance(pubKey, meta.getID()); MasterClientTransferAction.instance.transferInstance(pubKey, meta.getID());

View File

@ -9,7 +9,7 @@ import java.util.Map;
import java.util.concurrent.atomic.AtomicInteger; import java.util.concurrent.atomic.AtomicInteger;
public class KillUnitContractResultCollector extends ResultCallback { public class KillUnitContractResultCollector extends ResultCallback {
// private static final Logger LOGGER = LogManager.getLogger(ResultCallback.class); // private static final Logger LOGGER = LogManager.getLogger(ResultCallback.class);
int total; int total;
String requestID; String requestID;
AtomicInteger count = new AtomicInteger(0); AtomicInteger count = new AtomicInteger(0);
@ -24,9 +24,9 @@ public class KillUnitContractResultCollector extends ResultCallback {
@Override @Override
public void onResult(String str) { public void onResult(String str) {
// 解析str判断该节点是否kill成功 //解析str判断该节点是否kill成功
Map<String, String> map = Map<String, String> map = JsonUtil.fromJson(str, new TypeToken<Map<String, String>>() {
JsonUtil.fromJson(str, new TypeToken<Map<String, String>>() {}.getType()); }.getType());
String data = map.get("data"); String data = map.get("data");
if (data != null && data.equals("success")) { if (data != null && data.equals("success")) {
// //

View File

@ -5,9 +5,9 @@ import org.bdware.sc.bean.ContractExecType;
import java.util.List; import java.util.List;
import java.util.concurrent.atomic.AtomicInteger; import java.util.concurrent.atomic.AtomicInteger;
// 在master上 //在master上
public class MultiPointContractInfo { public class MultiPointContractInfo {
public List<String> members; // pubKey public List<String> members; //pubKey
public String masterNode; public String masterNode;
public ContractExecType type; public ContractExecType type;
public ContractUnitStatus unitStatus = ContractUnitStatus.CommonMode; public ContractUnitStatus unitStatus = ContractUnitStatus.CommonMode;

View File

@ -5,10 +5,10 @@ import org.bdware.sc.bean.ContractExecType;
import java.util.List; import java.util.List;
import java.util.concurrent.atomic.AtomicInteger; import java.util.concurrent.atomic.AtomicInteger;
// 改名 MultiPointCooperateContractInfo //改名 MultiPointCooperateContractInfo
public class MultiPointCooperateContractInfo extends MultiPointContractInfo { public class MultiPointCooperateContractInfo extends MultiPointContractInfo {
public List<String> members; // pubKey public List<String> members; //pubKey
public List<Integer> shardingId; // sharding id 初始化时被分配 public List<Integer> shardingId; //sharding id 初始化时被分配
public String masterNode; public String masterNode;
public ContractExecType type; public ContractExecType type;
public ContractUnitStatus unitStatus = ContractUnitStatus.CommonMode; public ContractUnitStatus unitStatus = ContractUnitStatus.CommonMode;

View File

@ -0,0 +1,11 @@
package org.bdware.server.trustedmodel;
public class MultiReqSeq {
public final int seq;
public final long startTime;
public MultiReqSeq(int s){
seq = s;
startTime = System.currentTimeMillis();
}
}

View File

@ -6,7 +6,7 @@ import org.bdware.server.action.p2p.MasterServerTCPAction;
import java.util.concurrent.atomic.AtomicInteger; import java.util.concurrent.atomic.AtomicInteger;
public class ResultCollector extends ResultCallback { public class ResultCollector extends ResultCallback {
// private static final Logger LOGGER = LogManager.getLogger(ResultCallback.class); // private static final Logger LOGGER = LogManager.getLogger(ResultCallback.class);
int total; int total;
String requestID; String requestID;
AtomicInteger count = new AtomicInteger(0); AtomicInteger count = new AtomicInteger(0);

View File

@ -0,0 +1,305 @@
package org.bdware.server.trustedmodel;
import com.google.gson.JsonObject;
import com.google.gson.JsonPrimitive;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import org.bdware.sc.ContractClient;
import org.bdware.sc.ContractManager;
import org.bdware.sc.ContractResult;
import org.bdware.sc.bean.ContractRequest;
import org.bdware.sc.bean.FunctionDesp;
import org.bdware.sc.bean.SM2Verifiable;
import org.bdware.sc.conn.OnHashCallback;
import org.bdware.sc.conn.ResultCallback;
import org.bdware.sc.units.MultiContractMeta;
import org.bdware.sc.units.RecoverFlag;
import org.bdware.sc.util.HashUtil;
import org.bdware.sc.util.JsonUtil;
import org.bdware.server.action.CMActions;
import org.bdware.server.action.p2p.MasterServerRecoverMechAction;
import org.bdware.units.NetworkManager;
import java.util.*;
import java.util.concurrent.*;
import java.util.stream.Collectors;
/**
* @author Kaidong Wu
*/
public class SelfAdaptiveShardingExecutor implements ContractExecutor {
private static final Logger LOGGER = LogManager.getLogger(SelfAdaptiveShardingExecutor.class);
private static final int SUBMIT_LIMIT = 1024;
private final Queue<ContractRequest> reqQueue = new ConcurrentLinkedQueue<>();
private final MultiContractMeta meta;
private final Map<String, Block> toExecuted = new ConcurrentHashMap<>();
private final Set<String> executedBlocks = ConcurrentHashMap.newKeySet();
private final Map<String, Boolean> executedTxs = new ConcurrentHashMap<>();
private final Object flag = new Object();
private final ScheduledFuture<?> future;
private boolean running = true;
private Block b = new Block();
public SelfAdaptiveShardingExecutor(String contractID) {
this.meta =
CMActions.manager.multiContractRecorder.getMultiContractMeta(contractID);
this.future = ContractManager.scheduledThreadPool.scheduleWithFixedDelay(
this::submitBlock,
2,
2,
TimeUnit.SECONDS);
LOGGER.debug(String.format("ContractManager.threadPool=%d/%d",
((ThreadPoolExecutor) ContractManager.threadPool).getActiveCount(),
((ThreadPoolExecutor) ContractManager.threadPool).getPoolSize()));
ContractManager.threadPool.execute(() -> {
LOGGER.info(
"[SelfAdaptiveShardingExecutor " + meta.getContractID() + "] starting service..." + running);
while (running) {
LOGGER.info("checking blocks to be executed, latest block=" +
this.b.prevHash + ", to be executed size=" + toExecuted.size());
LOGGER.debug("executed: " + JsonUtil.toJson(executedBlocks) + "\n\t" + JsonUtil.toJson(executedTxs));
while (!toExecuted.isEmpty()) {
String key = this.b.prevHash;
Block block = toExecuted.get(key);
if (null != block) {
executeBlock(block);
}
toExecuted.remove(key);
}
synchronized (flag) {
try {
flag.wait();
} catch (InterruptedException e) {
LOGGER.warn(String.format(
"[SelfAdaptiveShardingExecutor %s] waiting is interrupted: %s",
meta.getContractID(),
e.getMessage()));
}
}
}
});
}
@Override
public void execute(String requestID, ContractRequest req, ResultCallback rcb, OnHashCallback hcb) {
// check client
ContractClient client = CMActions.manager.getClient(meta.getContractID());
if (null == client) {
LOGGER.error("contract " + meta.getContractID() + " not found!");
rcb.onResult(JsonUtil.toJson(new ContractResult(
ContractResult.Status.Error,
new JsonPrimitive("contract " + meta.getContractID() + " not found!"))));
return;
}
// check function
FunctionDesp funDesp = client.contractMeta.getExportedFunction(req.getAction());
if (null == funDesp) {
LOGGER.warn("action " + req.getAction() + " of contract " + meta.getContractID() + " not found!");
rcb.onResult(JsonUtil.toJson(new ContractResult(
ContractResult.Status.Error,
new JsonPrimitive(
String.format("action %s of contract %s not found!",
req.getAction(),
meta.getContractID())))));
return;
}
// for view function, execute it
if (funDesp.isView) {
CMActions.manager.executeLocallyAsync(req, rcb, hcb);
return;
}
// normal function, check if it is in blocks
if (executedTxs.containsKey(requestID)) {
rcb.onResult(JsonUtil.toJson(new ContractResult(
ContractResult.Status.Error,
new JsonPrimitive("this request has been packed!"))));
return;
}
// add blocks into request cache
LOGGER.debug("receive contract request " + requestID);
executedTxs.put(requestID, false);
reqQueue.add(req);
rcb.onResult(JsonUtil.toJson(new ContractResult(
ContractResult.Status.Executing,
new JsonPrimitive("this request is adding into blocks"))));
// if cache is full, submit
if (reqQueue.size() >= SUBMIT_LIMIT) {
ContractManager.threadPool.execute(this::submitBlock);
}
}
@Override
public void close() {
// stop threads
this.future.cancel(true);
this.running = false;
LOGGER.info("destruct executor of contract " + meta.getContractID());
}
public void execute(String blockStr) {
Block block = JsonUtil.fromJson(blockStr, Block.class);
// the block must have not been cached or executed, and must be valid
if (!toExecuted.containsKey(block.prevHash) &&
!executedBlocks.contains(block.hash) &&
block.isValid()) {
// add block into block cache
LOGGER.info(String.format(
"[SelfAdaptiveShardingExecutor %s] receive block %s -> %s," +
" %d transactions, timestamp=%d, size=%d",
meta.getContractID(),
block.hash,
block.prevHash,
block.requests.length,
block.timestamp,
blockStr.length()));
toExecuted.put(block.prevHash, block);
// notify thread to execute blocks
synchronized (flag) {
flag.notify();
}
}
}
private synchronized void executeBlock(Block block) {
// used for the thread to execute blocks
LOGGER.debug("start");
// check contract requests, requests must have not been executed
for (ContractRequest request : block.requests) {
if (executedTxs.containsKey(request.getRequestID()) && executedTxs.get(request.getRequestID())) {
LOGGER.debug("find request " + request.getRequestID() + " has been executed!");
return;
}
}
// TODO check status
// executed requests
for (ContractRequest request : block.requests) {
String ret = CMActions.manager.executeLocally(request, null);
LOGGER.debug(String.format(
"[SelfAdaptiveShardingExecutor %s] result of request %s: %s",
meta.getContractID(),
request.getRequestID(),
ret));
executedTxs.put(request.getRequestID(), true);
}
LOGGER.info(String.format(
"[SelfAdaptiveShardingExecutor %s] execute %d transactions of block %s",
meta.getContractID(),
block.requests.length,
block.hash));
// TODO create check point
this.b = new Block(block.hash, this.b.height + 1);
executedBlocks.add(block.hash);
}
private void submitBlock() {
Block block = fillBlock();
if (null != block) {
LOGGER.info("deliver block " + block.hash + "...");
LOGGER.debug(JsonUtil.toPrettyJson(block));
String[] nodes = this.meta.getMembers();
JsonObject req = new JsonObject();
req.addProperty("action", "deliverBlock");
req.addProperty("data", JsonUtil.toJson(block));
req.addProperty("contractID", this.meta.getContractID());
String reqStr = req.toString();
// deliver blocks
for (String node : nodes) {
if (MasterServerRecoverMechAction.recoverStatus.get(node).get(this.meta.getContractID())
== RecoverFlag.Fine) {
NetworkManager.instance.sendToAgent(node, reqStr);
}
}
}
}
private synchronized Block fillBlock() {
// pack contract requests into a block
ContractRequest[] requests = new ContractRequest[Math.min(reqQueue.size(), SUBMIT_LIMIT)];
if (requests.length == 0) {
return null;
}
for (int i = 0; i < requests.length; ++i) {
requests[i] = reqQueue.poll();
}
this.b.fillBlock(requests);
return this.b;
}
static class Block extends SM2Verifiable {
String prevHash = "0";
String hash;
int height;
String checkPoint;
String body;
String nodePubKey;
ContractRequest[] requests;
long timestamp;
public Block() {
this.height = 0;
}
public Block(String prev, int height) {
this.prevHash = prev;
this.height = height;
}
public void fillBlock(ContractRequest[] requests) {
this.requests = requests;
this.timestamp = System.currentTimeMillis();
this.body = merkle(requests);
this.hash = computeHash();
doSignature(CMActions.manager.nodeCenterConn.getNodeKeyPair());
}
public boolean isValid() {
return computeHash().equals(hash) && body.equals(merkle(this.requests)) && verifySignature();
}
private String computeHash() {
return HashUtil.sha3(
String.valueOf(this.height),
this.prevHash,
this.checkPoint,
this.body);
}
private String merkle(ContractRequest[] requests) {
// manage requests as a merkle tree
if (requests.length == 0) {
return null;
}
if (requests.length == 1) {
return HashUtil.sha3(requests[0].getRequestID());
}
Queue<String> reqQueue =
Arrays.stream(requests).map(ContractRequest::getRequestID)
.collect(Collectors.toCollection(ArrayDeque::new));
do {
int size;
for (size = reqQueue.size(); size > 1; size -= 2) {
reqQueue.add(HashUtil.sha3(reqQueue.poll(), reqQueue.poll()));
}
if (size == 1) {
reqQueue.add(reqQueue.poll());
}
} while (1 != reqQueue.size());
return reqQueue.poll();
}
@Override
public String getPublicKey() {
return nodePubKey;
}
@Override
public void setPublicKey(String pubkey) {
this.nodePubKey = pubkey;
}
@Override
public String getContentStr() {
return this.hash;
}
}
}

View File

@ -29,7 +29,7 @@ public class ContractManagerFrameHandler extends SimpleChannelInboundHandler<Web
public FileActions fileAction; public FileActions fileAction;
CMActions cmAction; CMActions cmAction;
// TemporyTestAction temAction; //TemporyTestAction temAction;
StringBuilder dataCache = new StringBuilder(); StringBuilder dataCache = new StringBuilder();
// TODO optimize ae-> too much method? // TODO optimize ae-> too much method?
@ -45,41 +45,60 @@ public class ContractManagerFrameHandler extends SimpleChannelInboundHandler<Web
public void initActionExecutor() { public void initActionExecutor() {
CongestionControl.wsCounter.getAndIncrement(); CongestionControl.wsCounter.getAndIncrement();
cmAction = new CMActions(this); cmAction = new CMActions(this);
// temAction = new TemporyTestAction(); //temAction = new TemporyTestAction();
fileAction = new FileActions(this); fileAction = new FileActions(this);
userManagerAction = new UserManagerAction(this); userManagerAction = new UserManagerAction(this);
ae = new ActionExecutor<ResultCallback, JsonObject>(executorService, cmAction, ae =
// temAction, new ActionExecutor<ResultCallback, JsonObject>(
fileAction, ManagerActions.instance, userManagerAction, new MasterWSAction(this), // 多节点执行 executorService,
new CMLogAction(), new ProcessAction(), GRPCPool.instance, new EventWSActions()) { cmAction,
@Override //temAction,
public boolean checkPermission(Action a, JsonObject arg, long permission) { fileAction,
long val = a.userPermission(); ManagerActions.instance,
userManagerAction,
new MasterWSAction(userManagerAction), // 多节点执行
new CMLogAction(),
new ProcessAction(),
GRPCPool.instance,
new EventWSActions()) {
@Override
public boolean checkPermission(Action a, JsonObject arg, long permission) {
long val = a.userPermission();
boolean flag; boolean flag;
String status = "refuse"; String status = "refuse";
String action = arg.get("action").getAsString(); String action = arg.get("action").getAsString();
if (val == 0) { if (val == 0) {
flag = true; flag = true;
status = "accept"; status = "accept";
} else if ((permission & val) == val) { } else if ((permission & val) == val) {
flag = true; flag = true;
status = "accept"; status = "accept";
} else { } else {
flag = false; flag = false;
} }
LOGGER.debug(String.format("%s val:%d permission:%d status:%s", action, val, LOGGER.debug(
permission, status)); String.format(
"%s val:%d permission:%d status:%s",
action,
val,
permission,
status));
CMHttpServer.nodeLogDB.put(action, String.format( CMHttpServer.nodeLogDB.put(
"{\"action\":\"%s\",\"pubKey\":\"%s\",\"status\":\"%s\",\"date\":%d}", action,
action, userManagerAction.getPubKey(), status, System.currentTimeMillis())); String.format(
// TimeDBUtil.instance.put(CMTables.LocalNodeLogDB.toString(), "{\"action\":\"%s\",\"pubKey\":\"%s\",\"status\":\"%s\",\"date\":%d}",
// sb.toString()); action,
return flag; userManagerAction.getPubKey(),
} status,
}; System.currentTimeMillis()));
// TimeDBUtil.instance.put(CMTables.LocalNodeLogDB.toString(),
// sb.toString());
return flag;
}
};
for (String str : CMHttpHandler.wsPluginActions) { for (String str : CMHttpHandler.wsPluginActions) {
Object obj = createInstanceByClzName(str); Object obj = createInstanceByClzName(str);
ae.appendHandler(obj); ae.appendHandler(obj);
@ -137,7 +156,8 @@ public class ContractManagerFrameHandler extends SimpleChannelInboundHandler<Web
dataCache.append(map.get("data").getAsString()); dataCache.append(map.get("data").getAsString());
response = new Response(); response = new Response();
response.action = "sendNextSegment"; response.action = "sendNextSegment";
ctx.channel().writeAndFlush(new TextWebSocketFrame(JsonUtil.toJson(response))); ctx.channel()
.writeAndFlush(new TextWebSocketFrame(JsonUtil.toJson(response)));
return; return;
} else { } else {
if (dataCache.length() > 0) { if (dataCache.length() > 0) {
@ -150,39 +170,41 @@ public class ContractManagerFrameHandler extends SimpleChannelInboundHandler<Web
} }
String action = map.get("action").getAsString(); String action = map.get("action").getAsString();
map.remove("verifiedPubKey"); map.remove("verifiedPubKey");
if (ae == null) if (ae == null) initActionExecutor();
initActionExecutor();
if (userManagerAction.getPubKey() != null if (userManagerAction.getPubKey() != null
&& userManagerAction.getPubKey().length() > 0) { && userManagerAction.getPubKey().length() > 0) {
map.addProperty("verifiedPubKey", userManagerAction.getPubKey()); map.addProperty("verifiedPubKey", userManagerAction.getPubKey());
} }
final JsonObject jmap = map; final JsonObject jmap = map;
ae.handle(action, map, new ResultCallback(ctx.channel()) { ae.handle(
@Override action,
public void onResult(Map jo) { map,
if (jmap.has("requestID")) { new ResultCallback(ctx.channel()) {
jo.put("responseID", jmap.get("requestID").getAsString()); @Override
} public void onResult(Map jo) {
onResult(JsonUtil.toJson(jo)); if (jmap.has("requestID")) {
} jo.put("responseID", jmap.get("requestID").getAsString());
}
onResult(JsonUtil.toJson(jo));
}
@Override @Override
public void onResult(JsonObject jo) { public void onResult(JsonObject jo) {
if (jmap.has("requestID")) { if (jmap.has("requestID")) {
jo.add("responseID", jmap.get("requestID")); jo.add("responseID", jmap.get("requestID"));
} }
onResult(jo.toString()); onResult(jo.toString());
} }
@Override @Override
public void onResult(String ret) { public void onResult(String ret) {
if (ret != null) { if (ret != null) {
ctx.channel().writeAndFlush(new TextWebSocketFrame(ret)); ctx.channel().writeAndFlush(new TextWebSocketFrame(ret));
} }
} }
}); });
} catch (IllegalArgumentException e) { } catch (IllegalArgumentException e) {
response = new Response(); response = new Response();
response.action = "onException"; response.action = "onException";
@ -217,8 +239,7 @@ public class ContractManagerFrameHandler extends SimpleChannelInboundHandler<Web
} }
ret.append(s); ret.append(s);
ret.append("\n"); ret.append("\n");
if (count++ > 5) if (count++ > 5) break;
break;
} }
response.data = ret.toString(); response.data = ret.toString();
ctx.channel().writeAndFlush(new TextWebSocketFrame(JsonUtil.toJson(response))); ctx.channel().writeAndFlush(new TextWebSocketFrame(JsonUtil.toJson(response)));

View File

@ -16,30 +16,26 @@ import org.apache.logging.log4j.Logger;
/** /**
* An HTTP server which serves Web Socket requests at: * An HTTP server which serves Web Socket requests at:
* *
* <p> * <p>http://localhost:8080/websocket
* http://localhost:8080/websocket
* *
* <p> * <p>Open your browser at <a href="http://localhost:8080/">http://localhost:8080/</a>, then the
* Open your browser at <a href="http://localhost:8080/">http://localhost:8080/</a>, then the demo * demo page will be loaded and a Web Socket connection will be made automatically.
* page will be loaded and a Web Socket connection will be made automatically.
* *
* <p> * <p>This server illustrates support for the different web socket specification versions and will
* This server illustrates support for the different web socket specification versions and will work * work with:
* with:
* *
* <ul> * <ul>
* <li>Safari 5+ (draft-ietf-hybi-thewebsocketprotocol-00) * <li>Safari 5+ (draft-ietf-hybi-thewebsocketprotocol-00)
* <li>Chrome 6-13 (draft-ietf-hybi-thewebsocketprotocol-00) * <li>Chrome 6-13 (draft-ietf-hybi-thewebsocketprotocol-00)
* <li>Chrome 14+ (draft-ietf-hybi-thewebsocketprotocol-10) * <li>Chrome 14+ (draft-ietf-hybi-thewebsocketprotocol-10)
* <li>Chrome 16+ (RFC 6455 aka draft-ietf-hybi-thewebsocketprotocol-17) * <li>Chrome 16+ (RFC 6455 aka draft-ietf-hybi-thewebsocketprotocol-17)
* <li>Firefox 7+ (draft-ietf-hybi-thewebsocketprotocol-10) * <li>Firefox 7+ (draft-ietf-hybi-thewebsocketprotocol-10)
* <li>Firefox 11+ (RFC 6455 aka draft-ietf-hybi-thewebsocketprotocol-17) * <li>Firefox 11+ (RFC 6455 aka draft-ietf-hybi-thewebsocketprotocol-17)
* </ul> * </ul>
*/ */
public final class WebSocketServer { public final class WebSocketServer {
private static final boolean SSL = System.getProperty("ssl") != null; private static final boolean SSL = System.getProperty("ssl") != null;
private static final int PORT = private static final int PORT = Integer.parseInt(System.getProperty("port", SSL ? "8443" : "8080"));
Integer.parseInt(System.getProperty("port", SSL ? "8443" : "8080"));
private static final Logger LOGGER = LogManager.getLogger(WebSocketServer.class); private static final Logger LOGGER = LogManager.getLogger(WebSocketServer.class);
public static void main(String[] args) throws Exception { public static void main(String[] args) throws Exception {
@ -56,14 +52,19 @@ public final class WebSocketServer {
EventLoopGroup workerGroup = new NioEventLoopGroup(); EventLoopGroup workerGroup = new NioEventLoopGroup();
try { try {
ServerBootstrap b = new ServerBootstrap(); ServerBootstrap b = new ServerBootstrap();
b.group(bossGroup, workerGroup).channel(NioServerSocketChannel.class) b.group(bossGroup, workerGroup)
.channel(NioServerSocketChannel.class)
.handler(new LoggingHandler(LogLevel.INFO)) .handler(new LoggingHandler(LogLevel.INFO))
.childHandler(new WebSocketServerInitializer(sslCtx)); .childHandler(new WebSocketServerInitializer(sslCtx));
Channel ch = b.bind(PORT).sync().channel(); Channel ch = b.bind(PORT).sync().channel();
LOGGER.info("Open your web browser and navigate to " + (SSL ? "https" : "http") LOGGER.info(
+ "://127.0.0.1:" + PORT + '/'); "Open your web browser and navigate to "
+ (SSL ? "https" : "http")
+ "://127.0.0.1:"
+ PORT
+ '/');
ch.closeFuture().sync(); ch.closeFuture().sync();
} finally { } finally {

View File

@ -13,25 +13,25 @@ import io.netty.handler.ssl.SslContext;
*/ */
public class WebSocketServerInitializer extends ChannelInitializer<SocketChannel> { public class WebSocketServerInitializer extends ChannelInitializer<SocketChannel> {
private static final String WEBSOCKET_PATH = "/websocket"; private static final String WEBSOCKET_PATH = "/websocket";
private final SslContext sslCtx; private final SslContext sslCtx;
public WebSocketServerInitializer(SslContext sslCtx) { public WebSocketServerInitializer(SslContext sslCtx) {
this.sslCtx = sslCtx; this.sslCtx = sslCtx;
} }
@Override @Override
public void initChannel(SocketChannel ch) throws Exception { public void initChannel(SocketChannel ch) throws Exception {
ChannelPipeline pipeline = ch.pipeline(); ChannelPipeline pipeline = ch.pipeline();
if (sslCtx != null) { if (sslCtx != null) {
pipeline.addLast(sslCtx.newHandler(ch.alloc())); pipeline.addLast(sslCtx.newHandler(ch.alloc()));
} }
pipeline.addLast(new HttpServerCodec()); pipeline.addLast(new HttpServerCodec());
pipeline.addLast(new HttpObjectAggregator(65536)); pipeline.addLast(new HttpObjectAggregator(65536));
pipeline.addLast(new WebSocketServerCompressionHandler()); pipeline.addLast(new WebSocketServerCompressionHandler());
pipeline.addLast(new WebSocketServerProtocolHandler(WEBSOCKET_PATH, null, true)); pipeline.addLast(new WebSocketServerProtocolHandler(WEBSOCKET_PATH, null, true));
pipeline.addLast(new WebSocketIndexPageHandler(WEBSOCKET_PATH)); pipeline.addLast(new WebSocketIndexPageHandler(WEBSOCKET_PATH));
pipeline.addLast(new ContractManagerFrameHandler()); pipeline.addLast(new ContractManagerFrameHandler());
} }
} }

View File

@ -41,11 +41,10 @@ import java.util.concurrent.TimeUnit;
* @author OliveDS (Shuang Deng) * @author OliveDS (Shuang Deng)
*/ */
public class NetworkManager { public class NetworkManager {
// Manage server->client connection; //Manage server->client connection;
public static final Map<String, AgentConnector> CONNECTORS = new ConcurrentHashMap<>(); public static final Map<String, AgentConnector> CONNECTORS = new ConcurrentHashMap<>();
// Manage client->server connection; //Manage client->server connection;
public static final Map<String, TCPServerFrameHandler> SERVER_CONNECTORS = public static final Map<String, TCPServerFrameHandler> SERVER_CONNECTORS = new ConcurrentHashMap<>();
new ConcurrentHashMap<>();
public static final String NODE_CENTER_CLIENT = "NODE_CENTER_CLIENT"; public static final String NODE_CENTER_CLIENT = "NODE_CENTER_CLIENT";
public static final String P2P_GRPC_CLIENT = "P2P_GRPC_CLIENT"; public static final String P2P_GRPC_CLIENT = "P2P_GRPC_CLIENT";
private static final Map<String, String> slaverRouter = new HashMap<>(); private static final Map<String, String> slaverRouter = new HashMap<>();
@ -60,13 +59,18 @@ public class NetworkManager {
} }
public static void reconnectAgent(String master) { public static void reconnectAgent(String master) {
LOGGER.debug(String.format("master=%s\t%s", master, JsonUtil.toJson(slaverRouter))); LOGGER.debug(
String.format("master=%s\t%s",
master,
JsonUtil.toJson(slaverRouter)));
try { try {
NetworkManager.AgentConnector conn; NetworkManager.AgentConnector conn;
synchronized (conn = NetworkManager.CONNECTORS.get(master)) { synchronized (conn = NetworkManager.CONNECTORS.get(master)) {
if (!conn.handler.isOpen()) { if (!conn.handler.isOpen()) {
String[] ipAndPort = slaverRouter.get(master).split(":"); String[] ipAndPort = slaverRouter.get(master).split(":");
conn.bootstrap.connect(ipAndPort[0], Integer.parseInt(ipAndPort[1])).sync() conn.bootstrap
.connect(ipAndPort[0], Integer.parseInt(ipAndPort[1]))
.sync()
.channel(); .channel();
} }
} }
@ -90,36 +94,46 @@ public class NetworkManager {
nodeCenterClientHandler = ControllerManager.createNodeCenterClientHandler(); nodeCenterClientHandler = ControllerManager.createNodeCenterClientHandler();
EventLoopGroup group = new NioEventLoopGroup(); EventLoopGroup group = new NioEventLoopGroup();
b.group(group); b.group(group);
b.channel(NioSocketChannel.class).handler(new ChannelInitializer<SocketChannel>() { b.channel(NioSocketChannel.class)
@Override .handler(
protected void initChannel(SocketChannel ch) { new ChannelInitializer<SocketChannel>() {
ChannelPipeline p = ch.pipeline(); @Override
p.addLast(new DelimiterCodec()).addLast(nodeCenterClientHandler); protected void initChannel(SocketChannel ch) {
} ChannelPipeline p = ch.pipeline();
}); p.addLast(new DelimiterCodec()).addLast(nodeCenterClientHandler);
ContractManager.scheduledThreadPool.scheduleWithFixedDelay(() -> { }
try { });
// manager.clearCache(); ContractManager.scheduledThreadPool.scheduleWithFixedDelay(
String URL = GlobalConf.getNodeCenterUrl(); () -> {
// LOGGER.debug("GlobalConf.getNodeCenterUrl() -> URL=" + URL); try {
URI uri = null; // manager.clearCache();
try { String URL = GlobalConf.getNodeCenterUrl();
uri = new URI(URL); // LOGGER.debug("GlobalConf.getNodeCenterUrl() -> URL=" + URL);
} catch (URISyntaxException e) { URI uri = null;
LOGGER.error("creating uri failed! " + e.getMessage()); try {
} uri = new URI(URL);
if (!nodeCenterClientHandler.isConnected() } catch (URISyntaxException e) {
|| !ControllerManager.getNodeCenterController().syncPing()) { LOGGER.error("creating uri failed! " + e.getMessage());
nodeCenterClientHandler.close(); }
assert null != uri; if (!nodeCenterClientHandler.isConnected()
b.connect(uri.getHost(), uri.getPort()).sync().channel(); || !ControllerManager.getNodeCenterController().syncPing()) {
LOGGER.info("connect to node center: " + uri.getHost() + ":" + uri.getPort()); nodeCenterClientHandler.close();
} assert null != uri;
} catch (Exception e) { b.connect(uri.getHost(), uri.getPort()).sync().channel();
// e.printStackTrace(); LOGGER.info(
// LOGGER.warn("connecting to node center failed! " + e.getMessage()); "connect to node center: "
} + uri.getHost()
}, 4, 30 + (int) (20 * Math.random()), TimeUnit.SECONDS); + ":"
+ uri.getPort());
}
} catch (Exception e) {
// e.printStackTrace();
LOGGER.warn("connecting to node center failed! " + e.getMessage());
}
},
0,
10,
TimeUnit.SECONDS);
} }
@ -128,16 +142,20 @@ public class NetworkManager {
ServerBootstrap b = new ServerBootstrap(); ServerBootstrap b = new ServerBootstrap();
EventLoopGroup bossGroup = new NioEventLoopGroup(1); EventLoopGroup bossGroup = new NioEventLoopGroup(1);
b.option(ChannelOption.ALLOCATOR, PooledByteBufAllocator.DEFAULT); b.option(ChannelOption.ALLOCATOR, PooledByteBufAllocator.DEFAULT);
b.group(bossGroup, workerGroup).channel(NioServerSocketChannel.class) b.group(bossGroup, workerGroup)
.option(ChannelOption.SO_BACKLOG, 100).localAddress(port) .channel(NioServerSocketChannel.class)
.option(ChannelOption.SO_BACKLOG, 100)
.localAddress(port)
.childOption(ChannelOption.SO_KEEPALIVE, true) .childOption(ChannelOption.SO_KEEPALIVE, true)
.childHandler(new ChannelInitializer<SocketChannel>() { .childHandler(
@Override new ChannelInitializer<SocketChannel>() {
protected void initChannel(SocketChannel arg0) { @Override
arg0.pipeline().addLast(new DelimiterCodec()) protected void initChannel(SocketChannel arg0) {
.addLast(new TCPServerFrameHandler()); arg0.pipeline()
} .addLast(new DelimiterCodec())
}); .addLast(new TCPServerFrameHandler());
}
});
b.bind(port).sync().channel(); b.bind(port).sync().channel();
} catch (InterruptedException e) { } catch (InterruptedException e) {
@ -146,7 +164,7 @@ public class NetworkManager {
} }
// TODO Remove in future //TODO Remove in future
public void sendToNodeCenter(String msg) { public void sendToNodeCenter(String msg) {
nodeCenterClientHandler.sendMsg(msg); nodeCenterClientHandler.sendMsg(msg);
} }
@ -156,8 +174,9 @@ public class NetworkManager {
} }
public void waitForNodeCenterConnected() { public void waitForNodeCenterConnected() {
for (int i = 0; i < 10 && null != nodeCenterClientHandler for (int i = 0;
&& !nodeCenterClientHandler.isConnected(); i++) { i < 10 && null != nodeCenterClientHandler && !nodeCenterClientHandler.isConnected();
i++) {
try { try {
Thread.sleep(200); Thread.sleep(200);
} catch (InterruptedException e) { } catch (InterruptedException e) {
@ -172,7 +191,7 @@ public class NetworkManager {
} }
} }
// ----------AgentNetworkManagement //----------AgentNetworkManagement
public void updateAgentRouter(String nodeID, String address) { public void updateAgentRouter(String nodeID, String address) {
@ -198,6 +217,7 @@ public class NetworkManager {
public void connectToAgent(String master, String contractID) { public void connectToAgent(String master, String contractID) {
LOGGER.info("master=" + master); LOGGER.info("master=" + master);
// LOGGER.debug("master=" + master + "\n\trouter=" + slaverRouter.get(master));
Bootstrap b; Bootstrap b;
AgentConnector connector = null; AgentConnector connector = null;
synchronized (CONNECTORS) { synchronized (CONNECTORS) {
@ -214,13 +234,15 @@ public class NetworkManager {
connector.handler = handler; connector.handler = handler;
b.option(ChannelOption.CONNECT_TIMEOUT_MILLIS, 5000); b.option(ChannelOption.CONNECT_TIMEOUT_MILLIS, 5000);
b.group(CMHttpServer.workerGroup); b.group(CMHttpServer.workerGroup);
b.channel(NioSocketChannel.class).handler(new ChannelInitializer<SocketChannel>() { b.channel(NioSocketChannel.class)
@Override .handler(
protected void initChannel(SocketChannel ch) { new ChannelInitializer<SocketChannel>() {
ChannelPipeline p = ch.pipeline(); @Override
p.addLast(new DelimiterCodec()).addLast(handler); protected void initChannel(SocketChannel ch) {
} ChannelPipeline p = ch.pipeline();
}); p.addLast(new DelimiterCodec()).addLast(handler);
}
});
} }
reconnectAgent(master); reconnectAgent(master);
} }
@ -271,8 +293,8 @@ public class NetworkManager {
return CONNECTORS.containsKey(pubKey); return CONNECTORS.containsKey(pubKey);
} }
// -------UNUSED TOMerge------------ //-------UNUSED TOMerge------------
// UNUSED //UNUSED
public TCPClientFrameHandler createTCPClient(String peer, String ipPort) public TCPClientFrameHandler createTCPClient(String peer, String ipPort)
throws InterruptedException { throws InterruptedException {
if (peer.equals(GlobalConf.instance.peerID)) { if (peer.equals(GlobalConf.instance.peerID)) {
@ -285,28 +307,30 @@ public class NetworkManager {
NioEventLoopGroup group = new NioEventLoopGroup(); NioEventLoopGroup group = new NioEventLoopGroup();
Bootstrap b = new Bootstrap(); Bootstrap b = new Bootstrap();
final TCPClientFrameHandler handler = new TCPClientFrameHandler(peer); final TCPClientFrameHandler handler = new TCPClientFrameHandler(peer);
// tcpClientMap.put(peer, handler); //tcpClientMap.put(peer, handler);
b.group(group).channel(NioSocketChannel.class) b.group(group)
.channel(NioSocketChannel.class)
.remoteAddress(new InetSocketAddress(host, port)) .remoteAddress(new InetSocketAddress(host, port))
.option(ChannelOption.TCP_NODELAY, true) .option(ChannelOption.TCP_NODELAY, true)
.handler(new ChannelInitializer<SocketChannel>() { .handler(
@Override new ChannelInitializer<SocketChannel>() {
public void initChannel(SocketChannel ch) throws Exception { @Override
ch.pipeline() public void initChannel(SocketChannel ch) throws Exception {
// .addLast(new ch.pipeline()
// IdleStateHandler(0, 4, 0, TimeUnit.SECONDS)) // .addLast(new
.addLast(new DelimiterCodec()) // IdleStateHandler(0, 4, 0, TimeUnit.SECONDS))
.addLast(new IdleStateHandler(0, 5, 0)) .addLast(new DelimiterCodec())
// .addLast(new .addLast(new IdleStateHandler(0, 5, 0))
// HeartBeatEncode()) // .addLast(new
.addLast(handler); // HeartBeatEncode())
} .addLast(handler);
}); }
});
ChannelFuture f = b.connect().sync(); ChannelFuture f = b.connect().sync();
if (f.isSuccess()) { if (f.isSuccess()) {
LOGGER.info("TCP Client " + peer + " started"); LOGGER.info("TCP Client " + peer + " started");
} }
// channel = (SocketChannel) future.channel(); // channel = (SocketChannel) future.channel();
return handler; return handler;
} }
@ -329,14 +353,14 @@ public class NetworkManager {
} }
/** /**
* UNUSED send to TCP nodes, if fail send by p2p * UNUSED send to TCP nodes, if fail send by p2p
* *
* @param msg unit message * @param msg unit message
*/ */
public void send(UnitMessage msg) { public void send(UnitMessage msg) {
Iterator<String> iterator = msg.getReceiverList().iterator(); Iterator<String> iterator = msg.getReceiverList().iterator();
String peer; String peer;
// boolean sendByP2P = false; // boolean sendByP2P = false;
TCPClientFrameHandler tcpClientFrameHandler; TCPClientFrameHandler tcpClientFrameHandler;
while (iterator.hasNext()) { while (iterator.hasNext()) {
peer = iterator.next(); peer = iterator.next();
@ -345,16 +369,17 @@ public class NetworkManager {
LOGGER.info("send msg to itself " + msg); LOGGER.info("send msg to itself " + msg);
continue; continue;
} }
// tcpClientFrameHandler = NetworkManager.instance.tcpClientMap.getOrDefault(peer, // tcpClientFrameHandler = NetworkManager.instance.tcpClientMap.getOrDefault(peer, null);
// null);
if (peerID2TCPAddress.containsKey(peer)) { if (peerID2TCPAddress.containsKey(peer)) {
// recreateTCPClient(peer); //recreateTCPClient(peer);
// instance.tcpClientMap.put(peer, tcpClientFrameHandler); // instance.tcpClientMap.put(peer, tcpClientFrameHandler);
UnitMessage unitMessage = msg.toBuilder().clearReceiver().addReceiver(peer).build(); UnitMessage unitMessage =
msg.toBuilder().clearReceiver().addReceiver(peer).build();
LOGGER.info("send msg by p2p to " + peer); LOGGER.info("send msg by p2p to " + peer);
JavaContractServiceGrpcServer.sendMsg(unitMessage); JavaContractServiceGrpcServer.sendMsg(unitMessage);
} else { } else {
UnitMessage unitMessage = msg.toBuilder().clearReceiver().addReceiver(peer).build(); UnitMessage unitMessage =
msg.toBuilder().clearReceiver().addReceiver(peer).build();
LOGGER.info("send msg by p2p to " + peer); LOGGER.info("send msg by p2p to " + peer);
JavaContractServiceGrpcServer.sendMsg(unitMessage); JavaContractServiceGrpcServer.sendMsg(unitMessage);
} }

View File

@ -1,5 +1,6 @@
package org.bdware.units.beans; package org.bdware.units.beans;
import org.bdware.sc.bean.ContractExecType;
import org.bdware.units.enums.ConsensusType; import org.bdware.units.enums.ConsensusType;
import org.bdware.units.enums.NetworkType; import org.bdware.units.enums.NetworkType;
import org.bdware.units.enums.ResponseType; import org.bdware.units.enums.ResponseType;
@ -10,33 +11,29 @@ public class MultiPointContractInfo {
public Set<String> members; public Set<String> members;
public Map<String, String> member2PubKey; public Map<String, String> member2PubKey;
public String master; public String master;
// public ContractType contractType; // public ContractType contractType;
public String contractId; public String contractId;
public ConsensusType consensusType; public ConsensusType consensusType;
public ResponseType responseType; public ResponseType responseType;
public NetworkType networkType; public NetworkType networkType;
public MultiPointContractInfo() { public MultiPointContractInfo(){
// member2PubKey = new HashMap<>(10); // member2PubKey = new HashMap<>(10);
// members = new HashSet<>(10); // members = new HashSet<>(10);
} }
public Set<String> getMembers() { public Set<String> getMembers() {
return members; return members;
} }
public String getContractId() { public String getContractId() {
return contractId; return contractId;
} }
public String getMaster() { public String getMaster() {
return master; return master;
} }
public boolean hasPeer(String peerID) { public boolean hasPeer(String peerID) {
return members.contains(peerID); return members.contains(peerID);
} }
public String getPubKey(String peerID) { public String getPubKey(String peerID) {
return member2PubKey.get(peerID); return member2PubKey.get(peerID);

View File

@ -4,7 +4,6 @@ import java.io.Serializable;
/** /**
* ExecutionManager内部消息封装在UnitMessage中作为content * ExecutionManager内部消息封装在UnitMessage中作为content
*
* @author oliveds * @author oliveds
*/ */
public class UnitContractMessage implements Serializable { public class UnitContractMessage implements Serializable {

View File

@ -8,7 +8,7 @@ public interface ConsensusCenter {
void handle(UnitSequencingMessage unitSequencingMessage); void handle(UnitSequencingMessage unitSequencingMessage);
// void updateMaster(String master); // void updateMaster(String master);
// UnitSequencingMessage formConsensusRequest(UnitContractMessage msg); // UnitSequencingMessage formConsensusRequest(UnitContractMessage msg);
} }

View File

@ -23,8 +23,8 @@ public class PBFTCenter implements ConsensusCenter {
MultiPointContractInfo contractInfo; MultiPointContractInfo contractInfo;
Map<Long, PBFTInfo> infos; Map<Long, PBFTInfo> infos;
Map<Long, UnitContractMessage> committedMsg; Map<Long, UnitContractMessage> committedMsg;
// Map<String, PBFTInfo> original; // Map<String, PBFTInfo> original;
// String master; // String master;
boolean isMaster; boolean isMaster;
private String contractID; private String contractID;
private NetworkType networkType; private NetworkType networkType;
@ -36,12 +36,12 @@ public class PBFTCenter implements ConsensusCenter {
networkType = NetworkType.getType(msg.network); networkType = NetworkType.getType(msg.network);
infos = new HashMap<>(); infos = new HashMap<>();
committedMsg = new HashMap<>(); committedMsg = new HashMap<>();
// original = new HashMap<>(); // original = new HashMap<>();
// receive init, then insert // receive init, then insert
// members = ContractUnitManager.instance.getContractInfo(contractID); // members = ContractUnitManager.instance.getContractInfo(contractID);
// if (members.master.equals(GlobalConf.instance.peerID)) { // if (members.master.equals(GlobalConf.instance.peerID)) {
// isMaster = true; // isMaster = true;
// } // }
} }
@Override @Override
@ -59,33 +59,32 @@ public class PBFTCenter implements ConsensusCenter {
PBFTInfo temp; PBFTInfo temp;
switch (ConsensusStage.fromByte(unitSequencingMessage.stageType)) { switch (ConsensusStage.fromByte(unitSequencingMessage.stageType)) {
case Init: case Init:
MultiPointContractInfo contractInfo = JsonUtil MultiPointContractInfo contractInfo =
.fromJson(unitSequencingMessage.content, MultiPointContractInfo.class); JsonUtil.fromJson(unitSequencingMessage.content, MultiPointContractInfo.class);
updateUnitInfo(contractInfo); updateUnitInfo(contractInfo);
break; break;
case AddMember: case AddMember:
// PBFTMember member = PBFTMember.parse(pbftMessage.content); // PBFTMember member = PBFTMember.parse(pbftMessage.content);
// if (member != null) // if (member != null)
// members.put(sender, member); // members.put(sender, member);
// case DeleteMember: // case DeleteMember:
break; break;
case Request: case Request:
// master form preprepare, full content // master form preprepare, full content
// int hash = unitSequencingMessage.content.hashCode(); // int hash = unitSequencingMessage.content.hashCode();
// original.put(hash, new Pair<Node, PBFTMessage>(sender, pbftMessage)); // original.put(hash, new Pair<Node, PBFTMessage>(sender, pbftMessage));
if (isMaster) { if (isMaster) {
temp = new PBFTInfo(); temp = new PBFTInfo();
temp.order = allocatedID.incrementAndGet(); temp.order = allocatedID.incrementAndGet();
temp.request = unitSequencingMessage.content; temp.request = unitSequencingMessage.content;
infos.put(temp.order, temp); infos.put(temp.order, temp);
// original.put(unitSequencingMessage.requestID, temp); // original.put(unitSequencingMessage.requestID, temp);
unitSequencingMessage.stageType = PBFTType.PrePrepare.toInt(); unitSequencingMessage.stageType = PBFTType.PrePrepare.toInt();
unitSequencingMessage.order = temp.order; unitSequencingMessage.order = temp.order;
// unitSequencingMessage.content = unitSequencingMessage.content.hashCode() + // unitSequencingMessage.content = unitSequencingMessage.content.hashCode() + "";
// "";
broadcast(unitSequencingMessage); broadcast(unitSequencingMessage);
} else { } else {
// sendToMaster(unitSequencingMessage); // sendToMaster(unitSequencingMessage);
} }
break; break;
case PrePrepare: case PrePrepare:
@ -112,7 +111,7 @@ public class PBFTCenter implements ConsensusCenter {
} }
if (temp.updatePrepare(unitSequencingMessage, this)) { if (temp.updatePrepare(unitSequencingMessage, this)) {
UnitSequencingMessage commitMsg = temp.formCommit(unitSequencingMessage); UnitSequencingMessage commitMsg = temp.formCommit(unitSequencingMessage);
// temp.updateCommit(commitMsg, this); // temp.updateCommit(commitMsg, this);
broadcast(commitMsg); broadcast(commitMsg);
} }
break; break;
@ -139,7 +138,7 @@ public class PBFTCenter implements ConsensusCenter {
unitSequencingMessage.stageType = ConsensusStage.PrePrepare.toInt(); unitSequencingMessage.stageType = ConsensusStage.PrePrepare.toInt();
unitSequencingMessage.sender = GlobalConf.instance.peerID; unitSequencingMessage.sender = GlobalConf.instance.peerID;
String content = JsonUtil.toJson(unitSequencingMessage); String content = JsonUtil.toJson(unitSequencingMessage);
SequencingManager.instance.send(content, new String[] {peer}); SequencingManager.instance.send(content, new String[]{peer});
} }
break; break;
default: default:
@ -153,8 +152,7 @@ public class PBFTCenter implements ConsensusCenter {
} }
private void broadcast(UnitSequencingMessage msg) { private void broadcast(UnitSequencingMessage msg) {
SequencingManager.instance.send(JsonUtil.toJson(msg), SequencingManager.instance.send(JsonUtil.toJson(msg), contractInfo.getMembers().toArray(new String[0]));
contractInfo.getMembers().toArray(new String[0]));
} }
class PBFTInfo { class PBFTInfo {
@ -177,8 +175,7 @@ public class PBFTCenter implements ConsensusCenter {
isPrePrepareReceived = false; isPrePrepareReceived = false;
} }
public synchronized boolean updatePrepare(UnitSequencingMessage message, public synchronized boolean updatePrepare(UnitSequencingMessage message, PBFTCenter center) {
PBFTCenter center) {
if (isSendCommit) { if (isSendCommit) {
return false; return false;
} }
@ -212,15 +209,18 @@ public class PBFTCenter implements ConsensusCenter {
} }
public String getDisplayStr() { public String getDisplayStr() {
return String.format("pSize=%d cSize=%d isSendCommit=%b isSendReply=%b buffSize=%d", return String.format(
null == prepare ? -1 : prepare.size(), null == commit ? -1 : commit.size(), "pSize=%d cSize=%d isSendCommit=%b isSendReply=%b buffSize=%d",
isSendCommit, isSendReply, buff.size()); null == prepare ? -1 : prepare.size(),
null == commit ? -1 : commit.size(),
isSendCommit,
isSendReply,
buff.size());
} }
public UnitSequencingMessage formPrepare(UnitSequencingMessage unitSequencingMessage) { public UnitSequencingMessage formPrepare(UnitSequencingMessage unitSequencingMessage) {
// UnitSequencingMessage prepareMsg = new // UnitSequencingMessage prepareMsg = new UnitSequencingMessage(ConsensusStage.Prepare.toInt());
// UnitSequencingMessage(ConsensusStage.Prepare.toInt()); // prepareMsg.order = this.order;
// prepareMsg.order = this.order;
unitSequencingMessage.content = String.valueOf(this.request.hashCode()); unitSequencingMessage.content = String.valueOf(this.request.hashCode());
unitSequencingMessage.sender = GlobalConf.instance.peerID; unitSequencingMessage.sender = GlobalConf.instance.peerID;
unitSequencingMessage.stageType = ConsensusStage.Prepare.toInt(); unitSequencingMessage.stageType = ConsensusStage.Prepare.toInt();
@ -228,19 +228,17 @@ public class PBFTCenter implements ConsensusCenter {
} }
public void requestPrePrepareFromMaster() { public void requestPrePrepareFromMaster() {
UnitSequencingMessage requestMsg = UnitSequencingMessage requestMsg = new UnitSequencingMessage(ConsensusStage.ReSend.toInt());
new UnitSequencingMessage(ConsensusStage.ReSend.toInt());
requestMsg.order = this.order; requestMsg.order = this.order;
requestMsg.sender = GlobalConf.instance.peerID; requestMsg.sender = GlobalConf.instance.peerID;
// return requestMsg; // return requestMsg;
String content = JsonUtil.toJson(requestMsg); String content = JsonUtil.toJson(requestMsg);
SequencingManager.instance.send(content, new String[] {contractInfo.master}); SequencingManager.instance.send(content, new String[]{contractInfo.master});
} }
public UnitSequencingMessage formCommit(UnitSequencingMessage unitSequencingMessage) { public UnitSequencingMessage formCommit(UnitSequencingMessage unitSequencingMessage) {
// UnitSequencingMessage commitMsg = new // UnitSequencingMessage commitMsg = new UnitSequencingMessage(ConsensusStage.Commit.toInt());
// UnitSequencingMessage(ConsensusStage.Commit.toInt()); // unitSequencingMessage.order = this.order;
// unitSequencingMessage.order = this.order;
unitSequencingMessage.content = String.valueOf(this.request.hashCode()); unitSequencingMessage.content = String.valueOf(this.request.hashCode());
unitSequencingMessage.sender = GlobalConf.instance.peerID; unitSequencingMessage.sender = GlobalConf.instance.peerID;
unitSequencingMessage.stageType = ConsensusStage.Commit.toInt(); unitSequencingMessage.stageType = ConsensusStage.Commit.toInt();
@ -248,8 +246,7 @@ public class PBFTCenter implements ConsensusCenter {
} }
public void onCommit() { public void onCommit() {
UnitContractMessage unitContractMessage = UnitContractMessage unitContractMessage = JsonUtil.fromJson(request, UnitContractMessage.class);
JsonUtil.fromJson(request, UnitContractMessage.class);
if (this.order == (committedID.get() + 1L)) { if (this.order == (committedID.get() + 1L)) {
execute(unitContractMessage, this.order); execute(unitContractMessage, this.order);
} else { } else {

View File

@ -10,7 +10,8 @@ public class RAFTCenter implements ConsensusCenter {
private static ConsensusType PBFT; private static ConsensusType PBFT;
private String contractID; private String contractID;
public RAFTCenter(UnitContractMessage msg) {} public RAFTCenter(UnitContractMessage msg) {
}
@Override @Override
public void updateUnitInfo(MultiPointContractInfo contractInfo) { public void updateUnitInfo(MultiPointContractInfo contractInfo) {

View File

@ -35,12 +35,12 @@ public class SingleCenter implements ConsensusCenter {
networkType = NetworkType.getType(msg.network); networkType = NetworkType.getType(msg.network);
infos = new HashMap<>(); infos = new HashMap<>();
committedMsg = new HashMap<>(); committedMsg = new HashMap<>();
// original = new HashMap<>(); // original = new HashMap<>();
// receive init, then insert // receive init, then insert
// members = ContractUnitManager.instance.getContractInfo(contractID); // members = ContractUnitManager.instance.getContractInfo(contractID);
// if (members.master.equals(GlobalConf.instance.peerID)) { // if (members.master.equals(GlobalConf.instance.peerID)) {
// isMaster = true; // isMaster = true;
// } // }
} }
@Override @Override
@ -58,8 +58,8 @@ public class SingleCenter implements ConsensusCenter {
SingleInfo temp; SingleInfo temp;
switch (ConsensusStage.fromByte(unitSequencingMessage.stageType)) { switch (ConsensusStage.fromByte(unitSequencingMessage.stageType)) {
case Init: case Init:
MultiPointContractInfo contractInfo = JsonUtil MultiPointContractInfo contractInfo =
.fromJson(unitSequencingMessage.content, MultiPointContractInfo.class); JsonUtil.fromJson(unitSequencingMessage.content, MultiPointContractInfo.class);
updateUnitInfo(contractInfo); updateUnitInfo(contractInfo);
break; break;
case Request: case Request:
@ -72,7 +72,7 @@ public class SingleCenter implements ConsensusCenter {
unitSequencingMessage.order = temp.order; unitSequencingMessage.order = temp.order;
broadcast(unitSequencingMessage); broadcast(unitSequencingMessage);
} else { } else {
// sendToMaster(unitSequencingMessage); // sendToMaster(unitSequencingMessage);
} }
break; break;
case Commit: case Commit:
@ -93,7 +93,7 @@ public class SingleCenter implements ConsensusCenter {
unitSequencingMessage.stageType = ConsensusStage.PrePrepare.toInt(); unitSequencingMessage.stageType = ConsensusStage.PrePrepare.toInt();
unitSequencingMessage.sender = GlobalConf.instance.peerID; unitSequencingMessage.sender = GlobalConf.instance.peerID;
String content = JsonUtil.toJson(unitSequencingMessage); String content = JsonUtil.toJson(unitSequencingMessage);
SequencingManager.instance.send(content, new String[] {peer}); SequencingManager.instance.send(content, new String[]{peer});
} }
break; break;
default: default:
@ -102,7 +102,8 @@ public class SingleCenter implements ConsensusCenter {
} }
private void broadcast(UnitSequencingMessage msg) { private void broadcast(UnitSequencingMessage msg) {
SequencingManager.instance.send(JsonUtil.toJson(msg), SequencingManager.instance.send(
JsonUtil.toJson(msg),
contractInfo.getMembers().toArray(new String[contractInfo.members.size()])); contractInfo.getMembers().toArray(new String[contractInfo.members.size()]));
} }
@ -115,8 +116,7 @@ public class SingleCenter implements ConsensusCenter {
isSendReply = false; isSendReply = false;
} }
public synchronized boolean updateCommit(UnitSequencingMessage message, public synchronized boolean updateCommit(UnitSequencingMessage message, SingleCenter center) {
SingleCenter center) {
if (isSendReply) { if (isSendReply) {
return false; return false;
} }
@ -126,8 +126,7 @@ public class SingleCenter implements ConsensusCenter {
} }
public void onCommit() { public void onCommit() {
UnitContractMessage unitContractMessage = UnitContractMessage unitContractMessage = JsonUtil.fromJson(request, UnitContractMessage.class);
JsonUtil.fromJson(request, UnitContractMessage.class);
if (this.order == (committedID.get() + 1L)) { if (this.order == (committedID.get() + 1L)) {
execute(unitContractMessage, this.order); execute(unitContractMessage, this.order);
} else { } else {

View File

@ -1,8 +1,7 @@
package org.bdware.units.enums; package org.bdware.units.enums;
public enum ConsensusStage { public enum ConsensusStage {
Init(0), Request(1), PrePrepare(2), Prepare(3), Commit(4), Reply(5), Unknown(6), ReSend( Init(0), Request(1), PrePrepare(2), Prepare(3), Commit(4), Reply(5), Unknown(6), ReSend(7), AddMember(8);
7), AddMember(8);
private int type; private int type;

View File

@ -1,8 +1,12 @@
package org.bdware.units.enums; package org.bdware.units.enums;
public enum UnitContractMessageType { public enum UnitContractMessageType {
ContractUnitRequest(0), ContractUnitResponse(1), GetMyPeerID(2), MyPeerIDResponse( ContractUnitRequest(0),
3), ContractStatusRequest(4), ContractStatusResponse(5); ContractUnitResponse (1),
GetMyPeerID(2),
MyPeerIDResponse(3),
ContractStatusRequest(4),
ContractStatusResponse (5);
private final int value; private final int value;

View File

@ -1,7 +1,8 @@
package org.bdware.units.enums; package org.bdware.units.enums;
public enum UnitContractNetworkType { public enum UnitContractNetworkType {
TCP(0), P2P(1); TCP(0),
P2P (1);
private final int value; private final int value;

View File

@ -1,7 +1,11 @@
package org.bdware.units.enums; package org.bdware.units.enums;
public enum UnitContractRequestType { public enum UnitContractRequestType {
START(0), STOP(1), EXECUTE(2), REPLY(3), REQUEST(4); START(0),
STOP (1),
EXECUTE(2),
REPLY(3),
REQUEST(4);
private final int value; private final int value;

View File

@ -26,8 +26,7 @@ public class BaseFunctionManager {
public void send(String msg, String[] peers) { public void send(String msg, String[] peers) {
String requestId = getRequestId(); String requestId = getRequestId();
BDLedgerContract.UnitMessage unitMessage = BDLedgerContract.UnitMessage unitMessage = this.addRequestIdAndGetMessage(requestId, msg, peers);
this.addRequestIdAndGetMessage(requestId, msg, peers);
NetworkManager.instance.send(unitMessage); NetworkManager.instance.send(unitMessage);
} }
@ -40,8 +39,7 @@ public class BaseFunctionManager {
public void send(String msg, String[] peers, ResultCallback resultCallback) { public void send(String msg, String[] peers, ResultCallback resultCallback) {
String requestId = getRequestId(); String requestId = getRequestId();
BDLedgerContract.UnitMessage unitMessage = BDLedgerContract.UnitMessage unitMessage = this.addRequestIdAndGetMessage(requestId, msg, peers);
this.addRequestIdAndGetMessage(requestId, msg, peers);
NetworkManager.instance.send(unitMessage); NetworkManager.instance.send(unitMessage);
requestCallbacks.put(requestId, resultCallback); requestCallbacks.put(requestId, resultCallback);
} }
@ -60,8 +58,10 @@ public class BaseFunctionManager {
System.out.println("[BaseFunctionManager] handleResponse null"); System.out.println("[BaseFunctionManager] handleResponse null");
return; return;
} }
if (responseCenter.updateReply(arg.get("content").getAsString(), if (responseCenter.updateReply(
arg.get("sender").getAsString(), arg.get("pubkey").getAsString())) { arg.get("content").getAsString(),
arg.get("sender").getAsString(),
arg.get("pubkey").getAsString())) {
responseCenter.formReply(); responseCenter.formReply();
} }
} }
@ -74,12 +74,12 @@ public class BaseFunctionManager {
return UNIT_MESSAGE_TYPE; return UNIT_MESSAGE_TYPE;
} }
private BDLedgerContract.UnitMessage addRequestIdAndGetMessage(String requestId, String msg, private BDLedgerContract.UnitMessage addRequestIdAndGetMessage(String requestId, String msg, String[] peers) {
String[] peers) {
JsonObject jsonObject = (JsonObject) JsonParser.parseString(msg); JsonObject jsonObject = (JsonObject) JsonParser.parseString(msg);
jsonObject.addProperty(REQUEST_ID, requestId); jsonObject.addProperty(REQUEST_ID, requestId);
BDLedgerContract.UnitMessage.Builder builder = BDLedgerContract.UnitMessage.newBuilder() BDLedgerContract.UnitMessage.Builder builder = BDLedgerContract.UnitMessage.newBuilder()
.setMsgType(getMessageType()).setSender(GlobalConf.instance.peerID) .setMsgType(getMessageType())
.setSender(GlobalConf.instance.peerID)
.setContent(ByteString.copyFromUtf8(jsonObject.toString())); .setContent(ByteString.copyFromUtf8(jsonObject.toString()));
for (String peer : peers) { for (String peer : peers) {
builder.addReceiver(peer); builder.addReceiver(peer);
@ -87,12 +87,16 @@ public class BaseFunctionManager {
return builder.build(); return builder.build();
} }
private BDLedgerContract.UnitMessage addRequestIdAndGetMessage(String requestId, String msg, private BDLedgerContract.UnitMessage addRequestIdAndGetMessage(
String[] peers, BDLedgerContract.UnitMessageType unitMessageType) { String requestId,
String msg,
String[] peers,
BDLedgerContract.UnitMessageType unitMessageType) {
JsonObject jsonObject = (JsonObject) JsonParser.parseString(msg); JsonObject jsonObject = (JsonObject) JsonParser.parseString(msg);
jsonObject.addProperty(REQUEST_ID, requestId); jsonObject.addProperty(REQUEST_ID, requestId);
BDLedgerContract.UnitMessage.Builder builder = BDLedgerContract.UnitMessage.newBuilder() BDLedgerContract.UnitMessage.Builder builder = BDLedgerContract.UnitMessage.newBuilder()
.setMsgType(unitMessageType).setSender(GlobalConf.instance.peerID) .setMsgType(unitMessageType)
.setSender(GlobalConf.instance.peerID)
.setContent(ByteString.copyFromUtf8(jsonObject.toString())); .setContent(ByteString.copyFromUtf8(jsonObject.toString()));
for (String peer : peers) { for (String peer : peers) {
builder.addReceiver(peer); builder.addReceiver(peer);

View File

@ -34,10 +34,9 @@ public class CommunicationManager extends BaseFunctionManager {
private static final String MANAGER_SYMBOL = "COMM"; private static final String MANAGER_SYMBOL = "COMM";
private static final Logger LOGGER = LogManager.getLogger(CommunicationManager.class); private static final Logger LOGGER = LogManager.getLogger(CommunicationManager.class);
public static ExecutorService executorService = Executors.newFixedThreadPool(10); public static ExecutorService executorService = Executors.newFixedThreadPool(10);
private final BDLedgerContract.UnitMessageType UNIT_MESSAGE_TYPE = private final BDLedgerContract.UnitMessageType UNIT_MESSAGE_TYPE = BDLedgerContract.UnitMessageType.UnitCommunicateMessage;
BDLedgerContract.UnitMessageType.UnitCommunicateMessage;
protected CommunicationAction communicationAction; protected CommunicationAction communicationAction;
// new ThreadPoolExecutor(10,30,1L, TimeUnit.HOURS, new LinkedBlockingDeque<Runnable>(100)); //new ThreadPoolExecutor(10,30,1L, TimeUnit.HOURS, new LinkedBlockingDeque<Runnable>(100));
private ActionExecutor<ResultCallback, JsonObject> ae; private ActionExecutor<ResultCallback, JsonObject> ae;
private NodeCenterClientController nodeCenterClientController; private NodeCenterClientController nodeCenterClientController;
private String[] p2pPeers; private String[] p2pPeers;
@ -50,8 +49,11 @@ public class CommunicationManager extends BaseFunctionManager {
instance = new CommunicationManager(); instance = new CommunicationManager();
instance.nodeCenterClientController = ControllerManager.getNodeCenterController(); instance.nodeCenterClientController = ControllerManager.getNodeCenterController();
instance.communicationAction = new CommunicationAction(); instance.communicationAction = new CommunicationAction();
instance.ae = new ActionExecutor<ResultCallback, JsonObject>(executorService, instance.ae = new ActionExecutor<ResultCallback, JsonObject>(
instance.nodeCenterClientController, instance.communicationAction) { executorService,
instance.nodeCenterClientController,
instance.communicationAction
) {
@Override @Override
public boolean checkPermission(Action a, final JsonObject args, long permission) { public boolean checkPermission(Action a, final JsonObject args, long permission) {
return true; return true;
@ -65,9 +67,11 @@ public class CommunicationManager extends BaseFunctionManager {
} }
public static void send(String msg, String symbol) { public static void send(String msg, String symbol) {
UnitMessage unitMessage = UnitMessage.newBuilder().setSender(GlobalConf.instance.peerID) UnitMessage unitMessage = UnitMessage.newBuilder()
.setSender(GlobalConf.instance.peerID)
.setMsgType(BDLedgerContract.UnitMessageType.UnitCommunicateMessage) .setMsgType(BDLedgerContract.UnitMessageType.UnitCommunicateMessage)
.setContent(ByteString.copyFromUtf8(msg)).build(); .setContent(ByteString.copyFromUtf8(msg))
.build();
NetworkManager.instance.sendTo(unitMessage, symbol); NetworkManager.instance.sendTo(unitMessage, symbol);
} }
@ -77,38 +81,39 @@ public class CommunicationManager extends BaseFunctionManager {
} }
public void handle(String str, String sender) { public void handle(String str, String sender) {
// JsonObject jsonObject = (JsonObject) JsonParser.parseStringAsJsonObject(str); // JsonObject jsonObject = (JsonObject) JsonParser.parseStringAsJsonObject(str);
// if(jsonObject.has("action")) { // if(jsonObject.has("action")) {
// String action = jsonObject.get("action").getAsString(); // String action = jsonObject.get("action").getAsString();
// switch (action) { // switch (action) {
// case "myPeerId": // case "myPeerId":
// GlobalConf.setPeerID(jsonObject.get("peerId").getAsString()); // GlobalConf.setPeerID(jsonObject.get("peerId").getAsString());
// break; // break;
// default: // default:
// logger.debug("[CommunicationManager] not handled " + jsonObject.toString()); // logger.debug("[CommunicationManager] not handled " + jsonObject.toString());
// } // }
// } // }
JsonObject arg = (JsonObject) JsonParser.parseString(str); JsonObject arg = (JsonObject) JsonParser.parseString(str);
Response response; Response response;
try { try {
final String action = arg.get("action").getAsString(); final String action = arg.get("action").getAsString();
// if (isResponse(action)) { // if (isResponse(action)) {
// handleResponse(arg); // handleResponse(arg);
// return; // return;
// } // }
// logger.info("[CommunicationManager] handle:" + arg.toString()); // logger.info("[CommunicationManager] handle:" + arg.toString());
ae.handle(action, arg, new ResultCallback() { ae.handle(action, arg,
@Override new ResultCallback() {
public void onResult(String arg) { @Override
System.out.println("[CommunicationManager] onResult"); public void onResult(String arg) {
// CommunicationManager.instance.send(arg, new String[]{sender}); System.out.println("[CommunicationManager] onResult");
} // CommunicationManager.instance.send(arg, new String[]{sender});
}); }
});
} catch (IllegalArgumentException e) { } catch (IllegalArgumentException e) {
response = new Response(); response = new Response();
response.action = "onException"; response.action = "onException";
response.data = e.getMessage(); response.data = e.getMessage();
CommunicationManager.instance.send(JsonUtil.toJson(response), new String[] {sender}); CommunicationManager.instance.send(JsonUtil.toJson(response), new String[]{sender});
} catch (Exception e) { } catch (Exception e) {
e.printStackTrace(); e.printStackTrace();
ByteArrayOutputStream bo = new ByteArrayOutputStream(); ByteArrayOutputStream bo = new ByteArrayOutputStream();
@ -119,9 +124,12 @@ public class CommunicationManager extends BaseFunctionManager {
StringBuilder ret = new StringBuilder(); StringBuilder ret = new StringBuilder();
int count = 0; int count = 0;
for (String s : strs) { for (String s : strs) {
if (s.contains("sun.reflect") || s.contains("java.lang.reflect") if (s.contains("sun.reflect")
|| s.contains("org.apache") || s.contains("java.util") || s.contains("java.lang.reflect")
|| s.contains("java.lang") || s.contains("io.netty")) { || s.contains("org.apache")
|| s.contains("java.util")
|| s.contains("java.lang")
|| s.contains("io.netty")) {
continue; continue;
} }
ret.append(s); ret.append(s);
@ -141,9 +149,11 @@ public class CommunicationManager extends BaseFunctionManager {
JsonObject jsonObject = new JsonObject(); JsonObject jsonObject = new JsonObject();
jsonObject.addProperty(ACTION, "getP2PNodes"); jsonObject.addProperty(ACTION, "getP2PNodes");
jsonObject.addProperty(REQUEST_ID, requestID); jsonObject.addProperty(REQUEST_ID, requestID);
UnitMessage unitMessage = UnitMessage.newBuilder().setSender(GlobalConf.instance.peerID) UnitMessage unitMessage = UnitMessage.newBuilder()
.setSender(GlobalConf.instance.peerID)
.setMsgType(BDLedgerContract.UnitMessageType.UnitCommunicateMessage) .setMsgType(BDLedgerContract.UnitMessageType.UnitCommunicateMessage)
.setContent(ByteString.copyFromUtf8(jsonObject.toString())).build(); .setContent(ByteString.copyFromUtf8(jsonObject.toString()))
.build();
NetworkManager.instance.send(unitMessage, NetworkType.P2P); NetworkManager.instance.send(unitMessage, NetworkType.P2P);
} }
@ -176,9 +186,11 @@ public class CommunicationManager extends BaseFunctionManager {
public void askForNextContractID() { public void askForNextContractID() {
JsonObject jsonObject = new JsonObject(); JsonObject jsonObject = new JsonObject();
jsonObject.addProperty(ACTION, "askForNextContractID"); jsonObject.addProperty(ACTION, "askForNextContractID");
UnitMessage unitMessage = UnitMessage.newBuilder().setSender(GlobalConf.instance.peerID) UnitMessage unitMessage = UnitMessage.newBuilder()
.setSender(GlobalConf.instance.peerID)
.setMsgType(BDLedgerContract.UnitMessageType.UnitCommunicateMessage) .setMsgType(BDLedgerContract.UnitMessageType.UnitCommunicateMessage)
.setContent(ByteString.copyFromUtf8(jsonObject.toString())).build(); .setContent(ByteString.copyFromUtf8(jsonObject.toString()))
.build();
NetworkManager.instance.send(unitMessage, NetworkType.P2P); NetworkManager.instance.send(unitMessage, NetworkType.P2P);
} }
@ -194,4 +206,5 @@ public class CommunicationManager extends BaseFunctionManager {
} }

View File

@ -26,17 +26,15 @@ public class ContractUnitManager extends BaseFunctionManager {
private static final String MANAGER_SYMBOL = "UNIT"; private static final String MANAGER_SYMBOL = "UNIT";
private static final Logger LOGGER = LogManager.getLogger(ExecutionManager.class); private static final Logger LOGGER = LogManager.getLogger(ExecutionManager.class);
public static ExecutorService executorService = Executors.newFixedThreadPool(10); public static ExecutorService executorService = Executors.newFixedThreadPool(10);
final private BDLedgerContract.UnitMessageType UNIT_MESSAGE_TYPE = final private BDLedgerContract.UnitMessageType UNIT_MESSAGE_TYPE = BDLedgerContract.UnitMessageType.UnitUnitMessage; // init after all static is inited
BDLedgerContract.UnitMessageType.UnitUnitMessage; // init after all static is inited
public static ContractUnitManager instance = init(); public static ContractUnitManager instance = init();
private final Map<String, MultiPointContractInfo> contractID2Members = private final Map<String, MultiPointContractInfo> contractID2Members = new ConcurrentHashMap<>();
new ConcurrentHashMap<>();
protected ActionExecutor<ResultCallback, JsonObject> actionExecutor; protected ActionExecutor<ResultCallback, JsonObject> actionExecutor;
protected UnitsInfoAction unitsInfoActions; protected UnitsInfoAction unitsInfoActions;
private Map<String, RequestCache> requestCache = new ConcurrentHashMap<>(); private Map<String, RequestCache> requestCache = new ConcurrentHashMap<>();
private Map<String, CMNodeBean> nodeinfos; private Map<String, CMNodeBean> nodeinfos;
public ContractUnitManager() {
public ContractUnitManager() {} }
public static ContractUnitManager init() { public static ContractUnitManager init() {
if (instance != null) { if (instance != null) {
@ -44,8 +42,7 @@ public class ContractUnitManager extends BaseFunctionManager {
} }
instance = new ContractUnitManager(); instance = new ContractUnitManager();
instance.unitsInfoActions = new UnitsInfoAction(); instance.unitsInfoActions = new UnitsInfoAction();
instance.actionExecutor = new ActionExecutor<ResultCallback, JsonObject>(executorService, instance.actionExecutor = new ActionExecutor<ResultCallback, JsonObject>(executorService, instance.unitsInfoActions) {
instance.unitsInfoActions) {
@Override @Override
public boolean checkPermission(Action a, final JsonObject args, long permission) { public boolean checkPermission(Action a, final JsonObject args, long permission) {
return true; return true;
@ -65,17 +62,18 @@ public class ContractUnitManager extends BaseFunctionManager {
return; return;
} }
LOGGER.info("[ContractUnitManager] handle:" + arg); LOGGER.info("[ContractUnitManager] handle:" + arg);
actionExecutor.handle(action, arg, new ResultCallback() { actionExecutor.handle(action, arg,
@Override new ResultCallback() {
public void onResult(String arg) { @Override
ContractUnitManager.instance.send(arg, new String[] {sender}); public void onResult(String arg) {
} ContractUnitManager.instance.send(arg, new String[]{sender});
}); }
});
} catch (IllegalArgumentException e) { } catch (IllegalArgumentException e) {
response = new Response(); response = new Response();
response.action = "onException"; response.action = "onException";
response.data = e.getMessage(); response.data = e.getMessage();
ContractUnitManager.instance.send(JsonUtil.toJson(response), new String[] {sender}); ContractUnitManager.instance.send(JsonUtil.toJson(response), new String[]{sender});
} catch (Exception e) { } catch (Exception e) {
e.printStackTrace(); e.printStackTrace();
ByteArrayOutputStream bo = new ByteArrayOutputStream(); ByteArrayOutputStream bo = new ByteArrayOutputStream();
@ -86,9 +84,12 @@ public class ContractUnitManager extends BaseFunctionManager {
StringBuilder ret = new StringBuilder(); StringBuilder ret = new StringBuilder();
int count = 0; int count = 0;
for (String s : strs) { for (String s : strs) {
if (s.contains("sun.reflect") || s.contains("java.lang.reflect") if (s.contains("sun.reflect")
|| s.contains("org.apache") || s.contains("java.util") || s.contains("java.lang.reflect")
|| s.contains("java.lang") || s.contains("io.netty")) { || s.contains("org.apache")
|| s.contains("java.util")
|| s.contains("java.lang")
|| s.contains("io.netty")) {
continue; continue;
} }
ret.append(s); ret.append(s);

View File

@ -46,31 +46,34 @@ public class ExecutionManager extends BaseFunctionManager {
private final BDLedgerContract.UnitMessageType UNIT_MESSAGE_TYPE = private final BDLedgerContract.UnitMessageType UNIT_MESSAGE_TYPE =
BDLedgerContract.UnitMessageType.UnitContractMessage; BDLedgerContract.UnitMessageType.UnitContractMessage;
public Map<String, String> contractID2Sequencing = new HashMap<>(); public Map<String, String> contractID2Sequencing = new HashMap<>();
// protected MasterServerTCPAction masterActions; // protected MasterServerTCPAction masterActions;
// protected MasterClientTCPAction clientActions; // protected MasterClientTCPAction clientActions;
protected ActionExecutor<ResultCallback, JsonObject> actionExecutor; protected ActionExecutor<ResultCallback, JsonObject> actionExecutor;
private Map<String, String> contractID2PubKey = new HashMap<>(); private Map<String, String> contractID2PubKey = new HashMap<>();
private Map<String, RequestCache> requestCaches = new ConcurrentHashMap<>(); private Map<String, RequestCache> requestCaches = new ConcurrentHashMap<>();
private String nextContractID; private String nextContractID;
public static ExecutionManager instance = init(); public static ExecutionManager instance = init();
public ExecutionManager() {} public ExecutionManager() {
}
public static ExecutionManager init() { public static ExecutionManager init() {
if (instance != null) { if (instance != null) {
return instance; return instance;
} }
instance = new ExecutionManager(); instance = new ExecutionManager();
// instance.masterActions = new MasterServerTCPAction(); // instance.masterActions = new MasterServerTCPAction();
// instance.clientActions = new MasterClientTCPAction(); // instance.clientActions = new MasterClientTCPAction();
instance.actionExecutor = new ActionExecutor<ResultCallback, JsonObject>(executorService) { // , instance.actionExecutor =
// instance.masterActions, new ActionExecutor<ResultCallback, JsonObject>(
// instance.clientActions) { executorService) { // , instance.masterActions,
@Override // instance.clientActions) {
public boolean checkPermission(Action a, final JsonObject args, long permission) { @Override
return true; public boolean checkPermission(
} Action a, final JsonObject args, long permission) {
}; return true;
}
};
return instance; return instance;
} }
@ -79,29 +82,33 @@ public class ExecutionManager extends BaseFunctionManager {
arg.addProperty("sender", sender); arg.addProperty("sender", sender);
Response response; Response response;
try { try {
// if (arg.get("msgType").getAsInt() == 1) { // if (arg.get("msgType").getAsInt() == 1) {
// handleResponse(arg); // handleResponse(arg);
// return; // return;
// } // }
final String action = arg.get("action").getAsString(); final String action = arg.get("action").getAsString();
LOGGER.info("[ExecutionManager] handle:" + arg.toString()); LOGGER.info("[ExecutionManager] handle:" + arg.toString());
// requestID2Sender.put(arg.get("requestID").getAsString(), sender); // requestID2Sender.put(arg.get("requestID").getAsString(), sender);
actionExecutor.handle(action, arg, new ResultCallback() { actionExecutor.handle(
@Override action,
public void onResult(String msg) { arg,
try { new ResultCallback() {
UnitMessage unitMessage = UnitMessage.parseFrom(ByteUtil.decodeBASE64(msg)); @Override
NetworkManager.instance.send(unitMessage); public void onResult(String msg) {
} catch (InvalidProtocolBufferException e) { try {
e.printStackTrace(); UnitMessage unitMessage =
} UnitMessage.parseFrom(ByteUtil.decodeBASE64(msg));
} NetworkManager.instance.send(unitMessage);
}); } catch (InvalidProtocolBufferException e) {
e.printStackTrace();
}
}
});
} catch (IllegalArgumentException e) { } catch (IllegalArgumentException e) {
response = new Response(); response = new Response();
response.action = "onException"; response.action = "onException";
response.data = e.getMessage(); response.data = e.getMessage();
ExecutionManager.instance.send(JsonUtil.toJson(response), new String[] {sender}); ExecutionManager.instance.send(JsonUtil.toJson(response), new String[]{sender});
} catch (Exception e) { } catch (Exception e) {
e.printStackTrace(); e.printStackTrace();
ByteArrayOutputStream bo = new ByteArrayOutputStream(); ByteArrayOutputStream bo = new ByteArrayOutputStream();
@ -112,9 +119,12 @@ public class ExecutionManager extends BaseFunctionManager {
StringBuilder ret = new StringBuilder(); StringBuilder ret = new StringBuilder();
int count = 0; int count = 0;
for (String s : strs) { for (String s : strs) {
if (s.contains("sun.reflect") || s.contains("java.lang.reflect") if (s.contains("sun.reflect")
|| s.contains("org.apache") || s.contains("java.util") || s.contains("java.lang.reflect")
|| s.contains("java.lang") || s.contains("io.netty")) { || s.contains("org.apache")
|| s.contains("java.util")
|| s.contains("java.lang")
|| s.contains("io.netty")) {
continue; continue;
} }
ret.append(s); ret.append(s);
@ -133,11 +143,11 @@ public class ExecutionManager extends BaseFunctionManager {
*/ */
public void updateLocalContractToNodeCenter() { public void updateLocalContractToNodeCenter() {
ControllerManager.getNodeCenterController().updateContract(); ControllerManager.getNodeCenterController().updateContract();
// List<?> info = CMActions.manager.getContractDespList(); // List<?> info = CMActions.manager.getContractDespList();
// JsonObject jo = new JsonObject(); // JsonObject jo = new JsonObject();
// jo.addProperty("action", "updateContract"); // jo.addProperty("action", "updateContract");
// jo.addProperty("contracts", JsonUtil.toJson(info)); // jo.addProperty("contracts", JsonUtil.toJson(info));
// send(jo.toString(), new String[]{GlobalConf.getNodeCenterAddress()}); // send(jo.toString(), new String[]{GlobalConf.getNodeCenterAddress()});
} }
public void killContractRequest(String contract, ResultCallback rc) { public void killContractRequest(String contract, ResultCallback rc) {
@ -154,15 +164,21 @@ public class ExecutionManager extends BaseFunctionManager {
if (info.consensusType == ConsensusType.None) { if (info.consensusType == ConsensusType.None) {
peers = info.getMembers().toArray(new String[info.members.size()]); peers = info.getMembers().toArray(new String[info.members.size()]);
} else { } else {
peers = new String[] {info.master}; peers = new String[]{info.master};
} }
ResponseCenter responseCenter = new ResponseCenter(requestId, rc, peers.length, ResponseCenter responseCenter =
UnitContractRequestType.STOP, ResponseType.ALL.getValue()); new ResponseCenter(
requestId,
rc,
peers.length,
UnitContractRequestType.STOP,
ResponseType.ALL.getValue());
responseCenter.setInfos(contract); responseCenter.setInfos(contract);
this.responseCenters.put(requestId, responseCenter); this.responseCenters.put(requestId, responseCenter);
// respCaches.put(requestId, new RespCache(num)); // respCaches.put(requestId, new RespCache(num));
UnitContractMessage unitContractMessage = UnitContractMessage unitContractMessage =
new UnitContractMessage(UnitContractMessageType.ContractUnitRequest.getValue(), new UnitContractMessage(
UnitContractMessageType.ContractUnitRequest.getValue(),
UnitContractRequestType.STOP.getValue()); UnitContractRequestType.STOP.getValue());
unitContractMessage.action = "stopContractAtSlave"; unitContractMessage.action = "stopContractAtSlave";
unitContractMessage.requestID = requestId; unitContractMessage.requestID = requestId;
@ -174,38 +190,49 @@ public class ExecutionManager extends BaseFunctionManager {
unitContractMessage.collector = GlobalConf.instance.peerID; unitContractMessage.collector = GlobalConf.instance.peerID;
// Sequencing // Sequencing
if (consensusType != ConsensusType.None) { if (consensusType != ConsensusType.None) {
SequencingManager.instance.sequencingRequest(unitContractMessage.contractID, SequencingManager.instance.sequencingRequest(
unitContractMessage, peers, rc); unitContractMessage.contractID, unitContractMessage, peers, rc);
} else { } else {
String msgContent = JsonUtil.toJson(unitContractMessage); String msgContent = JsonUtil.toJson(unitContractMessage);
UnitMessage unitMessage; UnitMessage unitMessage;
unitMessage = UnitMessage.newBuilder() unitMessage =
.setMsgType(BDLedgerContract.UnitMessageType.UnitContractMessage) UnitMessage.newBuilder()
.setContent(ByteString.copyFromUtf8(msgContent)) .setMsgType(BDLedgerContract.UnitMessageType.UnitContractMessage)
.setSender(GlobalConf.instance.peerID).addAllReceiver(Arrays.asList(peers)) .setContent(ByteString.copyFromUtf8(msgContent))
.build(); .setSender(GlobalConf.instance.peerID)
.addAllReceiver(Arrays.asList(peers))
.build();
NetworkManager.instance.send(unitMessage, networkType); NetworkManager.instance.send(unitMessage, networkType);
} }
} }
public void startContractRequest(boolean tcpType, String contract, int num, String[] peers, public void startContractRequest(
String content, int sequencing, int response, ResultCallback resultCallback) { boolean tcpType,
String contract,
int num,
String[] peers,
String content,
int sequencing,
int response,
ResultCallback resultCallback) {
LOGGER.info("[startContractRequest] " + contract + " " + num); LOGGER.info("[startContractRequest] " + contract + " " + num);
String requestId = getRequestId(); String requestId = getRequestId();
// this.requestCallbacks.put(requestId, resultCallback); // this.requestCallbacks.put(requestId, resultCallback);
ResponseCenter responseCenter = new ResponseCenter(requestId, resultCallback, num, ResponseCenter responseCenter =
UnitContractRequestType.START, response); new ResponseCenter(
requestId, resultCallback, num, UnitContractRequestType.START, response);
responseCenter.setType(ResponseType.ALL); responseCenter.setType(ResponseType.ALL);
this.responseCenters.put(requestId, responseCenter); this.responseCenters.put(requestId, responseCenter);
// respCaches.put(requestId, new RespCache(num)); // respCaches.put(requestId, new RespCache(num));
UnitContractMessage unitContractMessage = UnitContractMessage unitContractMessage =
new UnitContractMessage(UnitContractMessageType.ContractUnitRequest.getValue(), new UnitContractMessage(
UnitContractMessageType.ContractUnitRequest.getValue(),
UnitContractRequestType.START.getValue()); UnitContractRequestType.START.getValue());
unitContractMessage.action = "startContractAtSlave"; unitContractMessage.action = "startContractAtSlave";
unitContractMessage.requestID = requestId; unitContractMessage.requestID = requestId;
unitContractMessage.contractID = getNextContractID(); unitContractMessage.contractID = getNextContractID();
ExecutionManager.instance.askForNextContractID(); ExecutionManager.instance.askForNextContractID();
// logger.info("hashcode " + nextContractID.hashCode()); // logger.info("hashcode " + nextContractID.hashCode());
unitContractMessage.content = content; unitContractMessage.content = content;
unitContractMessage.sequencing = sequencing; unitContractMessage.sequencing = sequencing;
unitContractMessage.rcheck = response; unitContractMessage.rcheck = response;
@ -215,18 +242,22 @@ public class ExecutionManager extends BaseFunctionManager {
UnitMessage unitMessage; UnitMessage unitMessage;
if (null != peers && peers.length > 0) { if (null != peers && peers.length > 0) {
responseCenter.updatePeers(peers); responseCenter.updatePeers(peers);
unitMessage = UnitMessage.newBuilder() unitMessage =
.setMsgType(BDLedgerContract.UnitMessageType.UnitContractMessage) UnitMessage.newBuilder()
.setContent(ByteString.copyFromUtf8(msgContent)) .setMsgType(BDLedgerContract.UnitMessageType.UnitContractMessage)
.addAllReceiver(Arrays.asList(peers)).setSender(GlobalConf.instance.peerID) .setContent(ByteString.copyFromUtf8(msgContent))
.build(); .addAllReceiver(Arrays.asList(peers))
.setSender(GlobalConf.instance.peerID)
.build();
} else { } else {
// abandon java needs to know peers in order to collect response // abandon java needs to know peers in order to collect response
// No specified receiver, send to p2p nodes randomly // No specified receiver, send to p2p nodes randomly
unitMessage = UnitMessage.newBuilder() unitMessage =
.setMsgType(BDLedgerContract.UnitMessageType.UnitContractMessage) UnitMessage.newBuilder()
.setContent(ByteString.copyFromUtf8(msgContent)) .setMsgType(BDLedgerContract.UnitMessageType.UnitContractMessage)
.setSender(GlobalConf.instance.peerID).build(); .setContent(ByteString.copyFromUtf8(msgContent))
.setSender(GlobalConf.instance.peerID)
.build();
} }
NetworkManager.instance.send(unitMessage, tcpType ? NetworkType.TCP : NetworkType.P2P); NetworkManager.instance.send(unitMessage, tcpType ? NetworkType.TCP : NetworkType.P2P);
} }
@ -241,24 +272,32 @@ public class ExecutionManager extends BaseFunctionManager {
nextContractID = content; nextContractID = content;
} }
public void executeContractRequest(String contract, String operation, String arg, int network, public void executeContractRequest(
int sequencing, int responseType, ResultCallback rc) { String contract,
String operation,
String arg,
int network,
int sequencing,
int responseType,
ResultCallback rc) {
String requestId = getRequestId(); String requestId = getRequestId();
// this.requestCallbacks.put(requestId, resultCallback); // this.requestCallbacks.put(requestId, resultCallback);
String[] peers; String[] peers;
MultiPointContractInfo info = ContractUnitManager.instance.getContractInfo(contract); MultiPointContractInfo info = ContractUnitManager.instance.getContractInfo(contract);
if (info.consensusType == ConsensusType.None) { if (info.consensusType == ConsensusType.None) {
peers = info.getMembers().toArray(new String[info.members.size()]); peers = info.getMembers().toArray(new String[info.members.size()]);
} else { } else {
peers = new String[] {info.master}; peers = new String[]{info.master};
} }
ResponseCenter responseCenter = new ResponseCenter(requestId, rc, peers.length, ResponseCenter responseCenter =
UnitContractRequestType.EXECUTE, responseType); new ResponseCenter(
requestId, rc, peers.length, UnitContractRequestType.EXECUTE, responseType);
responseCenter.setInfos(contract); responseCenter.setInfos(contract);
this.responseCenters.put(requestId, responseCenter); this.responseCenters.put(requestId, responseCenter);
// respCaches.put(requestId, new RespCache(num)); // respCaches.put(requestId, new RespCache(num));
UnitContractMessage unitContractMessage = UnitContractMessage unitContractMessage =
new UnitContractMessage(UnitContractMessageType.ContractUnitRequest.getValue(), new UnitContractMessage(
UnitContractMessageType.ContractUnitRequest.getValue(),
UnitContractRequestType.EXECUTE.getValue()); UnitContractRequestType.EXECUTE.getValue());
unitContractMessage.action = "executeContractAtSlave"; unitContractMessage.action = "executeContractAtSlave";
unitContractMessage.requestID = requestId; unitContractMessage.requestID = requestId;
@ -271,54 +310,61 @@ public class ExecutionManager extends BaseFunctionManager {
// Sequencing // Sequencing
ConsensusType consensusType = ConsensusType.getType(sequencing); ConsensusType consensusType = ConsensusType.getType(sequencing);
if (consensusType != ConsensusType.None) { if (consensusType != ConsensusType.None) {
SequencingManager.instance.sequencingRequest(unitContractMessage.contractID, SequencingManager.instance.sequencingRequest(
unitContractMessage, peers, rc); unitContractMessage.contractID, unitContractMessage, peers, rc);
} else { } else {
String msgContent = JsonUtil.toJson(unitContractMessage); String msgContent = JsonUtil.toJson(unitContractMessage);
UnitMessage unitMessage; UnitMessage unitMessage;
unitMessage = UnitMessage.newBuilder() unitMessage =
.setMsgType(BDLedgerContract.UnitMessageType.UnitContractMessage) UnitMessage.newBuilder()
.setContent(ByteString.copyFromUtf8(msgContent)) .setMsgType(BDLedgerContract.UnitMessageType.UnitContractMessage)
.setSender(GlobalConf.instance.peerID).addAllReceiver(Arrays.asList(peers)) .setContent(ByteString.copyFromUtf8(msgContent))
.build(); .setSender(GlobalConf.instance.peerID)
.addAllReceiver(Arrays.asList(peers))
.build();
NetworkManager.instance.send(unitMessage, NetworkType.getType(network)); NetworkManager.instance.send(unitMessage, NetworkType.getType(network));
} }
} }
public void stopContractRequest(String contract, String operation, String arg, int network, public void stopContractRequest(
int sequencing, ResultCallback rc) { String contract,
// String requestId = getRequestId(); String operation,
//// this.requestCallbacks.put(requestId, resultCallback); String arg,
// MultiPointContractInfo info = int network,
int sequencing,
ResultCallback rc) {
// String requestId = getRequestId();
//// this.requestCallbacks.put(requestId, resultCallback);
// MultiPointContractInfo info =
// ContractUnitManager.instance.getContractInfo(contract); // ContractUnitManager.instance.getContractInfo(contract);
// String[] peers; // String[] peers;
// if (info.consensusType == ConsensusType.None) { // if (info.consensusType == ConsensusType.None) {
// peers = info.getMembers().toArray(new String[info.members.size()]); // peers = info.getMembers().toArray(new String[info.members.size()]);
// } else { // } else {
// peers = new String[]{info.master}; // peers = new String[]{info.master};
// } // }
// this.responseCenters.put(requestId, new ResponseCenter(requestId, rc, // this.responseCenters.put(requestId, new ResponseCenter(requestId, rc,
// peers.length, UnitContractRequestType.EXECUTE, sequencing)); // peers.length, UnitContractRequestType.EXECUTE, sequencing));
//// respCaches.put(requestId, new RespCache(num)); //// respCaches.put(requestId, new RespCache(num));
// UnitContractMessage unitContractMessage = new UnitContractMessage( // UnitContractMessage unitContractMessage = new UnitContractMessage(
// UnitContractMessageType.ContractUnitRequest.getValue(), // UnitContractMessageType.ContractUnitRequest.getValue(),
// UnitContractRequestType.EXECUTE.getValue()); // UnitContractRequestType.EXECUTE.getValue());
// unitContractMessage.action = "executeContractAtSlave"; // unitContractMessage.action = "executeContractAtSlave";
// unitContractMessage.requestID = requestId; // unitContractMessage.requestID = requestId;
// unitContractMessage.contractID = contract; // unitContractMessage.contractID = contract;
// unitContractMessage.operation = operation; // unitContractMessage.operation = operation;
// unitContractMessage.arg = arg; // unitContractMessage.arg = arg;
// unitContractMessage.sequencing = sequencing; // unitContractMessage.sequencing = sequencing;
// unitContractMessage.network = network; // unitContractMessage.network = network;
// String msgContent = gson.toJson(unitContractMessage); // String msgContent = gson.toJson(unitContractMessage);
// UnitMessage unitMessage; // UnitMessage unitMessage;
// unitMessage = UnitMessage.newBuilder() // unitMessage = UnitMessage.newBuilder()
// .setMsgType(BDLedgerContract.UnitMessageType.UnitContractMessage) // .setMsgType(BDLedgerContract.UnitMessageType.UnitContractMessage)
// .setContent(ByteString.copyFromUtf8(msgContent)) // .setContent(ByteString.copyFromUtf8(msgContent))
// .setSender(GlobalConf.instance.peerID) // .setSender(GlobalConf.instance.peerID)
// .addAllReceiver(Arrays.asList(peers)) // .addAllReceiver(Arrays.asList(peers))
// .build(); // .build();
// NetworkManager.instance.send(unitMessage, NetworkType.getType(network)); // NetworkManager.instance.send(unitMessage, NetworkType.getType(network));
} }
public void askForNextContractID() { public void askForNextContractID() {
@ -343,4 +389,5 @@ public class ExecutionManager extends BaseFunctionManager {
} }

View File

@ -9,7 +9,7 @@ public class RecoveryManager extends BaseFunctionManager {
JsonObject jo = new JsonObject(); JsonObject jo = new JsonObject();
jo.addProperty("action", "NCStartElect"); jo.addProperty("action", "NCStartElect");
jo.addProperty("contractID", contractID); jo.addProperty("contractID", contractID);
// NetworkManager.instance.cmClientHandler.sendMsg(JsonUtil.toJson(jo)); //NetworkManager.instance.cmClientHandler.sendMsg(JsonUtil.toJson(jo));
} }

View File

@ -23,15 +23,16 @@ import java.util.Map;
public class SequencingManager extends BaseFunctionManager { public class SequencingManager extends BaseFunctionManager {
private static final String MANAGER_SYMBOL = "SEQUENCING"; private static final String MANAGER_SYMBOL = "SEQUENCING";
private static final Logger LOGGER = LogManager.getLogger(SequencingManager.class); private static final Logger LOGGER = LogManager.getLogger(SequencingManager.class);
// protected SequencingActions sequencingActions; // protected SequencingActions sequencingActions;
// protected ActionExecutor<ResultCallback, JsonObject> actionExecutor; // protected ActionExecutor<ResultCallback, JsonObject> actionExecutor;
private final BDLedgerContract.UnitMessageType UNIT_MESSAGE_TYPE = private final BDLedgerContract.UnitMessageType UNIT_MESSAGE_TYPE =
BDLedgerContract.UnitMessageType.UnitSequencingMessage; BDLedgerContract.UnitMessageType.UnitSequencingMessage;
// protected static ExecutorService executorService = Executors.newFixedThreadPool(10); // protected static ExecutorService executorService = Executors.newFixedThreadPool(10);
private final Map<String, ConsensusCenter> consensusCenters = new HashMap<>(); private final Map<String, ConsensusCenter> consensusCenters = new HashMap<>();
public static SequencingManager instance = init(); public static SequencingManager instance = init();
public SequencingManager() {} public SequencingManager() {
}
public static SequencingManager init() { public static SequencingManager init() {
if (null != instance) { if (null != instance) {
@ -50,8 +51,8 @@ public class SequencingManager extends BaseFunctionManager {
String contractID = unitSequencingMessage.contractID; String contractID = unitSequencingMessage.contractID;
ConsensusCenter consensusCenter = consensusCenters.get(contractID); ConsensusCenter consensusCenter = consensusCenters.get(contractID);
if (null == consensusCenter) { if (null == consensusCenter) {
// consensusCenter = createConsensusCenter(unitSequencingMessage); // consensusCenter = createConsensusCenter(unitSequencingMessage);
// this.consensusCenters.put(contractID, consensusCenter); // this.consensusCenters.put(contractID, consensusCenter);
} }
// create null, then no dingxu // create null, then no dingxu
if (null == consensusCenter) { if (null == consensusCenter) {
@ -59,124 +60,125 @@ public class SequencingManager extends BaseFunctionManager {
return; return;
} }
consensusCenter.handle(unitSequencingMessage); consensusCenter.handle(unitSequencingMessage);
// try { // try {
//// if (arg.get("msgType").getAsInt() == 1) { //// if (arg.get("msgType").getAsInt() == 1) {
//// handleResponse(arg); //// handleResponse(arg);
//// return; //// return;
//// } //// }
// final String action = arg.get("action").getAsString(); // final String action = arg.get("action").getAsString();
// logger.info("[SequencingManager] handle:" + arg.toString()); // logger.info("[SequencingManager] handle:" + arg.toString());
// actionExecutor.handle(action, arg, // actionExecutor.handle(action, arg,
// new ResultCallback() { // new ResultCallback() {
// @Override // @Override
// public void onResult(String msg) { // public void onResult(String msg) {
// try { // try {
// BDLedgerContract.UnitMessage unitMessage = // BDLedgerContract.UnitMessage unitMessage =
// BDLedgerContract.UnitMessage.parseFrom(Base64.decode(msg)); // BDLedgerContract.UnitMessage.parseFrom(Base64.decode(msg));
// NetworkManager.instance.send(unitMessage); // NetworkManager.instance.send(unitMessage);
// } catch (InvalidProtocolBufferException e) { // } catch (InvalidProtocolBufferException e) {
// e.printStackTrace(); // e.printStackTrace();
// } // }
// } // }
// }); // });
// } catch (IllegalArgumentException e) { // } catch (IllegalArgumentException e) {
// response = new SequencingManager.Response(); // response = new SequencingManager.Response();
// response.action = "onException"; // response.action = "onException";
// response.data = e.getMessage(); // response.data = e.getMessage();
// ExecutionManager.instance.send(JsonUtil.toJson(response), new String[]{sender}); // ExecutionManager.instance.send(JsonUtil.toJson(response), new String[]{sender});
// } catch (Exception e) { // } catch (Exception e) {
// e.printStackTrace(); // e.printStackTrace();
// ByteArrayOutputStream bo = new ByteArrayOutputStream(); // ByteArrayOutputStream bo = new ByteArrayOutputStream();
// e.printStackTrace(new PrintStream(bo)); // e.printStackTrace(new PrintStream(bo));
// response = new SequencingManager.Response(); // response = new SequencingManager.Response();
// response.action = "onException"; // response.action = "onException";
// String[] strs = bo.toString().split("\n"); // String[] strs = bo.toString().split("\n");
// StringBuilder ret = new StringBuilder(); // StringBuilder ret = new StringBuilder();
// int count = 0; // int count = 0;
// for (String s : strs) { // for (String s : strs) {
// if (s.contains("sun.reflect") // if (s.contains("sun.reflect")
// || s.contains("java.lang.reflect") // || s.contains("java.lang.reflect")
// || s.contains("org.apache") // || s.contains("org.apache")
// || s.contains("java.util") // || s.contains("java.util")
// || s.contains("java.lang") // || s.contains("java.lang")
// || s.contains("io.netty")) { // || s.contains("io.netty")) {
// continue; // continue;
// } // }
// ret.append(s); // ret.append(s);
// ret.append("\n"); // ret.append("\n");
// if (count++ > 10) { // if (count++ > 10) {
// break; // break;
// } // }
// } // }
// response.data = ret.toString(); // response.data = ret.toString();
// logger.debug(JsonUtil.toJson(response)); // logger.debug(JsonUtil.toJson(response));
// } // }
} }
public void createConsensusCenterToStore(UnitContractMessage msg) { public void createConsensusCenterToStore(UnitContractMessage msg) {
// create local center //create local center
String contractID = msg.contractID; String contractID = msg.contractID;
ConsensusCenter consensusCenter = createConsensusCenter(msg); ConsensusCenter consensusCenter = createConsensusCenter(msg);
consensusCenters.put(contractID, consensusCenter); consensusCenters.put(contractID, consensusCenter);
} }
public void sequencingRequest(String contractID, UnitContractMessage msg, String[] peers, public void sequencingRequest(
String contractID,
UnitContractMessage msg,
String[] peers,
ResultCallback resultCallback) { ResultCallback resultCallback) {
// content is UnitContractMessage // content is UnitContractMessage
// ConsensusCenter consensusCenter = consensusCenters.get(contractID); // ConsensusCenter consensusCenter = consensusCenters.get(contractID);
// if (null == consensusCenter) { // if (null == consensusCenter) {
// consensusCenter = createConsensusCenter(msg); // consensusCenter = createConsensusCenter(msg);
// this.consensusCenters.put(contractID, consensusCenter); // this.consensusCenters.put(contractID, consensusCenter);
// } // }
// // create null, then no dingxu // // create null, then no dingxu
// if (consensusCenter == null) { // if (consensusCenter == null) {
// ExecutionManager.instance.send(gson.toJson(msg), peers); // ExecutionManager.instance.send(gson.toJson(msg), peers);
// return; // return;
// } // }
String requestID = msg.requestID; String requestID = msg.requestID;
requestCallbacks.put(requestID, resultCallback); requestCallbacks.put(requestID, resultCallback);
UnitSequencingMessage sequencingMessage = UnitSequencingMessage sequencingMessage = new UnitSequencingMessage(ConsensusStage.Request.toInt());
new UnitSequencingMessage(ConsensusStage.Request.toInt());
sequencingMessage.sequencing = msg.sequencing; sequencingMessage.sequencing = msg.sequencing;
sequencingMessage.network = msg.network; sequencingMessage.network = msg.network;
sequencingMessage.contractID = contractID; sequencingMessage.contractID = contractID;
sequencingMessage.requestID = requestID; sequencingMessage.requestID = requestID;
sequencingMessage.content = JsonUtil.toJson(msg); sequencingMessage.content = JsonUtil.toJson(msg);
sequencingMessage.master = ContractUnitManager.instance.getMaster(contractID); sequencingMessage.master = ContractUnitManager.instance.getMaster(contractID);
send(JsonUtil.toJson(sequencingMessage), new String[] {sequencingMessage.master}); send(JsonUtil.toJson(sequencingMessage), new String[]{sequencingMessage.master});
// this.responseCenters.put(requestId, // this.responseCenters.put(requestId,
// new ResponseCenter(requestId, resultCallback, num, UnitContractRequestType.START, // new ResponseCenter(requestId, resultCallback, num, UnitContractRequestType.START, sequencing));
// sequencing)); //// respCaches.put(requestId, new RespCache(num));
//// respCaches.put(requestId, new RespCache(num)); // UnitContractMessage unitContractMessage = new UnitContractMessage(
// UnitContractMessage unitContractMessage = new UnitContractMessage( // UnitContractMessageType.ContractUnitRequest.getValue(),
// UnitContractMessageType.ContractUnitRequest.getValue(), // UnitContractRequestType.START.getValue());
// UnitContractRequestType.START.getValue()); // unitContractMessage.action = "startContractAtSlave";
// unitContractMessage.action = "startContractAtSlave"; // unitContractMessage.requestID = requestId;
// unitContractMessage.requestID = requestId; //// unitContractMessage.contractID = contract;
//// unitContractMessage.contractID = contract; // unitContractMessage.content = content;
// unitContractMessage.content = content; // unitContractMessage.sequencing = sequencing;
// unitContractMessage.sequencing = sequencing; // unitContractMessage.num = num;
// unitContractMessage.num = num; // unitContractMessage.network = tcpType?0:1;
// unitContractMessage.network = tcpType?0:1; // String msgContent = gson.toJson(unitContractMessage);
// String msgContent = gson.toJson(unitContractMessage); // BDLedgerContract.UnitMessage unitMessage;
// BDLedgerContract.UnitMessage unitMessage; // if (null != peers && peers.length > 0) {
// if (null != peers && peers.length > 0) { // unitMessage = BDLedgerContract.UnitMessage.newBuilder()
// unitMessage = BDLedgerContract.UnitMessage.newBuilder() // .setMsgType(BDLedgerContract.UnitMessageType.UnitContractMessage)
// .setMsgType(BDLedgerContract.UnitMessageType.UnitContractMessage) // .setContent(ByteString.copyFromUtf8(msgContent))
// .setContent(ByteString.copyFromUtf8(msgContent)) // .addAllReceiver(Arrays.asList(peers))
// .addAllReceiver(Arrays.asList(peers)) // .setSender(GlobalConf.instance.peerID)
// .setSender(GlobalConf.instance.peerID) // .build();
// .build(); // } else {
// } else { // // No specified receiver, send to p2p nodes randomly
// // No specified receiver, send to p2p nodes randomly // unitMessage = BDLedgerContract.UnitMessage.newBuilder()
// unitMessage = BDLedgerContract.UnitMessage.newBuilder() // .setMsgType(BDLedgerContract.UnitMessageType.UnitContractMessage)
// .setMsgType(BDLedgerContract.UnitMessageType.UnitContractMessage) // .setContent(ByteString.copyFromUtf8(msgContent))
// .setContent(ByteString.copyFromUtf8(msgContent)) // .setSender(GlobalConf.instance.peerID)
// .setSender(GlobalConf.instance.peerID) // .build();
// .build(); // }
// } // NetworkManager.instance.send(unitMessage, tcpType?null:NetworkManager.P2P_GRPC_CLIENT);
// NetworkManager.instance.send(unitMessage, tcpType?null:NetworkManager.P2P_GRPC_CLIENT);
} }
private ConsensusCenter createConsensusCenter(UnitContractMessage msg) { private ConsensusCenter createConsensusCenter(UnitContractMessage msg) {
@ -193,21 +195,19 @@ public class SequencingManager extends BaseFunctionManager {
} }
public void updateContractInfo2Unit(int network, String contractID, String firstSuccessPeer) { public void updateContractInfo2Unit(int network, String contractID, String firstSuccessPeer) {
MultiPointContractInfo contractInfo = MultiPointContractInfo contractInfo = ContractUnitManager.instance.getContractInfo(contractID);
ContractUnitManager.instance.getContractInfo(contractID);
contractInfo.master = firstSuccessPeer; contractInfo.master = firstSuccessPeer;
UnitContractMessage unitContractMessage = new UnitContractMessage(0); UnitContractMessage unitContractMessage = new UnitContractMessage(0);
unitContractMessage.content = JsonUtil.toJson(contractInfo); unitContractMessage.content = JsonUtil.toJson(contractInfo);
unitContractMessage.contractID = contractID; unitContractMessage.contractID = contractID;
// unitContractMessage.network = network; // unitContractMessage.network = network;
unitContractMessage.action = "updateContractStartInfo"; unitContractMessage.action = "updateContractStartInfo";
send(JsonUtil.toJson(unitContractMessage), contractInfo.getMembers().toArray(new String[0]), send(JsonUtil.toJson(unitContractMessage),
BDLedgerContract.UnitMessageType.UnitUnitMessage); contractInfo.getMembers().toArray(new String[0]), BDLedgerContract.UnitMessageType.UnitUnitMessage);
} }
public void updateConsensusCenter(String contractID, MultiPointContractInfo info) { public void updateConsensusCenter(String contractID, MultiPointContractInfo info) {
LOGGER.info("[updateConsensusCenter] consensusCenters " + contractID + " " LOGGER.info("[updateConsensusCenter] consensusCenters " + contractID + " " + consensusCenters.size());
+ consensusCenters.size());
ConsensusCenter consensusCenter = consensusCenters.get(contractID); ConsensusCenter consensusCenter = consensusCenters.get(contractID);
while (null == consensusCenter) { while (null == consensusCenter) {
try { try {
@ -232,4 +232,5 @@ public class SequencingManager extends BaseFunctionManager {
} }

File diff suppressed because it is too large Load Diff

View File

@ -1,207 +1,216 @@
package org.bdware.units.grpc; package org.bdware.units.grpc;
import static io.grpc.stub.ClientCalls.asyncUnaryCall;
import static io.grpc.stub.ClientCalls.asyncServerStreamingCall;
import static io.grpc.stub.ClientCalls.asyncClientStreamingCall;
import static io.grpc.stub.ClientCalls.asyncBidiStreamingCall; import static io.grpc.stub.ClientCalls.asyncBidiStreamingCall;
import static io.grpc.stub.ClientCalls.blockingUnaryCall;
import static io.grpc.stub.ClientCalls.blockingServerStreamingCall;
import static io.grpc.stub.ClientCalls.futureUnaryCall;
import static io.grpc.MethodDescriptor.generateFullMethodName; import static io.grpc.MethodDescriptor.generateFullMethodName;
import static io.grpc.stub.ServerCalls.asyncUnaryCall;
import static io.grpc.stub.ServerCalls.asyncServerStreamingCall;
import static io.grpc.stub.ServerCalls.asyncClientStreamingCall;
import static io.grpc.stub.ServerCalls.asyncBidiStreamingCall; import static io.grpc.stub.ServerCalls.asyncBidiStreamingCall;
import static io.grpc.stub.ServerCalls.asyncUnimplementedUnaryCall;
import static io.grpc.stub.ServerCalls.asyncUnimplementedStreamingCall; import static io.grpc.stub.ServerCalls.asyncUnimplementedStreamingCall;
/** /**
*/ */
@javax.annotation.Generated(value = "by gRPC proto compiler (version 1.4.1-SNAPSHOT)", @javax.annotation.Generated(
comments = "Source: BDLedgerContract.proto") value = "by gRPC proto compiler (version 1.4.1-SNAPSHOT)",
comments = "Source: BDLedgerContract.proto")
public final class BDLedgerContractServiceGrpc { public final class BDLedgerContractServiceGrpc {
private BDLedgerContractServiceGrpc() {} private BDLedgerContractServiceGrpc() {}
public static final String SERVICE_NAME = "BDLedgerContractService"; public static final String SERVICE_NAME = "BDLedgerContractService";
// Static method descriptors that strictly reflect the proto. // Static method descriptors that strictly reflect the proto.
@io.grpc.ExperimentalApi("https://github.com/grpc/grpc-java/issues/1901") @io.grpc.ExperimentalApi("https://github.com/grpc/grpc-java/issues/1901")
public static final io.grpc.MethodDescriptor<BDLedgerContract.UnitMessage, BDLedgerContract.UnitMessage> METHOD_BDLEDGER_CONTRACT_STREAM = public static final io.grpc.MethodDescriptor<BDLedgerContract.UnitMessage,
io.grpc.MethodDescriptor.<BDLedgerContract.UnitMessage, BDLedgerContract.UnitMessage>newBuilder() BDLedgerContract.UnitMessage> METHOD_BDLEDGER_CONTRACT_STREAM =
.setType(io.grpc.MethodDescriptor.MethodType.BIDI_STREAMING) io.grpc.MethodDescriptor.<BDLedgerContract.UnitMessage, BDLedgerContract.UnitMessage>newBuilder()
.setFullMethodName(generateFullMethodName("BDLedgerContractService", .setType(io.grpc.MethodDescriptor.MethodType.BIDI_STREAMING)
"BDLedgerContractStream")) .setFullMethodName(generateFullMethodName(
.setRequestMarshaller(io.grpc.protobuf.ProtoUtils "BDLedgerContractService", "BDLedgerContractStream"))
.marshaller(BDLedgerContract.UnitMessage.getDefaultInstance())) .setRequestMarshaller(io.grpc.protobuf.ProtoUtils.marshaller(
.setResponseMarshaller(io.grpc.protobuf.ProtoUtils BDLedgerContract.UnitMessage.getDefaultInstance()))
.marshaller(BDLedgerContract.UnitMessage.getDefaultInstance())) .setResponseMarshaller(io.grpc.protobuf.ProtoUtils.marshaller(
.build(); BDLedgerContract.UnitMessage.getDefaultInstance()))
.build();
/**
* Creates a new async stub that supports all call types for the service
*/
public static BDLedgerContractServiceStub newStub(io.grpc.Channel channel) {
return new BDLedgerContractServiceStub(channel);
}
/**
* Creates a new blocking-style stub that supports unary and streaming output calls on the service
*/
public static BDLedgerContractServiceBlockingStub newBlockingStub(
io.grpc.Channel channel) {
return new BDLedgerContractServiceBlockingStub(channel);
}
/**
* Creates a new ListenableFuture-style stub that supports unary calls on the service
*/
public static BDLedgerContractServiceFutureStub newFutureStub(
io.grpc.Channel channel) {
return new BDLedgerContractServiceFutureStub(channel);
}
/**
*/
public static abstract class BDLedgerContractServiceImplBase implements io.grpc.BindableService {
/** /**
* Creates a new async stub that supports all call types for the service
*/ */
public static BDLedgerContractServiceStub newStub(io.grpc.Channel channel) { public io.grpc.stub.StreamObserver<BDLedgerContract.UnitMessage> bDLedgerContractStream(
return new BDLedgerContractServiceStub(channel); io.grpc.stub.StreamObserver<BDLedgerContract.UnitMessage> responseObserver) {
return asyncUnimplementedStreamingCall(METHOD_BDLEDGER_CONTRACT_STREAM, responseObserver);
} }
/** @Override public final io.grpc.ServerServiceDefinition bindService() {
* Creates a new blocking-style stub that supports unary and streaming output calls on the return io.grpc.ServerServiceDefinition.builder(getServiceDescriptor())
* service .addMethod(
*/ METHOD_BDLEDGER_CONTRACT_STREAM,
public static BDLedgerContractServiceBlockingStub newBlockingStub(io.grpc.Channel channel) { asyncBidiStreamingCall(
return new BDLedgerContractServiceBlockingStub(channel); new MethodHandlers<
BDLedgerContract.UnitMessage,
BDLedgerContract.UnitMessage>(
this, METHODID_BDLEDGER_CONTRACT_STREAM)))
.build();
}
}
/**
*/
public static final class BDLedgerContractServiceStub extends io.grpc.stub.AbstractStub<BDLedgerContractServiceStub> {
private BDLedgerContractServiceStub(io.grpc.Channel channel) {
super(channel);
} }
/** private BDLedgerContractServiceStub(io.grpc.Channel channel,
* Creates a new ListenableFuture-style stub that supports unary calls on the service io.grpc.CallOptions callOptions) {
*/ super(channel, callOptions);
public static BDLedgerContractServiceFutureStub newFutureStub(io.grpc.Channel channel) { }
return new BDLedgerContractServiceFutureStub(channel);
@Override
protected BDLedgerContractServiceStub build(io.grpc.Channel channel,
io.grpc.CallOptions callOptions) {
return new BDLedgerContractServiceStub(channel, callOptions);
} }
/** /**
*/ */
public static abstract class BDLedgerContractServiceImplBase public io.grpc.stub.StreamObserver<BDLedgerContract.UnitMessage> bDLedgerContractStream(
implements io.grpc.BindableService { io.grpc.stub.StreamObserver<BDLedgerContract.UnitMessage> responseObserver) {
return asyncBidiStreamingCall(
getChannel().newCall(METHOD_BDLEDGER_CONTRACT_STREAM, getCallOptions()), responseObserver);
}
}
/** /**
*/ */
public io.grpc.stub.StreamObserver<BDLedgerContract.UnitMessage> bDLedgerContractStream( public static final class BDLedgerContractServiceBlockingStub extends io.grpc.stub.AbstractStub<BDLedgerContractServiceBlockingStub> {
io.grpc.stub.StreamObserver<BDLedgerContract.UnitMessage> responseObserver) { private BDLedgerContractServiceBlockingStub(io.grpc.Channel channel) {
return asyncUnimplementedStreamingCall(METHOD_BDLEDGER_CONTRACT_STREAM, super(channel);
responseObserver);
}
@Override
public final io.grpc.ServerServiceDefinition bindService() {
return io.grpc.ServerServiceDefinition.builder(getServiceDescriptor())
.addMethod(METHOD_BDLEDGER_CONTRACT_STREAM, asyncBidiStreamingCall(
new MethodHandlers<BDLedgerContract.UnitMessage, BDLedgerContract.UnitMessage>(
this, METHODID_BDLEDGER_CONTRACT_STREAM)))
.build();
}
} }
/** private BDLedgerContractServiceBlockingStub(io.grpc.Channel channel,
*/ io.grpc.CallOptions callOptions) {
public static final class BDLedgerContractServiceStub super(channel, callOptions);
extends io.grpc.stub.AbstractStub<BDLedgerContractServiceStub> {
private BDLedgerContractServiceStub(io.grpc.Channel channel) {
super(channel);
}
private BDLedgerContractServiceStub(io.grpc.Channel channel,
io.grpc.CallOptions callOptions) {
super(channel, callOptions);
}
@Override
protected BDLedgerContractServiceStub build(io.grpc.Channel channel,
io.grpc.CallOptions callOptions) {
return new BDLedgerContractServiceStub(channel, callOptions);
}
/**
*/
public io.grpc.stub.StreamObserver<BDLedgerContract.UnitMessage> bDLedgerContractStream(
io.grpc.stub.StreamObserver<BDLedgerContract.UnitMessage> responseObserver) {
return asyncBidiStreamingCall(
getChannel().newCall(METHOD_BDLEDGER_CONTRACT_STREAM, getCallOptions()),
responseObserver);
}
} }
/** @Override
*/ protected BDLedgerContractServiceBlockingStub build(io.grpc.Channel channel,
public static final class BDLedgerContractServiceBlockingStub io.grpc.CallOptions callOptions) {
extends io.grpc.stub.AbstractStub<BDLedgerContractServiceBlockingStub> { return new BDLedgerContractServiceBlockingStub(channel, callOptions);
private BDLedgerContractServiceBlockingStub(io.grpc.Channel channel) { }
super(channel); }
}
private BDLedgerContractServiceBlockingStub(io.grpc.Channel channel, /**
io.grpc.CallOptions callOptions) { */
super(channel, callOptions); public static final class BDLedgerContractServiceFutureStub extends io.grpc.stub.AbstractStub<BDLedgerContractServiceFutureStub> {
} private BDLedgerContractServiceFutureStub(io.grpc.Channel channel) {
super(channel);
@Override
protected BDLedgerContractServiceBlockingStub build(io.grpc.Channel channel,
io.grpc.CallOptions callOptions) {
return new BDLedgerContractServiceBlockingStub(channel, callOptions);
}
} }
/** private BDLedgerContractServiceFutureStub(io.grpc.Channel channel,
*/ io.grpc.CallOptions callOptions) {
public static final class BDLedgerContractServiceFutureStub super(channel, callOptions);
extends io.grpc.stub.AbstractStub<BDLedgerContractServiceFutureStub> {
private BDLedgerContractServiceFutureStub(io.grpc.Channel channel) {
super(channel);
}
private BDLedgerContractServiceFutureStub(io.grpc.Channel channel,
io.grpc.CallOptions callOptions) {
super(channel, callOptions);
}
@Override
protected BDLedgerContractServiceFutureStub build(io.grpc.Channel channel,
io.grpc.CallOptions callOptions) {
return new BDLedgerContractServiceFutureStub(channel, callOptions);
}
} }
private static final int METHODID_BDLEDGER_CONTRACT_STREAM = 0; @Override
protected BDLedgerContractServiceFutureStub build(io.grpc.Channel channel,
io.grpc.CallOptions callOptions) {
return new BDLedgerContractServiceFutureStub(channel, callOptions);
}
}
private static final class MethodHandlers<Req, Resp> private static final int METHODID_BDLEDGER_CONTRACT_STREAM = 0;
implements io.grpc.stub.ServerCalls.UnaryMethod<Req, Resp>,
io.grpc.stub.ServerCalls.ServerStreamingMethod<Req, Resp>,
io.grpc.stub.ServerCalls.ClientStreamingMethod<Req, Resp>,
io.grpc.stub.ServerCalls.BidiStreamingMethod<Req, Resp> {
private final BDLedgerContractServiceImplBase serviceImpl;
private final int methodId;
MethodHandlers(BDLedgerContractServiceImplBase serviceImpl, int methodId) { private static final class MethodHandlers<Req, Resp> implements
this.serviceImpl = serviceImpl; io.grpc.stub.ServerCalls.UnaryMethod<Req, Resp>,
this.methodId = methodId; io.grpc.stub.ServerCalls.ServerStreamingMethod<Req, Resp>,
} io.grpc.stub.ServerCalls.ClientStreamingMethod<Req, Resp>,
io.grpc.stub.ServerCalls.BidiStreamingMethod<Req, Resp> {
private final BDLedgerContractServiceImplBase serviceImpl;
private final int methodId;
@Override MethodHandlers(BDLedgerContractServiceImplBase serviceImpl, int methodId) {
@SuppressWarnings("unchecked") this.serviceImpl = serviceImpl;
public void invoke(Req request, io.grpc.stub.StreamObserver<Resp> responseObserver) { this.methodId = methodId;
switch (methodId) {
default:
throw new AssertionError();
}
}
@Override
@SuppressWarnings("unchecked")
public io.grpc.stub.StreamObserver<Req> invoke(
io.grpc.stub.StreamObserver<Resp> responseObserver) {
switch (methodId) {
case METHODID_BDLEDGER_CONTRACT_STREAM:
return (io.grpc.stub.StreamObserver<Req>) serviceImpl.bDLedgerContractStream(
(io.grpc.stub.StreamObserver<BDLedgerContract.UnitMessage>) responseObserver);
default:
throw new AssertionError();
}
}
} }
private static final class BDLedgerContractServiceDescriptorSupplier @Override
implements io.grpc.protobuf.ProtoFileDescriptorSupplier { @SuppressWarnings("unchecked")
@Override public void invoke(Req request, io.grpc.stub.StreamObserver<Resp> responseObserver) {
public com.google.protobuf.Descriptors.FileDescriptor getFileDescriptor() { switch (methodId) {
return BDLedgerContract.getDescriptor(); default:
} throw new AssertionError();
}
} }
private static volatile io.grpc.ServiceDescriptor serviceDescriptor; @Override
@SuppressWarnings("unchecked")
public io.grpc.stub.StreamObserver<Req> invoke(
io.grpc.stub.StreamObserver<Resp> responseObserver) {
switch (methodId) {
case METHODID_BDLEDGER_CONTRACT_STREAM:
return (io.grpc.stub.StreamObserver<Req>) serviceImpl.bDLedgerContractStream(
(io.grpc.stub.StreamObserver<BDLedgerContract.UnitMessage>) responseObserver);
default:
throw new AssertionError();
}
}
}
public static io.grpc.ServiceDescriptor getServiceDescriptor() { private static final class BDLedgerContractServiceDescriptorSupplier implements io.grpc.protobuf.ProtoFileDescriptorSupplier {
io.grpc.ServiceDescriptor result = serviceDescriptor; @Override
public com.google.protobuf.Descriptors.FileDescriptor getFileDescriptor() {
return BDLedgerContract.getDescriptor();
}
}
private static volatile io.grpc.ServiceDescriptor serviceDescriptor;
public static io.grpc.ServiceDescriptor getServiceDescriptor() {
io.grpc.ServiceDescriptor result = serviceDescriptor;
if (result == null) {
synchronized (BDLedgerContractServiceGrpc.class) {
result = serviceDescriptor;
if (result == null) { if (result == null) {
synchronized (BDLedgerContractServiceGrpc.class) { serviceDescriptor = result = io.grpc.ServiceDescriptor.newBuilder(SERVICE_NAME)
result = serviceDescriptor; .setSchemaDescriptor(new BDLedgerContractServiceDescriptorSupplier())
if (result == null) { .addMethod(METHOD_BDLEDGER_CONTRACT_STREAM)
serviceDescriptor = result = io.grpc.ServiceDescriptor.newBuilder(SERVICE_NAME) .build();
.setSchemaDescriptor(new BDLedgerContractServiceDescriptorSupplier())
.addMethod(METHOD_BDLEDGER_CONTRACT_STREAM).build();
}
}
} }
return result; }
} }
return result;
}
} }

View File

@ -76,13 +76,15 @@ public class JavaContractServiceGrpcServer {
public void start() throws IOException { public void start() throws IOException {
server.start(); server.start();
logger.info("[JavaContractServiceGrpcServer] Server started, listening on " + port); logger.info("[JavaContractServiceGrpcServer] Server started, listening on " + port);
Runtime.getRuntime().addShutdownHook(new Thread(() -> { Runtime.getRuntime()
// Use stderr here since the logger may has been reset by its JVM .addShutdownHook(
// shutdown hook. new Thread(() -> {
System.err.println("*** shutting down gRPC server since JVM is shutting down"); // Use stderr here since the logger may has been reset by its JVM
JavaContractServiceGrpcServer.this.stop(); // shutdown hook.
System.err.println("*** server shut down"); System.err.println("*** shutting down gRPC server since JVM is shutting down");
})); JavaContractServiceGrpcServer.this.stop();
System.err.println("*** server shut down");
}));
} }
/** /**
@ -92,9 +94,9 @@ public class JavaContractServiceGrpcServer {
if (server != null) { if (server != null) {
server.shutdown(); server.shutdown();
} }
// if (sendTask != null) { // if (sendTask != null) {
// sendTask.shutdown(); // sendTask.shutdown();
// } // }
} }
/** /**
@ -109,8 +111,7 @@ public class JavaContractServiceGrpcServer {
/** /**
* Our implementation of RouteGuide service. * Our implementation of RouteGuide service.
* *
* <p> * <p>See route_guide.proto for details of the methods.
* See route_guide.proto for details of the methods.
*/ */
private static class JavaContractService private static class JavaContractService
extends BDLedgerContractServiceGrpc.BDLedgerContractServiceImplBase { extends BDLedgerContractServiceGrpc.BDLedgerContractServiceImplBase {
@ -133,7 +134,7 @@ public class JavaContractServiceGrpcServer {
javaServer = new StreamObserver<BDLedgerContract.UnitMessage>() { javaServer = new StreamObserver<BDLedgerContract.UnitMessage>() {
@Override @Override
public void onNext(BDLedgerContract.UnitMessage msg) { public void onNext(BDLedgerContract.UnitMessage msg) {
// System.out.println("P2P receive "+ msg.toString()); // System.out.println("P2P receive "+ msg.toString());
UnitMessageHandler.instance.handle(msg); UnitMessageHandler.instance.handle(msg);
} }

Some files were not shown because too many files have changed in this diff Show More