build: config spotless plugin and reformat code

This commit is contained in:
Frank.R.Wu 2023-06-15 11:08:00 +08:00
parent 1bf3ccc059
commit 73feba9b0e
101 changed files with 5179 additions and 5698 deletions

View File

@ -5,6 +5,7 @@ plugins {
mainClassName = 'org.bdware.server.CMHttpServer' mainClassName = 'org.bdware.server.CMHttpServer'
apply from: '../spotless.gradle'
application { application {
mainClass = mainClassName mainClass = mainClassName

View File

@ -41,9 +41,8 @@ public class HeartBeatUtil {
if (recordedFuture.containsKey(checkAliveTask)) { if (recordedFuture.containsKey(checkAliveTask)) {
cancel(checkAliveTask); cancel(checkAliveTask);
} }
ScheduledFuture<?> future = ScheduledFuture<?> future = ContractManager.scheduledThreadPool
ContractManager.scheduledThreadPool.scheduleWithFixedDelay( .scheduleWithFixedDelay(checkAliveTask, delay, period, TimeUnit.MILLISECONDS);
checkAliveTask, delay, period, TimeUnit.MILLISECONDS);
recordedFuture.put(checkAliveTask, future); recordedFuture.put(checkAliveTask, future);
} catch (Exception e) { } catch (Exception e) {
e.printStackTrace(); e.printStackTrace();

View File

@ -24,10 +24,8 @@ 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 = public transient Map<Integer, String> uniReqIDMap = new ConcurrentHashMap<>(); // 用于请求
new ConcurrentHashMap<>(); // 用于请求 public transient Map<Integer, ResultCallback> resultMap = 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;
@ -44,10 +42,14 @@ public class ContractExecuteInfo implements Serializable {
} }
public void init() { public void init() {
if (queue == null) queue = new PriorityQueue<ContractRequest>(); if (queue == null)
if (trans_queue == null) trans_queue = new PriorityQueue<TransRecord>(); queue = new PriorityQueue<ContractRequest>();
if (uniReqIDMap == null) uniReqIDMap = new ConcurrentHashMap<Integer, String>(); if (trans_queue == null)
if (resultMap == null) resultMap = new ConcurrentHashMap<Integer, ResultCallback>(); trans_queue = new PriorityQueue<TransRecord>();
if (uniReqIDMap == null)
uniReqIDMap = new ConcurrentHashMap<Integer, String>();
if (resultMap == null)
resultMap = new ConcurrentHashMap<Integer, ResultCallback>();
} }
public int getLastExeSeq() { public int getLastExeSeq() {
@ -56,15 +58,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( if (KeyValueDBUtil.instance.containsKey(CMTables.LastExeSeq.toString(), contractID)) { // 如果现在是Stable模式就同步刷到磁盘
CMTables.LastExeSeq.toString(), contractID)) { // 如果现在是Stable模式就同步刷到磁盘 KeyValueDBUtil.instance.setValue(CMTables.LastExeSeq.toString(), contractID,
KeyValueDBUtil.instance.setValue( lastExeSeq + "");
CMTables.LastExeSeq.toString(), contractID, lastExeSeq + "");
} }
} }
public boolean isSequent(int a) { public boolean isSequent(int a) {
if (a - lastExeSeq.get() == 1) return true; if (a - lastExeSeq.get() == 1)
return true;
return false; return false;
} }
@ -85,7 +87,8 @@ public class ContractExecuteInfo implements Serializable {
} }
public String getPubKeyPath() { public String getPubKeyPath() {
if (!isPrivate) return null; if (!isPrivate)
return null;
return pubKeyPath; return pubKeyPath;
} }
@ -136,7 +139,8 @@ 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, ResultCallback result) { public boolean isDirectExecute(ContractRequest request, String uniReqID,
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

@ -57,8 +57,7 @@ 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 = public static MultiIndexTimeRocksDBUtil nodeLogDB = new MultiIndexTimeRocksDBUtil(
new MultiIndexTimeRocksDBUtil(
"./ContractManagerDB", CMTables.LocalNodeLogDB.toString()); "./ContractManagerDB", CMTables.LocalNodeLogDB.toString());
public static URLClassLoader pluginLoader; public static URLClassLoader pluginLoader;
private static SslContext sslContext = null; private static SslContext sslContext = null;
@ -88,23 +87,21 @@ public class CMHttpServer {
GlobalConf.initDOAConfig(doaConf); GlobalConf.initDOAConfig(doaConf);
if (cmdConf.withBdledgerServer) { if (cmdConf.withBdledgerServer) {
ContractManager.threadPool.execute( ContractManager.threadPool
() -> NetworkManager.instance.initP2P(cmdConf.servicePort + 4)); .execute(() -> 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); File ledgerClient = new File(cmdConf.withBdledgerClient);
LOGGER.debug("canRead=" + ledgerClient.canRead() + LOGGER.debug("canRead=" + ledgerClient.canRead() + " path="
" path=" + ledgerClient.getAbsolutePath()); + ledgerClient.getAbsolutePath());
try { try {
Runtime.getRuntime().exec(ledgerClient.getAbsolutePath()); Runtime.getRuntime().exec(ledgerClient.getAbsolutePath());
} catch (IOException e) { } catch (IOException e) {
LOGGER.warn("start bdledger client failed: " + e.getMessage()); 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;
@ -114,13 +111,10 @@ public class CMHttpServer {
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 = sslContext = SslContextBuilder.forServer(chainedFile, keyFile)
SslContextBuilder.forServer(chainedFile, keyFile) .ciphers(null,
.ciphers( (ciphers, defaultCiphers, supportedCiphers) -> defaultCiphers
null, .stream().filter(x -> null != x && !x.contains("RC4"))
(ciphers, defaultCiphers, supportedCiphers) ->
defaultCiphers.stream()
.filter(x -> null != x && !x.contains("RC4"))
.toArray(String[]::new)) .toArray(String[]::new))
.build(); .build();
LOGGER.info("openssl isAvailable:" + OpenSsl.isAvailable()); LOGGER.info("openssl isAvailable:" + OpenSsl.isAvailable());
@ -142,7 +136,8 @@ 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 = parseStrAsList(cmdConf.clientToClusterPlugins); NodeCenterClientHandler.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 (!StringUtil.isNullOrEmpty(cmdConf.debug)) {
try { try {
@ -161,8 +156,7 @@ public class CMHttpServer {
} }
if (cmdConf.startContract != null && cmdConf.startContract.size() > 0) { if (cmdConf.startContract != null && cmdConf.startContract.size() > 0) {
ContractManager.scheduledThreadPool.schedule( ContractManager.scheduledThreadPool.schedule(() -> {
() -> {
try { try {
for (JsonElement je : cmdConf.startContract) { for (JsonElement je : cmdConf.startContract) {
JsonObject jo = je.getAsJsonObject(); JsonObject jo = je.getAsJsonObject();
@ -177,7 +171,8 @@ public class CMHttpServer {
c.setScript(f.getAbsolutePath()); c.setScript(f.getAbsolutePath());
c.setType(ContractExecType.Sole); c.setType(ContractExecType.Sole);
if (jo.has("killBeforeStart")) { if (jo.has("killBeforeStart")) {
ContractManager.instance.stopContract(jo.get("killBeforeStart").getAsString()); ContractManager.instance
.stopContract(jo.get("killBeforeStart").getAsString());
} }
if (jo.has("owner")) if (jo.has("owner"))
c.setOwner(jo.get("owner").getAsString()); c.setOwner(jo.get("owner").getAsString());
@ -190,8 +185,7 @@ public class CMHttpServer {
} catch (Exception e) { } catch (Exception e) {
e.printStackTrace(); e.printStackTrace();
} }
}, }, 10, TimeUnit.SECONDS);
10, TimeUnit.SECONDS);
} }
if (cmdConf.datachainConf != null) { if (cmdConf.datachainConf != null) {
GlobalConf.resetDataChain(cmdConf.datachainConf); GlobalConf.resetDataChain(cmdConf.datachainConf);
@ -204,7 +198,7 @@ public class CMHttpServer {
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(",");
} }
@ -262,19 +256,15 @@ public class CMHttpServer {
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 = String nowManager = KeyValueDBUtil.instance.getValue(CMTables.ConfigDB.toString(),
KeyValueDBUtil.instance.getValue( "__NodeManager__");
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( KeyValueDBUtil.instance.setValue(CMTables.ConfigDB.toString(),
CMTables.ConfigDB.toString(), "__NodeManager__", pubKey); "__NodeManager__", pubKey);
KeyValueDBUtil.instance.setValue( KeyValueDBUtil.instance.setValue(CMTables.NodeRole.toString(), pubKey,
CMTables.NodeRole.toString(), pubKey,
"NodeManager,ContractProvider,ContractUser,ContractInstanceManager"); "NodeManager,ContractProvider,ContractUser,ContractInstanceManager");
KeyValueDBUtil.instance.setValue( KeyValueDBUtil.instance.setValue(CMTables.NodeTime.toString(), pubKey,
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");
} }
@ -290,7 +280,7 @@ public class CMHttpServer {
LOGGER.info("start server at:" + port); LOGGER.info("start server at:" + port);
LOGGER.debug("dir:" + new File("./").getAbsolutePath()); LOGGER.debug("dir:" + new File("./").getAbsolutePath());
new CMHttpServer(port).start(); new CMHttpServer(port).start();
//never reach here!! // never reach here!!
} }
/** /**
@ -302,8 +292,8 @@ public class CMHttpServer {
// 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 = new File("./pluginLib/") File[] pluginJar =
.listFiles(pathname -> pathname.getName().endsWith(".jar")); new File("./pluginLib/").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];
@ -316,7 +306,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) {
@ -332,25 +322,17 @@ public class CMHttpServer {
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) b1.group(bossGroup, workerGroup).channel(NioServerSocketChannel.class)
.channel(NioServerSocketChannel.class) .localAddress(port).childHandler(new ChannelInitializer<SocketChannel>() {
.localAddress(port)
.childHandler(
new ChannelInitializer<SocketChannel>() {
@Override @Override
protected void initChannel(SocketChannel arg0) { protected void initChannel(SocketChannel arg0) {
if (sslContext != null) { if (sslContext != null) {
arg0.pipeline().addLast(new OptionalSslHandler(sslContext)); arg0.pipeline().addLast(new OptionalSslHandler(sslContext));
} }
arg0.pipeline() arg0.pipeline().addLast(trafficSharp).addLast(new HttpServerCodec())
.addLast(trafficSharp)
.addLast(new HttpServerCodec())
.addLast(new HttpObjectAggregator(10 * 1024 * 1024)) .addLast(new HttpObjectAggregator(10 * 1024 * 1024))
.addLast( .addLast(new WebSocketServerProtocolHandler(PATH, null, true))
new WebSocketServerProtocolHandler( .addLast(new ChunkedWriteHandler()).addLast(serverHandler)
PATH, null, true))
.addLast(new ChunkedWriteHandler())
.addLast(serverHandler)
.addLast(new ContractManagerFrameHandler()); .addLast(new ContractManagerFrameHandler());
} }
}); });
@ -370,8 +352,7 @@ public class CMHttpServer {
@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

@ -68,11 +68,12 @@ public class GRPCPool implements ChainOpener {
private String dataNodeIP; private String dataNodeIP;
private int dataNodePort; private int dataNodePort;
static final String DBDir = "ContractManagerDB/GRPCPool"; 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("./" + DBDir + "/hashToData.index", 20);
requestID2Hash = openDB("./"+DBDir+"/requestIDToHash", "req2Hash"); requestID2Hash = openDB("./" + DBDir + "/requestIDToHash", "req2Hash");
hash2Data = openDB("./"+DBDir+"/hashToData", "hash2Data"); hash2Data = openDB("./" + DBDir + "/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) {
@ -112,14 +113,11 @@ 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( params.put("Address",
"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 = signature = SM2Util.sign(GlobalConf.instance.keyPair.getPrivateKeyParameter(),
SM2Util.sign(
GlobalConf.instance.keyPair.getPrivateKeyParameter(),
origin.getBytes()); origin.getBytes());
} catch (Exception e) { } catch (Exception e) {
signature = "no signature".getBytes(); signature = "no signature".getBytes();
@ -130,14 +128,8 @@ public class GRPCPool implements ChainOpener {
HttpPostForm.postForm(url, params); HttpPostForm.postForm(url, params);
} }
private static Line wrapperLine( private static Line wrapperLine(OnHashCallback cb, String from, String to, String data,
OnHashCallback cb, String requestID, String contractName, String namedLedger) {
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;
@ -150,24 +142,15 @@ 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( KeyValueDBUtil.instance.setValue(CMTables.ContractInfo.toString(), contractName + "-Times",
CMTables.ContractInfo.toString(), contractName + "-Times", times + ""); times + "");
KeyValueDBUtil.instance.setValue( KeyValueDBUtil.instance.setValue(CMTables.ContractInfo.toString(),
CMTables.ContractInfo.toString(), contractName + "-Traffic", traffic + ""); contractName + "-Traffic", traffic + "");
} }
public static void addLocalContractLog( public static void addLocalContractLog(String action, String contractID, String contractName,
String action, String pubKey, String function, long startTime, long costTime, long totalGas,
String contractID, long executionGas, long extraGas, Map<String, String> logType) {
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);
@ -191,8 +174,7 @@ 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);
@ -222,25 +204,14 @@ public class GRPCPool implements ChainOpener {
} }
@Override @Override
public void writeToChain( public void writeToChain(OnHashCallback callback, String from, String to, String data,
OnHashCallback callback, String requestID, String namedLedger) {
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( public void writeToChainWithContract(OnHashCallback cb, String from, String to, String data,
OnHashCallback cb, String requestID, String contractName, String namedLedger) {
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) {
@ -271,7 +242,7 @@ public class GRPCPool implements ChainOpener {
@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");
} }
@ -280,13 +251,8 @@ public class GRPCPool implements ChainOpener {
} }
@Override @Override
public void writeContractResultToLocalAndLedger( public void writeContractResultToLocalAndLedger(String result, ContractClient client,
String result, ContractRequest contractRequest, OnHashCallback cb, long start, long time) {
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;
@ -343,21 +309,14 @@ 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( ret.put("data", new String(
"data", requestID2Hash.get(args.get("requestID").getAsString().getBytes())));
new String(
requestID2Hash.get(
args.get("requestID").getAsString().getBytes())));
} catch (Exception e) { } catch (Exception e) {
ret.put( ret.put("data", "Match failed! " + "Can't find hash by this requestID "
"data",
"Match failed! "
+ "Can't find hash by this requestID "
+ args.get("requestID").getAsString()); + args.get("requestID").getAsString());
} }
} else { } else {
ret.put( ret.put("data",
"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));
@ -384,13 +343,16 @@ 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 index = logIndex; } else
index = logIndex;
List<byte[]> result; List<byte[]> result;
if (offset < 0) result = index.requestLast(count); if (offset < 0)
else result = index.request(offset, count); result = index.requestLast(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);
@ -419,11 +381,9 @@ 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 = JsonObject jo = JsonParser
JsonParser.parseString( .parseString(new String(
new String( hash2Data.get(args.get("hash").getAsString().getBytes())))
hash2Data.get(
args.get("hash").getAsString().getBytes())))
.getAsJsonObject(); .getAsJsonObject();
jo.addProperty("action", "onQueryDataByHash"); jo.addProperty("action", "onQueryDataByHash");
resultCallback.onResult(JsonUtil.toJson(jo)); resultCallback.onResult(JsonUtil.toJson(jo));
@ -457,19 +417,16 @@ 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 = JsonObject jo = JsonParser
JsonParser.parseString( .parseString(new String(
new String( hash2Data.get(args.get("hash").getAsString().getBytes())))
hash2Data.get(
args.get("hash").getAsString().getBytes())))
.getAsJsonObject(); .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( ret.put("data",
"data",
"!!! " + "Can't find data by hash " + args.get("hash").getAsString()); "!!! " + "Can't find data by hash " + args.get("hash").getAsString());
} }
} else { } else {
@ -485,7 +442,8 @@ 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) index = logIndex; if (index == null)
index = logIndex;
ret.put("count", index.size() + ""); ret.put("count", index.size() + "");
resultCallback.onResult(JsonUtil.toJson(ret)); resultCallback.onResult(JsonUtil.toJson(ret));
} }
@ -512,11 +470,8 @@ 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( obj.put("data", JsonParser.parseString(
"data", new String(hash2Data.get(args.get("hash").getAsString().getBytes()))));
JsonParser.parseString(
new String(
hash2Data.get(args.get("hash").getAsString().getBytes()))));
} catch (Exception e) { } catch (Exception e) {
e.printStackTrace(); e.printStackTrace();
} }
@ -547,11 +502,8 @@ 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( obj.put("data", shortStr(
"data", new String(hash2Data.get(args.get("hash").getAsString().getBytes()))));
shortStr(
new String(
hash2Data.get(args.get("hash").getAsString().getBytes()))));
} catch (Exception e) { } catch (Exception e) {
e.printStackTrace(); e.printStackTrace();
} }
@ -561,8 +513,10 @@ public class GRPCPool implements ChainOpener {
} }
private String shortStr(String str) { private String shortStr(String str) {
if (str != null && str.length() > 50) return str.substring(0, 50); if (str != null && str.length() > 50)
else return str; return str.substring(0, 50);
else
return str;
} }
@Action(async = true, userPermission = 1L << 24) @Action(async = true, userPermission = 1L << 24)
@ -575,7 +529,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();
@ -584,7 +538,8 @@ 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) continue; if (time < 0)
continue;
times.add(time); times.add(time);
memoryIndex.put(time, str); memoryIndex.put(time, str);
} }
@ -602,8 +557,7 @@ 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>>() { JsonUtil.fromJson(obj, new TypeToken<Map<String, String>>() {}.getType());
}.getType());
String data = parsedObj.get("data"); String data = parsedObj.get("data");
int len = "1575452533275".length(); int len = "1575452533275".length();
@ -620,9 +574,8 @@ 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 = index = new LenVarTimeSerialIndex(
new LenVarTimeSerialIndex( "./" + DBDir + "/hashByContract/" + contractName + ".index", 20);
"./"+DBDir+"/hashByContract/" + contractName + ".index", 20);
contractName2LogIndex.put(contractName, index); contractName2LogIndex.put(contractName, index);
} }
return index; return index;
@ -647,8 +600,7 @@ 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();
@ -711,26 +663,16 @@ 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 = ret2 = client.sendTransaction(l.ledgerName, CommonProto.TransactionType.MESSAGE,
client.sendTransaction( l.from, random.nextLong(), l.to,
l.ledgerName,
CommonProto.TransactionType.MESSAGE,
l.from,
random.nextLong(),
l.to,
l.data.getBytes(StandardCharsets.UTF_8)); l.data.getBytes(StandardCharsets.UTF_8));
} else { } else {
ret2 = ret2 = client.sendTransaction(LEDGER_NAME, CommonProto.TransactionType.MESSAGE,
client.sendTransaction( l.from, random.nextLong(), l.to,
LEDGER_NAME,
CommonProto.TransactionType.MESSAGE,
l.from, random.nextLong(),
l.to,
l.data.getBytes(StandardCharsets.UTF_8)); l.data.getBytes(StandardCharsets.UTF_8));
} }
if (ret2 != null) if (ret2 != null)
ret2.addListener( ret2.addListener(new Runnable() {
new Runnable() {
@Override @Override
public void run() { public void run() {
try { try {
@ -750,26 +692,21 @@ public class GRPCPool implements ChainOpener {
instance.logIndex.index(HashUtil.str16ToBytes(hashStr)); instance.logIndex.index(HashUtil.str16ToBytes(hashStr));
if (null != l.contractName) { if (null != l.contractName) {
LenVarTimeSerialIndex index = LenVarTimeSerialIndex index =
instance.createIndexIfNotExist( instance.createIndexIfNotExist(l.contractName);
l.contractName);
index.index(HashUtil.str16ToBytes(hashStr)); index.index(HashUtil.str16ToBytes(hashStr));
} }
instance.hash2Data.put( instance.hash2Data.put(hashStr.getBytes(),
hashStr.getBytes(), JsonUtil.toJson(l).getBytes()); JsonUtil.toJson(l).getBytes());
instance.requestID2Hash.put( instance.requestID2Hash.put(l.requestID.getBytes(),
l.requestID.getBytes(), hashStr.getBytes()); hashStr.getBytes());
LOGGER.debug( LOGGER.debug(
"put requestID: " "put requestID: " + l.requestID + " hash: " + hashStr);
+ l.requestID
+ " hash: "
+ hashStr);
} }
} catch (Exception e) { } catch (Exception e) {
LOGGER.warn(e.getMessage()); 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) {
@ -779,8 +716,8 @@ public class GRPCPool implements ChainOpener {
} }
} }
public Map<String, String> analysisLocalContractLog( public Map<String, String> analysisLocalContractLog(String data2, ContractRequest c,
String data2, ContractRequest c, String detail) { 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<>();
@ -870,32 +807,14 @@ public class GRPCPool implements ChainOpener {
// LOGGER.debug("type: " + JsonUtil.toJson(logType) + " | detail: " + // LOGGER.debug("type: " + JsonUtil.toJson(logType) + " | detail: " +
// detail); // detail);
addLocalContractLog( addLocalContractLog("executeContract", contractID, contractName,
"executeContract", l.contractRequest.getPublicKey(), l.contractRequest.getAction(), l.start,
contractID, l.costTime, cr.totalGas, cr.executionGas, cr.extraGas, logType);
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( addLocalContractLog("executeContract", contractID, contractName,
"executeContract", l.contractRequest.fromContract, l.contractRequest.getAction(), l.start,
contractID, l.costTime, cr.totalGas, cr.executionGas, cr.extraGas, logType);
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) {
@ -910,29 +829,17 @@ public class GRPCPool implements ChainOpener {
// 1025 1422 1497 1447 1445 // 1025 1422 1497 1447 1445
if (toBDContract) { if (toBDContract) {
Line l1 = Line l1 = wrapperLine(l.cb, l.contractRequest.getPublicKey(), "executeContract",
wrapperLine( JsonUtil.toJson(logType), l.contractRequest.getRequestID(),
l.cb, contractName, "");
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 = Line l2 = wrapperLine(l.cb, l.contractRequest.getPublicKey(),
wrapperLine( "executeContract", JsonUtil.toJson(logType),
l.cb, l.contractRequest.getRequestID(), contractName, name);
l.contractRequest.getPublicKey(),
"executeContract",
JsonUtil.toJson(logType),
l.contractRequest.getRequestID(),
contractName,
name);
writeChain(l2); writeChain(l2);
} }
} }

View File

@ -17,7 +17,6 @@ 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 {
@ -64,14 +63,11 @@ public class GlobalConf {
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( Configurator.setLevel("io.netty.handler.codec.http.websocketx.WebSocket08FrameEncoder",
"io.netty.handler.codec.http.websocketx.WebSocket08FrameEncoder",
org.apache.logging.log4j.Level.OFF); org.apache.logging.log4j.Level.OFF);
Configurator.setLevel( Configurator.setLevel("io.netty.handler.codec.http.websocketx.WebSocket08FrameDecoder",
"io.netty.handler.codec.http.websocketx.WebSocket08FrameDecoder",
org.apache.logging.log4j.Level.OFF); org.apache.logging.log4j.Level.OFF);
Configurator.setLevel( Configurator.setLevel("io.netty.handler.codec.http.websocketx.WebSocketServerHandshaker",
"io.netty.handler.codec.http.websocketx.WebSocketServerHandshaker",
org.apache.logging.log4j.Level.OFF); org.apache.logging.log4j.Level.OFF);
KeyValueDBUtil.setupCM(); KeyValueDBUtil.setupCM();
@ -83,19 +79,17 @@ public class GlobalConf {
String dbName = CMTables.ConfigDB.toString(); String dbName = CMTables.ConfigDB.toString();
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( KeyValueDBUtil.instance.setValue(dbName, "projectDir",
dbName, "projectDir", new File("./BDWareProjectDir/").getAbsolutePath()); new File("./BDWareProjectDir/").getAbsolutePath());
KeyValueDBUtil.instance.setValue( KeyValueDBUtil.instance.setValue(dbName, "ADSPDir",
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( KeyValueDBUtil.instance.setValue(dbName, "yjsPath",
dbName, "yjsPath", new File("./yjs.jar").getAbsolutePath()); new File("./yjs.jar").getAbsolutePath());
} else { } else {
KeyValueDBUtil.instance.setValue( KeyValueDBUtil.instance.setValue(dbName, "yjsPath",
dbName, "yjsPath", new File("./cp/yjs.jar").getAbsolutePath()); new File("./cp/yjs.jar").getAbsolutePath());
} }
conf.keyPairStr = SM2Util.generateSM2KeyPair().toJson(); conf.keyPairStr = SM2Util.generateSM2KeyPair().toJson();
@ -111,40 +105,27 @@ public class GlobalConf {
// long time = System.currentTimeMillis()+15811200000; // long time = System.currentTimeMillis()+15811200000;
String licence = String licence =
ByteHexUtil.encode( ByteHexUtil
SM2Util.encrypt( .encode(SM2Util.encrypt(conf.keyPair.getPublicKey(),
conf.keyPair.getPublicKey(), (HardwareInfo.getCPUID() + "=="
(HardwareInfo.getCPUID() + (System.currentTimeMillis() + 15811200000L))
+ "=="
+ (System.currentTimeMillis()
+ 15811200000L))
.getBytes())); .getBytes()));
LOGGER.debug("licence:" + licence); LOGGER.debug("licence:" + licence);
LOGGER.debug( LOGGER.debug(String.format("deviceName %s license %s %s==%d", deviceName, licence,
String.format( HardwareInfo.getCPUID(), (System.currentTimeMillis() + 15811200000L)));
"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"); KeyValueDBUtil.instance.setValue(dbName, "nodeCenter", "ws://127.0.0.1:18005");
KeyValueDBUtil.instance.setValue( KeyValueDBUtil.instance.setValue(dbName, "datachainConf",
dbName, "39.104.70.160:18091\n" + "47.98.247.70:18091\n" + "47.98.248.208:18091\n"
"datachainConf", + "39.104.77.165:18091\n" + "47.98.249.131:18091");
"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.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 =
@ -211,8 +192,7 @@ 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( LOGGER.debug("[GlobalConf] publicDirCompiled Path:"
"[GlobalConf] publicDirCompiled Path:"
+ new File(conf.publicCompiledDir).getAbsolutePath()); + 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());
@ -250,16 +230,17 @@ public class GlobalConf {
private static void verifyLicence(GlobalConf conf) { private static void verifyLicence(GlobalConf conf) {
try { try {
// String pubkey = // String pubkey =
// "OTIzNmUzMGNmOGI1ZjFkMDBjZjEyMWY4OThmM2ZmYTIwNjE2ODYxOWNiMDNhMTVlM2FiZTA0OThhNTlkZDg1MmRi" + // "OTIzNmUzMGNmOGI1ZjFkMDBjZjEyMWY4OThmM2ZmYTIwNjE2ODYxOWNiMDNhMTVlM2FiZTA0OThhNTlkZDg1MmRi"
// "MjA5Njc1NmM3ZDBhOWM3YTNkOTg2NWVlYzk2YzM1MmY0MDdkMGMyOTA4M2NkNDI4YmY1YjM5M2U5OTA1" + // +
// "NWE0MzM0MTJhM2Y2ZDhkZWVmZDk4MmI4NmZiZTMyYjhlMGE3ZWFmZmE5ODM3M2E4ZTRmNTYyNDgxNTY0" + // "MjA5Njc1NmM3ZDBhOWM3YTNkOTg2NWVlYzk2YzM1MmY0MDdkMGMyOTA4M2NkNDI4YmY1YjM5M2U5OTA1" +
// "Yjk2ZjFkMTZiODk2MGRhZDAwMTNjZDYwOGZmOTcxNjdiOWI1MDU1MjJlMzk0ODhmODczNDJjNWUwOGRj" + // "NWE0MzM0MTJhM2Y2ZDhkZWVmZDk4MmI4NmZiZTMyYjhlMGE3ZWFmZmE5ODM3M2E4ZTRmNTYyNDgxNTY0" +
// "ZjFhZjFkYzBjODUxZjRlNDg2ZWIyOTM5NDI3MDc4MjA5NDg5ODliODVhZDNlOGJlNWJiYWEzZDUyMWU2" + // "Yjk2ZjFkMTZiODk2MGRhZDAwMTNjZDYwOGZmOTcxNjdiOWI1MDU1MjJlMzk0ODhmODczNDJjNWUwOGRj" +
// "MjdmZjE3NGY4Y2ZlZDk3NTY4OWNlNDEzOGYyMTgyOWIwMDVmMzE0YjM3MmNlZmFkZjBkNmUyOTY4ZGUz" + // "ZjFhZjFkYzBjODUxZjRlNDg2ZWIyOTM5NDI3MDc4MjA5NDg5ODliODVhZDNlOGJlNWJiYWEzZDUyMWU2" +
// "ZmFlNGUxNTFkMWFmNWE4Mjc4ZjQ2MDI5ODBjY2JkMDM0ZDE0YWRjZDk1ZjI1MjY3NmRlODRjYzdkNzU5" + // "MjdmZjE3NGY4Y2ZlZDk3NTY4OWNlNDEzOGYyMTgyOWIwMDVmMzE0YjM3MmNlZmFkZjBkNmUyOTY4ZGUz" +
// "NGYyYTAxMTliYWJmYjgyMGRjMWNjZWZjNThjNWUwYWRjMDQyM2MzYzA1ODNhZTU1MWZlN2Y5YTYwYjkx" + // "ZmFlNGUxNTFkMWFmNWE4Mjc4ZjQ2MDI5ODBjY2JkMDM0ZDE0YWRjZDk1ZjI1MjY3NmRlODRjYzdkNzU5" +
// "Zjg2YWViNDNlMzU0NzlhYWI5YmFjOTAwN2IsMTAwMDEsMA=="; // "NGYyYTAxMTliYWJmYjgyMGRjMWNjZWZjNThjNWUwYWRjMDQyM2MzYzA1ODNhZTU1MWZlN2Y5YTYwYjkx" +
// "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) {
@ -267,10 +248,7 @@ 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 = String arr = new String(SM2Util.decrypt(conf.keyPair.getPrivateKeyParameter(),
new String(
SM2Util.decrypt(
conf.keyPair.getPrivateKeyParameter(),
ByteHexUtil.decode(conf.licence))); ByteHexUtil.decode(conf.licence)));
LOGGER.debug("[GlobalConf] actualKey:" + arr); LOGGER.debug("[GlobalConf] actualKey:" + arr);
@ -326,7 +304,8 @@ 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);
} }
} }

View File

@ -28,7 +28,8 @@ public class SDKContext implements ISDKContext {
ICMActions cmActionsProxy = new CMActionsProxy(); ICMActions cmActionsProxy = new CMActionsProxy();
IMasterServerRecoverMechAction masterServerRecoverMechActionProxy = new MasterServerRecoverMechActionProxy(); IMasterServerRecoverMechAction masterServerRecoverMechActionProxy =
new MasterServerRecoverMechActionProxy();
IGlobalConf globalConfProxy = new GlobalProxy(); IGlobalConf globalConfProxy = new GlobalProxy();
@ -81,9 +82,7 @@ public class SDKContext implements ISDKContext {
@Override @Override
public void asyncExecuteContractLocally(JsonObject jo, ResultCallback rc) { public void asyncExecuteContractLocally(JsonObject jo, ResultCallback rc) {
executorService.execute( executorService.execute(() -> _masterClientTCPAction.executeContractLocally(jo, rc));
() -> _masterClientTCPAction.executeContractLocally(jo, rc)
);
} }
} }
@ -111,7 +110,8 @@ public class SDKContext implements ISDKContext {
} }
} }
public static class MasterServerRecoverMechActionProxy implements IMasterServerRecoverMechAction { public static class MasterServerRecoverMechActionProxy
implements IMasterServerRecoverMechAction {
@Override @Override
public Map<String, Map<String, RecoverFlag>> getRecoverStatusMap() { public Map<String, Map<String, RecoverFlag>> getRecoverStatusMap() {
return MasterServerRecoverMechAction.recoverStatus; return MasterServerRecoverMechAction.recoverStatus;

View File

@ -40,8 +40,8 @@ public class CMActions implements OnHashCallback {
private static final JsonObject MISSING_ARGUMENT = private static final JsonObject MISSING_ARGUMENT =
JsonUtil.parseStringAsJsonObject("{\"action\":\"onExecuteResult\",\"executeTime\":-1," JsonUtil.parseStringAsJsonObject("{\"action\":\"onExecuteResult\",\"executeTime\":-1,"
+ "\"status\":\"Error\",\"result\":\"missing arguments\"}"); + "\"status\":\"Error\",\"result\":\"missing arguments\"}");
private static final JsonObject INVALID_DOI = JsonUtil.parseStringAsJsonObject( private static final JsonObject INVALID_DOI =
"{\"action\":\"onExecuteResult\",\"executeTime\":-1," JsonUtil.parseStringAsJsonObject("{\"action\":\"onExecuteResult\",\"executeTime\":-1,"
+ "\"status\":\"Error\",\"result\":\"invalid contract doi\"}"); + "\"status\":\"Error\",\"result\":\"invalid contract doi\"}");
private static final Logger LOGGER = LogManager.getLogger(CMActions.class); private static final Logger LOGGER = LogManager.getLogger(CMActions.class);
public static ContractManager manager = initManager(); public static ContractManager manager = initManager();
@ -66,8 +66,7 @@ public class CMActions implements OnHashCallback {
contractManager.chainOpener = GRPCPool.instance; contractManager.chainOpener = GRPCPool.instance;
GRPCPool.logsDB = ContractManager.logsDB; GRPCPool.logsDB = ContractManager.logsDB;
// expiredDate = Long.parseLong(GlobalConf.instance.licence); // expiredDate = Long.parseLong(GlobalConf.instance.licence);
ContractManager.threadPool.execute( ContractManager.threadPool.execute(() -> {
() -> {
long start = System.currentTimeMillis(); long start = System.currentTimeMillis();
contractManager.reconnectContractProcess(); contractManager.reconnectContractProcess();
// 重启动时所有合约都不是master // 重启动时所有合约都不是master
@ -90,8 +89,8 @@ public class CMActions implements OnHashCallback {
return contractManager; return contractManager;
} }
public static void listContractProcessWithFirstWithOwner( public static void listContractProcessWithFirstWithOwner(String owner, String id,
String owner, String id, ResultCallback resultCallback) { ResultCallback resultCallback) {
LOGGER.debug("[CMActions listContractProcessWithFirstWithOwner] id=" + id); LOGGER.debug("[CMActions listContractProcessWithFirstWithOwner] id=" + id);
String data = manager.listContractsWithOwner(owner, id, 1 << 1); String data = manager.listContractsWithOwner(owner, id, 1 << 1);
ReplyUtil.simpleReply(resultCallback, "onListContractProcess", data); ReplyUtil.simpleReply(resultCallback, "onListContractProcess", data);
@ -112,14 +111,10 @@ public class CMActions implements OnHashCallback {
return sb.toString(); return sb.toString();
} }
public static void executeContractInternal( public static void executeContractInternal(final JsonObject args,
final JsonObject args, final ResultCallback resultCallback, final OnHashCallback hashcb) {
final ResultCallback resultCallback,
final OnHashCallback hashcb) {
final ContractRequest cReq = new ContractRequest(); final ContractRequest cReq = new ContractRequest();
if (!args.has("contractName") && if (!args.has("contractName") && !args.has("contractID") && !args.has("contractDOI")) {
!args.has("contractID") &&
!args.has("contractDOI")) {
resultCallback.onResult(MISSING_ARGUMENT); resultCallback.onResult(MISSING_ARGUMENT);
return; return;
} }
@ -185,23 +180,17 @@ public class CMActions implements OnHashCallback {
} }
cReq.setRequestID(reqID); cReq.setRequestID(reqID);
long start = System.currentTimeMillis(); long start = System.currentTimeMillis();
manager.executeContractInternal( manager.executeContractInternal(cReq, new ResultCallback() {
cReq,
new ResultCallback() {
@Override @Override
public void onResult(JsonObject ret) { public void onResult(JsonObject ret) {
ret.addProperty("responseID", cReq.getRequestID()); ret.addProperty("responseID", cReq.getRequestID());
ret.addProperty("action", "onExecuteResult"); ret.addProperty("action", "onExecuteResult");
String costTime = (System.currentTimeMillis() - start) + ""; String costTime = (System.currentTimeMillis() - start) + "";
ret.addProperty("executeTime", costTime); ret.addProperty("executeTime", costTime);
ContractMeta meta = ContractMeta meta = manager.statusRecorder.getContractMeta(cReq.getContractID());
manager.statusRecorder.getContractMeta(cReq.getContractID());
if (meta != null && meta.getIsDebug()) { if (meta != null && meta.getIsDebug()) {
FUNCINVOKEINFO.putOneInvoke( FUNCINVOKEINFO.putOneInvoke(cReq.getContractID(), cReq.getAction(),
cReq.getContractID(), cReq.getRequestID(), cReq.getArg(),
cReq.getAction(),
cReq.getRequestID(),
cReq.getArg(),
ret.has("result") ? ret.get("result").toString() : ""); ret.has("result") ? ret.get("result").toString() : "");
} }
LOGGER.debug("result of request " + cReq.getRequestID() + ": " + ret); LOGGER.debug("result of request " + cReq.getRequestID() + ": " + ret);
@ -212,12 +201,11 @@ public class CMActions implements OnHashCallback {
public void onResult(String str) { public void onResult(String str) {
throw new IllegalStateException("Can't reach here"); throw new IllegalStateException("Can't reach here");
} }
}, }, hashcb);
hashcb);
} }
public static void generateReadmeInternal( public static void generateReadmeInternal(JsonObject args, final ResultCallback resultCallback,
JsonObject args, final ResultCallback resultCallback, final OnHashCallback hashcb) { final OnHashCallback hashcb) {
final ContractRequest c = new ContractRequest(); final ContractRequest c = new ContractRequest();
if (!args.has("contractName") && !args.has("contractID") && !args.has("contractDOI")) { if (!args.has("contractName") && !args.has("contractID") && !args.has("contractDOI")) {
resultCallback.onResult(MISSING_ARGUMENT); resultCallback.onResult(MISSING_ARGUMENT);
@ -248,7 +236,7 @@ public class CMActions implements OnHashCallback {
String argSchema = ""; String argSchema = "";
String resSchema = ""; String resSchema = "";
String argTemplate = ""; String argTemplate = "";
//String resTemplate = ""; // String resTemplate = "";
String descStr = null; String descStr = null;
String invokeRocords = null; String invokeRocords = null;
if (desp.annotations != null) { if (desp.annotations != null) {
@ -295,16 +283,11 @@ public class CMActions implements OnHashCallback {
} }
ReadmeGenerator.ReadmeFunction joFunction = ReadmeGenerator.ReadmeFunction joFunction = new ReadmeGenerator.ReadmeFunction(
new ReadmeGenerator.ReadmeFunction(
// new ReadmeGenerator.ReadmeFunc // new ReadmeGenerator.ReadmeFunc
desp.functionName, desp.functionName, descStr, argSchema, argTemplate, resSchema,
descStr, // resTemplate,
argSchema,
argTemplate,
resSchema,
//resTemplate,
invokeRocords); // 第二个参数是调用结果的一个集合 invokeRocords); // 第二个参数是调用结果的一个集合
// 注入之后将该函数的记录清空 // 注入之后将该函数的记录清空
FUNCINVOKEINFO.clearOneFunction(c.getContractID(), desp.functionName); FUNCINVOKEINFO.clearOneFunction(c.getContractID(), desp.functionName);
@ -342,8 +325,7 @@ public class CMActions implements OnHashCallback {
} }
} }
generator.setContractDescription(contractDesp.toString()); generator.setContractDescription(contractDesp.toString());
ResultCallback rb = ResultCallback rb = new ResultCallback() {
new ResultCallback() {
@Override @Override
public void onResult(String str) { public void onResult(String str) {
final Map<String, String> ret = new HashMap<>(); final Map<String, String> ret = new HashMap<>();
@ -367,28 +349,30 @@ public class CMActions implements OnHashCallback {
} }
private static String truncQuotation(String str) { private static String truncQuotation(String str) {
if (str.startsWith("\"")) str = str.substring(1); if (str.startsWith("\""))
if (str.endsWith("\"")) str = str.substring(0, str.length() - 1); str = str.substring(1);
if (str.endsWith("\""))
str = str.substring(0, str.length() - 1);
return str; return str;
} }
public static void killContractByMaster( public static void killContractByMaster(String contractID, JsonObject request,
String contractID, JsonObject request, ResultCallback rc) { ResultCallback rc) {
LOGGER.info("[MasterClientTCPAction] killContract : "); LOGGER.info("[MasterClientTCPAction] killContract : ");
try { try {
MasterClientTCPAction.killUnitContractMap.put( MasterClientTCPAction.killUnitContractMap.put(request.get("requestID").getAsString(),
request.get("requestID").getAsString(),
new KillUnitContractInfo(rc, System.currentTimeMillis())); new KillUnitContractInfo(rc, System.currentTimeMillis()));
MultiContractMeta mcm = CMActions.manager.multiContractRecorder.getMultiContractMeta(contractID); MultiContractMeta mcm =
CMActions.manager.multiContractRecorder.getMultiContractMeta(contractID);
NetworkManager.instance.sendToAgent(mcm.getMasterNode(), JsonUtil.toJson(request)); NetworkManager.instance.sendToAgent(mcm.getMasterNode(), JsonUtil.toJson(request));
} catch (Exception e) { } catch (Exception e) {
e.printStackTrace(); e.printStackTrace();
} finally { } finally {
CMActions.manager.stopContractWithOwner( CMActions.manager.stopContractWithOwner(request.get("verifiedPubKey").getAsString(),
request.get("verifiedPubKey").getAsString(), contractID); contractID);
ContractMeta meta = manager.statusRecorder.getContractMeta(contractID); ContractMeta meta = manager.statusRecorder.getContractMeta(contractID);
if (null != meta && meta.contractExecutor != null) { if (null != meta && meta.contractExecutor != null) {
//TODO why close? // TODO why close?
// meta.contractExecutor.close(); // meta.contractExecutor.close();
} }
} }
@ -428,7 +412,7 @@ public class CMActions implements OnHashCallback {
String data = "failed"; String data = "failed";
String contractID = ""; String contractID = "";
String operation = ""; String operation = "";
//String mock = ""; // String mock = "";
if (args.has("contractID") && args.has("operation") && args.has("arg")) { if (args.has("contractID") && args.has("operation") && args.has("arg")) {
contractID = args.get("contractID").getAsString(); contractID = args.get("contractID").getAsString();
System.out.println(contractID); System.out.println(contractID);
@ -480,7 +464,7 @@ public class CMActions implements OnHashCallback {
String data = "failed"; String data = "failed";
String contractID; String contractID;
String operation; String operation;
//JsonElement mask = JsonUtil.parseString(""); // JsonElement mask = JsonUtil.parseString("");
if (args.has("contractID") && args.has("operation") && args.has("arg")) { if (args.has("contractID") && args.has("operation") && args.has("arg")) {
contractID = args.get("contractID").getAsString(); contractID = args.get("contractID").getAsString();
System.out.println(contractID); System.out.println(contractID);
@ -513,10 +497,8 @@ public class CMActions implements OnHashCallback {
if (!args.has("useP2P") || !args.get("useP2P").getAsBoolean()) { if (!args.has("useP2P") || !args.get("useP2P").getAsBoolean()) {
executeContractInternal(args, resultCallback, this); executeContractInternal(args, resultCallback, this);
} else { } else {
resultCallback.onResult( resultCallback.onResult(JsonUtil.toJson(new ContractResult(ContractResult.Status.Error,
JsonUtil.toJson( new JsonPrimitive("noResult"))));
new ContractResult(
ContractResult.Status.Error, new JsonPrimitive("noResult"))));
} }
} }
@ -550,10 +532,8 @@ public class CMActions implements OnHashCallback {
if (!args.has("useP2P") || !args.get("useP2P").getAsBoolean()) { if (!args.has("useP2P") || !args.get("useP2P").getAsBoolean()) {
executeContractInternal(args, wrapped, this); executeContractInternal(args, wrapped, this);
} else { } else {
wrapped.onResult( wrapped.onResult(JsonUtil.toJson(new ContractResult(ContractResult.Status.Error,
JsonUtil.toJson( new JsonPrimitive("noResult"))));
new ContractResult(
ContractResult.Status.Error, new JsonPrimitive("noResult"))));
} }
} }
@ -568,9 +548,7 @@ public class CMActions implements OnHashCallback {
public void listContractProcess(JsonObject args, ResultCallback resultCallback) { public void listContractProcess(JsonObject args, ResultCallback resultCallback) {
String data; String data;
if (args.has("verifiedPubKey")) { if (args.has("verifiedPubKey")) {
data = manager.listContractsWithOwner( data = manager.listContractsWithOwner(args.get("verifiedPubKey").getAsString(), null,
args.get("verifiedPubKey").getAsString(),
null,
args.has("filters") ? args.get("filters").getAsInt() : 0); args.has("filters") ? args.get("filters").getAsInt() : 0);
ReplyUtil.simpleReply(resultCallback, "onListContractProcess", data); ReplyUtil.simpleReply(resultCallback, "onListContractProcess", data);
} else { } else {
@ -603,12 +581,14 @@ public class CMActions implements OnHashCallback {
@Action(userPermission = 1L << 16) @Action(userPermission = 1L << 16)
public void queryContractResourceInfo(JsonObject args, ResultCallback resultCallback) { public void queryContractResourceInfo(JsonObject args, ResultCallback resultCallback) {
ReplyUtil.simpleReply(resultCallback, "onQueryContractResourceInfo", manager.getContractResourceInfo()); ReplyUtil.simpleReply(resultCallback, "onQueryContractResourceInfo",
manager.getContractResourceInfo());
} }
@Action(userPermission = 1L << 16) @Action(userPermission = 1L << 16)
public void queryFreeResourceInfo(JsonObject args, ResultCallback resultCallback) { public void queryFreeResourceInfo(JsonObject args, ResultCallback resultCallback) {
ReplyUtil.simpleReply(resultCallback, "onQueryFreeResourceInfo", manager.getFreeResourceInfo()); ReplyUtil.simpleReply(resultCallback, "onQueryFreeResourceInfo",
manager.getFreeResourceInfo());
} }
// 查看本地合约日志详情 // 查看本地合约日志详情
@ -626,7 +606,8 @@ public class CMActions implements OnHashCallback {
data2.addProperty("date", sDate); data2.addProperty("date", sDate);
resultCallback.onResult(data2); resultCallback.onResult(data2);
} else { } else {
ReplyUtil.simpleReply(resultCallback, "onQueryContractLogDetail", "Can't get detail by this key!"); ReplyUtil.simpleReply(resultCallback, "onQueryContractLogDetail",
"Can't get detail by this key!");
} }
} }
@ -675,8 +656,7 @@ public class CMActions implements OnHashCallback {
public void startContractBatched(JsonObject args, ResultCallback resultCallback) { public void startContractBatched(JsonObject args, ResultCallback resultCallback) {
Map<String, Object> ret = new HashMap<>(); Map<String, Object> ret = new HashMap<>();
ret.put("action", "onStartContract"); ret.put("action", "onStartContract");
JsonArray array = JsonArray array = JsonUtil.parseString(args.get("fileList").getAsString()).getAsJsonArray();
JsonUtil.parseString(args.get("fileList").getAsString()).getAsJsonArray();
for (int i = 0; i < array.size(); i++) { for (int i = 0; i < array.size(); i++) {
String fileName = array.get(i).getAsString(); String fileName = array.get(i).getAsString();
Contract c = new Contract(); Contract c = new Contract();
@ -773,7 +753,8 @@ public class CMActions implements OnHashCallback {
try { try {
// TODO script should encoded!! // TODO script should encoded!!
File temp = new File(parPath + path); File temp = new File(parPath + path);
if (temp.isFile() && temp.exists()) c.setScript(temp.getAbsolutePath()); if (temp.isFile() && temp.exists())
c.setScript(temp.getAbsolutePath());
} catch (Exception e) { } catch (Exception e) {
e.printStackTrace(); e.printStackTrace();
} }
@ -785,10 +766,8 @@ public class CMActions implements OnHashCallback {
LOGGER.info("handler is null " + (handler == null)); LOGGER.info("handler is null " + (handler == null));
LOGGER.info(args.get("verifiedPubKey").getAsString()); LOGGER.info(args.get("verifiedPubKey").getAsString());
if (handler != null) { if (handler != null) {
listContractProcessWithFirstWithOwner( listContractProcessWithFirstWithOwner(args.get("verifiedPubKey").getAsString(),
args.get("verifiedPubKey").getAsString(), c.getID(), new ResultCallback() {
c.getID(),
new ResultCallback() {
@Override @Override
public void onResult(String str) { public void onResult(String str) {
handler.sendMsg(str); handler.sendMsg(str);
@ -878,10 +857,8 @@ public class CMActions implements OnHashCallback {
ret.put("executeTime", System.currentTimeMillis() - start); ret.put("executeTime", System.currentTimeMillis() - start);
resultCallback.onResult(ret); resultCallback.onResult(ret);
if (handler != null) { if (handler != null) {
listContractProcessWithFirstWithOwner( listContractProcessWithFirstWithOwner(args.get("verifiedPubKey").getAsString(),
args.get("verifiedPubKey").getAsString(), c.getID(), new ResultCallback() {
c.getID(),
new ResultCallback() {
@Override @Override
public void onResult(String str) { public void onResult(String str) {
handler.sendMsg(str); handler.sendMsg(str);
@ -894,14 +871,16 @@ public class CMActions implements OnHashCallback {
manager.changeDumpPeriod(c.getID(), args.get("dumpPeriod").getAsString()); manager.changeDumpPeriod(c.getID(), args.get("dumpPeriod").getAsString());
} }
} else { } else {
ReplyUtil.replyWithStatus(resultCallback, "onStartContract", false, "Failed: Illegal user"); ReplyUtil.replyWithStatus(resultCallback, "onStartContract", false,
"Failed: Illegal user");
} }
ExecutionManager.instance.updateLocalContractToNodeCenter(); ExecutionManager.instance.updateLocalContractToNodeCenter();
} }
private String getLoginPubkey(JsonObject args) { private String getLoginPubkey(JsonObject args) {
try { try {
if (handler != null) return handler.getPubKey(); if (handler != null)
return handler.getPubKey();
return args.get("pubKey").getAsString(); return args.get("pubKey").getAsString();
} catch (Exception e) { } catch (Exception e) {
e.printStackTrace(); e.printStackTrace();
@ -981,28 +960,16 @@ public class CMActions implements OnHashCallback {
c.setScript(ypkPath); c.setScript(ypkPath);
/* /*
if (DoConfig.openContractDORegister) { * if (DoConfig.openContractDORegister) { File file = new
File file = new File(dir.getAbsolutePath() + "/manifest.json"); * File(dir.getAbsolutePath() + "/manifest.json"); if (file.isFile() &&
if (file.isFile() && file.exists()) { * file.exists()) { try { InputStream manifestInput = new FileInputStream(file);
try { * ContractManifest cm = JsonUtil .fromJson( new
InputStream manifestInput = new FileInputStream(file); * InputStreamReader(manifestInput), ContractManifest.class);
ContractManifest cm = * c.setDoipFlag(cm.doipFlag); if (cm.doi != null && !cm.doi.equals(""))
JsonUtil * c.setDOI(cm.doi); if (cm.authInfoPersistDOI != null &&
.fromJson( * !cm.authInfoPersistDOI.equals(""))
new InputStreamReader(manifestInput), * c.setAuthInfoPersistDOI(cm.authInfoPersistDOI); } catch (Exception e) {
ContractManifest.class); * e.printStackTrace(); } } } else { c.setDoipFlag(false); }
c.setDoipFlag(cm.doipFlag);
if (cm.doi != null && !cm.doi.equals("")) c.setDOI(cm.doi);
if (cm.authInfoPersistDOI != null
&& !cm.authInfoPersistDOI.equals(""))
c.setAuthInfoPersistDOI(cm.authInfoPersistDOI);
} catch (Exception e) {
e.printStackTrace();
}
}
} else {
c.setDoipFlag(false);
}
*/ */
} catch (Exception e) { } catch (Exception e) {
e.printStackTrace(); e.printStackTrace();
@ -1017,10 +984,8 @@ public class CMActions implements OnHashCallback {
resultCallback.onResult(ret); resultCallback.onResult(ret);
ExecutionManager.instance.updateLocalContractToNodeCenter(); ExecutionManager.instance.updateLocalContractToNodeCenter();
if (handler != null) { if (handler != null) {
listContractProcessWithFirstWithOwner( listContractProcessWithFirstWithOwner(args.get("verifiedPubKey").getAsString(),
args.get("verifiedPubKey").getAsString(), c.getID(), new ResultCallback() {
c.getID(),
new ResultCallback() {
@Override @Override
public void onResult(String str) { public void onResult(String str) {
handler.sendMsg(str); handler.sendMsg(str);
@ -1107,8 +1072,8 @@ public class CMActions implements OnHashCallback {
} }
SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd.HH_mm_ss"); // 设置日期格式 SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd.HH_mm_ss"); // 设置日期格式
File f = File f = new File(GlobalConf.instance.memoryDir + "/" + contractName,
new File(GlobalConf.instance.memoryDir + "/" + contractName, df.format(new Date())); df.format(new Date()));
File parent = f.getParentFile(); File parent = f.getParentFile();
if (!parent.exists()) { if (!parent.exists()) {
parent.mkdirs(); parent.mkdirs();
@ -1204,17 +1169,11 @@ public class CMActions implements OnHashCallback {
} }
ContractClient cl = manager.getClient(rc.getContractID()); ContractClient cl = manager.getClient(rc.getContractID());
if (null == cl) { if (null == cl) {
String ret = String ret = manager.stopContractWithOwner(args.get("verifiedPubKey").getAsString(),
manager.stopContractWithOwner( rc.getContractID());
args.get("verifiedPubKey").getAsString(), rc.getContractID());
GRPCPool.instance.writeToChain( GRPCPool.instance.writeToChain(this, rc.getContractID(), "stopContract", ret,
this, args.has("requestID") ? args.get("requestID").getAsString() : null, "");
rc.getContractID(),
"stopContract",
ret,
args.has("requestID") ? args.get("requestID").getAsString() : null,
"");
Map<String, Object> r = new HashMap<>(); Map<String, Object> r = new HashMap<>();
r.put("action", "onKillContractProcess"); r.put("action", "onKillContractProcess");
r.put("data", ret); r.put("data", ret);
@ -1229,16 +1188,10 @@ public class CMActions implements OnHashCallback {
killContractByMaster(rc.getContractID(), args, resultCallback); killContractByMaster(rc.getContractID(), args, resultCallback);
} else { } else {
String ret = String ret = manager.stopContractWithOwner(args.get("verifiedPubKey").getAsString(),
manager.stopContractWithOwner( rc.getContractID());
args.get("verifiedPubKey").getAsString(), rc.getContractID()); GRPCPool.instance.writeToChain(this, rc.getContractID(), "stopContract", ret,
GRPCPool.instance.writeToChain( args.has("requestID") ? args.get("requestID").getAsString() : null, "");
this,
rc.getContractID(),
"stopContract",
ret,
args.has("requestID") ? args.get("requestID").getAsString() : null,
"");
JsonObject r = new JsonObject(); JsonObject r = new JsonObject();
r.addProperty("action", "onKillContractProcess"); r.addProperty("action", "onKillContractProcess");
r.addProperty("data", ret); r.addProperty("data", ret);
@ -1247,7 +1200,8 @@ public class CMActions implements OnHashCallback {
ExecutionManager.instance.updateLocalContractToNodeCenter(); ExecutionManager.instance.updateLocalContractToNodeCenter();
} }
} else { } else {
ReplyUtil.simpleReply(resultCallback, "onKillContractProcess", "Failed: Illegal parameters"); ReplyUtil.simpleReply(resultCallback, "onKillContractProcess",
"Failed: Illegal parameters");
} }
} }
@ -1268,13 +1222,12 @@ public class CMActions implements OnHashCallback {
Contract contract = meta.contract; Contract contract = meta.contract;
killContractProcess(args, resultCallback); killContractProcess(args, resultCallback);
manager.startContract(contract); manager.startContract(contract);
String data = manager.listContractsWithOwner( String data = manager.listContractsWithOwner(args.get("verifiedPubKey").getAsString(),
args.get("verifiedPubKey").getAsString(), null, args.has("filters") ? args.get("filters").getAsInt() : 0);
null,
args.has("filters") ? args.get("filters").getAsInt() : 0);
ReplyUtil.simpleReply(resultCallback, "onListContractProcess", data); ReplyUtil.simpleReply(resultCallback, "onListContractProcess", data);
} else { } else {
ReplyUtil.simpleReply(resultCallback, "onRestartContractProcess", "Failed: Illegal parameters"); ReplyUtil.simpleReply(resultCallback, "onRestartContractProcess",
"Failed: Illegal parameters");
} }
} }
@ -1297,7 +1250,8 @@ public class CMActions implements OnHashCallback {
LOGGER.info("pruneKilledContract!!! size:" + toRemove.size()); LOGGER.info("pruneKilledContract!!! size:" + toRemove.size());
for (ContractMeta key : toRemove) { for (ContractMeta key : toRemove) {
CMActions.manager.statusRecorder.remove(key); CMActions.manager.statusRecorder.remove(key);
MultiContractMeta multiMeta = CMActions.manager.multiContractRecorder.getMultiContractMeta(key.getID()); MultiContractMeta multiMeta =
CMActions.manager.multiContractRecorder.getMultiContractMeta(key.getID());
CMActions.manager.multiContractRecorder.remove(multiMeta); CMActions.manager.multiContractRecorder.remove(multiMeta);
} }
resultCallback.onResult("size:" + toRemove.size()); resultCallback.onResult("size:" + toRemove.size());
@ -1383,7 +1337,8 @@ public class CMActions implements OnHashCallback {
String dirPath; String dirPath;
if (args.has("isPrivate") && args.get("isPrivate").getAsBoolean()) if (args.has("isPrivate") && args.get("isPrivate").getAsBoolean())
dirPath = GlobalConf.instance.privateDir; dirPath = GlobalConf.instance.privateDir;
else dirPath = GlobalConf.instance.publicDir; else
dirPath = GlobalConf.instance.publicDir;
String ypkPath = FileActions.autoCompile(dirPath, project); String ypkPath = FileActions.autoCompile(dirPath, project);
Contract c = new Contract(); Contract c = new Contract();
c.setScript(ypkPath); c.setScript(ypkPath);
@ -1418,7 +1373,8 @@ public class CMActions implements OnHashCallback {
if (sc2.hasNext()) { if (sc2.hasNext()) {
sc2.next(); sc2.next();
if (sc2.hasNextInt()) pid = sc2.nextInt() + ""; if (sc2.hasNextInt())
pid = sc2.nextInt() + "";
} }
sc2.close(); sc2.close();
if (pid != null) { if (pid != null) {
@ -1443,7 +1399,8 @@ public class CMActions implements OnHashCallback {
ReplyUtil.replyWithStatus(resultCallback, "onKillAllContract", true, "Success"); ReplyUtil.replyWithStatus(resultCallback, "onKillAllContract", true, "Success");
} }
} else { } else {
ReplyUtil.replyWithStatus(resultCallback, "onKillAllContract", false, "Failed: Illegal user"); ReplyUtil.replyWithStatus(resultCallback, "onKillAllContract", false,
"Failed: Illegal user");
} }
} }
@ -1511,11 +1468,8 @@ public class CMActions implements OnHashCallback {
ContractResult cr = manager.requestLog(contractID, offset, count); ContractResult cr = manager.requestLog(contractID, offset, count);
Map<String, Object> ret = new HashMap<>(); Map<String, Object> ret = new HashMap<>();
ret.put("status", cr.status.toString()); ret.put("status", cr.status.toString());
ret.put( ret.put("result", JsonUtil.fromJson(cr.result,
"result", new TypeToken<List<Map<String, String>>>() {}.getType()));
JsonUtil.fromJson(
cr.result, new TypeToken<List<Map<String, String>>>() {
}.getType()));
resultCallback.onResult(ret); resultCallback.onResult(ret);
} }
@ -1535,10 +1489,8 @@ public class CMActions implements OnHashCallback {
Map<String, Object> ret = new HashMap<>(); Map<String, Object> ret = new HashMap<>();
ret.put("status", cr.status.toString()); ret.put("status", cr.status.toString());
try { try {
Object obj = Object obj = JsonUtil.fromJson(cr.result,
JsonUtil.fromJson( new TypeToken<List<Map<String, String>>>() {}.getType());
cr.result, new TypeToken<List<Map<String, String>>>() {
}.getType());
ret.put("result", obj); ret.put("result", obj);
} catch (Exception e) { } catch (Exception e) {
e.printStackTrace(); e.printStackTrace();
@ -1572,7 +1524,8 @@ public class CMActions implements OnHashCallback {
String nodeName; String nodeName;
for (JsonElement jsonElement : jsonArray) { for (JsonElement jsonElement : jsonArray) {
jsonObject = jsonElement.getAsJsonObject(); jsonObject = jsonElement.getAsJsonObject();
unitPeers = JsonUtil.parseString(jsonObject.get("value").getAsString()).getAsJsonArray(); unitPeers =
JsonUtil.parseString(jsonObject.get("value").getAsString()).getAsJsonArray();
for (JsonElement jsonElemenPeer : unitPeers) { for (JsonElement jsonElemenPeer : unitPeers) {
jsonPeer = jsonElemenPeer.getAsJsonObject(); jsonPeer = jsonElemenPeer.getAsJsonObject();
if (jsonPeer.has("nodeName")) if (jsonPeer.has("nodeName"))
@ -1582,15 +1535,15 @@ public class CMActions implements OnHashCallback {
if (jsonPeer.has("ipPort")) if (jsonPeer.has("ipPort"))
ipPort = jsonPeer.get("ipPort").getAsString(); ipPort = jsonPeer.get("ipPort").getAsString();
// NetworkManager.instance.peerID2TCPAddress.put(peer, ipPort); // NetworkManager.instance.peerID2TCPAddress.put(peer, ipPort);
// try { // try {
// NetworkManager.instance.createTCPClient(peerID, ipPort); // NetworkManager.instance.createTCPClient(peerID, ipPort);
// } catch (InterruptedException e) { // } catch (InterruptedException e) {
// e.printStackTrace(); // e.printStackTrace();
// JsonObject ret = new JsonObject(); // JsonObject ret = new JsonObject();
// ret.addProperty("status", "Error"); // ret.addProperty("status", "Error");
// ret.addProperty("result", "Cannot form TCP connection to " + nodeName); // ret.addProperty("result", "Cannot form TCP connection to " + nodeName);
// rc.onResult(ret); // rc.onResult(ret);
// } // }
} }
} }
} }
@ -1775,19 +1728,19 @@ public class CMActions implements OnHashCallback {
// } // }
/* /*
* @Action(userPermission = 1 << 19, async = true) public void * @Action(userPermission = 1 << 19, async = true) public void staticVerify(JsonObject args,
* staticVerify(JsonObject args, ResultCallback resultCallback) { Map<String, * ResultCallback resultCallback) { Map<String, Object> r = new HashMap<>(); r.put("action",
* Object> r = new HashMap<>(); r.put("action", "onStaticVerifyResult"); * "onStaticVerifyResult");
* *
* long start = System.currentTimeMillis(); Map<String, Object> ret = new * long start = System.currentTimeMillis(); Map<String, Object> ret = new HashMap<>(); Contract
* HashMap<>(); Contract c = new Contract(); // c.setType(Type.Algorithm); * c = new Contract(); // c.setType(Type.Algorithm); c.setType(ContractType.Sole);
* c.setType(ContractType.Sole); ret.put("action", "onStartContract"); String path = * ret.put("action", "onStartContract"); String path = null; if (args.has("path")) path =
* null; if (args.has("path")) path = args.get("path").getAsString(); if (path * args.get("path").getAsString(); if (path != null && path.startsWith("/"))
* != null && path.startsWith("/")) c.setScript(args.get("path").getAsString()); * c.setScript(args.get("path").getAsString()); else
* else c.setScript(args.get("script").getAsString()); if * c.setScript(args.get("script").getAsString()); if (args.has("publicKey")) {
* (args.has("publicKey")) { c.setOwner(args.get("publicKey").getAsString()); * c.setOwner(args.get("publicKey").getAsString());
* c.setSignature(args.get("signature").getAsString()); } else if * c.setSignature(args.get("signature").getAsString()); } else if (args.has("owner")) {
* (args.has("owner")) { c.setOwner(args.get("owner").getAsString()); * c.setOwner(args.get("owner").getAsString());
* c.setSignature(args.get("signature").getAsString()); * c.setSignature(args.get("signature").getAsString());
* *
* } else { c.setOwner(GlobalConf.instance.keyPair.getPublicKeyStr()); * } else { c.setOwner(GlobalConf.instance.keyPair.getPublicKeyStr());
@ -1796,27 +1749,23 @@ public class CMActions implements OnHashCallback {
* if (!c.verifySignature()) { ret.put("data", "verify failed"); * if (!c.verifySignature()) { ret.put("data", "verify failed");
* resultCallback.onResult(gson.toJson(ret)); return; } if (path != null && * resultCallback.onResult(gson.toJson(ret)); return; } if (path != null &&
* path.startsWith("/")) { String parPath; if (args.has("isPrivate") && * path.startsWith("/")) { String parPath; if (args.has("isPrivate") &&
* args.get("isPrivate").getAsBoolean()) { parPath = * args.get("isPrivate").getAsBoolean()) { parPath = GlobalConf.instance.privateDir + "/" +
* GlobalConf.instance.privateDir + "/" + handler.pubKey; } else { parPath = * handler.pubKey; } else { parPath = GlobalConf.instance.publicDir; } try { String[] pp =
* GlobalConf.instance.publicDir; } try { String[] pp = path.split("/"); String * path.split("/"); String parentPath = path; for (int i = 0; i < pp.length && i < 2; i++) {
* parentPath = path; for (int i = 0; i < pp.length && i < 2; i++) { parentPath * parentPath += pp[i] + "/"; } System.out.println("[CMActions] pack Dir, from:" + path +
* += pp[i] + "/"; } System.out.println("[CMActions] pack Dir, from:" + path +
* " --> " + parentPath); byte[] bb = YJSPacker.pack(new File(parPath, * " --> " + parentPath); byte[] bb = YJSPacker.pack(new File(parPath,
* parentPath).getAbsolutePath()); File temp = File.createTempFile(pp[pp.length * parentPath).getAbsolutePath()); File temp = File.createTempFile(pp[pp.length - 1], ".zip");
* - 1], ".zip"); FileOutputStream fout = new FileOutputStream(temp); * FileOutputStream fout = new FileOutputStream(temp); fout.write(bb); fout.close();
* fout.write(bb); fout.close(); System.out.println("StartContract, zipPath:" + * System.out.println("StartContract, zipPath:" + temp.getAbsolutePath()); // TODO script should
* temp.getAbsolutePath()); // TODO script should encoded!! * encoded!! c.setScript(temp.getAbsolutePath()); } catch (Exception e) { e.printStackTrace(); }
* c.setScript(temp.getAbsolutePath()); } catch (Exception e) { * }
* e.printStackTrace(); } }
* *
* System.out.println("[CMActions] verifyContract: " + gson.toJson(c)); * System.out.println("[CMActions] verifyContract: " + gson.toJson(c)); r.put("data",
* r.put("data", manager.staticVerify(c)); r.put("cid", c.getID()); * manager.staticVerify(c)); r.put("cid", c.getID()); r.put("executeTime",
* r.put("executeTime", System.currentTimeMillis() - start); // * System.currentTimeMillis() - start); // GRPCPool.writeToChain(c.getOwner(), privKey,
* GRPCPool.writeToChain(c.getOwner(), privKey, gson.toJson(r), // * gson.toJson(r), // json.getString("requestID"));
* json.getString("requestID"));
* *
* //addLocalContractLog("staticVerify", c.getID(), path.split("/")[1], * //addLocalContractLog("staticVerify", c.getID(), path.split("/")[1], c.getOwner(),null);
* c.getOwner(),null);
* *
* resultCallback.onResult(gson.toJson(r)); } * resultCallback.onResult(gson.toJson(r)); }
*/ */
@ -1899,8 +1848,8 @@ public class CMActions implements OnHashCallback {
old_num = peers.length; old_num = peers.length;
} }
} }
ExecutionManager.instance.startContractRequest( ExecutionManager.instance.startContractRequest(type, contract, old_num, peers, content,
type, contract, old_num, peers, content, sequencing, response, rc); sequencing, response, rc);
} }
static class WSPrintStream extends PrintStream { static class WSPrintStream extends PrintStream {

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,7 +49,8 @@ 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, result); queryByOffset(ContractManager.logsDB, "onQueryContractLogByOffset", contractName, json,
result);
} }
@Action(async = true, userPermission = 1L << 22) @Action(async = true, userPermission = 1L << 22)
@ -220,12 +221,8 @@ 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( ret.add("result", JsonParser.parseString(JsonUtil
"result", .toJson(ActionExecutor.getStatistic(json.get("caller").getAsString()))));
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())));
} }
@ -244,17 +241,15 @@ 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 = CMActions.manager.nodeCenterConn.checkIsContract(requestID, json.toString()); JsonObject ret =
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( private void queryLogSize(MultiIndexTimeDBUtilIntf db, String action, String label,
MultiIndexTimeDBUtilIntf db,
String action,
String label,
ResultCallback result) { ResultCallback result) {
try { try {
JsonObject ret = new JsonObject(); JsonObject ret = new JsonObject();
@ -274,19 +269,13 @@ public class CMLogAction {
} }
private void queryByDate( private void queryByDate(MultiIndexTimeDBUtilIntf db, String action, String label,
MultiIndexTimeDBUtilIntf db, JsonObject json, ResultCallback result) {
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( result.onResult("{\"action\":\"" + action
"{\"action\":\""
+ action
+ "\",\"status\":\"failed\",\"data\":\"missing start\"}"); + "\",\"status\":\"failed\",\"data\":\"missing start\"}");
return; return;
} }
@ -307,16 +296,10 @@ public class CMLogAction {
result.onResult(JsonUtil.toJson(ret)); result.onResult(JsonUtil.toJson(ret));
} }
private void queryByOffset( private void queryByOffset(MultiIndexTimeDBUtilIntf db, String action, String label,
MultiIndexTimeDBUtilIntf db, JsonObject json, ResultCallback result) {
String action,
String label,
JsonObject json,
ResultCallback result) {
if (!json.has("count")) { if (!json.has("count")) {
result.onResult( result.onResult("{\"action\":\"" + action
"{\"action\":\""
+ action
+ "\",\"status\":\"failed\",\"data\":\"missing count\"}"); + "\",\"status\":\"failed\",\"data\":\"missing count\"}");
return; return;
} }

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 = CMActions.manager.multiContractRecorder.getMultiContractMeta(contractID); MultiContractMeta info =
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( System.out.println("发送请求给 " + node.substring(0, 5) + " 更新ledger中最新检查点的hash!");
"发送请求给 " + 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.deliverEvent( CMActions.manager
JsonUtil.fromJson(args.get("data").getAsString(), REvent.class)); .deliverEvent(JsonUtil.fromJson(args.get("data").getAsString(), REvent.class));
} }
} }

View File

@ -52,13 +52,11 @@ public class EventWSActions {
rcb.onResult(ret); rcb.onResult(ret);
return; return;
} }
String requestID = args.has("requestID") ? String requestID = args.has("requestID") ? args.get("requestID").getAsString()
args.get("requestID").getAsString() : : HashUtil.sha3(String.valueOf(System.currentTimeMillis()), "_",
HashUtil.sha3(String.valueOf(System.currentTimeMillis()), "_", String.valueOf(Math.random())); String.valueOf(Math.random()));
REvent event = new REvent(args.get("topic").getAsString(), REvent event = new REvent(args.get("topic").getAsString(), PUBLISH,
PUBLISH, args.get("content").getAsString(), requestID);
args.get("content").getAsString(),
requestID);
if (args.has("semantics")) { if (args.has("semantics")) {
try { try {
event.setSemantics(valueOf(args.get("semantics").getAsString())); event.setSemantics(valueOf(args.get("semantics").getAsString()));

View File

@ -59,8 +59,7 @@ public class FileActions {
ContractManagerFrameHandler handler; ContractManagerFrameHandler handler;
static { static {
clearUploadFailed = clearUploadFailed = new TimerTask() {
new TimerTask() {
@Override @Override
public void run(Timeout arg0) { public void run(Timeout arg0) {
clearUploadFailed(); clearUploadFailed();
@ -85,10 +84,7 @@ public class FileActions {
String fileName = compileInternal(parentPath, projectName, isPrivate, true); String fileName = compileInternal(parentPath, projectName, isPrivate, true);
File dir; File dir;
if (isPrivate) { if (isPrivate) {
dir = dir = new File(parentPath.replace(GlobalConf.instance.privateDir,
new File(
parentPath.replace(
GlobalConf.instance.privateDir,
GlobalConf.instance.privateCompiledDir)); GlobalConf.instance.privateCompiledDir));
} else { } else {
dir = new File(GlobalConf.instance.publicCompiledDir); dir = new File(GlobalConf.instance.publicCompiledDir);
@ -107,9 +103,7 @@ public class FileActions {
return ret != null && ret.equals("locked"); return ret != null && ret.equals("locked");
} }
@URIPath( @URIPath(method = org.bdware.server.http.HttpMethod.POST, value = {"/SCIDE/Upload", "/Upload"})
method = org.bdware.server.http.HttpMethod.POST,
value = {"/SCIDE/Upload", "/Upload"})
public static void handleUploadRequest(ChannelHandlerContext ctx, FullHttpRequest request) { public static void handleUploadRequest(ChannelHandlerContext ctx, FullHttpRequest request) {
// logger.info("[CMHttpHandler] handleUploadRequest : "); // logger.info("[CMHttpHandler] handleUploadRequest : ");
// Upload method is POST // Upload method is POST
@ -124,17 +118,13 @@ public class FileActions {
} }
} }
if (!transformedParam.containsKey("path") if (!transformedParam.containsKey("path") || !transformedParam.containsKey("fileName")
|| !transformedParam.containsKey("fileName")
|| !transformedParam.containsKey("isPrivate") || !transformedParam.containsKey("isPrivate")
|| !transformedParam.containsKey("order") || !transformedParam.containsKey("order") || !transformedParam.containsKey("count")
|| !transformedParam.containsKey("count")
|| !transformedParam.containsKey("pubKey") || !transformedParam.containsKey("pubKey")
|| !transformedParam.containsKey("sign")) { || !transformedParam.containsKey("sign")) {
DefaultFullHttpResponse fullResponse = DefaultFullHttpResponse fullResponse = new DefaultFullHttpResponse(
new DefaultFullHttpResponse( request.protocolVersion(), OK,
request.protocolVersion(),
OK,
Unpooled.wrappedBuffer( Unpooled.wrappedBuffer(
"{\"status\":\"false\",\"data\":\"Missing argument, please check: path, fileName, isPrivate, order, count, pubKey, sign!\"}" "{\"status\":\"false\",\"data\":\"Missing argument, please check: path, fileName, isPrivate, order, count, pubKey, sign!\"}"
.getBytes())); .getBytes()));
@ -147,9 +137,7 @@ public class FileActions {
// 验签 // 验签
// HttpMethod method = request.method(); // HttpMethod method = request.method();
String uri = String uri = URLDecoder.decode(request.uri()).split("\\?")[1]; // http请求中规定签名必须是最后一个且公钥名必须为pubKey否则验签失败
URLDecoder.decode(request.uri())
.split("\\?")[1]; // http请求中规定签名必须是最后一个且公钥名必须为pubKey否则验签失败
int index = uri.lastIndexOf('&'); int index = uri.lastIndexOf('&');
String str = uri.substring(0, index); String str = uri.substring(0, index);
// logger.info("uri=" + uri); // logger.info("uri=" + uri);
@ -183,9 +171,8 @@ public class FileActions {
Method mm; Method mm;
Action a = null; Action a = null;
try { try {
mm = mm = FileActions.class.getDeclaredMethod("uploadFile", JsonObject.class,
FileActions.class.getDeclaredMethod( ResultCallback.class);
"uploadFile", JsonObject.class, ResultCallback.class);
a = mm.getAnnotation(Action.class); a = mm.getAnnotation(Action.class);
} catch (SecurityException | NoSuchMethodException e1) { } catch (SecurityException | NoSuchMethodException e1) {
// TODO Auto-generated catch block // TODO Auto-generated catch block
@ -215,28 +202,17 @@ public class FileActions {
status = "accept"; status = "accept";
} }
TimeDBUtil.instance.put( TimeDBUtil.instance.put(CMTables.LocalNodeLogDB.toString(),
CMTables.LocalNodeLogDB.toString(), "{\"action\":\"" + action + "\",\"pubKey\":\"" + transformedParam.get("pubKey")
"{\"action\":\"" + "\",\"status\":\"" + status + "\",\"date\":" + System.currentTimeMillis()
+ action
+ "\",\"pubKey\":\""
+ transformedParam.get("pubKey")
+ "\",\"status\":\""
+ status
+ "\",\"date\":"
+ System.currentTimeMillis()
+ "}"); + "}");
// logger.info("[CMHttpHandler] flag = " + flag + " flag2 = " + flag2); // logger.info("[CMHttpHandler] flag = " + flag + " flag2 = " + flag2);
if (!flag || !flag2) { if (!flag || !flag2) {
DefaultFullHttpResponse fullResponse = DefaultFullHttpResponse fullResponse = new DefaultFullHttpResponse(
new DefaultFullHttpResponse( request.protocolVersion(), OK, Unpooled.wrappedBuffer(
request.protocolVersion(), "{\"status\":\"false\",\"data\":\"Permission denied!\"}".getBytes()));
OK,
Unpooled.wrappedBuffer(
"{\"status\":\"false\",\"data\":\"Permission denied!\"}"
.getBytes()));
ChannelFuture f = addCrossOriginHeaderAndWrite(ctx, fullResponse); ChannelFuture f = addCrossOriginHeaderAndWrite(ctx, fullResponse);
f.addListener(ChannelFutureListener.CLOSE); f.addListener(ChannelFutureListener.CLOSE);
@ -256,9 +232,7 @@ public class FileActions {
ContractMeta meta = CMActions.manager.statusRecorder.getContractMeta(contractID); ContractMeta meta = CMActions.manager.statusRecorder.getContractMeta(contractID);
if (meta == null) { if (meta == null) {
DefaultFullHttpResponse fullResponse = DefaultFullHttpResponse fullResponse =
new DefaultFullHttpResponse( new DefaultFullHttpResponse(request.protocolVersion(), OK,
request.protocolVersion(),
OK,
Unpooled.wrappedBuffer( Unpooled.wrappedBuffer(
"{\"status\":\"false\",\"data\":\"no such contract!\"}" "{\"status\":\"false\",\"data\":\"no such contract!\"}"
.getBytes())); .getBytes()));
@ -267,23 +241,19 @@ public class FileActions {
return; return;
} }
if (!meta.contract.getOwner().equals(pubkey)) { if (!meta.contract.getOwner().equals(pubkey)) {
DefaultFullHttpResponse fullResponse = DefaultFullHttpResponse fullResponse = new DefaultFullHttpResponse(
new DefaultFullHttpResponse( request.protocolVersion(), OK, Unpooled.wrappedBuffer(
request.protocolVersion(), "{\"status\":\"false\",\"data\":\"not owner!\"}".getBytes()));
OK,
Unpooled.wrappedBuffer(
"{\"status\":\"false\",\"data\":\"not owner!\"}"
.getBytes()));
ChannelFuture f = addCrossOriginHeaderAndWrite(ctx, fullResponse); ChannelFuture f = addCrossOriginHeaderAndWrite(ctx, fullResponse);
f.addListener(ChannelFutureListener.CLOSE); f.addListener(ChannelFutureListener.CLOSE);
return; return;
} }
dir = new File(GlobalConf.instance.getDBPath(), meta.getName()); dir = new File(GlobalConf.instance.getDBPath(), meta.getName());
dir = new File(dir, dirName); dir = new File(dir, dirName);
if (!dir.exists()) dir.mkdirs(); if (!dir.exists())
dir.mkdirs();
} else { } else {
boolean isPrivate = boolean isPrivate = transformedParam.containsKey("isPrivate")
transformedParam.containsKey("isPrivate")
&& Boolean.parseBoolean(transformedParam.get("isPrivate")); && Boolean.parseBoolean(transformedParam.get("isPrivate"));
// TODO verify signature and // TODO verify signature and
if (isPrivate) { if (isPrivate) {
@ -298,13 +268,9 @@ public class FileActions {
} }
File target = new File(dir, fileName); File target = new File(dir, fileName);
if (fileName.contains("..")) { if (fileName.contains("..")) {
DefaultFullHttpResponse fullResponse = DefaultFullHttpResponse fullResponse = new DefaultFullHttpResponse(
new DefaultFullHttpResponse( request.protocolVersion(), OK, Unpooled.wrappedBuffer(
request.protocolVersion(), "{\"status\":\"false\",\"data\":\"FileName illegal!\"}".getBytes()));
OK,
Unpooled.wrappedBuffer(
"{\"status\":\"false\",\"data\":\"FileName illegal!\"}"
.getBytes()));
ChannelFuture f = addCrossOriginHeaderAndWrite(ctx, fullResponse); ChannelFuture f = addCrossOriginHeaderAndWrite(ctx, fullResponse);
f.addListener(ChannelFutureListener.CLOSE); f.addListener(ChannelFutureListener.CLOSE);
@ -318,7 +284,8 @@ public class FileActions {
if (order == 0) { if (order == 0) {
try { try {
LOGGER.debug("Path:" + target.getAbsolutePath()); LOGGER.debug("Path:" + target.getAbsolutePath());
if (!target.getParentFile().exists()) target.getParentFile().mkdirs(); if (!target.getParentFile().exists())
target.getParentFile().mkdirs();
fout = new FileOutputStream(target, false); fout = new FileOutputStream(target, false);
fileMap.put(target.getAbsolutePath(), fout); fileMap.put(target.getAbsolutePath(), fout);
} catch (FileNotFoundException e) { } catch (FileNotFoundException e) {
@ -339,24 +306,24 @@ public class FileActions {
} }
fileMap.remove(target.getAbsolutePath()); fileMap.remove(target.getAbsolutePath());
updateTime.remove(target.getAbsolutePath()); updateTime.remove(target.getAbsolutePath());
boolean isDebug = boolean isDebug = transformedParam.containsKey("isDebug")
transformedParam.containsKey("isDebug")
&& Boolean.parseBoolean(transformedParam.get("isDebug")); && Boolean.parseBoolean(transformedParam.get("isDebug"));
String doi = null; String doi = null;
if (target.getParentFile().getParentFile().equals(new File(GlobalConf.instance.privateDir))) if (target.getParentFile().getParentFile()
.equals(new File(GlobalConf.instance.privateDir)))
doi = unzipIfYpk(target, dir, isDebug); doi = unzipIfYpk(target, dir, isDebug);
if (null != doi) { if (null != doi) {
retStr = retStr.replaceFirst("null", doi); retStr = retStr.replaceFirst("null", doi);
} }
} }
DefaultFullHttpResponse fullResponse = DefaultFullHttpResponse fullResponse = new DefaultFullHttpResponse(
new DefaultFullHttpResponse(
request.protocolVersion(), OK, Unpooled.wrappedBuffer(retStr.getBytes())); request.protocolVersion(), OK, Unpooled.wrappedBuffer(retStr.getBytes()));
ChannelFuture f = addCrossOriginHeaderAndWrite(ctx, fullResponse); ChannelFuture f = addCrossOriginHeaderAndWrite(ctx, fullResponse);
f.addListener(ChannelFutureListener.CLOSE); f.addListener(ChannelFutureListener.CLOSE);
} }
private static ChannelFuture addCrossOriginHeaderAndWrite(ChannelHandlerContext ctx, DefaultFullHttpResponse fullResponse) { private static ChannelFuture addCrossOriginHeaderAndWrite(ChannelHandlerContext ctx,
DefaultFullHttpResponse fullResponse) {
fullResponse.headers().add("Access-Control-Allow-Origin", "*"); fullResponse.headers().add("Access-Control-Allow-Origin", "*");
fullResponse.headers().add("Access-Control-Allow-Methods", "*"); fullResponse.headers().add("Access-Control-Allow-Methods", "*");
return ctx.write(fullResponse); return ctx.write(fullResponse);
@ -375,14 +342,11 @@ public class FileActions {
private static String unzipIfYpk(File target, File dir, boolean isDebug) { private static String unzipIfYpk(File target, File dir, boolean isDebug) {
// [FileAction] unzipIfYpk, // [FileAction] unzipIfYpk,
// target:/data/bdwaas/bdcontract/./BDWareProjectDir/private/045eeda3a001faad9d636ab1e973599ea87338a9576756eb10ceeca6083c1f76aac5cd201eab21c41342eb8aac40e9b283f0b6eae019644cdcc0a9f9aeb73de8fc/ContractUNknown.ypk targetDir:/data/bdwaas/bdcontract/./BDWareProjectDir/private/045eeda3a001faad9d636ab1e973599ea87338a9576756eb10ceeca6083c1f76aac5cd201eab21c41342eb8aac40e9b283f0b6eae019644cdcc0a9f9aeb73de8fc/ContractUNknown // target:/data/bdwaas/bdcontract/./BDWareProjectDir/private/045eeda3a001faad9d636ab1e973599ea87338a9576756eb10ceeca6083c1f76aac5cd201eab21c41342eb8aac40e9b283f0b6eae019644cdcc0a9f9aeb73de8fc/ContractUNknown.ypk
LOGGER.info( // targetDir:/data/bdwaas/bdcontract/./BDWareProjectDir/private/045eeda3a001faad9d636ab1e973599ea87338a9576756eb10ceeca6083c1f76aac5cd201eab21c41342eb8aac40e9b283f0b6eae019644cdcc0a9f9aeb73de8fc/ContractUNknown
"[FileAction] unzipIfYpk, date:" LOGGER.info("[FileAction] unzipIfYpk, date:"
+ new SimpleDateFormat("MM-dd hh:mm:ss").format(new Date()) + new SimpleDateFormat("MM-dd hh:mm:ss").format(new Date()) + " -> target:"
+ " -> target:" + target.getAbsolutePath() + " dir:" + dir.getAbsolutePath());
+ target.getAbsolutePath()
+ " dir:"
+ dir.getAbsolutePath());
if (target.getParentFile().equals(dir)) { if (target.getParentFile().equals(dir)) {
if (target.getName().endsWith(".ypk")) { if (target.getName().endsWith(".ypk")) {
String dirName = target.getName().substring(0, target.getName().length() - 4); String dirName = target.getName().substring(0, target.getName().length() - 4);
@ -396,11 +360,8 @@ public class FileActions {
} }
} }
targetDir.mkdirs(); targetDir.mkdirs();
LOGGER.info( LOGGER.info("[FileAction] unzipIfYpk, target:" + target.getAbsolutePath()
"[FileAction] unzipIfYpk, target:" + " targetDir:" + targetDir.getAbsolutePath());
+ target.getAbsolutePath()
+ " targetDir:"
+ targetDir.getAbsolutePath());
YJSPacker.unpack(target.getAbsolutePath(), targetDir.getAbsolutePath()); YJSPacker.unpack(target.getAbsolutePath(), targetDir.getAbsolutePath());
final File tempDir = targetDir; final File tempDir = targetDir;
ContractManager.threadPool.execute(() -> startIfManifestDetected(tempDir, isDebug)); ContractManager.threadPool.execute(() -> startIfManifestDetected(tempDir, isDebug));
@ -418,8 +379,7 @@ public class FileActions {
String doi = "86.5000.470/do." + geneRandomID(); String doi = "86.5000.470/do." + geneRandomID();
jo.addProperty("doi", doi); jo.addProperty("doi", doi);
} }
ContractManager.threadPool.execute( ContractManager.threadPool.execute(() -> {
() -> {
try { try {
GRPCPool.instance.reRegister(jo.get("doi").getAsString()); GRPCPool.instance.reRegister(jo.get("doi").getAsString());
} catch (Exception e) { } catch (Exception e) {
@ -450,9 +410,8 @@ public class FileActions {
LOGGER.info("startContractProcess:" + targetDir); LOGGER.info("startContractProcess:" + targetDir);
Contract c = new Contract(); Contract c = new Contract();
c.setType(ContractExecType.Sole); c.setType(ContractExecType.Sole);
String ypkPath = String ypkPath = FileActions
FileActions.autoCompile( .autoCompile(targetDir.getParentFile().getAbsolutePath(), contractName);
targetDir.getParentFile().getAbsolutePath(), contractName);
c.setScript(ypkPath); c.setScript(ypkPath);
c.setOwner(owner); c.setOwner(owner);
c.setDebug(isDebug); c.setDebug(isDebug);
@ -487,8 +446,8 @@ public class FileActions {
} }
} }
private static void writeChunk( private static void writeChunk(ChannelHandlerContext ctx, HttpPostRequestDecoder httpDecoder,
ChannelHandlerContext ctx, HttpPostRequestDecoder httpDecoder, File file) { File file) {
try { try {
if (!file.exists()) { if (!file.exists()) {
file.createNewFile(); file.createNewFile();
@ -521,8 +480,8 @@ public class FileActions {
} }
} }
private static String compileInternal( private static String compileInternal(String parPath, String projectName, boolean isPrivate,
String parPath, String projectName, boolean isPrivate, boolean isAuto) { boolean isAuto) {
File project = new File(parPath, projectName); File project = new File(parPath, projectName);
try { try {
if (project.isDirectory()) { if (project.isDirectory()) {
@ -534,10 +493,7 @@ public class FileActions {
File dir; File dir;
if (isPrivate) { if (isPrivate) {
dir = dir = new File(parPath.replace(GlobalConf.instance.privateDir,
new File(
parPath.replace(
GlobalConf.instance.privateDir,
GlobalConf.instance.privateCompiledDir)); GlobalConf.instance.privateCompiledDir));
} else { } else {
@ -545,13 +501,10 @@ public class FileActions {
} }
tempZip = new File(dir, projectName + "_" + time + isAutoStr + ".ypk"); tempZip = new File(dir, projectName + "_" + time + isAutoStr + ".ypk");
if (isAuto) { if (isAuto) {
File[] files = File[] files = dir
dir.listFiles( .listFiles(pathname -> pathname.getName().startsWith(projectName + "_")
pathname ->
pathname.getName().startsWith(projectName + "_")
&& pathname.getName().endsWith("_Auto.ypk")); && pathname.getName().endsWith("_Auto.ypk"));
if (files != null if (files != null && files.length == 1
&& files.length == 1
&& !changeSet.contains(project.getAbsolutePath())) { && !changeSet.contains(project.getAbsolutePath())) {
return files[0].getName(); return files[0].getName();
} else if (files != null) { } else if (files != null) {
@ -576,8 +529,7 @@ public class FileActions {
Map<String, String> header = new HashMap<>(); Map<String, String> header = new HashMap<>();
header.put("accept", "*/*"); header.put("accept", "*/*");
header.put("connection", "Keep-Alive"); header.put("connection", "Keep-Alive");
header.put( header.put("user-agent",
"user-agent",
" Mozilla/5.0 (Macintosh; Intel Mac OS X 10_13_6) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/70.0.3538.77 Safari/537.36)"); " Mozilla/5.0 (Macintosh; Intel Mac OS X 10_13_6) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/70.0.3538.77 Safari/537.36)");
// header.put("Content-Type", "application/json"); // header.put("Content-Type", "application/json");
return header; return header;
@ -652,7 +604,8 @@ public class FileActions {
} }
private static String toProjectName(String path) { private static String toProjectName(String path) {
if (path.startsWith("/")) path = path.substring(1); if (path.startsWith("/"))
path = path.substring(1);
return path.replaceAll("/.*$", ""); return path.replaceAll("/.*$", "");
} }
@ -771,9 +724,7 @@ public class FileActions {
int counter = 0; int counter = 0;
while ((s = br.readLine()) != null) { while ((s = br.readLine()) != null) {
if (s.equals("{") if (s.equals("{") || s.equals("}") || s.equals("")
|| s.equals("}")
|| s.equals("")
|| s.trim().startsWith("\"doi\":\"") || s.trim().startsWith("\"doi\":\"")
|| s.trim().startsWith("\"doipFlag\":\"")) { || s.trim().startsWith("\"doipFlag\":\"")) {
continue; continue;
@ -852,8 +803,8 @@ public class FileActions {
returnFileListResponse(resultCallback, response, dirs, f); returnFileListResponse(resultCallback, response, dirs, f);
} }
private void returnFileListResponse( private void returnFileListResponse(ResultCallback resultCallback, Response response,
ResultCallback resultCallback, Response response, List<String> dirs, File f) { List<String> dirs, File f) {
if (f.exists() && f.isDirectory()) { if (f.exists() && f.isDirectory()) {
for (File subFile : f.listFiles()) { for (File subFile : f.listFiles()) {
dirs.add(subFile.getName()); dirs.add(subFile.getName());
@ -895,7 +846,8 @@ public class FileActions {
String fileName = subFile.getName(); String fileName = subFile.getName();
dirs.add(fileName); dirs.add(fileName);
} }
} else dirs.add(project); } else
dirs.add(project);
} }
response.data = JsonUtil.toJson(dirs); response.data = JsonUtil.toJson(dirs);
} }
@ -1077,7 +1029,7 @@ public class FileActions {
long downloaded = 0; long downloaded = 0;
byte[] buff = new byte[1024 * 100 * 4]; byte[] buff = new byte[1024 * 100 * 4];
int d = 5; int d = 5;
for (int k; (k = input.read(buff)) > 0; ) { for (int k; (k = input.read(buff)) > 0;) {
fout.write(buff, 0, k); fout.write(buff, 0, k);
downloaded += k; downloaded += k;
response.data = "downloading"; response.data = "downloading";
@ -1195,7 +1147,8 @@ public class FileActions {
// e.setData("{}".getBytes()); // e.setData("{}".getBytes());
// contractDO.addElements(e); // contractDO.addElements(e);
// // // //
// DOAClient.getGlobalInstance().create(DOIPMainServer.repoIdentifier, contractDO); // DOAClient.getGlobalInstance().create(DOIPMainServer.repoIdentifier,
// contractDO);
// DoipClient doipClient = // DoipClient doipClient =
// //
// DoipClient.createByRepoUrlAndMsgFmt( // DoipClient.createByRepoUrlAndMsgFmt(
@ -1215,52 +1168,34 @@ public class FileActions {
// } // }
if (args.has("projectDOI")) if (args.has("projectDOI"))
manifestFout.write( manifestFout.write(("{\n \"main\":\"" + fileName + ".yjs\",\n"
("{\n \"main\":\"" + " \"doipFlag\":true,\n" + " \"doi\":\""
+ fileName + args.get("projectDOI").getAsString() + "\",\n"
+ ".yjs\",\n" + " \"authInfoPersistDOI\":\"" + authInfoPersistDOI
+ " \"doipFlag\":true,\n" + "\"\n}").getBytes());
+ " \"doi\":\""
+ args.get("projectDOI").getAsString()
+ "\",\n"
+ " \"authInfoPersistDOI\":\""
+ authInfoPersistDOI
+ "\"\n}")
.getBytes());
else else
manifestFout.write( manifestFout.write(("{\n \"main\":\"" + fileName + ".yjs\",\n"
("{\n \"main\":\"" + " \"authInfoPersistDOI\":\"" + authInfoPersistDOI
+ fileName + "\"\n}").getBytes());
+ ".yjs\",\n"
+ " \"authInfoPersistDOI\":\""
+ authInfoPersistDOI
+ "\"\n}")
.getBytes());
YJSPacker.unpack( YJSPacker.unpack(
new File("./WebContent/ProjectTemplate/naiveDAC.zip") new File("./WebContent/ProjectTemplate/naiveDAC.zip")
.getAbsolutePath(), .getAbsolutePath(),
newFile.getPath() + "/naiveDAC"); newFile.getPath() + "/naiveDAC");
mainyjsFout.write( mainyjsFout
("import \"naiveDAC/naiveDAC.yjs\"\n\n").getBytes()); .write(("import \"naiveDAC/naiveDAC.yjs\"\n\n").getBytes());
mainyjsFout.write( mainyjsFout.write(("contract " + fileName
("contract "
+ fileName
+ "{\n function onCreate(){\n initDAC(requester);\n }\n}") + "{\n function onCreate(){\n initDAC(requester);\n }\n}")
.getBytes()); .getBytes());
break; break;
default: default:
if (args.has("projectDOI")) if (args.has("projectDOI"))
manifestFout.write( manifestFout.write(("{\n \"main\":\"" + fileName
("{\n \"main\":\""
+ fileName
+ ".yjs\",\n \"doipFlag\":true,\n \"doi\":\"" + ".yjs\",\n \"doipFlag\":true,\n \"doi\":\""
+ args.get("projectDOI").getAsString() + args.get("projectDOI").getAsString() + "\"\n}")
+ "\"\n}")
.getBytes()); .getBytes());
else else
manifestFout.write( manifestFout.write(("{\n \"main\":\"" + fileName + ".yjs\"\n}")
("{\n \"main\":\"" + fileName + ".yjs\"\n}")
.getBytes()); .getBytes());
mainyjsFout.write(("contract " + fileName + "{\n\n}").getBytes()); mainyjsFout.write(("contract " + fileName + "{\n\n}").getBytes());
} }
@ -1323,10 +1258,7 @@ public class FileActions {
File f = new File(parPath + "/" + oldFile); File f = new File(parPath + "/" + oldFile);
if (!oldFile.contains("..") && f.exists()) { if (!oldFile.contains("..") && f.exists()) {
LOGGER.debug( LOGGER.debug("[FileController] delete:" + f.getAbsolutePath() + " exists:"
"[FileController] delete:"
+ f.getAbsolutePath()
+ " exists:"
+ f.exists()); + f.exists());
if (f.isDirectory()) { if (f.isDirectory()) {
deleteDir(f); deleteDir(f);
@ -1465,10 +1397,8 @@ public class FileActions {
// 文本文件 // 文本文件
if (!path.contains("..") && isTextFile(path)) { if (!path.contains("..") && isTextFile(path)) {
LOGGER.debug("[FileActions] 上传文本文件类型 : "); LOGGER.debug("[FileActions] 上传文本文件类型 : ");
BufferedWriter bw = BufferedWriter bw = new BufferedWriter(
new BufferedWriter( new FileWriter(target.getAbsolutePath() + "/" + fileName, isAppend));
new FileWriter(
target.getAbsolutePath() + "/" + fileName, isAppend));
bw.write(content); bw.write(content);
bw.close(); bw.close();
} else { // 其他类型文件 } else { // 其他类型文件
@ -1505,7 +1435,8 @@ public class FileActions {
private String getPubkey(JsonObject args) { private String getPubkey(JsonObject args) {
try { try {
if (handler != null) return handler.getPubKey(); if (handler != null)
return handler.getPubKey();
return args.get("pubKey").getAsString(); return args.get("pubKey").getAsString();
} catch (Exception e) { } catch (Exception e) {
e.printStackTrace(); e.printStackTrace();
@ -1648,9 +1579,8 @@ public class FileActions {
if (null != ypkPath) { if (null != ypkPath) {
try { try {
ret.put("ypk", new File(ypkPath).getName()); ret.put("ypk", new File(ypkPath).getName());
ret.put( ret.put("permissions", JsonUtil
"permissions", .parseStringAsJsonObject(CMActions.manager.parseYpkPermissions(ypkPath)));
JsonUtil.parseStringAsJsonObject(CMActions.manager.parseYpkPermissions(ypkPath)));
} catch (Exception e) { } catch (Exception e) {
ByteArrayOutputStream bo = new ByteArrayOutputStream(); ByteArrayOutputStream bo = new ByteArrayOutputStream();
e.printStackTrace(new PrintStream(bo)); e.printStackTrace(new PrintStream(bo));

View File

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

View File

@ -69,7 +69,8 @@ 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++) array.add(ledgers.getLedgers(i)); for (int i = 0; i < ledgers.getLedgersCount(); 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();
@ -99,48 +100,43 @@ 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")) ledgerName = jo.get("ledger").getAsString(); if (jo.has("ledger"))
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( wt.sendTransaction(ledgerName, CommonProto.TransactionType.MESSAGE, from,
ledgerName, random.nextLong(), to, data.getBytes());
CommonProto.TransactionType.MESSAGE, future.addListener(() -> {
from,
random.nextLong(),
to,
data.getBytes());
future.addListener(
() -> {
try { try {
ByteString hash = future.get().getHash(); ByteString hash = future.get().getHash();
ReplyUtil.replyWithStatus(resultCallback, "onSendTransaction", true, HashUtil.byteArray2Str(hash.toByteArray())); ReplyUtil.replyWithStatus(resultCallback, "onSendTransaction", true,
HashUtil.byteArray2Str(hash.toByteArray()));
} catch (Exception e) { } catch (Exception e) {
ByteArrayOutputStream bo = new ByteArrayOutputStream(); ByteArrayOutputStream bo = new ByteArrayOutputStream();
String dataStr = bo.toString(); String dataStr = bo.toString();
ReplyUtil.replyWithStatus(resultCallback, "onSendTransaction", false, dataStr); ReplyUtil.replyWithStatus(resultCallback, "onSendTransaction", false, dataStr);
e.printStackTrace(); e.printStackTrace();
} }
}, }, ContractManager.threadPool);
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")) ledgerName = jo.get("ledger").getAsString(); if (jo.has("ledger"))
ledgerName = jo.get("ledger").getAsString();
Client wt = GRPCPool.grpcClients.get(0); Client wt = GRPCPool.grpcClients.get(0);
if (wt == null) { if (wt == null) {
resultCallback.onResult( resultCallback
"{\"status\":\"Exception\",\"data\":\"no available worker thread\"}"); .onResult("{\"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 { try {
CommonProto.Transaction trans = future.get().getTransaction(); CommonProto.Transaction trans = future.get().getTransaction();
Map<String, String> ret = new HashMap<>(); Map<String, String> ret = new HashMap<>();
@ -159,7 +155,6 @@ public class LedgerActions {
resultCallback.onResult(JsonUtil.toJson(ret)); resultCallback.onResult(JsonUtil.toJson(ret));
e.printStackTrace(); e.printStackTrace();
} }
}, }, ContractManager.threadPool);
ContractManager.threadPool);
} }
} }

View File

@ -42,7 +42,8 @@ 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(), HardwareInfo.getCPUID().getBytes())); data = ByteUtils.toHexString(SM2Util.encrypt(GlobalConf.instance.keyPair.getPublicKey(),
HardwareInfo.getCPUID().getBytes()));
} catch (Exception e) { } catch (Exception e) {
e.printStackTrace(); e.printStackTrace();
} }
@ -51,7 +52,8 @@ public class ManagerActions {
@Action(userPermission = 1 << 10) @Action(userPermission = 1 << 10)
public void downloadUUID(JsonObject args, ResultCallback resultCallback) { public void downloadUUID(JsonObject args, ResultCallback resultCallback) {
String uuid = ByteUtil.encodeBASE64(HardwareInfo.getCPUID().getBytes()).replaceAll("\n", ""); String uuid =
ByteUtil.encodeBASE64(HardwareInfo.getCPUID().getBytes()).replaceAll("\n", "");
resultCallback.onResult(uuid); resultCallback.onResult(uuid);
} }
@ -98,7 +100,8 @@ public class ManagerActions {
return; return;
} catch (Exception e) { } catch (Exception e) {
e.printStackTrace(); e.printStackTrace();
ReplyUtil.replyWithStatus(resultCallback, "onUpdateConfig", false, "exception:" + e.getMessage()); ReplyUtil.replyWithStatus(resultCallback, "onUpdateConfig", false,
"exception:" + e.getMessage());
} }
} }
@ -109,7 +112,8 @@ public class ManagerActions {
Map<String, Object> data = new HashMap<>(); Map<String, Object> data = new HashMap<>();
data.put("projectDir", GlobalConf.instance.projectDir); data.put("projectDir", GlobalConf.instance.projectDir);
data.put("yjsPath", GlobalConf.instance.yjsPath); data.put("yjsPath", GlobalConf.instance.yjsPath);
if (GlobalConf.instance.datachainConf != null) data.put("datachainConf", GlobalConf.instance.datachainConf); if (GlobalConf.instance.datachainConf != null)
data.put("datachainConf", GlobalConf.instance.datachainConf);
data.put("nodeCenter", GlobalConf.getNodeCenterUrl()); data.put("nodeCenter", GlobalConf.getNodeCenterUrl());
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) + "");
@ -146,7 +150,8 @@ public class ManagerActions {
data.put("doipConfig", JsonUtil.toJson(GlobalConf.instance.doaConf)); data.put("doipConfig", JsonUtil.toJson(GlobalConf.instance.doaConf));
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", String.valueOf(NetworkManager.instance.isConnectedToNodeCenter())); data.put("clusterConnected",
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()); data.put("nodeCenterWS", GlobalConf.getNodeCenterWSUrl());
@ -157,14 +162,16 @@ 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, GlobalConf.resetNodeCenter(val)); ReplyUtil.replyWithStatus(resultCallback, "onChangeNodeCenter", true,
GlobalConf.resetNodeCenter(val));
} }
@Action(userPermission = 1 << 10) @Action(userPermission = 1 << 10)
public void changeNodeCenterWS(JsonObject args, ResultCallback resultCallback) { public void changeNodeCenterWS(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, GlobalConf.resetNodeCenterWS(val)); ReplyUtil.replyWithStatus(resultCallback, "onChangeNodeCenter", true,
GlobalConf.resetNodeCenterWS(val));
} }
@ -173,37 +180,43 @@ public class ManagerActions {
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, GlobalConf.resetDataChain(lines)); ReplyUtil.replyWithStatus(resultCallback, "onChangeBDledger", true,
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, GlobalConf.resetNodeName(val)); ReplyUtil.replyWithStatus(resultCallback, "onChangeNodeName", true,
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, GlobalConf.resetIpPort(val)); ReplyUtil.replyWithStatus(resultCallback, "onChangeIpPort", true,
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, GlobalConf.resetDOAConfig(val)); ReplyUtil.replyWithStatus(resultCallback, "onChangeDOIPConfig", true,
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, GlobalConf.resetYjsPath(val)); ReplyUtil.replyWithStatus(resultCallback, "onChangeYJSPath", true,
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, GlobalConf.resetLicence(val)); ReplyUtil.replyWithStatus(resultCallback, "onUploadLicence", true,
GlobalConf.resetLicence(val));
} }
@Action(userPermission = 1 << 11) @Action(userPermission = 1 << 11)
@ -215,9 +228,11 @@ 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")) pubKey = json.get("verifiedPubKey").getAsString(); if (json.has("verifiedPubKey"))
pubKey = json.get("verifiedPubKey").getAsString();
if (pubKey == null) { if (pubKey == null) {
resultCallback.onResult("{\"action\":\"onApplyNodeRole\",\"data\":\"Failed: Illegal user\"}"); resultCallback.onResult(
"{\"action\":\"onApplyNodeRole\",\"data\":\"Failed: Illegal user\"}");
return; return;
} }
String ro = json.get("role").getAsString(); String ro = json.get("role").getAsString();
@ -225,21 +240,26 @@ public class ManagerActions {
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) {
String str = KeyValueDBUtil.instance.getValue(CMTables.ApplyRole.toString(), pubKey); String str =
String already = KeyValueDBUtil.instance.getValue(CMTables.NodeRole.toString(), pubKey); KeyValueDBUtil.instance.getValue(CMTables.ApplyRole.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())) {
ReplyUtil.simpleReply(resultCallback, "onApplyNodeRole", "already has!"); ReplyUtil.simpleReply(resultCallback, "onApplyNodeRole", "already has!");
return; return;
} }
if (str == null || str.length() == 0) { if (str == null || str.length() == 0) {
KeyValueDBUtil.instance.setValue(CMTables.ApplyRole.toString(), pubKey, role.name()); KeyValueDBUtil.instance.setValue(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, str + "," + role.name()); KeyValueDBUtil.instance.setValue(CMTables.ApplyRole.toString(), pubKey,
str + "," + role.name());
} }
KeyValueDBUtil.instance.setValue(CMTables.ApplyTime.toString(), pubKey, Long.toString(new Date().getTime())); KeyValueDBUtil.instance.setValue(CMTables.ApplyTime.toString(), pubKey,
Long.toString(new Date().getTime()));
ReplyUtil.simpleReply(resultCallback, "onApplyNodeRole", "success"); ReplyUtil.simpleReply(resultCallback, "onApplyNodeRole", "success");
return; return;
@ -253,7 +273,8 @@ public class ManagerActions {
} catch (Exception e) { } catch (Exception e) {
e.printStackTrace(); e.printStackTrace();
resultCallback.onResult("{\"action\":\"onApplyNodeRole\",\"data\":\"Failed: Exception happened\"}"); resultCallback.onResult(
"{\"action\":\"onApplyNodeRole\",\"data\":\"Failed: Exception happened\"}");
} }
} }
} }

View File

@ -13,7 +13,6 @@ 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;
@ -105,7 +104,8 @@ 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")); 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 =
@ -132,7 +132,8 @@ public class MasterWSAction {
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 + "/" + args.get("verifiedPubKey").getAsString(); parPath = GlobalConf.instance.privateCompiledDir + "/"
+ args.get("verifiedPubKey").getAsString();
} }
String scriptOrPath = contract.getScriptStr(); String scriptOrPath = contract.getScriptStr();
@ -140,7 +141,8 @@ public class MasterWSAction {
scriptOrPath = parPath + contract.getScriptStr(); scriptOrPath = parPath + contract.getScriptStr();
} }
String key = ContractManager.getContractMd5(scriptOrPath, contract); String key = ContractManager.getContractMd5(scriptOrPath, contract);
String privateKeyStr = KeyValueDBUtil.instance.getValue(CMTables.ContractInfo.toString(), key); String privateKeyStr =
KeyValueDBUtil.instance.getValue(CMTables.ContractInfo.toString(), key);
if (privateKeyStr == null || privateKeyStr.length() == 0) { if (privateKeyStr == null || privateKeyStr.length() == 0) {
privateKeyStr = SM2Util.generateSM2KeyPair().toJson(); privateKeyStr = SM2Util.generateSM2KeyPair().toJson();
KeyValueDBUtil.instance.setValue(CMTables.ContractInfo.toString(), key, privateKeyStr); KeyValueDBUtil.instance.setValue(CMTables.ContractInfo.toString(), key, privateKeyStr);
@ -155,45 +157,37 @@ public class MasterWSAction {
// contract.setNodeCenterRepoDOI(DOIPMainServer4NC.repoIdentifier); // contract.setNodeCenterRepoDOI(DOIPMainServer4NC.repoIdentifier);
// 多点合约部署时由NC预先注册一个DOI以备使用 // 多点合约部署时由NC预先注册一个DOI以备使用
/* /*
if (DoConfig.openContractDORegister) { * if (DoConfig.openContractDORegister) { try { HandleService hs = new
try { * HandleService(HandleServiceUtils.hrRegister); String tmpDOI =
HandleService hs = new HandleService(HandleServiceUtils.hrRegister); * hs.registerContract(DOIPMainServer4NC.repoIdentifier); if (tmpDOI == "" || tmpDOI ==
String tmpDOI = hs.registerContract(DOIPMainServer4NC.repoIdentifier); * null) contract.setDOI("RegisterFailed"); else contract.setDOI(tmpDOI); } catch (Exception
if (tmpDOI == "" || tmpDOI == null) * e) { e.printStackTrace(); contract.setDOI("RegisterFailed"); } }
contract.setDOI("RegisterFailed");
else
contract.setDOI(tmpDOI);
}
catch (Exception e) {
e.printStackTrace();
contract.setDOI("RegisterFailed");
}
}
*/ */
List<String> nodeNames; // nodes' peerID List<String> nodeNames; // nodes' peerID
// if (contract.getType().equals(ContractExecType.SelfAdaptiveSharding)) { // if (contract.getType().equals(ContractExecType.SelfAdaptiveSharding)) {
// if (ContractManager.instance.nodeCenterConn.listNodes().length < 3) { // if (ContractManager.instance.nodeCenterConn.listNodes().length < 3) {
// rc.onResult( // rc.onResult(
// "{\"status\":\"Error\",\"result\":\"No enough nodes!\"," // "{\"status\":\"Error\",\"result\":\"No enough nodes!\","
// + "\"action\":\"onStartTrustfulContract\"}"); // + "\"action\":\"onStartTrustfulContract\"}");
// return; // return;
// } // }
// int unitSize = args.get("selectUnitNum").getAsInt(); // int unitSize = args.get("selectUnitNum").getAsInt();
// nodeNames = // nodeNames =
// Arrays.asList(ContractManager.instance.nodeCenterConn.getClusterByKey( // Arrays.asList(ContractManager.instance.nodeCenterConn.getClusterByKey(
// contractID, // contractID,
// Math.max(unitSize, 3))); // Math.max(unitSize, 3)));
// } else { // } 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()).collect(Collectors.toList()); nodeNames = Arrays.stream(nodeNamesStr).filter(x -> null != x && !x.isEmpty())
// } .collect(Collectors.toList());
// }
SM2KeyPair keyPair = GlobalConf.instance.keyPair; SM2KeyPair keyPair = GlobalConf.instance.keyPair;
String masterNode = keyPair.getPublicKeyStr(); String masterNode = keyPair.getPublicKeyStr();
assert nodeNames.contains(masterNode); 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<>();
@ -205,7 +199,7 @@ public class MasterWSAction {
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));
final long curr = System.currentTimeMillis(); final long curr = System.currentTimeMillis();
String requestID = curr + "_" + (int) (Math.random() * 10000); String requestID = curr + "_" + (int) (Math.random() * 10000);
@ -270,14 +264,17 @@ 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, RecoverFlag.Fine); MasterServerRecoverMechAction.recoverStatus.get(nodeID).put(contractID,
RecoverFlag.Fine);
} }
rc.onResult("{\"status\":\"Success\",\"result\":\"" + contract.getID() + "\"," + "\"action\":\"onStartTrustfulContract\"}"); rc.onResult("{\"status\":\"Success\",\"result\":\"" + contract.getID() + "\","
+ "\"action\":\"onStartTrustfulContract\"}");
LOGGER.info("startContractMultiPoint succeed!"); LOGGER.info("startContractMultiPoint succeed!");
} }
public String getPubKey(JsonObject jo) { public String getPubKey(JsonObject jo) {
if (handler != null) return handler.getPubKey(); if (handler != null)
return handler.getPubKey();
return jo.get("pubKey").getAsString(); return jo.get("pubKey").getAsString();
} }
} }

View File

@ -18,13 +18,14 @@ 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 = new ConcurrentHashMap<String, MultiRequestInfo>(); //key为requestID public static Map<String, MultiRequestInfo> reqInfos =
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;
@ -32,33 +33,38 @@ 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=" + Thread.currentThread().getId() + " ---1"); // logger.info("【exeMultiReqInternal】 uniID=" + uniID + " Thread-id=" +
// Thread.currentThread().getId() + " ---1");
//TODO 2个线程都卡在这 // TODO 2个线程都卡在这
long start = System.currentTimeMillis(); long start = System.currentTimeMillis();
//logger.info("【exeMultiReqInternal】 uniID=" + uniID + " Thread-id=" + Thread.currentThread().getId() + " ---2"); // logger.info("【exeMultiReqInternal】 uniID=" + uniID + " Thread-id=" +
// Thread.currentThread().getId() + " ---2");
MultiContractMeta cei = CMActions.manager.multiContractRecorder.getMultiContractMeta(request.getContractID()); MultiContractMeta cei = CMActions.manager.multiContractRecorder
//logger.info("【exeMultiReqInternal】 uniID=" + uniID + " Thread-id=" + Thread.currentThread().getId() + " ---3 " + (reqInfos.containsKey(request.getRequestID()))); .getMultiContractMeta(request.getContractID());
// 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=" + Thread.currentThread().getId() + " ---4"); // logger.info("【exeMultiReqInternal】 uniID=" + uniID + " Thread-id=" +
// Thread.currentThread().getId() + " ---4");
synchronized (mri.flag) { synchronized (mri.flag) {
//logger.info("【exeMultiReqInternal】 uniID=" + uniID + " Thread-id=" + Thread.currentThread().getId() + " ---5"); // logger.info("【exeMultiReqInternal】 uniID=" + uniID + " Thread-id=" +
// 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);
@ -66,7 +72,8 @@ public class MultiRequestInfo {
} }
if (mri.flag.get(uniID)) { if (mri.flag.get(uniID)) {
//logger.info("uniID=" + uniID + " 已执行过 " + " Thread-id=" + Thread.currentThread().getId()); // logger.info("uniID=" + uniID + " 已执行过 " + " Thread-id=" +
// Thread.currentThread().getId());
return; return;
} else { } else {
mri.flag.put(uniID, true); mri.flag.put(uniID, true);
@ -75,7 +82,8 @@ 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 执行请求 " + request.seq + " uniID=" + uniID + " Thread-id=" + Thread.currentThread().getId()); // logger.info("调试位置 3 cei.curExeSeq=" + cei.curExeSeq + " MultiRequestInfo 执行请求 " +
// request.seq + " uniID=" + uniID + " Thread-id=" + Thread.currentThread().getId());
CMActions.manager.executeLocallyAsync(request, new ResultCallback() { CMActions.manager.executeLocallyAsync(request, new ResultCallback() {
@Override @Override
public void onResult(String str) { public void onResult(String str) {
@ -89,7 +97,7 @@ public class MultiRequestInfo {
ret.put("executeTime", (System.currentTimeMillis() - start) + ""); ret.put("executeTime", (System.currentTimeMillis() - start) + "");
ret.put("data", str); ret.put("data", str);
mri.countIncrease(); mri.countIncrease();
//logger.info("返回 uniID=" + uniID + " 的结果"); // logger.info("返回 uniID=" + uniID + " 的结果");
mri.callbackMap.get(uniID).onResult(JsonUtil.toJson(ret)); mri.callbackMap.get(uniID).onResult(JsonUtil.toJson(ret));
} }
}, null); }, null);
@ -97,7 +105,7 @@ public class MultiRequestInfo {
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,7 +76,8 @@ 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")) continue; if (!line.contains("yjs.jar") || !line.contains("java"))
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,8 +23,7 @@ public class ReadmeGenerator {
private String generateReadme() { private String generateReadme() {
VelocityEngine engine = new VelocityEngine(); VelocityEngine engine = new VelocityEngine();
engine.setProperty( engine.setProperty("file.resource.loader.path",
"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();
@ -32,18 +31,17 @@ public class ReadmeGenerator {
readmeFuncs = new ArrayList<>(); readmeFuncs = new ArrayList<>();
} }
for (ReadmeFunction rm : readmeFuncs) { for (ReadmeFunction rm : readmeFuncs) {
/*if (rm.funcDefaultArg == null) { /*
rm.funcDefaultArg = "未提供默认参数"; * if (rm.funcDefaultArg == null) { rm.funcDefaultArg = "未提供默认参数"; } if
} * (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) { /*
rm.funcMockTemplate = "{\"result\":\"emptyMock\"}"; * if (rm.funcMockTemplate == null) { rm.funcMockTemplate =
}*/ * "{\"result\":\"emptyMock\"}"; }
*/
if (rm.funcArgTemplate == null) { if (rm.funcArgTemplate == null) {
rm.funcArgTemplate = "暂无参数模板"; rm.funcArgTemplate = "暂无参数模板";
} }
@ -76,63 +74,24 @@ 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( FileUtils.writeStringToFile(content,
content, /*
/*"# 简介\n" * "# 简介\n" + "\n" + "${contractDesp}\n" + "\n" + "#set($hash='#')\n" +
+ "\n" * "# 获取数据相关方法说明\n" + "#foreach($func in ${readmeFuncs})\n" + "\n" +
+ "${contractDesp}\n" * "$hash$hash ${func.funcName}\n" + "\n" + ">$func.funcDescription\n" +
+ "\n" * "\n" + "$hash$hash$hash 参数示例\n" + "```json\n" + "$func.funcDefaultArg\n"
+ "#set($hash='#')\n" * + "```\n" + "\n" + "$hash$hash$hash 数据模板\n" + "```json\n" +
+ "# 获取数据相关方法说明\n" * "$func.funcMockTemplate\n" + "```\n" + "\n" + "$hash$hash$hash 返回结果\n" +
+ "#foreach($func in ${readmeFuncs})\n" * "\n" + "```json\n" + "$func.funcDefaultResult\n" + "```\n" + "\n" +
+ "\n" * "#end\n" + "\n",
+ "$hash$hash ${func.funcName}\n" */
+ "\n" "# 简介\n" + "\n" + "${contractDesp}\n" + "\n" + "#set($hash='#')\n"
+ ">$func.funcDescription\n" + "# 获取数据相关方法说明\n" + "#foreach($func in ${readmeFuncs})\n" + "\n"
+ "\n" + "$hash$hash${func.funcName}\n" + "\n" + ">$func.funcDescription\n"
+ "$hash$hash$hash 参数示例\n" + "\n" + "$hash$hash$hash 参数模板\n" + "```json\n"
+ "```json\n" + "$func.funcDefaultArg\n" + "```\n" + "\n"
+ "$func.funcDefaultArg\n" + "$hash$hash$hash 调用结果\n" + "\n" + "```json\n"
+ "```\n" + "$func.funcRecordsString\n" + "```\n" + "\n" + "#end\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();
@ -149,7 +108,8 @@ 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 return "请删除已有README.md"; } else
return "请删除已有README.md";
} catch (Exception e) { } catch (Exception e) {
e.printStackTrace(); e.printStackTrace();
return "生成文档异常"; return "生成文档异常";
@ -170,19 +130,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( public ReadmeFunction(String name, String description, String argSchema, String argTemplate,
String name, String description, String argSchema, String argTemplate, String resultSchema, String recordsString) { 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;
@ -205,9 +165,9 @@ public class ReadmeGenerator {
return funcDefaultResult.replace("\\\"", "\""); return funcDefaultResult.replace("\\\"", "\"");
} }
/*public String getFuncMockTemplate() { /*
return funcMockTemplate; * public String getFuncMockTemplate() { return funcMockTemplate; }
}*/ */
public String getFuncArgTemplate() { public String getFuncArgTemplate() {
return funcArgTemplate; return funcArgTemplate;

View File

@ -1,11 +1,12 @@
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

@ -84,12 +84,9 @@ 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 privateDir = new File(GlobalConf.instance.privateDir);
File[] list = File[] list = privateDir.listFiles(new FileFilter() {
privateDir.listFiles(
new FileFilter() {
@Override @Override
public boolean accept(File pathname) { public boolean accept(File pathname) {
return pathname.isDirectory(); return pathname.isDirectory();
@ -189,8 +186,8 @@ public class TemporyTestAction {
reconnectVisitor.visit(host, args.get("port").getAsInt()); reconnectVisitor.visit(host, args.get("port").getAsInt());
else else
reconnectVisitor.visit(args.get("port").getAsInt()); reconnectVisitor.visit(args.get("port").getAsInt());
String data = ContractManager.instance.listContractsWithOwner( String data = ContractManager.instance
args.get("owner").getAsString(), null, 0); .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,11 +21,8 @@ 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 = static final Counter counter = Counter.build().name("contract_login_counter")
Counter.build() .help("contract login counter").register();
.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<>();
@ -50,18 +47,22 @@ public class UserManagerAction {
if (str.contains("NodeManager")) { if (str.contains("NodeManager")) {
if (json.has("newPubKey")) { if (json.has("newPubKey")) {
String newPubKey = json.get("newPubKey").getAsString(); String newPubKey = json.get("newPubKey").getAsString();
KeyValueDBUtil.instance.setValue(CMTables.ConfigDB.toString(), NodeManager, newPubKey); KeyValueDBUtil.instance.setValue(CMTables.ConfigDB.toString(), NodeManager,
KeyValueDBUtil.instance.setValue( newPubKey);
CMTables.NodeRole.toString(), newPubKey, "NodeManager"); KeyValueDBUtil.instance.setValue(CMTables.NodeRole.toString(), newPubKey,
resultCallback.onResult("{\"action\":\"onResetNodeManager\",\"data\":\"success\",\"pubKey\":\"" "NodeManager");
resultCallback.onResult(
"{\"action\":\"onResetNodeManager\",\"data\":\"success\",\"pubKey\":\""
+ newPubKey + "\"}"); + newPubKey + "\"}");
} else { } else {
//just keep the same // just keep the same
resultCallback.onResult("{\"action\":\"onResetNodeManager\",\"data\":\"success\",\"pubKey\":\"" resultCallback.onResult(
"{\"action\":\"onResetNodeManager\",\"data\":\"success\",\"pubKey\":\""
+ getPubKey(json) + "\"}"); + getPubKey(json) + "\"}");
} }
} else { } else {
resultCallback.onResult("{\"action\":\"onResetNodeManager\",\"data\":\"failed, no permission\"}"); resultCallback.onResult(
"{\"action\":\"onResetNodeManager\",\"data\":\"failed, no permission\"}");
} }
} }
@ -77,8 +78,8 @@ 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();
@ -95,15 +96,15 @@ public class UserManagerAction {
} else { } else {
setHandlerPermission(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) { private void setHandlerPermission(long i) {
if (handler != null) handler.setPermission(i); if (handler != null)
handler.setPermission(i);
} }
public void getNodeRole(JsonObject json, ResultCallback resultCallback) { public void getNodeRole(JsonObject json, ResultCallback resultCallback) {
@ -122,12 +123,12 @@ public class UserManagerAction {
if (isNodeManager) { if (isNodeManager) {
if (ret != null && ret.length() > 0) { if (ret != null && ret.length() > 0) {
setHandlerPermission(0x86000f41L | Role.compoundValue(ret.split(","))); setHandlerPermission(0x86000f41L | Role.compoundValue(ret.split(",")));
resultCallback.onResult( resultCallback
"{\"action\":\"onLogin\",\"data\":\"" + ret + "\"}"); .onResult("{\"action\":\"onLogin\",\"data\":\"" + ret + "\"}");
} else { } else {
setHandlerPermission(0x86000f41L); setHandlerPermission(0x86000f41L);
resultCallback.onResult( resultCallback
"{\"action\":\"onLogin\",\"data\":\"NodeManager\"}"); .onResult("{\"action\":\"onLogin\",\"data\":\"NodeManager\"}");
} }
} else { } else {
if (ret == null || ret.equals("")) { if (ret == null || ret.equals("")) {
@ -140,10 +141,10 @@ public class UserManagerAction {
} }
} else { } else {
KeyValueDBUtil.instance.setValue(CMTables.ConfigDB.toString(), NodeManager, pubKey); KeyValueDBUtil.instance.setValue(CMTables.ConfigDB.toString(), NodeManager, pubKey);
KeyValueDBUtil.instance.setValue( KeyValueDBUtil.instance.setValue(CMTables.NodeRole.toString(), pubKey,
CMTables.NodeRole.toString(), pubKey, "NodeManager"); "NodeManager");
KeyValueDBUtil.instance.setValue( KeyValueDBUtil.instance.setValue(CMTables.NodeTime.toString(), pubKey,
CMTables.NodeTime.toString(), pubKey, Long.toString(new Date().getTime())); Long.toString(new Date().getTime()));
setHandlerPermission(0x86000d41L); setHandlerPermission(0x86000d41L);
resultCallback.onResult("{\"action\":\"onLogin\",\"data\":\"NodeManager\"}"); resultCallback.onResult("{\"action\":\"onLogin\",\"data\":\"NodeManager\"}");
} }
@ -186,11 +187,11 @@ public class UserManagerAction {
} else { } else {
if (!str.contains(role.name())) if (!str.contains(role.name()))
KeyValueDBUtil.instance.setValue( KeyValueDBUtil.instance.setValue(CMTables.ApplyRole.toString(), pubKey,
CMTables.ApplyRole.toString(), pubKey, str + "," + role.name()); str + "," + role.name());
} }
KeyValueDBUtil.instance.setValue( KeyValueDBUtil.instance.setValue(CMTables.ApplyTime.toString(), pubKey,
CMTables.ApplyTime.toString(), pubKey, Long.toString(new Date().getTime())); Long.toString(new Date().getTime()));
resultCallback.onResult("{\"action\":\"onApplyRole\",\"data\":\"success\"}"); resultCallback.onResult("{\"action\":\"onApplyRole\",\"data\":\"success\"}");
} }
@ -270,8 +271,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( KeyValueDBUtil.instance.setValue(CMTables.NodeRole.toString(), pubKey,
CMTables.NodeRole.toString(), pubKey, roString.toString()); 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);
@ -312,8 +313,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( KeyValueDBUtil.instance.setValue(CMTables.NodeTime.toString(), pubKey,
CMTables.NodeTime.toString(), pubKey, Long.toString(new Date().getTime())); 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\"}");
@ -336,7 +337,8 @@ public class UserManagerAction {
private String getPubKey(JsonObject json) { private String getPubKey(JsonObject json) {
try { try {
if (this.publicKey != null) return this.publicKey; if (this.publicKey != null)
return this.publicKey;
return json.get("pubKey").getAsString(); return json.get("pubKey").getAsString();
} catch (Exception e) { } catch (Exception e) {
return null; return null;

View File

@ -57,16 +57,12 @@ public class AliveCheckClientAction {
public void checkMasterAlive(ResultCallback rc) { public void checkMasterAlive(ResultCallback rc) {
if (sendPingTask == null) if (sendPingTask == null)
sendPingTask = sendPingTask = new TimerTask() {
new TimerTask() {
@Override @Override
public void run() { public void run() {
try { try {
LOGGER.debug( LOGGER.debug(String.format("f %s",
String.format( DATE_FORMAT.format(System.currentTimeMillis())));
"f %s",
DATE_FORMAT
.format(System.currentTimeMillis())));
Map<String, String> ping = new HashMap<>(); Map<String, String> ping = new HashMap<>();
ping.put("action", "masterPing"); ping.put("action", "masterPing");
rc.onResult(JsonUtil.toJson(ping)); rc.onResult(JsonUtil.toJson(ping));
@ -76,8 +72,7 @@ public class AliveCheckClientAction {
} }
}; };
if (null == checkAliveTask) if (null == checkAliveTask)
checkAliveTask = checkAliveTask = new TimerTask() {
new TimerTask() {
@Override @Override
public void run() { public void run() {
try { try {
@ -91,10 +86,8 @@ public class AliveCheckClientAction {
public void run1() { public void run1() {
long cur = System.currentTimeMillis(); long cur = System.currentTimeMillis();
if (cur - lastMasterPongTime >= (2 * sendDelay)) { if (cur - lastMasterPongTime >= (2 * sendDelay)) {
LOGGER.info( LOGGER.info("master maybe crash down, because lastMasterPongTime="
"master maybe crash down, because lastMasterPongTime=" + DATE_FORMAT.format(lastMasterPongTime) + "!");
+ DATE_FORMAT.format(lastMasterPongTime)
+ "!");
// 向NC发通知重新选举master如果NC没有收到所有节点的重选请求就认为是这个节点和master连接断开 // 向NC发通知重新选举master如果NC没有收到所有节点的重选请求就认为是这个节点和master连接断开
// 这个节点需要重连master // 这个节点需要重连master
@ -102,20 +95,17 @@ public class AliveCheckClientAction {
request.put("action", "electMaster"); request.put("action", "electMaster");
SM2KeyPair keyPair = GlobalConf.instance.keyPair; SM2KeyPair keyPair = GlobalConf.instance.keyPair;
request.put("nodeID", keyPair.getPublicKeyStr()); request.put("nodeID", keyPair.getPublicKeyStr());
for (MultiContractMeta meta : CMActions.manager.multiContractRecorder.getStatus().values()) { for (MultiContractMeta meta : CMActions.manager.multiContractRecorder
.getStatus().values()) {
if (meta.getMasterNode().equals(masterPubkey)) { if (meta.getMasterNode().equals(masterPubkey)) {
LOGGER.info( LOGGER.info("master of contract " + meta.getContractID()
"master of contract " + " maybe crash down! master=" + masterPubkey);
+ meta.getContractID()
+ " maybe crash down! master="
+ masterPubkey);
request.put("contractID", meta.getContractID()); request.put("contractID", meta.getContractID());
int lastSeq = meta.getLastExeSeq(); int lastSeq = meta.getLastExeSeq();
request.put("lastExe", lastSeq + ""); request.put("lastExe", lastSeq + "");
request.put("master", masterPubkey); request.put("master", masterPubkey);
request.put("members", meta.joinMembers(",")); request.put("members", meta.joinMembers(","));
NetworkManager.instance.sendToNodeCenter( NetworkManager.instance.sendToNodeCenter(JsonUtil.toJson(request));
JsonUtil.toJson(request));
MasterElectTimeRecorder.findMasterCrash = MasterElectTimeRecorder.findMasterCrash =
System.currentTimeMillis(); System.currentTimeMillis();
} }
@ -125,8 +115,7 @@ public class AliveCheckClientAction {
} }
}; };
lastMasterPongTime = System.currentTimeMillis(); lastMasterPongTime = System.currentTimeMillis();
LOGGER.info( LOGGER.info("lastMasterPongTime=" + DATE_FORMAT.format(lastMasterPongTime));
"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);
} }
@ -138,7 +127,8 @@ 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) return; if (waitForSetNode)
return;
try { try {
Thread.sleep(30); Thread.sleep(30);
} catch (InterruptedException e) { } catch (InterruptedException e) {
@ -150,9 +140,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, "{\"action\":\"setNodeInfo\",\"pubKey\":\"" NetworkManager.instance.sendToAgent(masterPubkey,
+ GlobalConf.instance.keyPair.getPublicKeyStr() "{\"action\":\"setNodeInfo\",\"pubKey\":\""
+ "\"}"); + GlobalConf.instance.keyPair.getPublicKeyStr() + "\"}");
} }
} }

View File

@ -22,17 +22,11 @@ public class AliveCheckServerAction {
public String pubKey; public String pubKey;
public AliveCheckServerAction(TCPServerFrameHandler handler) { public AliveCheckServerAction(TCPServerFrameHandler handler) {
lastSlavePingTime = lastSlavePingTime = System.currentTimeMillis() + 5000L + AliveCheckClientAction.sendDelay
System.currentTimeMillis()
+ 5000L
+ AliveCheckClientAction.sendDelay
+ AliveCheckClientAction.checkDelay; + AliveCheckClientAction.checkDelay;
checkAliveTask = new HeartBeatTask(AliveCheckClientAction.sendDelay); checkAliveTask = new HeartBeatTask(AliveCheckClientAction.sendDelay);
HeartBeatUtil.getInstance() HeartBeatUtil.getInstance().schedule(checkAliveTask, AliveCheckClientAction.sendDelay,
.schedule(
checkAliveTask,
AliveCheckClientAction.sendDelay,
AliveCheckClientAction.checkDelay); AliveCheckClientAction.checkDelay);
this.handler = handler; this.handler = handler;
} }
@ -56,10 +50,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) {
@ -67,21 +61,17 @@ public class AliveCheckServerAction {
HeartBeatUtil.getInstance().cancel(this); HeartBeatUtil.getInstance().cancel(this);
return; return;
} }
LOGGER.info( LOGGER.info("Master心跳机制发现节点 " + nodeID.substring(0, 5) + " 下线! "
"Master心跳机制发现节点 "
+ nodeID.substring(0, 5)
+ " 下线! "
+ this.toString()); + this.toString());
HeartBeatUtil.getInstance().cancel(this); HeartBeatUtil.getInstance().cancel(this);
for (String contractID : for (String contractID : MasterServerRecoverMechAction.recoverStatus.get(nodeID)
MasterServerRecoverMechAction.recoverStatus.get(nodeID).keySet()) { .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 MasterServerRecoverMechAction.recoverStatus.get(nodeID).put(contractID,
.get(nodeID) RecoverFlag.ToRecover);
.put(contractID, RecoverFlag.ToRecover);
contracts.add(contractID); contracts.add(contractID);
MasterServerTCPAction.notifyNodeOffline(contractID, nodeID); MasterServerTCPAction.notifyNodeOffline(contractID, nodeID);
} }

View File

@ -14,8 +14,7 @@ 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) {
@ -26,13 +25,14 @@ 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 = CommunicationManager.instance.requestCallbacks.remove(requestID); ResultCallback resultCallback =
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

@ -34,26 +34,24 @@ 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 = public static Set<String> recoverSet = new ConcurrentSkipListSet<>(); // contracts which don't
new ConcurrentSkipListSet<>(); // contracts which don't finish recoverRestart // finish recoverRestart
public static Map<String, Queue<RequestToMaster>> public static Map<String, Queue<RequestToMaster>> requestsToMaster; // when master is
requestsToMaster; // when master is re-electing,client node cache ites received requests // re-electing,client node
// 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( LOGGER.info("[MasterClientRecoverMechAction] askForRecover contractID=" + contractID
"[MasterClientRecoverMechAction] askForRecover contractID=" + " masterID=" + masterID.substring(0, 5));
+ 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>();
@ -61,27 +59,22 @@ 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); * KeyValueDBUtil.instance.delete(CMTables.LastExeSeq.toString(),contractID); } }else{
} * ContractClient client = CMActions.manager.getClient(contractID); ContractExecuteInfo cei
}else{ * = MasterClientTCPAction.requests.get(contractID); if (client == null ||
ContractClient client = CMActions.manager.getClient(contractID); * !client.getContractType().equals(cei.type)){
ContractExecuteInfo cei = MasterClientTCPAction.requests.get(contractID); * if(KeyValueDBUtil.instance.containsKey(CMTables.LastExeSeq.toString(),contractID)){
if (client == null || !client.getContractType().equals(cei.type)){ * logger.info("[MasterClientRecoverMechAction] delete database lastExeSeq");
if(KeyValueDBUtil.instance.containsKey(CMTables.LastExeSeq.toString(),contractID)){ * KeyValueDBUtil.instance.delete(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( ret.put("lastExeSeq",
"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());
@ -98,19 +91,16 @@ 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 ( synchronized (cei =
cei = CMActions.manager.multiContractRecorder.getMultiContractMeta(contractID)) { CMActions.manager.multiContractRecorder.getMultiContractMeta(contractID)) {
KeyValueDBUtil.instance.setValue( KeyValueDBUtil.instance.setValue(CMTables.LastExeSeq.toString(), contractID,
CMTables.LastExeSeq.toString(), contractID, cei.getLastExeSeq() + ""); 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 = String fileName = "ContractExecuteInfo_" + format.format(new Date()) + "_"
"ContractExecuteInfo_"
+ format.format(new Date())
+ "_"
+ new Random().nextInt(); + 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);
@ -135,7 +125,8 @@ 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()) parent.mkdirs(); if (!parent.exists())
parent.mkdirs();
ObjectOutputStream writer; ObjectOutputStream writer;
try { try {
FileOutputStream fileout = new FileOutputStream(file); FileOutputStream fileout = new FileOutputStream(file);
@ -170,7 +161,8 @@ public class MasterClientRecoverMechAction {
} catch (FileNotFoundException e) { } catch (FileNotFoundException e) {
e.printStackTrace(); e.printStackTrace();
} }
} else fout = (FileOutputStream) stateFileMap.get(fileName); } else
fout = (FileOutputStream) stateFileMap.get(fileName);
String data = args.get("data").getAsString(); String data = args.get("data").getAsString();
try { try {
@ -252,9 +244,8 @@ public class MasterClientRecoverMechAction {
} }
// cei.printContent(); // cei.printContent();
if (cei.queue == null) { if (cei.queue == null) {
cei.init( cei.init(CMActions.manager.multiContractRecorder
CMActions.manager.multiContractRecorder.getMultiContractMeta( .getMultiContractMeta(cei.getContractID()));
cei.getContractID()));
} }
recoverSet.add(cei.getContractID()); recoverSet.add(cei.getContractID());
@ -298,12 +289,9 @@ public class MasterClientRecoverMechAction {
try { try {
LOGGER.info(" 开始等待 checkAndRestart锁 : "); LOGGER.info(" 开始等待 checkAndRestart锁 : ");
time1 = System.currentTimeMillis(); time1 = System.currentTimeMillis();
LOGGER.info( LOGGER.info("time1="
"time1=" + new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(new Date(time1))
+ new SimpleDateFormat("yyyy-MM-dd HH:mm:ss") + " " + time1);
.format(new Date(time1))
+ " "
+ time1);
ContractManager.checkAndStartLock.wait(10000); ContractManager.checkAndStartLock.wait(10000);
} catch (InterruptedException e) { } catch (InterruptedException e) {
e.printStackTrace(); e.printStackTrace();
@ -312,10 +300,8 @@ public class MasterClientRecoverMechAction {
long time2 = System.currentTimeMillis(); long time2 = System.currentTimeMillis();
LOGGER.info( LOGGER.info(
"time2=" "time2=" + new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(new Date(time2))
+ new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(new Date(time2)) + " " + time2);
+ " "
+ time2);
LOGGER.info("等待 checkAndRestart锁 结束 "); LOGGER.info("等待 checkAndRestart锁 结束 ");
if (time2 - time1 >= 10000) { if (time2 - time1 >= 10000) {
LOGGER.info("[ADSP]CheckAndStart 锁 等待超时"); LOGGER.info("[ADSP]CheckAndStart 锁 等待超时");
@ -333,31 +319,27 @@ 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( System.out.println("恢复 checkAndRestart client == null: false"
"恢复 checkAndRestart client == null: false" + " client.getContractType=" + client.getContractType() + "\n");
+ " client.getContractType="
+ client.getContractType()
+ "\n");
} }
ContractMeta meta = CMActions.manager.statusRecorder.getContractMeta(cei.getContractID()); ContractMeta meta = CMActions.manager.statusRecorder.getContractMeta(cei.getContractID());
meta.setContractExecutor( meta.setContractExecutor(MasterClientTCPAction.createContractExecutor(meta.contract,
MasterClientTCPAction.createContractExecutor(meta.contract, contractID, cei.getMasterNode(), cei.getMembers())); contractID, cei.getMasterNode(), cei.getMembers()));
Map<String, Object> args = new HashMap<>(); Map<String, Object> args = new HashMap<>();
args.put("ceiLastExeSeq", cei.getLastExeSeq()); args.put("ceiLastExeSeq", cei.getLastExeSeq());
meta.contractExecutor.onRecover(args); meta.contractExecutor.onRecover(args);
// 认为contractID不会重 // 认为contractID不会重
if (client != null if (client != null && client.isProcessAlive()
&& client.isProcessAlive()
&& client.getContractType().equals(cei.type)) { && client.getContractType().equals(cei.type)) {
LOGGER.info("恢复节点已有这个合约进程!"); LOGGER.info("恢复节点已有这个合约进程!");
if (!KeyValueDBUtil.instance.containsKey( if (!KeyValueDBUtil.instance.containsKey(CMTables.UnitContracts.toString(),
CMTables.UnitContracts.toString(), cei.getContractID())) { cei.getContractID())) {
KeyValueDBUtil.instance.setValue( KeyValueDBUtil.instance.setValue(CMTables.UnitContracts.toString(),
CMTables.UnitContracts.toString(), cei.getContractID(), "exist"); 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] 恢复节点没有这个合约进程 : ");
@ -373,22 +355,18 @@ 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( if (!KeyValueDBUtil.instance.containsKey(CMTables.UnitContracts.toString(),
CMTables.UnitContracts.toString(), cei.getContractID())) { cei.getContractID())) {
KeyValueDBUtil.instance.setValue( KeyValueDBUtil.instance.setValue(CMTables.UnitContracts.toString(),
CMTables.UnitContracts.toString(), cei.getContractID(), "exist"); 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 = parPath = GlobalConf.instance.privateCompiledDir + "/" + cei.getPubKeyPath()
GlobalConf.instance.privateCompiledDir + "/" + cei.getYpkName();
+ "/"
+ cei.getPubKeyPath()
+ "/"
+ cei.getYpkName();
} }
} }
@ -454,7 +432,8 @@ 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()) parent.mkdirs(); if (!parent.exists())
parent.mkdirs();
ObjectOutputStream writer; ObjectOutputStream writer;
try { try {
FileOutputStream fileout = new FileOutputStream(file); FileOutputStream fileout = new FileOutputStream(file);
@ -491,7 +470,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);
@ -534,17 +513,12 @@ 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 = int lastExeSeq = Integer.parseInt(
Integer.parseInt( KeyValueDBUtil.instance.getValue(CMTables.LastExeSeq.toString(), contractID));
KeyValueDBUtil.instance.getValue(
CMTables.LastExeSeq.toString(), contractID));
LOGGER.info("unitLastExeSeq=" + unitLastExeSeq + " lastExeSeq=" + lastExeSeq); LOGGER.info("unitLastExeSeq=" + unitLastExeSeq + " lastExeSeq=" + lastExeSeq);
LOGGER.info( LOGGER.info("从StableMode恢复采用先从本地load的方式 unitLastExeSeq=" + unitLastExeSeq
"从StableMode恢复采用先从本地load的方式 unitLastExeSeq=" + " lastExeDeq=" + lastExeSeq);
+ 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";
@ -600,9 +574,8 @@ public class MasterClientRecoverMechAction {
} }
// record.printContent(); // record.printContent();
if (cei.queue == null) { if (cei.queue == null) {
cei.init( cei.init(CMActions.manager.multiContractRecorder
CMActions.manager.multiContractRecorder.getMultiContractMeta( .getMultiContractMeta(cei.getContractID()));
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);
@ -625,14 +598,8 @@ public class MasterClientRecoverMechAction {
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 = String temp1 = CMActions.manager.loadMemory(client,
CMActions.manager.loadMemory( GlobalConf.instance.ADSPDir + "/" + contractID + "/memory/" + memoryFileName);
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, ""));
@ -640,9 +607,7 @@ 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 = String temp = CMActions.manager.redo(contractID,
CMActions.manager.redo(
contractID,
GlobalConf.instance.ADSPDir + "/" + contractID + "/trans/" + transFileName); GlobalConf.instance.ADSPDir + "/" + contractID + "/trans/" + transFileName);
LOGGER.info("redo from local结果" + temp); LOGGER.info("redo from local结果" + temp);
synchronized (cei) { synchronized (cei) {
@ -708,13 +673,12 @@ 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 jo.addProperty("mode", ContractUnitStatus.CommonMode.toString()); else
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());
@ -729,7 +693,8 @@ 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 cur_mode = ContractUnitStatus.CommonMode; else
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())) {
@ -779,7 +744,8 @@ public class MasterClientRecoverMechAction {
} catch (FileNotFoundException e) { } catch (FileNotFoundException e) {
e.printStackTrace(); e.printStackTrace();
} }
} else fout = (FileOutputStream) transFileMap.get(fileName); } else
fout = (FileOutputStream) transFileMap.get(fileName);
String data = args.get("data").getAsString(); String data = args.get("data").getAsString();
try { try {

View File

@ -49,35 +49,40 @@ 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).getLastExeSeq(); int lastSeq = 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) request.put("uniNumber", uniNumber); if (null != uniNumber)
request.put("uniNumber", uniNumber);
String members = CMActions.manager.multiContractRecorder.getMultiContractMeta(contractID).joinMembers(","); String members = CMActions.manager.multiContractRecorder.getMultiContractMeta(contractID)
.joinMembers(",");
request.put("members", members); request.put("members", members);
NetworkManager.instance.sendToNodeCenter(JsonUtil.toJson(request)); NetworkManager.instance.sendToNodeCenter(JsonUtil.toJson(request));
LOGGER.info("认为合约 " + contractID + " 的master崩溃 当前master为null 向NC发送重选信息"); LOGGER.info("认为合约 " + contractID + " 的master崩溃 当前master为null 向NC发送重选信息");
} }
public static ContractExecutor createContractExecutor(Contract contract, String contractID, String masterPubkey, String[] members) { public static ContractExecutor createContractExecutor(Contract contract, String contractID,
String masterPubkey, String[] members) {
Map<String, Object> args = new HashMap<>(); Map<String, Object> args = new HashMap<>();
args.put("contractID", contractID); args.put("contractID", contractID);
args.put("nodeSize", contract.getNumOfCopies()); args.put("nodeSize", contract.getNumOfCopies());
args.put("masterPubkey", masterPubkey); args.put("masterPubkey", masterPubkey);
args.put("members", members); args.put("members", members);
return ConsistencyPluginManager.getInstance().createContractExecutor(contract.getType().name(), args); return ConsistencyPluginManager.getInstance()
.createContractExecutor(contract.getType().name(), args);
} }
public static void dealRequests(String contractID) { public static void dealRequests(String contractID) {
@ -107,7 +112,8 @@ public class MasterClientTCPAction {
if (isMultiReq) { if (isMultiReq) {
// 开始执行多点合约请求需要将缓存的其他节点发来的同requestID的请求也触发调用 // 开始执行多点合约请求需要将缓存的其他节点发来的同requestID的请求也触发调用
LOGGER.info("开始执行多点合约请求需要将缓存的其他节点发来的同requestID的请求也触发调用"); LOGGER.info("开始执行多点合约请求需要将缓存的其他节点发来的同requestID的请求也触发调用");
MultiRequestInfo mri = MultiRequestInfo.reqInfos.get(request.getRequestID()); MultiRequestInfo mri =
MultiRequestInfo.reqInfos.get(request.getRequestID());
for (String uniID : mri.callbackMap.keySet()) { for (String uniID : mri.callbackMap.keySet()) {
LOGGER.info("触发 uniID=" + uniID); LOGGER.info("触发 uniID=" + uniID);
MultiRequestInfo.exeMultiReq(request, uniID); MultiRequestInfo.exeMultiReq(request, uniID);
@ -134,8 +140,10 @@ 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(), contractID)) { if (KeyValueDBUtil.instance.containsKey(CMTables.LastExeSeq.toString(),
KeyValueDBUtil.instance.setValue(CMTables.LastExeSeq.toString(), contractID, seq + ""); contractID)) {
KeyValueDBUtil.instance.setValue(CMTables.LastExeSeq.toString(), contractID,
seq + "");
} }
// ledger检查点 public static final int LEDGER_PERIOD = 100; //账本检查点 // ledger检查点 public static final int LEDGER_PERIOD = 100; //账本检查点
@ -144,8 +152,10 @@ public class MasterClientTCPAction {
boolean isMaster = CMActions.manager.getContractIsMaster(contractID); boolean isMaster = CMActions.manager.getContractIsMaster(contractID);
if (isMaster) { if (isMaster) {
String lastHash; String lastHash;
if (KeyValueDBUtil.instance.containsKey(CMTables.CheckPointLastHash.toString(), contractID)) { if (KeyValueDBUtil.instance.containsKey(
lastHash = KeyValueDBUtil.instance.getValue(CMTables.CheckPointLastHash.toString(), contractID); CMTables.CheckPointLastHash.toString(), contractID)) {
lastHash = KeyValueDBUtil.instance.getValue(
CMTables.CheckPointLastHash.toString(), contractID);
} else { } else {
lastHash = "firstCheckPoint"; lastHash = "firstCheckPoint";
} }
@ -154,7 +164,8 @@ public class MasterClientTCPAction {
map.put("state", state); map.put("state", state);
map.put("lastHash", lastHash); map.put("lastHash", lastHash);
String data = JsonUtil.toJson(map); String data = JsonUtil.toJson(map);
String requestID = contractID + "_" + "checkPoint_" + new Random().nextInt(); String requestID =
contractID + "_" + "checkPoint_" + new Random().nextInt();
CheckPointCallback cb = new CheckPointCallback(); CheckPointCallback cb = new CheckPointCallback();
ContractManager.checkPointToLedger(cb, contractID, data, requestID); ContractManager.checkPointToLedger(cb, contractID, data, requestID);
} else { } else {
@ -180,7 +191,8 @@ 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, new JsonPrimitive(ComponedContractResult.EXPIRED_REQ)); ContractResult cr = 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));
} }
@ -233,10 +245,12 @@ public class MasterClientTCPAction {
ContractClient cc = CMActions.manager.getClient(id); ContractClient cc = CMActions.manager.getClient(id);
if (KeyValueDBUtil.instance.containsKey(CMTables.LastExeSeq.toString(), cc.getContractID())) { if (KeyValueDBUtil.instance.containsKey(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(), cc.getContractID())) { if (KeyValueDBUtil.instance.containsKey(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());
@ -276,9 +290,10 @@ 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 = CMActions.manager.multiContractRecorder.createIfNotExist(contractID); MultiContractMeta multiContractMeta =
CMActions.manager.multiContractRecorder.createIfNotExist(contractID);
multiContractMeta.setLastExeSeq(-1); multiContractMeta.setLastExeSeq(-1);
if (!contract.getScriptStr().startsWith("/")) { if (!contract.getScriptStr().startsWith("/")) {
contract.setScript(dumpToDisk(contract, jo)); contract.setScript(dumpToDisk(contract, jo));
@ -287,7 +302,7 @@ 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!!! // TODO 第一次来的meta没有cid!!!
synchronized (multiContractMeta) { // 合约执行信息 synchronized (multiContractMeta) { // 合约执行信息
multiContractMeta.setYpkName(pp[pp.length - 1]); multiContractMeta.setYpkName(pp[pp.length - 1]);
multiContractMeta.setMembers(jo.get("members").getAsJsonArray()); multiContractMeta.setMembers(jo.get("members").getAsJsonArray());
@ -295,7 +310,8 @@ public class MasterClientTCPAction {
multiContractMeta.key = contract.getKey(); multiContractMeta.key = contract.getKey();
multiContractMeta.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 + "/" + jo.get("pubKey").getAsString(); parPath = GlobalConf.instance.privateCompiledDir + "/"
+ jo.get("pubKey").getAsString();
multiContractMeta.setIsPrivate(true); multiContractMeta.setIsPrivate(true);
multiContractMeta.setPubKeyPath(jo.get("pubKey").getAsString()); multiContractMeta.setPubKeyPath(jo.get("pubKey").getAsString());
@ -306,7 +322,11 @@ public class MasterClientTCPAction {
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("{\"action\":\"onStartContractTrustfully\",\"result\":\"missing contract files\"," + "\"requestID\":\"%s\",\"pubKey\":\"%s\"}", jo.get("requestID").getAsString(), GlobalConf.instance.keyPair.getPublicKeyStr())); result.onResult(String.format(
"{\"action\":\"onStartContractTrustfully\",\"result\":\"missing contract files\","
+ "\"requestID\":\"%s\",\"pubKey\":\"%s\"}",
jo.get("requestID").getAsString(),
GlobalConf.instance.keyPair.getPublicKeyStr()));
return; return;
} }
contract.setScript(temp.getAbsolutePath()); contract.setScript(temp.getAbsolutePath());
@ -316,7 +336,8 @@ public class MasterClientTCPAction {
// 这个地方判定从参数中的master数据 globalConf中的数据 进行对比如果一致的话说明该节点为master // 这个地方判定从参数中的master数据 globalConf中的数据 进行对比如果一致的话说明该节点为master
multiContractMeta.setMaster(jo.get("master").getAsString()); multiContractMeta.setMaster(jo.get("master").getAsString());
if (contract.getType().needSeq()) if (contract.getType().needSeq())
multiContractMeta.setIsMaster(GlobalConf.getNodeID().equals(jo.get("master").getAsString())); multiContractMeta
.setIsMaster(GlobalConf.getNodeID().equals(jo.get("master").getAsString()));
else { else {
multiContractMeta.setIsMaster(true); multiContractMeta.setIsMaster(true);
} }
@ -324,15 +345,19 @@ public class MasterClientTCPAction {
LOGGER.info("startup arguments: " + JsonUtil.toJson(contract)); LOGGER.info("startup arguments: " + JsonUtil.toJson(contract));
String ret = CMActions.manager.startContract(contract); // 调用CMActions 里的启动合约的方法,启动结果 String ret = CMActions.manager.startContract(contract); // 调用CMActions 里的启动合约的方法,启动结果
LOGGER.info("startup result: " + ret); LOGGER.info("startup result: " + ret);
//IMPORTANT!!!!!!!!!! // IMPORTANT!!!!!!!!!!
// meta should get after manger.startContract, because startContract reInitilized it! // meta should get after manger.startContract, because startContract reInitilized it!
ContractMeta meta = CMActions.manager.statusRecorder.getContractMeta(contractID); ContractMeta meta = CMActions.manager.statusRecorder.getContractMeta(contractID);
//IMPORTANT!!!!!!!!!! // IMPORTANT!!!!!!!!!!
meta.setContractExecutor(createContractExecutor(contract, contractID, jo.get("master").getAsString(), multiContractMeta.getMembers())); // 分配不同的Executor meta.setContractExecutor(createContractExecutor(contract, contractID,
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("{\"action\":\"onStartContractTrustfully\",\"result\":\"success\",\"requestID\":\"" + jo.get("requestID").getAsString() + "\",\"pubKey\":\"" + GlobalConf.instance.keyPair.getPublicKeyStr() + "\"}"); result.onResult(
"{\"action\":\"onStartContractTrustfully\",\"result\":\"success\",\"requestID\":\""
+ jo.get("requestID").getAsString() + "\",\"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<>();
@ -343,23 +368,26 @@ 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) {
String scriptName = String.format("Script_%s", Math.abs(contract.getScriptStr().hashCode())); String scriptName =
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, jo.get("pubKey").getAsString()); File scriptDir = new File(GlobalConf.instance.privateCompiledDir,
jo.get("pubKey").getAsString());
if (!scriptDir.exists()) { if (!scriptDir.exists()) {
scriptDir.mkdirs(); scriptDir.mkdirs();
} }
FileOutputStream fout = new FileOutputStream(new File(scriptDir, scriptName + ".ypk"), false); FileOutputStream fout =
new FileOutputStream(new File(scriptDir, scriptName + ".ypk"), false);
ZipOutputStream zout = new ZipOutputStream(fout); ZipOutputStream zout = new ZipOutputStream(fout);
zout.putNextEntry(new ZipEntry("/manifest.json")); zout.putNextEntry(new ZipEntry("/manifest.json"));
zout.write(("{\"main\":\"" + scriptName + ".yjs\"}").getBytes()); zout.write(("{\"main\":\"" + scriptName + ".yjs\"}").getBytes());
@ -376,7 +404,7 @@ 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")) {
@ -390,10 +418,12 @@ public class MasterClientTCPAction {
@Action(async = true) @Action(async = true)
public void executeContractLocally(JsonObject jo, ResultCallback result) { public void executeContractLocally(JsonObject jo, ResultCallback result) {
final ContractRequest request = JsonUtil.fromJson(jo.get("data").toString(), ContractRequest.class); final ContractRequest request =
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() + " ->reqID:" + request.getRequestID() + " " + jo.get("data").toString()); // LOGGER.info("[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) {
@ -411,7 +441,8 @@ public class MasterClientTCPAction {
result.onResult(JsonUtil.toJson(ret)); result.onResult(JsonUtil.toJson(ret));
} else { // reqeust all response all need seq } else { // reqeust all response all need seq
String contractID = request.getContractID(); String contractID = request.getContractID();
MultiContractMeta cei = CMActions.manager.multiContractRecorder.getMultiContractMeta(contractID); MultiContractMeta cei =
CMActions.manager.multiContractRecorder.getMultiContractMeta(contractID);
boolean putToQueue = false; boolean putToQueue = false;
// 对于多点合约的请求 // 对于多点合约的请求
if (request.getRequestID().endsWith("_mul")) { if (request.getRequestID().endsWith("_mul")) {
@ -423,12 +454,14 @@ public class MasterClientTCPAction {
// cei.curExeSeq + " cei.getLastExeSeq()=" + cei.getLastExeSeq() + " // cei.curExeSeq + " cei.getLastExeSeq()=" + cei.getLastExeSeq() + "
// 非第一个请求"); // 非第一个请求");
MultiRequestInfo mri = MultiRequestInfo.reqInfos.get(request.getRequestID()); MultiRequestInfo mri =
MultiRequestInfo.reqInfos.get(request.getRequestID());
if (request.seq == cei.curExeSeq) { if (request.seq == cei.curExeSeq) {
// 正在执行多点请求时收到多点请求说明这个请求不是第一个到的同requestID的请求s // 正在执行多点请求时收到多点请求说明这个请求不是第一个到的同requestID的请求s
mri.callbackMap.put(jo.get("uniReqID").getAsString(), result); mri.callbackMap.put(jo.get("uniReqID").getAsString(), result);
mri.putFlag(jo.get("uniReqID").getAsString(), false); mri.putFlag(jo.get("uniReqID").getAsString(), false);
} else if (request.seq > cei.curExeSeq && request.seq > cei.getLastExeSeq()) { } else if (request.seq > cei.curExeSeq
&& request.seq > cei.getLastExeSeq()) {
mri.callbackMap.put(jo.get("uniReqID").getAsString(), result); mri.callbackMap.put(jo.get("uniReqID").getAsString(), result);
mri.putFlag(jo.get("uniReqID").getAsString(), false); mri.putFlag(jo.get("uniReqID").getAsString(), false);
} }
@ -436,7 +469,8 @@ public class MasterClientTCPAction {
// 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 = new MultiRequestInfo(request.getRequestID(), request.seq); MultiRequestInfo mri =
new MultiRequestInfo(request.getRequestID(), request.seq);
MultiRequestInfo.reqInfos.put(request.getRequestID(), mri); MultiRequestInfo.reqInfos.put(request.getRequestID(), mri);
cei.addRequestQueue(request, jo.get("uniReqID").getAsString(), result); cei.addRequestQueue(request, jo.get("uniReqID").getAsString(), result);
LOGGER.info("队列中加入请求 " + request.seq); LOGGER.info("队列中加入请求 " + request.seq);
@ -451,7 +485,8 @@ public class MasterClientTCPAction {
} }
} else { } else {
synchronized (cei) { synchronized (cei) {
LOGGER.info("合约" + contractID + " 请求序号为 " + request.seq + " 上一次执行请求序号为 " + cei.getLastExeSeq()); LOGGER.info("合约" + contractID + " 请求序号为 " + request.seq + " 上一次执行请求序号为 "
+ cei.getLastExeSeq());
// cei.printContent(); // cei.printContent();
if (request.seq <= cei.getLastExeSeq()) { if (request.seq <= cei.getLastExeSeq()) {
@ -484,14 +519,17 @@ public class MasterClientTCPAction {
} }
@Action(async = true) @Action(async = true)
public void receiveContractExecutionServer(JsonObject jsonObject, ResultCallback resultCallback) { public void receiveContractExecutionServer(JsonObject jsonObject,
MasterServerTCPAction.sync.wakeUp(jsonObject.get("responseID").getAsString(), jsonObject.get("data").getAsString()); ResultCallback resultCallback) {
MasterServerTCPAction.sync.wakeUp(jsonObject.get("responseID").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 = CMActions.manager.multiContractRecorder.getMultiContractMeta(contractID); MultiContractMeta mcm =
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();
@ -505,55 +543,69 @@ 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(), (resultCallback, result1) -> { MasterServerTCPAction.sync.instrumentWakeUp(jo.get("responseID").getAsString(),
(resultCallback, result1) -> {
resultCallback.cancelTimeOut(); resultCallback.cancelTimeOut();
LOGGER.info("try To reRoute"); LOGGER.info("try To reRoute");
JsonObject cr = result1.get("data").getAsJsonObject(); JsonObject cr = result1.get("data").getAsJsonObject();
if (resultCallback instanceof SyncResult.ContractResultCallback) { if (resultCallback instanceof SyncResult.ContractResultCallback) {
SyncResult.ContractResultCallback cb = (SyncResult.ContractResultCallback) resultCallback; SyncResult.ContractResultCallback cb =
(SyncResult.ContractResultCallback) resultCallback;
if (cb.getReRouteCount() > 0) { if (cb.getReRouteCount() > 0) {
ContractResult contractResult = new ContractResult(ContractResult.Status.Error, new JsonPrimitive("Contract " + cr.get("contractID").getAsString() + "can't be located in router")); ContractResult contractResult =
new ContractResult(ContractResult.Status.Error,
new JsonPrimitive(
"Contract " + cr.get("contractID").getAsString()
+ "can't be located in router"));
resultCallback.onResult(JsonUtil.toJson(contractResult)); resultCallback.onResult(JsonUtil.toJson(contractResult));
return; return;
} else cb.incReRouteCount(); } else
cb.incReRouteCount();
LOGGER.info("inc reRoute:" + cb.getReRouteCount()); LOGGER.info("inc reRoute:" + cb.getReRouteCount());
} }
String pubkey = CMActions.manager.nodeCenterConn.reRouteContract(cr.get("contractID").getAsString()); String pubkey = CMActions.manager.nodeCenterConn
LOGGER.info("ReRoute Result:" + cr.get("contractID").getAsString() + " pubKey:" + pubkey); .reRouteContract(cr.get("contractID").getAsString());
LOGGER.info("ReRoute Result:" + cr.get("contractID").getAsString() + " pubKey:"
+ pubkey);
if (pubkey == null) { if (pubkey == null) {
ContractResult contractResult = new ContractResult(ContractResult.Status.Error, new JsonPrimitive("Contract " + cr.get("contractID").getAsString() + "can't be located in router using reroute")); ContractResult contractResult =
new ContractResult(ContractResult.Status.Error,
new JsonPrimitive("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 = JsonUtil.fromJson(cr, ContractRequest.class);
CMActions.manager.masterStub.executeByOtherNodeAsync(pubkey, contractRequest, resultCallback); CMActions.manager.masterStub.executeByOtherNodeAsync(pubkey, contractRequest,
resultCallback);
}, jo); }, 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,15 +25,14 @@ 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);
} }
@ -48,7 +47,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);
@ -66,7 +65,8 @@ 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 + "/" + csi.ypkName); file = new File(GlobalConf.instance.privateCompiledDir + "/" + csi.pubKeyPath + "/"
+ 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,11 +130,13 @@ 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() + "_" + System.currentTimeMillis(); String path = contractID + "_temp_stateFile_" + new Random().nextLong() + "_"
+ 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()) parent.mkdirs(); if (!parent.exists())
parent.mkdirs();
ObjectOutputStream writer; ObjectOutputStream writer;
try { try {
FileOutputStream fileout = new FileOutputStream(file); FileOutputStream fileout = new FileOutputStream(file);
@ -160,7 +162,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;
@ -175,7 +177,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();
} }
@ -190,16 +192,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

@ -30,8 +30,7 @@ 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) {
@ -46,8 +45,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 = int temp = CMActions.manager.multiContractRecorder.getMultiContractMeta(contractID)
CMActions.manager.multiContractRecorder.getMultiContractMeta(contractID).getCurSeqAtMaster(); .getCurSeqAtMaster();
request.put("unitLastExeSeq", temp + ""); request.put("unitLastExeSeq", temp + "");
NetworkManager.instance.sendToAgent(nodeID, JsonUtil.toJson(request)); NetworkManager.instance.sendToAgent(nodeID, JsonUtil.toJson(request));
} }
@ -81,15 +80,15 @@ public class MasterServerRecoverMechAction {
RecoverMechTimeRecorder.writeCEIStart.put(nodeID, System.currentTimeMillis()); RecoverMechTimeRecorder.writeCEIStart.put(nodeID, System.currentTimeMillis());
MultiContractMeta cei = MultiContractMeta cei =
CMActions.manager.multiContractRecorder.getMultiContractMeta( CMActions.manager.multiContractRecorder.getMultiContractMeta(contractID); // master的server直接调client端因为master自己的client端就在自己本地
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()) parent.mkdirs(); if (!parent.exists())
parent.mkdirs();
ObjectOutputStream writer; ObjectOutputStream writer;
try { try {
FileOutputStream fileout = new FileOutputStream(file); FileOutputStream fileout = new FileOutputStream(file);
@ -125,7 +124,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);
@ -163,8 +162,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 = String masterID = CMActions.manager.multiContractRecorder.getMultiContractMeta(contractID)
CMActions.manager.multiContractRecorder.getMultiContractMeta(contractID).getMasterNode(); .getMasterNode();
if (recoverStatus.get(masterID).get(contractID) != RecoverFlag.ToRecover) { if (recoverStatus.get(masterID).get(contractID) != RecoverFlag.ToRecover) {
return; return;
} }
@ -172,15 +171,15 @@ public class MasterServerRecoverMechAction {
// 找一个普通节点来dump // 找一个普通节点来dump
String relyNode = null; String relyNode = null;
for (String nodeID : for (String nodeID : CMActions.manager.multiContractRecorder
CMActions.manager.multiContractRecorder.getMultiContractMeta(contractID).getMembers()) { .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;
@ -202,14 +201,16 @@ 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 // just disable unitModeCheck
if (stateful!=null) return; if (stateful != null)
return;
if (stateful.equals("false")) { if (stateful.equals("false")) {
LOGGER.info("无状态集群合约无需运行模式检查及切换!"); LOGGER.info("无状态集群合约无需运行模式检查及切换!");
return; return;
} }
MultiContractMeta mpci = CMActions.manager.multiContractRecorder.getMultiContractMeta(contractID); MultiContractMeta mpci =
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()) {
@ -223,27 +224,17 @@ public class MasterServerRecoverMechAction {
total++; total++;
} }
LOGGER.info( LOGGER.info("合约" + contractID + "的集群,正常运行的节点有" + fineNum + "个,总共节点有" + total
"合约" + "个. Math.ceil(total / 2)=" + Math.ceil((double) total / 2)
+ contractID + " online > Math.ceil(total / 2)" + (fineNum > Math.ceil(total / 2))
+ "的集群,正常运行的节点有" + " 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( LOGGER.info("合约" + contractID + "的集群更改模式为" + unitStatus);
"合约" + 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");
@ -251,11 +242,7 @@ 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( LOGGER.info("发消息给节点 " + nodeId.substring(0, 5) + " 设置合约" + contractID
"发消息给节点 "
+ nodeId.substring(0, 5)
+ " 设置合约"
+ contractID
+ "的集群模式为StableMode"); + "的集群模式为StableMode");
@ -265,14 +252,15 @@ public class MasterServerRecoverMechAction {
} }
// 新选出的Master恢复 // 新选出的Master恢复
public static void newMasterRecover( public static void newMasterRecover(String contractID, String allMembers,
String contractID, String allMembers, List<String> onlineMembers) { 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 = CMActions.manager.multiContractRecorder.getMultiContractMeta(contractID); MultiContractMeta cei =
CMActions.manager.multiContractRecorder.getMultiContractMeta(contractID);
synchronized (cei) { synchronized (cei) {
cei.setSeqAtMaster(cei.getLastExeSeq()); cei.setSeqAtMaster(cei.getLastExeSeq());
} }
@ -294,8 +282,8 @@ public class MasterServerRecoverMechAction {
} }
ContractMeta meta = CMActions.manager.statusRecorder.getContractMeta(contractID); ContractMeta meta = CMActions.manager.statusRecorder.getContractMeta(contractID);
meta.setContractExecutor( meta.setContractExecutor(MasterClientTCPAction.createContractExecutor(meta.contract,
MasterClientTCPAction.createContractExecutor(meta.contract, contractID, cei.getMasterNode(), cei.getMembers())); contractID, cei.getMasterNode(), cei.getMembers()));
Map<String, Object> args = new HashMap<>(); Map<String, Object> args = new HashMap<>();
args.put("ceiLastExeSeq", cei.getLastExeSeq()); args.put("ceiLastExeSeq", cei.getLastExeSeq());
meta.contractExecutor.onRecover(args); meta.contractExecutor.onRecover(args);
@ -319,11 +307,7 @@ 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( LOGGER.info("新master设置 合约 " + contractID + " 节点 " + nodeID.substring(0, 5)
"新master设置 合约 "
+ contractID
+ " 节点 "
+ nodeID.substring(0, 5)
+ " 为ToRecover"); + " 为ToRecover");
} }
} }
@ -367,8 +351,8 @@ public class MasterServerRecoverMechAction {
LOGGER.info("[MasterServerRecoverMechAction] 新master恢复完成!"); LOGGER.info("[MasterServerRecoverMechAction] 新master恢复完成!");
} }
public String judegeRecoverMethod( public String judegeRecoverMethod(String contractID, String nodeMode, String unitMode,
String contractID, String nodeMode, String unitMode, int nodeLastExe, int unitLastExe) { int nodeLastExe, int unitLastExe) {
if (nodeMode.equals(ContractUnitStatus.CommonMode.toString()) if (nodeMode.equals(ContractUnitStatus.CommonMode.toString())
&& nodeLastExe == unitLastExe) { && nodeLastExe == unitLastExe) {
return ""; return "";
@ -405,13 +389,14 @@ 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 unitMode = ContractUnitStatus.CommonMode.toString(); else
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 = int unitLastExe = CMActions.manager.multiContractRecorder.getMultiContractMeta(contractID)
CMActions.manager.multiContractRecorder.getMultiContractMeta(contractID).getCurSeqAtMaster(); .getCurSeqAtMaster();
RecoverMechTimeRecorder.startJudgeRecoverMethod.put(nodeID, System.currentTimeMillis()); RecoverMechTimeRecorder.startJudgeRecoverMethod.put(nodeID, System.currentTimeMillis());
@ -420,15 +405,8 @@ public class MasterServerRecoverMechAction {
RecoverMechTimeRecorder.judgeRecoverMethodFinish.put(nodeID, System.currentTimeMillis()); RecoverMechTimeRecorder.judgeRecoverMethodFinish.put(nodeID, System.currentTimeMillis());
LOGGER.info( LOGGER.info("[MasterServerRecoverMechAciton] askForRecover mode=" + nodeMode
"[MasterServerRecoverMechAciton] askForRecover mode=" + " contractID=" + contractID + " nodeID=" + nodeID + " method=" + method);
+ 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);
@ -447,8 +425,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( restartContractFromCommonMode(jo.get("nodeID").getAsString(),
jo.get("nodeID").getAsString(), jo.get("contractID").getAsString()); jo.get("contractID").getAsString());
} }
@Action(async = true) @Action(async = true)
@ -457,7 +435,8 @@ 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 = CMActions.manager.multiContractRecorder.getMultiContractMeta(contractID); MultiContractMeta mpci =
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);
@ -477,7 +456,8 @@ 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()) parent.mkdirs(); if (!parent.exists())
parent.mkdirs();
try { try {
FileWriter fw = new FileWriter(file, true); FileWriter fw = new FileWriter(file, true);
@ -516,7 +496,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);
@ -599,7 +579,8 @@ public class MasterServerRecoverMechAction {
} catch (FileNotFoundException e) { } catch (FileNotFoundException e) {
e.printStackTrace(); e.printStackTrace();
} }
} else fout = (FileOutputStream) stateFileMap.get(fileName); } else
fout = (FileOutputStream) stateFileMap.get(fileName);
String data = args.get("data").getAsString(); String data = args.get("data").getAsString();
try { try {
@ -620,7 +601,8 @@ 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(), JsonUtil.toJson(req)); NetworkManager.instance.sendToAgent(keyPair.getPublicKeyStr(),
JsonUtil.toJson(req));
} }
} catch (IOException e) { } catch (IOException e) {
e.printStackTrace(); e.printStackTrace();

View File

@ -19,7 +19,6 @@ 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;
@ -40,8 +39,7 @@ public class MasterServerTCPAction {
static { static {
final Object flag = new Object(); final Object flag = new Object();
ContractManager.scheduledThreadPool.scheduleWithFixedDelay( ContractManager.scheduledThreadPool.scheduleWithFixedDelay(() -> {
() -> {
boolean cleared = clearCache(); boolean cleared = clearCache();
if (cleared) { if (cleared) {
try { try {
@ -52,14 +50,10 @@ public class MasterServerTCPAction {
e.printStackTrace(); 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) {
@ -68,23 +62,21 @@ public class MasterServerTCPAction {
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 NotifiableResultMerger) {
NotifiableResultMerger merger = NotifiableResultMerger merger = (NotifiableResultMerger) rc.getCommitter();
(NotifiableResultMerger) rc.getCommitter();
if (merger.getContractID().equals(contractID)) { if (merger.getContractID().equals(contractID)) {
LOGGER.info("node " + nodeID + " offline! in the cluster of contract " + contractID); LOGGER.info("node " + nodeID + " offline! in the cluster of contract "
LOGGER.debug("nodeID=" + nodeID + " contractID=" + contractID + + contractID);
": " + merger.getInfo()); LOGGER.debug("nodeID=" + nodeID + " contractID=" + contractID + ": "
ContractResult cr = + merger.getInfo());
new ContractResult( ContractResult cr = new ContractResult(ContractResult.Status.Exception,
ContractResult.Status.Exception,
new JsonPrimitive("node offline")); 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());
} }
} }
@ -96,7 +88,8 @@ 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) return cache; if (cache != null)
return cache;
else { else {
LOGGER.info("[MasterServerTCPAction] create requestcache:" + contractID); LOGGER.info("[MasterServerTCPAction] create requestcache:" + contractID);
RequestCache reqc = new RequestCache(); RequestCache reqc = new RequestCache();
@ -108,7 +101,8 @@ public class MasterServerTCPAction {
} }
static boolean clearCache() { static boolean clearCache() {
if (requestCache.isEmpty()) return true; if (requestCache.isEmpty())
return true;
// final long time = System.currentTimeMillis() - 120000L; // 120s // final long time = System.currentTimeMillis() - 120000L; // 120s
// requestCache // requestCache
@ -130,9 +124,7 @@ 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", LOGGER.debug(String.format("getCMInfo: %s %s %s", meta.getName(), meta.getID(),
meta.getName(),
meta.getID(),
meta.getStatus())); meta.getStatus()));
return ret; return ret;
} }
@ -172,8 +164,7 @@ 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 = KillUnitContractResultCollector collector = new KillUnitContractResultCollector(
new KillUnitContractResultCollector(
jo.get("requestID").getAsString(), cb, contractMeta.getMembers().length); 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()) {
@ -188,23 +179,23 @@ public class MasterServerTCPAction {
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)
@ -248,16 +239,14 @@ public class MasterServerTCPAction {
// null") + // null") +
// "\n"); // "\n");
if (info != null && if (info != null && ContractExecType.Sharding != contractMeta.contract.getType()
ContractExecType.Sharding != contractMeta.contract.getType() && !ContractExecType.SelfAdaptiveSharding
&& !ContractExecType.SelfAdaptiveSharding.equals(contractMeta.contract.getType())) { .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( contractMeta.contractExecutor.execute(requestID,
requestID, JsonUtil.fromJson(cr, ContractRequest.class), new ResultCallback() {
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<>();
@ -279,7 +268,8 @@ public class MasterServerTCPAction {
// 这个是个单节点的合约 // 这个是个单节点的合约
// executeContract(CacheTest应该要有多个进来 // executeContract(CacheTest应该要有多个进来
if (null != client && !client.getContractType().needSeq()) { if (null != client && !client.getContractType().needSeq()) {
contractMeta.contractExecutor.execute(requestID, contractRequest, new ResultCallback() { contractMeta.contractExecutor.execute(requestID, contractRequest,
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<>();

View File

@ -22,8 +22,7 @@ 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) {
@ -54,7 +53,8 @@ public class MasterServerTransferAction {
} catch (FileNotFoundException e) { } catch (FileNotFoundException e) {
e.printStackTrace(); e.printStackTrace();
} }
} else fout = (FileOutputStream) fileMap.get(fileKey); } else
fout = (FileOutputStream) fileMap.get(fileKey);
if (isDone) { if (isDone) {
if (fout != null) if (fout != null)
try { try {
@ -90,7 +90,8 @@ public class MasterServerTransferAction {
c.setOwner(GlobalConf.instance.keyPair.getPublicKeyStr()); c.setOwner(GlobalConf.instance.keyPair.getPublicKeyStr());
try { try {
File temp = new File(path); File temp = new File(path);
if (temp.isFile() && temp.exists()) c.setScript(temp.getAbsolutePath()); if (temp.isFile() && temp.exists())
c.setScript(temp.getAbsolutePath());
} catch (Exception e) { } catch (Exception e) {
e.printStackTrace(); e.printStackTrace();
} }
@ -142,7 +143,8 @@ public class MasterServerTransferAction {
} catch (FileNotFoundException e) { } catch (FileNotFoundException e) {
e.printStackTrace(); e.printStackTrace();
} }
} else fout = (FileOutputStream) fileMap.get(fileName); } else
fout = (FileOutputStream) fileMap.get(fileName);
if (isDone) { if (isDone) {
if (fout != null) if (fout != null)
try { try {

View File

@ -4,20 +4,17 @@ 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) {
@ -29,7 +26,8 @@ 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(), new String[]{"NetworkManager.instance.getTcpNodeCenter()"}, callback); ContractUnitManager.instance.send(jsonObject.toString(),
new String[] {"NetworkManager.instance.getTcpNodeCenter()"}, callback);
} }
} }
@ -43,7 +41,8 @@ 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(), new String[]{"NetworkManager.instance.getTcpNodeCenter()"}, callback); ContractUnitManager.instance.send(jsonObject.toString(),
new String[] {"NetworkManager.instance.getTcpNodeCenter()"}, callback);
} }
} }
@ -58,7 +57,8 @@ 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 = JsonUtil.fromJson(args.get("content").getAsString(), MultiPointContractInfo.class); MultiPointContractInfo contractInfo =
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,8 +35,7 @@ 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)
@ -75,17 +74,12 @@ public class _UNUSED_ExecutionAction implements OnHashCallback {
// UnitContractRequestType.START.getValue(); // UnitContractRequestType.START.getValue();
unitContractMessage.action = "startContractResponse"; unitContractMessage.action = "startContractResponse";
unitContractMessage.content = unitContractMessage.content =
JsonUtil.toJson( JsonUtil.toJson(new ContractResult(ContractResult.Status.Exception,
new ContractResult(
ContractResult.Status.Exception,
new JsonPrimitive("Contract not found"))); new JsonPrimitive("Contract not found")));
reply = reply = UnitMessage.newBuilder()
UnitMessage.newBuilder()
.setMsgType(BDLedgerContract.UnitMessageType.UnitContractMessage) .setMsgType(BDLedgerContract.UnitMessageType.UnitContractMessage)
.setSender(GlobalConf.instance.peerID) .setSender(GlobalConf.instance.peerID).addReceiver(sender)
.addReceiver(sender) .setContent(ByteString.copyFromUtf8(JsonUtil.toJson(unitContractMessage)))
.setContent(
ByteString.copyFromUtf8(JsonUtil.toJson(unitContractMessage)))
.build(); .build();
// byte[] bytes = reply.toByteArray(); // byte[] bytes = reply.toByteArray();
callback.onResult(JsonUtil.toJson(reply)); callback.onResult(JsonUtil.toJson(reply));
@ -107,13 +101,10 @@ public class _UNUSED_ExecutionAction implements OnHashCallback {
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 = reply = UnitMessage.newBuilder()
UnitMessage.newBuilder()
.setMsgType(BDLedgerContract.UnitMessageType.UnitContractMessage) .setMsgType(BDLedgerContract.UnitMessageType.UnitContractMessage)
.setSender(GlobalConf.instance.peerID) .setSender(GlobalConf.instance.peerID).addReceiver(sender)
.addReceiver(sender) .setContent(ByteString.copyFromUtf8(JsonUtil.toJson(unitContractMessage))).build();
.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) {
@ -130,10 +121,8 @@ public class _UNUSED_ExecutionAction implements OnHashCallback {
System.out.println("[BaseFunctionManager] handleResponse null"); System.out.println("[BaseFunctionManager] handleResponse null");
return; return;
} }
if (responseCenter.updateReply( if (responseCenter.updateReply(arg.get("content").getAsString(),
arg.get("content").getAsString(), arg.get("sender").getAsString(), arg.get("pubkey").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();
@ -158,7 +147,8 @@ 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 = JsonUtil.fromJson(args, UnitContractMessage.class); UnitContractMessage unitContractMessage =
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;
@ -189,31 +179,22 @@ public class _UNUSED_ExecutionAction implements OnHashCallback {
// 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( CMActions.manager.executeContractInternal(c, new ResultCallback() {
c,
new ResultCallback() {
@Override @Override
public void onResult(String str) { public void onResult(String str) {
// TODO qianming // TODO qianming
unitContractMessage.signature = str; unitContractMessage.signature = str;
unitContractMessage.action = "executeContractResponse"; unitContractMessage.action = "executeContractResponse";
unitContractMessage.content = str; unitContractMessage.content = str;
UnitMessage unitMessage = UnitMessage unitMessage = UnitMessage.newBuilder()
UnitMessage.newBuilder() .setMsgType(BDLedgerContract.UnitMessageType.UnitContractMessage)
.setMsgType( .setSender(GlobalConf.instance.peerID).addReceiver(sender)
BDLedgerContract.UnitMessageType .setContent(ByteString.copyFromUtf8(JsonUtil.toJson(unitContractMessage)))
.UnitContractMessage)
.setSender(GlobalConf.instance.peerID)
.addReceiver(sender)
.setContent(
ByteString.copyFromUtf8(
JsonUtil.toJson(unitContractMessage)))
.build(); .build();
byte[] bytes = unitMessage.toByteArray(); byte[] bytes = unitMessage.toByteArray();
callback.onResult(ByteUtil.encodeBASE64(bytes)); callback.onResult(ByteUtil.encodeBASE64(bytes));
} }
}, }, null);
null);
} }
@Action(async = true) @Action(async = true)
@ -225,10 +206,8 @@ public class _UNUSED_ExecutionAction implements OnHashCallback {
System.out.println("[BaseFunctionManager] responseCenter null"); System.out.println("[BaseFunctionManager] responseCenter null");
return; return;
} }
if (responseCenter.updateReply( if (responseCenter.updateReply(arg.get("content").getAsString(),
arg.get("content").getAsString(), arg.get("sender").getAsString(), arg.get("signature").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);
@ -238,7 +217,8 @@ 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 = JsonUtil.fromJson(args, UnitContractMessage.class); UnitContractMessage unitContractMessage =
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;
@ -248,28 +228,19 @@ public class _UNUSED_ExecutionAction implements OnHashCallback {
final ContractRequest c = new ContractRequest(); final ContractRequest c = new ContractRequest();
c.setContractID(contractID); c.setContractID(contractID);
c.setRequestID(requestID); c.setRequestID(requestID);
String ret = String ret = CMActions.manager
CMActions.manager.stopContractWithOwner( .stopContractWithOwner(GlobalConf.instance.keyPair.getPublicKeyStr(), contractID);
GlobalConf.instance.keyPair.getPublicKeyStr(), contractID); GRPCPool.instance.writeToChain(this, contractID, "stopContract", ret,
GRPCPool.instance.writeToChain( args.has("requestID") ? args.get("requestID").getAsString() : null, "");
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 unitMessage = UnitMessage.newBuilder()
UnitMessage.newBuilder()
.setMsgType(BDLedgerContract.UnitMessageType.UnitContractMessage) .setMsgType(BDLedgerContract.UnitMessageType.UnitContractMessage)
.setSender(GlobalConf.instance.peerID) .setSender(GlobalConf.instance.peerID).addReceiver(sender)
.addReceiver(sender) .setContent(ByteString.copyFromUtf8(JsonUtil.toJson(unitContractMessage))).build();
.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));
} }
@ -284,10 +255,8 @@ public class _UNUSED_ExecutionAction implements OnHashCallback {
System.out.println("[BaseFunctionManager] responseCenter null"); System.out.println("[BaseFunctionManager] responseCenter null");
return; return;
} }
if (responseCenter.updateReply( if (responseCenter.updateReply(arg.get("content").getAsString(),
arg.get("content").getAsString(), arg.get("sender").getAsString(), arg.get("signature").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();
@ -299,6 +268,5 @@ public class _UNUSED_ExecutionAction implements OnHashCallback {
} }
@Override @Override
public void publishHash(String reqID, String hashStr) { public void publishHash(String reqID, String hashStr) {}
}
} }

View File

@ -46,7 +46,8 @@ public class BCOManager {
String body = doipMessage.body.getDataAsJsonString(); String body = doipMessage.body.getDataAsJsonString();
LOGGER.info("Retrieve " + bCoId + " Result:" + body); LOGGER.info("Retrieve " + bCoId + " Result:" + body);
YPKInfo parsed = new Gson().fromJson(body, YPKInfo.class); YPKInfo parsed = new Gson().fromJson(body, YPKInfo.class);
if (parsed != null && parsed.md5 != null && parsed.status == UploadingStatus.Finished) { if (parsed != null && parsed.md5 != null
&& parsed.status == UploadingStatus.Finished) {
ypkInfo.copyFrom(parsed); ypkInfo.copyFrom(parsed);
} }
synchronized (ypkInfo) { synchronized (ypkInfo) {
@ -65,7 +66,8 @@ public class BCOManager {
if (ypkInfo.status == UploadingStatus.Finished) { if (ypkInfo.status == UploadingStatus.Finished) {
File target = getYpkFile(ypkInfo); File target = getYpkFile(ypkInfo);
if (target.exists() && (client.calFileMd5(target.getAbsolutePath()) + ".ypk").equals(target.getName())) if (target.exists() && (client.calFileMd5(target.getAbsolutePath()) + ".ypk")
.equals(target.getName()))
return target.getAbsolutePath(); return target.getAbsolutePath();
DownloadProgressChecker checker = new DownloadProgressChecker(); DownloadProgressChecker checker = new DownloadProgressChecker();
client.downloadYPK(bCoId, checker, target); client.downloadYPK(bCoId, checker, target);
@ -109,7 +111,8 @@ public class BCOManager {
synchronized (this) { synchronized (this) {
this.notify(); this.notify();
} }
LOGGER.info("[Download error]" + s + " doipMessage:" + doipMessage.body.getDataAsJsonString()); LOGGER.info("[Download error]" + s + " doipMessage:"
+ doipMessage.body.getDataAsJsonString());
} }

View File

@ -41,7 +41,8 @@ import java.util.ArrayList;
import java.util.List; import java.util.List;
@ChannelHandler.Sharable @ChannelHandler.Sharable
public class ContractRepositoryHandler extends RepositoryHandlerBase implements DefaultRepoHandlerInjector { public class ContractRepositoryHandler extends RepositoryHandlerBase
implements DefaultRepoHandlerInjector {
BCOManager bcoManager; BCOManager bcoManager;
static Logger LOGGER = LogManager.getLogger(ContractRepositoryHandler.class); static Logger LOGGER = LogManager.getLogger(ContractRepositoryHandler.class);
@ -49,7 +50,8 @@ public class ContractRepositoryHandler extends RepositoryHandlerBase implements
super(info); super(info);
GlobalConf.DOAConf doaConf = GlobalConf.instance.doaConf; GlobalConf.DOAConf doaConf = GlobalConf.instance.doaConf;
String bcoDir = GlobalConf.instance.bcoDir; String bcoDir = GlobalConf.instance.bcoDir;
bcoManager = new BCOManager(doaConf.repoDoid, new File(bcoDir), doaConf.lhsAddress, GlobalConf.instance.keyPair); bcoManager = new BCOManager(doaConf.repoDoid, new File(bcoDir), doaConf.lhsAddress,
GlobalConf.instance.keyPair);
} }
@Override @Override
@ -60,7 +62,9 @@ public class ContractRepositoryHandler extends RepositoryHandlerBase implements
@Override @Override
public DoipMessage handleListOps(DoipMessage doipMessage) { public DoipMessage handleListOps(DoipMessage doipMessage) {
if (!GlobalConf.instance.doaConf.repoDoid.equals(doipMessage.header.parameters.id)) { if (!GlobalConf.instance.doaConf.repoDoid.equals(doipMessage.header.parameters.id)) {
return replyStringWithStatus(doipMessage, "unsupported doid:" + doipMessage.header.parameters.id, DoipResponseCode.DoNotFound); 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());
@ -71,13 +75,17 @@ public class ContractRepositoryHandler extends RepositoryHandlerBase implements
@Override @Override
public DoipMessage handleCreate(DoipMessage doipMessage) { public DoipMessage handleCreate(DoipMessage doipMessage) {
if (!GlobalConf.instance.doaConf.repoDoid.equals(doipMessage.header.parameters.id)) { if (!GlobalConf.instance.doaConf.repoDoid.equals(doipMessage.header.parameters.id)) {
return replyStringWithStatus(doipMessage, "unsupported doid:" + doipMessage.header.parameters.id, DoipResponseCode.DoNotFound); return replyStringWithStatus(doipMessage,
"unsupported doid:" + doipMessage.header.parameters.id,
DoipResponseCode.DoNotFound);
} }
//TODD 验证签名完事后进入 // TODD 验证签名完事后进入
if (doipMessage.credential != null && doipMessage.credential.getSigner() != null) { if (doipMessage.credential != null && doipMessage.credential.getSigner() != null) {
String permissions = KeyValueDBUtil.instance.getValue(CMTables.NodeRole.toString(), doipMessage.credential.getSigner()); String permissions = KeyValueDBUtil.instance.getValue(CMTables.NodeRole.toString(),
doipMessage.credential.getSigner());
if (!permissions.contains("ContractInstanceManager")) { if (!permissions.contains("ContractInstanceManager")) {
return replyStringWithStatus(doipMessage, "permission denied, role:" + permissions, DoipResponseCode.Declined); return replyStringWithStatus(doipMessage, "permission denied, role:" + permissions,
DoipResponseCode.Declined);
} }
} }
DigitalObject digitalObject = null; DigitalObject digitalObject = null;
@ -87,7 +95,8 @@ public class ContractRepositoryHandler extends RepositoryHandlerBase implements
} catch (Exception e) { } catch (Exception e) {
ByteArrayOutputStream bo = new ByteArrayOutputStream(); ByteArrayOutputStream bo = new ByteArrayOutputStream();
e.printStackTrace(new PrintStream(bo)); e.printStackTrace(new PrintStream(bo));
return replyStringWithStatus(doipMessage, "exception:" + new String(bo.toByteArray()), DoipResponseCode.Invalid); return replyStringWithStatus(doipMessage, "exception:" + new String(bo.toByteArray()),
DoipResponseCode.Invalid);
} }
@ -98,16 +107,23 @@ public class ContractRepositoryHandler extends RepositoryHandlerBase implements
path = bcoManager.download(digitalObject.attributes.get("bCoId").getAsString()); path = bcoManager.download(digitalObject.attributes.get("bCoId").getAsString());
if (path == null) { if (path == null) {
return replyStringWithStatus(doipMessage, "exception, failed to locate bCoId:" + digitalObject.attributes.get("bCoId").getAsString(), DoipResponseCode.Invalid); return replyStringWithStatus(doipMessage,
"exception, failed to locate bCoId:"
+ digitalObject.attributes.get("bCoId").getAsString(),
DoipResponseCode.Invalid);
} }
digitalObject.attributes.addProperty("path", path); digitalObject.attributes.addProperty("path", path);
Contract c = new Contract(); Contract c = new Contract();
if (digitalObject.attributes.has("contractExecType")) if (digitalObject.attributes.has("contractExecType"))
c.setType(ContractExecType.valueOf(digitalObject.attributes.get("contractExecType").getAsString())); c.setType(ContractExecType
else c.setType(ContractExecType.Sole); .valueOf(digitalObject.attributes.get("contractExecType").getAsString()));
else
c.setType(ContractExecType.Sole);
if (digitalObject.attributes.has("shardingId")) if (digitalObject.attributes.has("shardingId"))
c.setShardingId(Integer.valueOf(digitalObject.attributes.get("shardingId").getAsString())); c.setShardingId(
else c.setShardingId(-1); Integer.valueOf(digitalObject.attributes.get("shardingId").getAsString()));
else
c.setShardingId(-1);
c.setScript(path); c.setScript(path);
c.setOwner(doipMessage.credential.getSigner()); c.setOwner(doipMessage.credential.getSigner());
if (digitalObject.attributes.has("createParam")) { if (digitalObject.attributes.has("createParam")) {
@ -116,25 +132,28 @@ public class ContractRepositoryHandler extends RepositoryHandlerBase implements
} }
SM2KeyPair sm2Key; SM2KeyPair sm2Key;
if (digitalObject.attributes.has("sm2KeyPair")) if (digitalObject.attributes.has("sm2KeyPair"))
sm2Key = SM2KeyPair.fromJson(digitalObject.attributes.get("sm2KeyPair").getAsJsonObject().toString()); sm2Key = SM2KeyPair.fromJson(
else sm2Key = SM2Util.generateSM2KeyPair(); digitalObject.attributes.get("sm2KeyPair").getAsJsonObject().toString());
else
sm2Key = SM2Util.generateSM2KeyPair();
String contractID = String.valueOf(sm2Key.getPublicKeyStr().hashCode()); String contractID = String.valueOf(sm2Key.getPublicKeyStr().hashCode());
c.setID(contractID); // contractID是根据hash算出来的 c.setID(contractID); // contractID是根据hash算出来的
c.setKey(sm2Key.getPrivateKeyStr()); c.setKey(sm2Key.getPrivateKeyStr());
c.setPublicKey(sm2Key.getPublicKeyStr()); c.setPublicKey(sm2Key.getPublicKeyStr());
if (c.getCreateParam() != null && c.getCreateParam().isJsonObject()) { if (c.getCreateParam() != null && c.getCreateParam().isJsonObject()) {
c.getCreateParam().getAsJsonObject().addProperty("repoId", GlobalConf.instance.doaConf.repoDoid + "/" + c.getID()); c.getCreateParam().getAsJsonObject().addProperty("repoId",
GlobalConf.instance.doaConf.repoDoid + "/" + c.getID());
} }
registerBDOID(contractID); registerBDOID(contractID);
String result = CMActions.manager.startContract(c); String result = CMActions.manager.startContract(c);
//Please note startContractByYPK is invoked in sync mode method. // Please note startContractByYPK is invoked in sync mode method.
return replyStringWithStatus(doipMessage, result, DoipResponseCode.Success); return replyStringWithStatus(doipMessage, result, DoipResponseCode.Success);
} }
private void registerBDOID(String contractID) { private void registerBDOID(String contractID) {
//TODO // TODO
} }
@Override @Override
@ -147,13 +166,15 @@ public class ContractRepositoryHandler extends RepositoryHandlerBase implements
String id = doipMessage.header.parameters.attributes.get("elementId").getAsString(); String id = doipMessage.header.parameters.attributes.get("elementId").getAsString();
id = id.replaceAll(".*/", ""); id = id.replaceAll(".*/", "");
LOGGER.info("handleDelete:" + id); LOGGER.info("handleDelete:" + id);
//TODO judge whethere the do exists // TODO judge whethere the do exists
ContractMeta meta = CMActions.manager.statusRecorder.getContractMeta(id); ContractMeta meta = CMActions.manager.statusRecorder.getContractMeta(id);
if (meta == null) { if (meta == null) {
return replyStringWithStatus(doipMessage, "can't locate do", DoipResponseCode.DoNotFound); return replyStringWithStatus(doipMessage, "can't locate do",
DoipResponseCode.DoNotFound);
} }
if (meta.getStatus() == ContractStatusEnum.KILLED) { if (meta.getStatus() == ContractStatusEnum.KILLED) {
return replyStringWithStatus(doipMessage, "already deleted!", DoipResponseCode.Declined); return replyStringWithStatus(doipMessage, "already deleted!",
DoipResponseCode.Declined);
} }
DoipMessage[] content = new DoipMessage[1]; DoipMessage[] content = new DoipMessage[1];
JsonObject jo = new JsonObject(); JsonObject jo = new JsonObject();
@ -172,11 +193,13 @@ public class ContractRepositoryHandler extends RepositoryHandlerBase implements
if (client == null) { if (client == null) {
String doid = doipMessage.header.parameters.id; String doid = doipMessage.header.parameters.id;
int off = doid.lastIndexOf("/"); int off = doid.lastIndexOf("/");
if (off > 0) doid = doid.substring(off + 1); if (off > 0)
doid = doid.substring(off + 1);
client = CMActions.manager.getContractClientByDoi(doid); client = CMActions.manager.getContractClientByDoi(doid);
} }
if (client == null) { if (client == null) {
return replyStringWithStatus(doipMessage, "Contract instance not exist!", DoipResponseCode.DoNotFound); return replyStringWithStatus(doipMessage, "Contract instance not exist!",
DoipResponseCode.DoNotFound);
} }
byte[] data = doipMessage.body.getEncodedData(); byte[] data = doipMessage.body.getEncodedData();
@ -213,7 +236,8 @@ public class ContractRepositoryHandler extends RepositoryHandlerBase implements
result.add(new JsonPrimitive("Timeout!")); result.add(new JsonPrimitive("Timeout!"));
retStatus = DoipResponseCode.MoreThanOneErrors; retStatus = DoipResponseCode.MoreThanOneErrors;
} }
DigitalObject digitalObject = new DigitalObject(doipMessage.header.parameters.id, DoType.DO); DigitalObject digitalObject =
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));
@ -236,29 +260,35 @@ public class ContractRepositoryHandler extends RepositoryHandlerBase implements
@Op(op = BasicOperations.Extension, name = "call") @Op(op = BasicOperations.Extension, name = "call")
public DoipMessage handleCall(DoipMessage doipMessage) { public DoipMessage handleCall(DoipMessage doipMessage) {
ContractClient cc = CMActions.manager.getContractClientByDoi(doipMessage.header.parameters.id); ContractClient cc =
CMActions.manager.getContractClientByDoi(doipMessage.header.parameters.id);
if (cc == null) if (cc == null)
return replyStringWithStatus(doipMessage, "Contract instance not exist!", DoipResponseCode.DoNotFound); return replyStringWithStatus(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());
if (args.has("withDynamicAnalysis")) cr.withDynamicAnalysis = args.get("withDynamicAnalysis").getAsBoolean(); if (args.has("withDynamicAnalysis"))
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", DoipResponseCode.Invalid); return replyStringWithStatus(doipMessage, "missing elementID",
DoipResponseCode.Invalid);
cr.setAction(args.get("elementID").getAsString()); cr.setAction(args.get("elementID").getAsString());
if (doipMessage.body.getEncodedData() != null) cr.setArg(new String(doipMessage.body.getEncodedData())); if (doipMessage.body.getEncodedData() != null)
cr.setArg(new String(doipMessage.body.getEncodedData()));
if (doipMessage.credential != null && doipMessage.credential.getSigner() != null) if (doipMessage.credential != null && doipMessage.credential.getSigner() != null)
cr.setRequesterDOI(doipMessage.credential.getSigner()); cr.setRequesterDOI(doipMessage.credential.getSigner());
String reqID; String reqID;
if (args.has("requestID")) reqID = args.get("requestID").getAsString(); if (args.has("requestID"))
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);
@ -285,7 +315,8 @@ public class ContractRepositoryHandler extends RepositoryHandlerBase implements
} }
@Override @Override
public void injectListOps(DoipMessage doipMessage, DoipMessageFactory.DoipMessageBuilder builder) { public void injectListOps(DoipMessage doipMessage,
DoipMessageFactory.DoipMessageBuilder builder) {
builder.setDoipMessage(handleListOps(doipMessage)); builder.setDoipMessage(handleListOps(doipMessage));
} }
@ -295,12 +326,14 @@ public class ContractRepositoryHandler extends RepositoryHandlerBase implements
} }
@Override @Override
public void injectRetrieve(DoipMessage doipMessage, DoipMessageFactory.DoipMessageBuilder builder) { public void injectRetrieve(DoipMessage doipMessage,
DoipMessageFactory.DoipMessageBuilder builder) {
builder.setDoipMessage(handleRetrieve(doipMessage)); builder.setDoipMessage(handleRetrieve(doipMessage));
} }
@Override @Override
public void injectDelete(DoipMessage doipMessage, DoipMessageFactory.DoipMessageBuilder builder) { public void injectDelete(DoipMessage doipMessage,
DoipMessageFactory.DoipMessageBuilder builder) {
builder.setDoipMessage(handleDelete(doipMessage)); builder.setDoipMessage(handleDelete(doipMessage));
} }
} }

View File

@ -34,7 +34,8 @@ public class ContractRepositoryMain {
String url = GlobalConf.instance.doaConf.doipAddress; String url = GlobalConf.instance.doaConf.doipAddress;
forwarder = new LocalDoipFrowarder(); forwarder = new LocalDoipFrowarder();
if (url == null || GlobalConf.instance.doaConf.repoDoid.isEmpty()) { if (url == null || GlobalConf.instance.doaConf.repoDoid.isEmpty()) {
LOGGER.warn("missing args, failed to start! url:" + url + " doid:" + GlobalConf.instance.doaConf.repoDoid); LOGGER.warn("missing args, failed to start! url:" + url + " doid:"
+ GlobalConf.instance.doaConf.repoDoid);
return; return;
} }
if (currentServer != null) { if (currentServer != null) {
@ -42,7 +43,8 @@ public class ContractRepositoryMain {
} }
List<DoipListenerConfig> infos = new ArrayList<>(); List<DoipListenerConfig> infos = new ArrayList<>();
infos.add(new DoipListenerConfig(url, "2.1")); infos.add(new DoipListenerConfig(url, "2.1"));
DoipServiceInfo info = new DoipServiceInfo(GlobalConf.instance.doaConf.repoDoid, GlobalConf.instance.keyPair.getPublicKeyStr(), repoType, infos); DoipServiceInfo info = new DoipServiceInfo(GlobalConf.instance.doaConf.repoDoid,
GlobalConf.instance.keyPair.getPublicKeyStr(), repoType, infos);
EndpointConfig config = new EndpointConfig(); EndpointConfig config = new EndpointConfig();
config.publicKey = GlobalConf.instance.keyPair.getPublicKeyStr(); config.publicKey = GlobalConf.instance.keyPair.getPublicKeyStr();
config.privateKey = GlobalConf.instance.keyPair.getPrivateKeyStr(); config.privateKey = GlobalConf.instance.keyPair.getPrivateKeyStr();
@ -55,8 +57,10 @@ public class ContractRepositoryMain {
SM2Signer signer = new SM2Signer(SM2KeyPair.fromJson(new Gson().toJson(config))); SM2Signer signer = new SM2Signer(SM2KeyPair.fromJson(new Gson().toJson(config)));
DelegateDoipHandler delegateHandler = new DelegateDoipHandler(requestCallback) { DelegateDoipHandler delegateHandler = new DelegateDoipHandler(requestCallback) {
@Override @Override
protected DoipMessage delegateMessage(ChannelHandlerContext context, DoipMessage message) { protected DoipMessage delegateMessage(ChannelHandlerContext context,
DoipMessageFactory.DoipMessageBuilder builder = new DoipMessageFactory.DoipMessageBuilder(); DoipMessage message) {
DoipMessageFactory.DoipMessageBuilder builder =
new DoipMessageFactory.DoipMessageBuilder();
builder.createResponse(DoipResponseCode.DelegateRequired, message); builder.createResponse(DoipResponseCode.DelegateRequired, message);
String id = message.header.parameters.id; String id = message.header.parameters.id;
id = id.replaceAll(".*/", ""); id = id.replaceAll(".*/", "");
@ -64,7 +68,7 @@ public class ContractRepositoryMain {
if (enableDelegate(meta)) { if (enableDelegate(meta)) {
LOGGER.info("delegate:" + message.requestID); LOGGER.info("delegate:" + message.requestID);
//if port is near cmhttp server port // if port is near cmhttp server port
builder.addAttributes("port", meta.contract.getDoipPort()); builder.addAttributes("port", meta.contract.getDoipPort());
DoipMessage ret; DoipMessage ret;
ret = builder.create(); ret = builder.create();

View File

@ -14,9 +14,12 @@ public abstract class DelegateDoipHandler implements DoipRequestHandler {
public DoipMessage onRequest(ChannelHandlerContext context, DoipMessage doipMessage) { public DoipMessage onRequest(ChannelHandlerContext context, DoipMessage doipMessage) {
if (accept(context, doipMessage)) { if (accept(context, doipMessage)) {
return delegateMessage(context, doipMessage); return delegateMessage(context, doipMessage);
} else return original.onRequest(context, doipMessage); } else
return original.onRequest(context, doipMessage);
} }
protected abstract DoipMessage delegateMessage(ChannelHandlerContext context, DoipMessage message); protected abstract DoipMessage delegateMessage(ChannelHandlerContext context,
DoipMessage message);
public abstract boolean accept(ChannelHandlerContext context, DoipMessage message); public abstract boolean accept(ChannelHandlerContext context, DoipMessage message);
} }

View File

@ -27,10 +27,12 @@ public class LocalDoipFrowarder {
connection = connections.get(meta.contract.getDoipPort()); connection = connections.get(meta.contract.getDoipPort());
} else { } else {
connection = new DoipClientImpl(); connection = new DoipClientImpl();
connection.connect(ClientConfig.fromUrl("tcp://127.0.0.1:" + meta.contract.getDoipPort())); connection.connect(
ClientConfig.fromUrl("tcp://127.0.0.1:" + meta.contract.getDoipPort()));
connections.put(meta.contract.getDoipPort(), connection); connections.put(meta.contract.getDoipPort(), connection);
} }
if (!connection.isConnected()) connection.reconnect(); if (!connection.isConnected())
connection.reconnect();
DoipMessage[] result = new DoipMessage[1]; DoipMessage[] result = new DoipMessage[1];
connection.sendRawMessage(message, new DoipMessageCallback() { connection.sendRawMessage(message, new DoipMessageCallback() {
@Override @Override
@ -49,7 +51,8 @@ public class LocalDoipFrowarder {
} catch (Exception e) { } catch (Exception e) {
ByteArrayOutputStream bo = new ByteArrayOutputStream(); ByteArrayOutputStream bo = new ByteArrayOutputStream();
e.printStackTrace(new PrintStream(bo)); e.printStackTrace(new PrintStream(bo));
DoipMessageFactory.DoipMessageBuilder builder = new DoipMessageFactory.DoipMessageBuilder(); DoipMessageFactory.DoipMessageBuilder builder =
new DoipMessageFactory.DoipMessageBuilder();
builder.createResponse(DoipResponseCode.UnKnownError, message); builder.createResponse(DoipResponseCode.UnKnownError, message);
builder.setBody(bo.toByteArray()); builder.setBody(bo.toByteArray());
return builder.create(); return builder.create();

View File

@ -1,40 +1,40 @@
//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;
@ -72,7 +72,8 @@
// } // }
// contractCluster = new ContractCluster(contractID, this.members); // contractCluster = new ContractCluster(contractID, this.members);
// pbft.setConnection(contractCluster); // pbft.setConnection(contractCluster);
// final MultiContractMeta cei = CMActions.manager.multiContractRecorder.getMultiContractMeta(contractID); // final MultiContractMeta cei =
// 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) {
@ -170,9 +171,11 @@
// } // }
// //
// @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)); // LOGGER.debug(JsonUtil.toJson(req));
// MultiContractMeta meta = CMActions.manager.multiContractRecorder.getMultiContractMeta(req.getContractID()); // MultiContractMeta meta =
// 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;
@ -372,4 +375,4 @@
// } // }
// } // }
// } // }
//} // }

View File

@ -43,8 +43,7 @@ public class RequestAllExecutor implements ContractExecutor {
// MultiPointContractInfo info; // MultiPointContractInfo info;
String contractID; String contractID;
public RequestAllExecutor( public RequestAllExecutor(ContractExecType t, int c, String con_id) {
ContractExecType t, int c, String con_id) {
type = t; type = t;
resultCount = c; resultCount = c;
contractID = con_id; contractID = con_id;
@ -54,16 +53,13 @@ public class RequestAllExecutor implements ContractExecutor {
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 int count, final int request_seq,
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( return new ResultCollector(requestID,
requestID, new ResultMerger(originalCb, count, request_seq, contractID), count); 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) {
@ -82,8 +78,8 @@ public class RequestAllExecutor implements ContractExecutor {
LOGGER.debug(JsonUtil.toJson(req)); LOGGER.debug(JsonUtil.toJson(req));
String[] nodes = String[] nodes = CMActions.manager.multiContractRecorder.getMultiContractMeta(contractID)
CMActions.manager.multiContractRecorder.getMultiContractMeta(contractID).getMembers(); .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) {
@ -91,19 +87,13 @@ 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\"," "{\"status\":\"Error\",\"result\":\"node offline\"," + "\"nodeID\":\""
+ "\"nodeID\":\"" + node + "\"," + "\"action\":\"onExecuteContractTrustfully\"}");
+ node } else if (MasterServerRecoverMechAction.recoverStatus.get(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\"," "{\"status\":\"Error\",\"result\":\"node recovering\"," + "\"nodeID\":\""
+ "\"nodeID\":\"" + node + "\"," + "\"action\":\"onExecuteContractTrustfully\"}");
+ 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));
@ -113,16 +103,17 @@ public class RequestAllExecutor implements ContractExecutor {
} }
public boolean checkCurNodeNumValid() { public boolean checkCurNodeNumValid() {
String[] nodes = String[] nodes = CMActions.manager.multiContractRecorder.getMultiContractMeta(contractID)
CMActions.manager.multiContractRecorder.getMultiContractMeta(contractID).getMembers(); .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), String.format("%s %s", NetworkManager.instance.hasAgentConnection(node) + "", mapResult.put(node.substring(0, 5),
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).get(contractID) && MasterServerRecoverMechAction.recoverStatus.get(node)
== RecoverFlag.Fine) { .get(contractID) == RecoverFlag.Fine) {
validNode++; validNode++;
} }
} }
@ -136,9 +127,11 @@ public class RequestAllExecutor implements ContractExecutor {
} }
@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)); LOGGER.debug(JsonUtil.toJson(req));
MultiContractMeta meta = CMActions.manager.multiContractRecorder.getMultiContractMeta(req.getContractID()); MultiContractMeta meta =
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;
@ -150,9 +143,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)) {
@ -180,31 +173,26 @@ public class RequestAllExecutor implements ContractExecutor {
} else { } else {
LOGGER.debug("invalidNodeNumOnResult"); LOGGER.debug("invalidNodeNumOnResult");
request_index.getAndDecrement(); request_index.getAndDecrement();
ContractResult finalResult = ContractResult finalResult = new ContractResult(ContractResult.Status.Error,
new ContractResult(
ContractResult.Status.Error,
new JsonPrimitive("node number unavailable, request refused.")); new JsonPrimitive("node number unavailable, request refused."));
rc.onResult(JsonUtil.toJson(finalResult)); rc.onResult(JsonUtil.toJson(finalResult));
} }
// } // }
/* // 三个相同requestID进来的时候会有冲突 /*
// 仅在此处有冲突么 * // 三个相同requestID进来的时候会有冲突 // 仅在此处有冲突么 //
// 这里是从MasterServer->MasterClient请求的是"executeContractLocally" * 这里是从MasterServer->MasterClient请求的是"executeContractLocally" req.seq =
req.seq = request_index.getAndIncrement(); * request_index.getAndIncrement(); req.needSeq = true; ResultCallback collector =
req.needSeq = true; * createResultCallback(id, rc, resultCount, req.getContractID());
ResultCallback collector = createResultCallback(id, rc, resultCount, req.getContractID()); * MasterServerTCPAction.sync.sleep(id, collector); sendRequest(id, req, collector);
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() seqMap.entrySet().removeIf(entry -> {
.removeIf(
entry -> {
MultiReqSeq cache = entry.getValue(); MultiReqSeq cache = entry.getValue();
if (null == cache) { if (null == cache) {
return true; return true;
@ -222,10 +210,7 @@ public class RequestAllExecutor implements ContractExecutor {
ResultCallback originalCallback; ResultCallback originalCallback;
Set<String> nodeIDs = new HashSet<>(); // 已收到返回结果的节点 Set<String> nodeIDs = new HashSet<>(); // 已收到返回结果的节点
ResultMerger( ResultMerger(final ResultCallback originalCb, final int count, final int request_seq,
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;
@ -240,16 +225,8 @@ public class RequestAllExecutor implements ContractExecutor {
} }
public String getInfo() { public String getInfo() {
return "contractID=" return "contractID=" + contractID + " 收到第 " + order + " 个节点回复 : " + " order=" + order
+ contractID + " count=" + count + " ";
+ " 收到第 "
+ order
+ " 个节点回复 : "
+ " order="
+ order
+ " count="
+ count
+ " ";
} }
@Override @Override
@ -263,18 +240,14 @@ 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( LOGGER.debug("ignored result because the result of node "
"ignored result because the result of node " + id.substring(0, 5) + " has been received");
+ id.substring(0, 5)
+ " has been received");
return; return;
} }
nodeIDs.add(id); nodeIDs.add(id);
} }
LOGGER.debug( LOGGER.debug(String.format("contractID=%s received=%s order=%d count=%d",
String.format(
"contractID=%s received=%s order=%d count=%d",
contractID, str, order.get(), count)); contractID, str, order.get(), count));
componedContractResult.add(obj); componedContractResult.add(obj);
// 收集到所有结果 // 收集到所有结果
@ -295,14 +268,11 @@ public class RequestAllExecutor implements ContractExecutor {
// } else { // } else {
originalCallback.onResult(JsonUtil.toJson(finalResult)); originalCallback.onResult(JsonUtil.toJson(finalResult));
// } // }
LOGGER.debug( LOGGER.debug(String.format("%d results are the same: %s", finalResult.size,
String.format( finalResult.result));
"%d results are the same: %s",
finalResult.size, finalResult.result));
// 集群中事务序号+1 // 集群中事务序号+1
CMActions.manager.multiContractRecorder CMActions.manager.multiContractRecorder.getMultiContractMeta(contractID)
.getMultiContractMeta(contractID)
.nextSeqAtMaster(); .nextSeqAtMaster();
// recover其中无状态合约CP出错无需恢复 // recover其中无状态合约CP出错无需恢复
@ -312,22 +282,21 @@ 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).get(contractID) if (MasterServerRecoverMechAction.recoverStatus.get(nodeID)
== RecoverFlag.Fine) { .get(contractID) == RecoverFlag.Fine) {
MasterServerRecoverMechAction.recoverStatus MasterServerRecoverMechAction.recoverStatus.get(nodeID).put(contractID,
.get(nodeID) RecoverFlag.ToRecover);
.put(contractID, RecoverFlag.ToRecover);
} }
} }
for (String nodeID : nodesID) { for (String nodeID : nodesID) {
if (MasterServerRecoverMechAction.recoverStatus.get(nodeID).get(contractID) if (MasterServerRecoverMechAction.recoverStatus.get(nodeID)
== RecoverFlag.ToRecover) { .get(contractID) == RecoverFlag.ToRecover) {
LOGGER.warn("node in recover " + nodeID); LOGGER.warn("node in recover " + nodeID);
// 因为该节点结果有误所以即时是stableMode也认为trans记录不可信 // 因为该节点结果有误所以即时是stableMode也认为trans记录不可信
// 直接通过load别的节点来恢复 // 直接通过load别的节点来恢复
MasterServerRecoverMechAction.restartContractFromCommonMode( MasterServerRecoverMechAction.restartContractFromCommonMode(nodeID,
nodeID, contractID); contractID);
} }
} }
} }

View File

@ -1,39 +1,39 @@
//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;
@ -67,7 +67,8 @@
// // TODO 加对应的超时 // // TODO 加对应的超时
// return new ResultCollector( // return new ResultCollector(
// requestID, // requestID,
// new MultiPointCooperationExecutor.ResultMerger(originalCb, count, request_seq, contractID, joinInfo), // new MultiPointCooperationExecutor.ResultMerger(originalCb, count, request_seq, contractID,
// joinInfo),
// count); // 把count改成了1设置成获得1个响应就行 // count); // 把count改成了1设置成获得1个响应就行
// } // }
// //
@ -98,7 +99,8 @@
// } // }
// } // }
// //
// private String[] getAccordingToRouteInfo(RouteInfo routeInfo, ContractRequest req, String[] members) { // private String[] getAccordingToRouteInfo(RouteInfo routeInfo, ContractRequest req, String[]
// members) {
// try { // try {
// int val; // int val;
// switch (routeInfo.useDefault) { // switch (routeInfo.useDefault) {
@ -155,7 +157,8 @@
// } // }
// //
// @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.info("[MultiPointCooperationExecutor] execute " + JsonUtil.toJson(req)); // LOGGER.info("[MultiPointCooperationExecutor] execute " + JsonUtil.toJson(req));
// // 获得action 函数名 // // 获得action 函数名
// LOGGER.info("action is : " + req.getAction()); // LOGGER.info("action is : " + req.getAction());
@ -397,4 +400,4 @@
// } // }
// } // }
// } // }
//} // }

View File

@ -1,25 +1,25 @@
//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);
@ -29,7 +29,8 @@
// } // }
// //
// @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
@ -47,7 +48,8 @@
// } // }
// }; // };
// MasterServerTCPAction.sync.sleep(requestID, cb); // MasterServerTCPAction.sync.sleep(requestID, cb);
// String[] members = CMActions.manager.multiContractRecorder.getMultiContractMeta(contractID).getMembers(); // String[] members =
// CMActions.manager.multiContractRecorder.getMultiContractMeta(contractID).getMembers();
// for (int i = 0; i < members.length; i++) { // for (int i = 0; i < members.length; i++) {
// LOGGER.info("[members]:" + members.length); // LOGGER.info("[members]:" + members.length);
// int size = members.length; // int size = members.length;
@ -65,4 +67,4 @@
// "{\"status\":\"Error\",\"result\":\"all nodes " // "{\"status\":\"Error\",\"result\":\"all nodes "
// + " offline\",\"action\":\"onExecuteContract\"}"); // + " offline\",\"action\":\"onExecuteContract\"}");
// } // }
//} // }

View File

@ -1,24 +1,24 @@
//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);
@ -28,7 +28,8 @@
// } // }
// //
// @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);
// } // }
// //
@ -63,11 +64,13 @@
// 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) { // private boolean sendOnce(String requestID, ContractRequest req) {
// String[] members = CMActions.manager.multiContractRecorder.getMultiContractMeta(contractID).getMembers(); // String[] members =
// CMActions.manager.multiContractRecorder.getMultiContractMeta(contractID).getMembers();
// for (int i = 0; i < members.length; i++) { // for (int i = 0; i < members.length; i++) {
// int size = members.length; // int size = members.length;
// String nodeID = members[order.incrementAndGet() % size]; // String nodeID = members[order.incrementAndGet() % size];
@ -80,4 +83,4 @@
// } // }
// return false; // return false;
// } // }
//} // }

View File

@ -33,24 +33,24 @@ public class _UNUSED_RouteEnabledExecutor implements ContractExecutor {
} }
@Override @Override
public void execute(String requestID, ContractRequest req, ResultCallback rc, OnHashCallback hashCallback) { public void execute(String requestID, ContractRequest req, ResultCallback rc,
OnHashCallback hashCallback) {
executeInternal(requestID, rc, req, 2); executeInternal(requestID, rc, req, 2);
} }
private void executeInternal( private void executeInternal(String requestID, ResultCallback rc, ContractRequest req,
String requestID, ResultCallback rc, ContractRequest req, int count) { 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();
JsonObject result = JsonObject result =
JsonParser.parseString(jo.get("data").getAsString()) JsonParser.parseString(jo.get("data").getAsString()).getAsJsonObject();
.getAsJsonObject(); for (String key : result.keySet())
for (String key : result.keySet()) jo.add(key, result.get(key)); 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());
@ -69,7 +69,8 @@ public class _UNUSED_RouteEnabledExecutor implements ContractExecutor {
req.getArg(); req.getArg();
req.getRequester(); req.getRequester();
req.getAction(); req.getAction();
MultiContractMeta mMeta = CMActions.manager.multiContractRecorder.getMultiContractMeta(meta.getID()); MultiContractMeta mMeta =
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();
@ -77,10 +78,8 @@ 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 = hash = new BigInteger(req.getRequester(), 16)
new BigInteger(req.getRequester(), 16) .mod(BigInteger.valueOf(mMeta.getMembers().length)).intValue();
.mod(BigInteger.valueOf(mMeta.getMembers().length))
.intValue();
break; break;
case byArgHash: case byArgHash:
hash = req.getArg().hashCode(); hash = req.getArg().hashCode();
@ -88,13 +87,15 @@ public class _UNUSED_RouteEnabledExecutor implements ContractExecutor {
} }
} }
String[] members = String[] members = CMActions.manager.multiContractRecorder.getMultiContractMeta(contractID)
CMActions.manager.multiContractRecorder.getMultiContractMeta(contractID).getMembers(); .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) nodeID = members[hash % size]; if (hash != -1)
else nodeID = members[order.incrementAndGet() % size]; nodeID = members[hash % 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

@ -44,11 +44,8 @@ public class CMHttpHandler extends SimpleChannelInboundHandler<HttpObject> {
URIHandler uriHandlers; URIHandler uriHandlers;
public CMHttpHandler() { public CMHttpHandler() {
FileFilter fileFilter = FileFilter fileFilter = pathname -> !pathname.getName().equals("CenterPortal.html")
pathname -> && !pathname.getAbsolutePath().contains(".."); // TODO 路径判断过滤下载任意文件
!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({"/"})
@ -57,8 +54,8 @@ public class CMHttpHandler extends SimpleChannelInboundHandler<HttpObject> {
channelRead0(ctx, request); channelRead0(ctx, request);
} }
}; };
HttpFileHandleAdapter otherFileService = new HttpFileHandleAdapter( HttpFileHandleAdapter otherFileService =
new File("./WebContent/").getAbsolutePath(), fileFilter) { new HttpFileHandleAdapter(new File("./WebContent/").getAbsolutePath(), fileFilter) {
@URIPath({"/client/", "/doc/", "/blog/"}) @URIPath({"/client/", "/doc/", "/blog/"})
private void handleFile(ChannelHandlerContext ctx, FullHttpRequest request) private void handleFile(ChannelHandlerContext ctx, FullHttpRequest request)
throws Exception { throws Exception {
@ -67,19 +64,11 @@ public class CMHttpHandler extends SimpleChannelInboundHandler<HttpObject> {
}; };
UserManagerAction userManagerAction = new UserManagerAction(null); UserManagerAction userManagerAction = new UserManagerAction(null);
MasterWSAction masterWSAction = new MasterWSAction(null); MasterWSAction masterWSAction = new MasterWSAction(null);
actionExecutor = actionExecutor = new ActionExecutor<ResultCallback, JsonObject>(
new ActionExecutor<ResultCallback, JsonObject>( ContractManagerFrameHandler.executorService, new CMActions(),
ContractManagerFrameHandler.executorService, ManagerActions.instance, new FileActions(null), userManagerAction, masterWSAction,
new CMActions(), GRPCPool.instance, new HttpFileAction(), new BDIndexerAction(),
ManagerActions.instance, LedgerActions.instance, new CMLogAction(), new TemporyTestAction()) {
new FileActions(null),
userManagerAction, masterWSAction,
GRPCPool.instance,
new HttpFileAction(),
new BDIndexerAction(),
LedgerActions.instance,
new CMLogAction(),
new TemporyTestAction()) {
@Override @Override
public boolean checkPermission(Action a, JsonObject arg, long per) { public boolean checkPermission(Action a, JsonObject arg, long per) {
boolean flag = a.httpAccess(); boolean flag = a.httpAccess();
@ -107,14 +96,9 @@ public class CMHttpHandler extends SimpleChannelInboundHandler<HttpObject> {
if (arg.has("pubKey")) { if (arg.has("pubKey")) {
pubkey = arg.get("pubKey").getAsString(); pubkey = arg.get("pubKey").getAsString();
} }
TimeDBUtil.instance.put( TimeDBUtil.instance.put(CMTables.LocalNodeLogDB.toString(), String.format(
CMTables.LocalNodeLogDB.toString(),
String.format(
"{\"action\":\"%s\",\"pubKey\":\"%s\",\"status\":\"%s\",\"date\":%d}", "{\"action\":\"%s\",\"pubKey\":\"%s\",\"status\":\"%s\",\"date\":%d}",
action, action, pubkey, status, System.currentTimeMillis()));
pubkey,
status,
System.currentTimeMillis()));
return flag && flag2; return flag && flag2;
} }
}; };
@ -166,20 +150,15 @@ 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 = DefaultFullHttpResponse fullResponse = new DefaultFullHttpResponse(
new DefaultFullHttpResponse( request.protocolVersion(), OK, Unpooled.wrappedBuffer("success".getBytes()));
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.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!");
@ -187,14 +166,17 @@ public class CMHttpHandler extends SimpleChannelInboundHandler<HttpObject> {
@URIPath({"/SCIDE/CMManager", "/SCIDE/SCManager", "/BDO"}) @URIPath({"/SCIDE/CMManager", "/SCIDE/SCManager", "/BDO"})
public void handleHttpGet(ChannelHandlerContext ctx, FullHttpRequest msg) throws Exception { public void handleHttpGet(ChannelHandlerContext ctx, FullHttpRequest msg) throws Exception {
JsonObject transformedParam = ArgParser.parseGetAndVerify(msg, new ArgParser.VerifiedCallback() { JsonObject transformedParam =
ArgParser.parseGetAndVerify(msg, new ArgParser.VerifiedCallback() {
@Override @Override
public void onResult(boolean verified, JsonObject transformedParam) { public void onResult(boolean verified, JsonObject transformedParam) {
LOGGER.info("verify signature: " + verified + " " + transformedParam.toString()); LOGGER.info("verify signature: " + verified + " "
+ transformedParam.toString());
if (verified) { if (verified) {
// 查permission // 查permission
String pubkey = transformedParam.get("pubKey").getAsString(); String pubkey = transformedParam.get("pubKey").getAsString();
String ret = KeyValueDBUtil.instance.getValue(CMTables.NodeRole.toString(), pubkey); String ret = KeyValueDBUtil.instance
.getValue(CMTables.NodeRole.toString(), pubkey);
long permission; long permission;
if (ret != null && ret.length() > 0) { if (ret != null && ret.length() > 0) {
permission = 0x86000d41L | Role.compoundValue(ret.split(",")); permission = 0x86000d41L | Role.compoundValue(ret.split(","));
@ -204,17 +186,15 @@ public class CMHttpHandler extends SimpleChannelInboundHandler<HttpObject> {
} }
transformedParam.addProperty("permission", permission); transformedParam.addProperty("permission", permission);
LOGGER.info("user permission: " + permission); LOGGER.info("user permission: " + permission);
transformedParam.addProperty( transformedParam.addProperty("verifiedPubKey",
"verifiedPubKey", transformedParam.get("pubKey").getAsString()); transformedParam.get("pubKey").getAsString());
} }
} }
}); });
handleReq(transformedParam, ctx, msg); handleReq(transformedParam, ctx, msg);
} }
@URIPath( @URIPath(method = HttpMethod.POST, value = {"/SCIDE/CMManager", "/SCIDE/SCManager", "/BDO"})
method = HttpMethod.POST,
value = {"/SCIDE/CMManager", "/SCIDE/SCManager", "/BDO"})
public void handleHttpPost(ChannelHandlerContext ctx, FullHttpRequest msg) public void handleHttpPost(ChannelHandlerContext ctx, FullHttpRequest msg)
throws UnsupportedEncodingException { throws UnsupportedEncodingException {
// http请求中规定签名必须是最后一个且公钥名必须为pubKey否则验签失败 // http请求中规定签名必须是最后一个且公钥名必须为pubKey否则验签失败
@ -242,10 +222,7 @@ public class CMHttpHandler extends SimpleChannelInboundHandler<HttpObject> {
String str = "action:" + action; String str = "action:" + action;
boolean verify = false; boolean verify = false;
try { try {
verify = verify = SM2Util.plainStrVerify(map.get("pubKey").getAsString(), str,
SM2Util.plainStrVerify(
map.get("pubKey").getAsString(),
str,
map.get("sign").getAsString()); map.get("sign").getAsString());
} catch (Exception e) { } catch (Exception e) {
LOGGER.error(e.getMessage()); LOGGER.error(e.getMessage());
@ -279,9 +256,8 @@ 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 = DefaultFullHttpResponse response = new DefaultFullHttpResponse(HttpVersion.HTTP_1_1,
new DefaultFullHttpResponse( OK, Unpooled.wrappedBuffer(ret));
HttpVersion.HTTP_1_1, OK, Unpooled.wrappedBuffer(ret));
response.headers().add("Access-Control-Allow-Origin", "*"); response.headers().add("Access-Control-Allow-Origin", "*");
response.headers().add("Access-Control-Allow-Methods", "*"); response.headers().add("Access-Control-Allow-Methods", "*");
ChannelFuture f = ctx.write(response); ChannelFuture f = ctx.write(response);
@ -323,10 +299,7 @@ public class CMHttpHandler extends SimpleChannelInboundHandler<HttpObject> {
actionExecutor.handle(action, map, cb); actionExecutor.handle(action, map, cb);
} }
} catch (IllegalArgumentException e) { } catch (IllegalArgumentException e) {
DefaultFullHttpResponse response = DefaultFullHttpResponse response = new DefaultFullHttpResponse(HttpVersion.HTTP_1_1, OK,
new DefaultFullHttpResponse(
HttpVersion.HTTP_1_1,
OK,
Unpooled.wrappedBuffer(e.getMessage().getBytes())); Unpooled.wrappedBuffer(e.getMessage().getBytes()));
response.headers().add("Access-Control-Allow-Origin", "*"); response.headers().add("Access-Control-Allow-Origin", "*");
response.headers().add("Access-Control-Allow-Methods", "*"); response.headers().add("Access-Control-Allow-Methods", "*");
@ -335,10 +308,7 @@ public class CMHttpHandler extends SimpleChannelInboundHandler<HttpObject> {
} 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 = DefaultFullHttpResponse response = new DefaultFullHttpResponse(HttpVersion.HTTP_1_1, OK,
new DefaultFullHttpResponse(
HttpVersion.HTTP_1_1,
OK,
Unpooled.wrappedBuffer(JsonUtil.toJson(ret).getBytes())); Unpooled.wrappedBuffer(JsonUtil.toJson(ret).getBytes()));
response.headers().add("Access-Control-Allow-Origin", "*"); response.headers().add("Access-Control-Allow-Origin", "*");
response.headers().add("Access-Control-Allow-Methods", "*"); response.headers().add("Access-Control-Allow-Methods", "*");
@ -349,7 +319,8 @@ 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) + ": " + cause.getClass().getSimpleName()); LOGGER.warn("catch exception in " + parseCtx2String(ctx) + ": "
+ cause.getClass().getSimpleName());
LOGGER.debug(ExceptionUtil.exceptionToString(cause)); LOGGER.debug(ExceptionUtil.exceptionToString(cause));
// ctx.close(); // ctx.close();
} }

View File

@ -62,25 +62,16 @@ 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( CMActions.executeContractInternal(arg, new ResultCallback() {
arg,
new ResultCallback() {
@Override @Override
public void onResult(String str) { public void onResult(String str) {
FullHttpResponse response = FullHttpResponse response = new DefaultFullHttpResponse(HTTP_1_1,
new DefaultFullHttpResponse( HttpResponseStatus.OK, Unpooled.wrappedBuffer(str.getBytes()));
HTTP_1_1, response.headers().set(HttpHeaderNames.CONTENT_TYPE,
HttpResponseStatus.OK,
Unpooled.wrappedBuffer(str.getBytes()));
response.headers()
.set(
HttpHeaderNames.CONTENT_TYPE,
"text/plain; charset=UTF-8"); "text/plain; charset=UTF-8");
ctx.writeAndFlush(response) ctx.writeAndFlush(response).addListener(ChannelFutureListener.CLOSE);
.addListener(ChannelFutureListener.CLOSE);
} }
}, }, null);
null);
} else { } else {
switch (defaultOp) { switch (defaultOp) {
case ListOps: case ListOps:
@ -105,10 +96,7 @@ 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 = FullHttpResponse response = new DefaultFullHttpResponse(HTTP_1_1, HttpResponseStatus.OK,
new DefaultFullHttpResponse(
HTTP_1_1,
HttpResponseStatus.OK,
Unpooled.wrappedBuffer(bo.toByteArray())); 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);
@ -118,12 +106,9 @@ 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( ret.addProperty("data",
"data", CMActions.manager.listTheContracts(arg.get("contractID").getAsString())); CMActions.manager.listTheContracts(arg.get("contractID").getAsString()));
FullHttpResponse response = FullHttpResponse response = new DefaultFullHttpResponse(HTTP_1_1, HttpResponseStatus.OK,
new DefaultFullHttpResponse(
HTTP_1_1,
HttpResponseStatus.OK,
Unpooled.wrappedBuffer(JsonUtil.toJson(ret).getBytes())); 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);
@ -131,9 +116,8 @@ public class DOIPOverHttpHandler {
private void sendYpk(JsonObject arg, ChannelHandlerContext ctx, FullHttpRequest request) private void sendYpk(JsonObject arg, ChannelHandlerContext ctx, FullHttpRequest request)
throws IOException { throws IOException {
ContractMeta meta = ContractMeta meta = CMActions.manager.statusRecorder
CMActions.manager.statusRecorder.getContractMeta( .getContractMeta(arg.get("contractID").getAsString());
arg.get("contractID").getAsString());
if (meta == null) { if (meta == null) {
HttpFileHandleAdapter.sendError(ctx, HttpResponseStatus.NOT_FOUND); HttpFileHandleAdapter.sendError(ctx, HttpResponseStatus.NOT_FOUND);
return; return;
@ -168,9 +152,8 @@ public class DOIPOverHttpHandler {
} }
private void sendPublicFiles(JsonObject arg, ChannelHandlerContext ctx) throws Exception { private void sendPublicFiles(JsonObject arg, ChannelHandlerContext ctx) throws Exception {
ContractMeta meta = ContractMeta meta = CMActions.manager.statusRecorder
CMActions.manager.statusRecorder.getContractMeta( .getContractMeta(arg.get("contractID").getAsString());
arg.get("contractID").getAsString());
if (meta == null) { if (meta == null) {
HttpFileHandleAdapter.sendError(ctx, HttpResponseStatus.NOT_FOUND); HttpFileHandleAdapter.sendError(ctx, HttpResponseStatus.NOT_FOUND);
return; return;
@ -193,8 +176,7 @@ public class DOIPOverHttpHandler {
HttpFileHandleAdapter.appendContentType(path, response.headers()); HttpFileHandleAdapter.appendContentType(path, response.headers());
ctx.write(response); ctx.write(response);
ChannelFuture future = ctx.writeAndFlush(new ChunkedStream(fin)); ChannelFuture future = ctx.writeAndFlush(new ChunkedStream(fin));
future.addListener( future.addListener(new GenericFutureListener<Future<? super Void>>() {
new GenericFutureListener<Future<? super Void>>() {
@Override @Override
public void operationComplete(Future<? super Void> arg0) throws Exception { public void operationComplete(Future<? super Void> arg0) throws Exception {
ctx.writeAndFlush(LastHttpContent.EMPTY_LAST_CONTENT); ctx.writeAndFlush(LastHttpContent.EMPTY_LAST_CONTENT);
@ -207,9 +189,8 @@ public class DOIPOverHttpHandler {
} }
private void sendAssets(JsonObject arg, ChannelHandlerContext ctx) throws Exception { private void sendAssets(JsonObject arg, ChannelHandlerContext ctx) throws Exception {
ContractMeta meta = ContractMeta meta = CMActions.manager.statusRecorder
CMActions.manager.statusRecorder.getContractMeta( .getContractMeta(arg.get("contractID").getAsString());
arg.get("contractID").getAsString());
if (meta == null) { if (meta == null) {
HttpFileHandleAdapter.sendError(ctx, HttpResponseStatus.NOT_FOUND); HttpFileHandleAdapter.sendError(ctx, HttpResponseStatus.NOT_FOUND);
return; return;
@ -226,8 +207,7 @@ public class DOIPOverHttpHandler {
HttpFileHandleAdapter.appendContentType(path, response.headers()); HttpFileHandleAdapter.appendContentType(path, response.headers());
ctx.write(response); ctx.write(response);
ChannelFuture future = ctx.writeAndFlush(new ChunkedStream(in)); ChannelFuture future = ctx.writeAndFlush(new ChunkedStream(in));
future.addListener( future.addListener(new GenericFutureListener<Future<? super Void>>() {
new GenericFutureListener<Future<? super Void>>() {
@Override @Override
public void operationComplete(Future<? super Void> arg0) throws Exception { public void operationComplete(Future<? super Void> arg0) throws Exception {
ctx.writeAndFlush(LastHttpContent.EMPTY_LAST_CONTENT); ctx.writeAndFlush(LastHttpContent.EMPTY_LAST_CONTENT);
@ -244,16 +224,14 @@ public class DOIPOverHttpHandler {
ZipFile cachedFile = zipFilePool.get(scriptStr); ZipFile cachedFile = zipFilePool.get(scriptStr);
if (cachedFile == null) { if (cachedFile == null) {
File f = new File(scriptStr); File f = new File(scriptStr);
cachedFile = cachedFile = new ZipFile(f);
new ZipFile(f);
zipFilePool.put(scriptStr, cachedFile); zipFilePool.put(scriptStr, cachedFile);
lastModified.put(scriptStr, f.lastModified()); lastModified.put(scriptStr, f.lastModified());
} else { } else {
File f = new File(scriptStr); File f = new File(scriptStr);
if (lastModified.get(scriptStr) != f.lastModified()) { if (lastModified.get(scriptStr) != f.lastModified()) {
cachedFile.close(); cachedFile.close();
cachedFile = cachedFile = new ZipFile(f);
new ZipFile(f);
zipFilePool.put(scriptStr, cachedFile); zipFilePool.put(scriptStr, cachedFile);
lastModified.put(scriptStr, f.lastModified()); lastModified.put(scriptStr, f.lastModified());
} }
@ -275,22 +253,21 @@ 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) str = fulluri.substring(0, index); if (index > 0)
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 = verify = SM2Util.plainStrVerify(transformedParam.get("pubKey").getAsString(), str,
SM2Util.plainStrVerify(
transformedParam.get("pubKey").getAsString(),
str,
transformedParam.get("sign").getAsString()); transformedParam.get("sign").getAsString());
} catch (Exception e) { } catch (Exception e) {
e.printStackTrace(); e.printStackTrace();
} }
if (verify) { if (verify) {
transformedParam.addProperty( transformedParam.addProperty("verifiedPubKey",
"verifiedPubKey", transformedParam.get("pubKey").getAsString()); transformedParam.get("pubKey").getAsString());
} else transformedParam.remove("verifiedPubKey"); } else
transformedParam.remove("verifiedPubKey");
} }
transformedParam.addProperty("contractID", data[2].replaceAll("\\?.*$", "")); transformedParam.addProperty("contractID", data[2].replaceAll("\\?.*$", ""));
if (data.length > 3) { if (data.length > 3) {
@ -325,22 +302,19 @@ 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) transformedParam.addProperty(key, val.get(0)); if (val != null)
transformedParam.addProperty(key, val.get(0));
} }
return transformedParam; return transformedParam;
} }
enum Operations { enum Operations {
Hello("0.DOIP/Op.Hello"), Hello("0.DOIP/Op.Hello"), ListOps("0.DOIP/Op.ListOperations"), Retrieve(
ListOps("0.DOIP/Op.ListOperations"), "0.DOIP/Op.Retrieve"), RetrieveYPK("86.BDWare/Op.RetrieveYPK"), Create(
Retrieve("0.DOIP/Op.Retrieve"), "0.DOIP/Op.Create"), Update("0.DOIP/Op.Update"), Delete(
RetrieveYPK("86.BDWare/Op.RetrieveYPK"), "0.DOIP/Op.Delete"), Search("0.DOIP/Op.Search"), Extension(
Create("0.DOIP/Op.Create"), "0.DOIP/Op.Extension"), Unknown("0.DOIP/Op.Unknown");
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) {
@ -349,7 +323,8 @@ 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)) return ops; if (ops.val.equals(str))
return ops;
} }
return null; return null;
} }

View File

@ -123,11 +123,8 @@ 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 = byte[] sig = SM2Util.sign(keyPair.getPrivateKeyParameter(),
SM2Util.sign( (keyPair.getPublicKeyStr() + json.get("session").getAsString()).getBytes());
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();
@ -148,8 +145,8 @@ public class NodeCenterClientController implements NodeCenterConn {
@Action @Action
public void syncPong(JsonObject json, ResultCallback resultCallback) { public void syncPong(JsonObject json, ResultCallback resultCallback) {
sync.wakeUp( sync.wakeUp(json.get("requestID").getAsString(),
json.get("requestID").getAsString(), "{\"status\":\"Success\",\"result\":\"a\"}"); "{\"status\":\"Success\",\"result\":\"a\"}");
} }
public boolean syncPing() { public boolean syncPing() {
@ -172,12 +169,9 @@ public class NodeCenterClientController implements NodeCenterConn {
} }
public void listCMInfo() { public void listCMInfo() {
sendMsg( sendMsg("{\"action\":\"listCMInfo\",\"pubKey\":\""
"{\"action\":\"listCMInfo\",\"pubKey\":\""
+ KeyValueDBUtil.instance.getValue(CMTables.ConfigDB.toString(), "pubKey") + KeyValueDBUtil.instance.getValue(CMTables.ConfigDB.toString(), "pubKey")
+ "\",\"requestID\":\"" + "\",\"requestID\":\"" + System.currentTimeMillis() + "\"}");
+ System.currentTimeMillis()
+ "\"}");
} }
@Action @Action
@ -229,7 +223,8 @@ public class NodeCenterClientController implements NodeCenterConn {
@Action(async = true) @Action(async = true)
public void publishEventFromCenter(JsonObject jo, ResultCallback rcb) { public void publishEventFromCenter(JsonObject jo, ResultCallback rcb) {
if (jo.has("event")) { if (jo.has("event")) {
CMActions.manager.deliverEvent(JsonUtil.fromJson(jo.get("event").getAsString(), REvent.class)); CMActions.manager
.deliverEvent(JsonUtil.fromJson(jo.get("event").getAsString(), REvent.class));
} }
} }
@ -256,7 +251,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());
@ -277,7 +272,8 @@ 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), new ResultCallback() { CMActions.manager.executeLocallyAsync(JsonUtil.fromJson(crStr, ContractRequest.class),
new ResultCallback() {
@Override @Override
public void onResult(String str) { public void onResult(String str) {
JsonObject ret = new JsonObject(); JsonObject ret = new JsonObject();
@ -287,7 +283,7 @@ public class NodeCenterClientController implements NodeCenterConn {
ret.addProperty("contractResult", str); ret.addProperty("contractResult", str);
sendMsg(JsonUtil.toJson(ret)); sendMsg(JsonUtil.toJson(ret));
} }
},null); }, null);
} }
@Action(async = true) @Action(async = true)
@ -357,15 +353,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( NetworkManager.instance.updateAgentRouter(jo.get("pubKey").getAsString(),
jo.get("pubKey").getAsString(), jo.get("masterAddress").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) {
@ -389,18 +385,17 @@ 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( NetworkManager.instance.updateAgentRouter(jo.get("pubKey").getAsString(),
jo.get("pubKey").getAsString(), jo.get("masterAddress").getAsString()); jo.get("masterAddress").getAsString());
NetworkManager.instance.connectToAgent(jo.get("pubKey").getAsString(), null); NetworkManager.instance.connectToAgent(jo.get("pubKey").getAsString(), null);
LOGGER.info( LOGGER.info(String.format("the master of contract %s: pubKey=%s address=%s",
String.format("the master of contract %s: pubKey=%s address=%s", contractID, jo.get("pubKey").getAsString(),
contractID,
jo.get("pubKey").getAsString(),
jo.get("masterAddress").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("the master of contract " + contractID + " is null! " + e.getMessage()); LOGGER.warn(
"the master of contract " + contractID + " is null! " + e.getMessage());
} }
} }
} catch (Exception e) { } catch (Exception e) {
@ -419,8 +414,8 @@ public class NodeCenterClientController implements NodeCenterConn {
return; return;
} }
startCheck = true; startCheck = true;
for (MultiContractMeta meta : for (MultiContractMeta meta : CMActions.manager.multiContractRecorder.getStatus()
CMActions.manager.multiContractRecorder.getStatus().values()) { .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());
@ -434,20 +429,21 @@ 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( if (KeyValueDBUtil.instance.containsKey(CMTables.CheckPointLastHash.toString(),
CMTables.CheckPointLastHash.toString(), contractID)) { contractID)) {
KeyValueDBUtil.instance.delete( KeyValueDBUtil.instance.delete(CMTables.CheckPointLastHash.toString(),
CMTables.CheckPointLastHash.toString(), contractID); contractID);
} }
if (KeyValueDBUtil.instance.containsKey( if (KeyValueDBUtil.instance.containsKey(CMTables.LastExeSeq.toString(),
CMTables.LastExeSeq.toString(), contractID)) { 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:" + contractID); LOGGER.info("queryUnitContractsID master为" + master.substring(0, 5) + " -> 合约id:"
+ contractID);
RecoverMechTimeRecorder.queryMasterFinish = System.currentTimeMillis(); RecoverMechTimeRecorder.queryMasterFinish = System.currentTimeMillis();
queryUnitContractsID2(contractID, master); queryUnitContractsID2(contractID, master);
} }
@ -488,9 +484,7 @@ 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") if (!json.has("requestID") || !json.has("contractID") || !json.has("offset")
|| !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");
@ -566,7 +560,7 @@ public class NodeCenterClientController implements NodeCenterConn {
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;
@ -630,8 +624,8 @@ public class NodeCenterClientController implements NodeCenterConn {
MasterElectTimeRecorder.slaveConnectFinish = System.currentTimeMillis(); MasterElectTimeRecorder.slaveConnectFinish = System.currentTimeMillis();
// 开启master恢复 // 开启master恢复
MasterServerRecoverMechAction.newMasterRecover( MasterServerRecoverMechAction.newMasterRecover(contractID,
contractID, json.get("members").getAsString(), onlineMembers); json.get("members").getAsString(), onlineMembers);
} }
private boolean waitForConnection(List<String> nodeNames) { private boolean waitForConnection(List<String> nodeNames) {
@ -651,7 +645,8 @@ public class NodeCenterClientController implements NodeCenterConn {
e.printStackTrace(); e.printStackTrace();
} }
} }
} else return true; } else
return true;
} }
return false; return false;
} }
@ -667,7 +662,8 @@ public class NodeCenterClientController implements NodeCenterConn {
String distributeID = null; String distributeID = null;
if (json.has("distributeID")) if (json.has("distributeID"))
distributeID = json.get("distributeID").getAsString(); distributeID = json.get("distributeID").getAsString();
else distributeID = json.get("responseID").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());
@ -719,12 +715,10 @@ 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")) uniNumber = jo.get("nuiNumber").getAsString(); if (jo.has("nuiNumber"))
uniNumber = jo.get("nuiNumber").getAsString();
ContractClient cc = CMActions.manager.getClient(conID); ContractClient cc = CMActions.manager.getClient(conID);
LOGGER.info( LOGGER.info("[CMClientController] NCStartElect : contractID=" + conID + " client==null:"
"[CMClientController] NCStartElect : contractID="
+ conID
+ " client==null:"
+ (null == cc)); + (null == cc));
// 不是自己本地的合约 // 不是自己本地的合约
@ -772,7 +766,7 @@ public class NodeCenterClientController implements NodeCenterConn {
} }
public void run() { public void run() {
for (; ; ) { for (;;) {
if (receiveQueue.size() > 0) { if (receiveQueue.size() > 0) {
try { try {
JsonObject jo = receiveQueue.poll(); JsonObject jo = receiveQueue.poll();
@ -799,11 +793,12 @@ public class NodeCenterClientController implements NodeCenterConn {
boolean isAppend = args.get("isAppend").getAsBoolean(); boolean isAppend = args.get("isAppend").getAsBoolean();
boolean isDone = args.get("isDone").getAsBoolean(); boolean isDone = args.get("isDone").getAsBoolean();
boolean isPrivate = args.get("isPrivate").getAsBoolean(); boolean isPrivate = args.get("isPrivate").getAsBoolean();
LOGGER.debug( LOGGER.debug(String.format("isAppend=%b isDone=%b isPrivate=%b", isAppend, isDone,
String.format("isAppend=%b isDone=%b isPrivate=%b", isAppend, isDone, isPrivate)); isPrivate));
String path = GlobalConf.instance.publicCompiledDir; String path = GlobalConf.instance.publicCompiledDir;
if (isPrivate && args.has("pubKey")) { if (isPrivate && args.has("pubKey")) {
path = GlobalConf.instance.privateCompiledDir + "/" + args.get("pubKey").getAsString(); path = GlobalConf.instance.privateCompiledDir + "/"
+ args.get("pubKey").getAsString();
} }
File dir = new File(path); File dir = new File(path);
if (!dir.exists()) { if (!dir.exists()) {

View File

@ -20,7 +20,6 @@ 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;
@ -104,10 +103,7 @@ public class NodeCenterClientHandler extends SimpleChannelInboundHandler<Object>
if (arg.has("action")) { if (arg.has("action")) {
final String action = arg.get("action").getAsString(); final String action = arg.get("action").getAsString();
ae.handle( ae.handle(action, arg, new ResultCallback() {
action,
arg,
new ResultCallback() {
@Override @Override
public void onResult(String str) { public void onResult(String str) {
sendMsg(str); sendMsg(str);
@ -136,7 +132,8 @@ public class NodeCenterClientHandler extends SimpleChannelInboundHandler<Object>
public void close() { public void close() {
try { try {
isConnected = false; isConnected = false;
if (channel != null) channel.close(); if (channel != null)
channel.close();
} catch (Exception e) { } catch (Exception e) {
e.printStackTrace(); e.printStackTrace();
} finally { } finally {

View File

@ -40,16 +40,10 @@ 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<>( ae = new ActionExecutor<>(executorService, aliveCheckClientAction,
executorService, new MasterClientTCPAction(), new MasterClientRecoverMechAction(),
aliveCheckClientAction, MasterClientTransferAction.instance, new MasterServerRecoverMechAction(),
new MasterClientTCPAction(), new MasterServerTransferAction(), new MasterServerTCPAction(), new EventActions());
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);
@ -66,21 +60,22 @@ 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) channel.close(); if (channel != null)
channel.close();
} catch (Exception e) { } catch (Exception e) {
e.printStackTrace(); e.printStackTrace();
} finally { } finally {
@ -108,7 +103,8 @@ public class TCPClientFrameHandler extends SimpleChannelInboundHandler<Object> {
ByteBuf bb = (ByteBuf) frame; ByteBuf bb = (ByteBuf) frame;
JsonObject arg; JsonObject arg;
try { try {
arg = JsonUtil.parseReaderAsJsonObject(new InputStreamReader(new ByteBufInputStream(bb))); arg = JsonUtil
.parseReaderAsJsonObject(new InputStreamReader(new ByteBufInputStream(bb)));
} catch (Exception e) { } catch (Exception e) {
e.printStackTrace(); e.printStackTrace();
Response response = new Response(); Response response = new Response();
@ -126,10 +122,7 @@ public class TCPClientFrameHandler extends SimpleChannelInboundHandler<Object> {
sendMsg(ret); sendMsg(ret);
} }
}); });
ae.handle( ae.handle(action, arg, pc);
action,
arg, pc
);
} catch (IllegalArgumentException e) { } catch (IllegalArgumentException e) {
response = new Response(); response = new Response();
response.action = "onException"; response.action = "onException";
@ -145,12 +138,9 @@ 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") if (s.contains("sun.reflect") || s.contains("java.lang.reflect")
|| s.contains("java.lang.reflect") || s.contains("org.apache") || s.contains("java.util")
|| s.contains("org.apache") || s.contains("java.lang") || s.contains("io.netty")) {
|| s.contains("java.util")
|| s.contains("java.lang")
|| s.contains("io.netty")) {
continue; continue;
} }
ret.append(s); ret.append(s);

View File

@ -31,20 +31,12 @@ public class TCPServerFrameHandler extends SimpleChannelInboundHandler<Object> {
public TCPServerFrameHandler() { public TCPServerFrameHandler() {
checkAction = new AliveCheckServerAction(this); checkAction = new AliveCheckServerAction(this);
ae = ae = new ActionExecutor<ResultCallback, JsonObject>(executorService, checkAction,
new ActionExecutor<ResultCallback, JsonObject>( new MasterClientTCPAction(), new MasterClientRecoverMechAction(),
executorService, MasterClientTransferAction.instance, new MasterServerRecoverMechAction(),
checkAction, new MasterServerTransferAction(), new MasterServerTCPAction(), new EventActions()) {
new MasterClientTCPAction(),
new MasterClientRecoverMechAction(),
MasterClientTransferAction.instance,
new MasterServerRecoverMechAction(),
new MasterServerTransferAction(),
new MasterServerTCPAction(),
new EventActions()) {
@Override @Override
public boolean checkPermission( public boolean checkPermission(Action a, final JsonObject args, long permission) {
Action a, final JsonObject args, long permission) {
return true; return true;
// long val = a.userPermission(); // long val = a.userPermission();
// //
@ -98,7 +90,8 @@ public class TCPServerFrameHandler extends SimpleChannelInboundHandler<Object> {
ByteBuf bb = (ByteBuf) frame; ByteBuf bb = (ByteBuf) frame;
JsonObject arg; JsonObject arg;
try { try {
arg = JsonUtil.parseReaderAsJsonObject(new InputStreamReader(new ByteBufInputStream(bb))); arg = JsonUtil
.parseReaderAsJsonObject(new InputStreamReader(new ByteBufInputStream(bb)));
// logger.info("[MasterServer] receive:" + arg.toString()); // logger.info("[MasterServer] receive:" + arg.toString());
} catch (Exception e) { } catch (Exception e) {
@ -114,16 +107,14 @@ public class TCPServerFrameHandler extends SimpleChannelInboundHandler<Object> {
final String action = arg.get("action").getAsString(); final String action = arg.get("action").getAsString();
PubkeyResultCallback pubkeyResultCallback = new PubkeyResultCallback(checkAction.pubKey, new ResultCallback() { PubkeyResultCallback pubkeyResultCallback =
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();
@ -141,12 +132,9 @@ 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") if (s.contains("sun.reflect") || s.contains("java.lang.reflect")
|| s.contains("java.lang.reflect") || s.contains("org.apache") || s.contains("java.util")
|| s.contains("org.apache") || s.contains("java.lang") || s.contains("io.netty")) {
|| s.contains("java.util")
|| s.contains("java.lang")
|| s.contains("io.netty")) {
continue; continue;
} }
ret.append(s); ret.append(s);

View File

@ -38,17 +38,13 @@ public class AgentManager implements AgentPeerManagerIntf {
if (maxMasterProxyLoad > CongestionControl.maxMasterProxyLoad) if (maxMasterProxyLoad > CongestionControl.maxMasterProxyLoad)
CongestionControl.maxMasterProxyLoad = maxMasterProxyLoad; CongestionControl.maxMasterProxyLoad = maxMasterProxyLoad;
if (CongestionControl.slaveControl()) { if (CongestionControl.slaveControl()) {
ContractResult cr = ContractResult cr = new ContractResult(ContractResult.Status.Error,
new ContractResult(
ContractResult.Status.Error,
new JsonPrimitive("canceled because of queue too long")); 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( MasterServerTCPAction.sync.sleep(c.getRequestID(), new ResultCallback() {
c.getRequestID(),
new ResultCallback() {
@Override @Override
public void onResult(String str) { public void onResult(String str) {
cb.onResult(JsonUtil.parseStringAsJsonObject(str)); cb.onResult(JsonUtil.parseStringAsJsonObject(str));

View File

@ -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 = JsonUtil.fromJson(str, new TypeToken<Map<String, String>>() { Map<String, String> map =
}.getType()); JsonUtil.fromJson(str, new TypeToken<Map<String, String>>() {}.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

@ -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,23 +45,14 @@ 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 = ae = new ActionExecutor<ResultCallback, JsonObject>(executorService, cmAction,
new ActionExecutor<ResultCallback, JsonObject>( // temAction,
executorService, fileAction, ManagerActions.instance, userManagerAction, new MasterWSAction(this), // 多节点执行
cmAction, new CMLogAction(), new ProcessAction(), GRPCPool.instance, new EventWSActions()) {
//temAction,
fileAction,
ManagerActions.instance,
userManagerAction,
new MasterWSAction(this), // 多节点执行
new CMLogAction(),
new ProcessAction(),
GRPCPool.instance,
new EventWSActions()) {
@Override @Override
public boolean checkPermission(Action a, JsonObject arg, long permission) { public boolean checkPermission(Action a, JsonObject arg, long permission) {
long val = a.userPermission(); long val = a.userPermission();
@ -78,22 +69,12 @@ public class ContractManagerFrameHandler extends SimpleChannelInboundHandler<Web
} else { } else {
flag = false; flag = false;
} }
LOGGER.debug( LOGGER.debug(String.format("%s val:%d permission:%d status:%s", action, val,
String.format( permission, status));
"%s val:%d permission:%d status:%s",
action,
val,
permission,
status));
CMHttpServer.nodeLogDB.put( CMHttpServer.nodeLogDB.put(action, String.format(
action,
String.format(
"{\"action\":\"%s\",\"pubKey\":\"%s\",\"status\":\"%s\",\"date\":%d}", "{\"action\":\"%s\",\"pubKey\":\"%s\",\"status\":\"%s\",\"date\":%d}",
action, action, userManagerAction.getPubKey(), status, System.currentTimeMillis()));
userManagerAction.getPubKey(),
status,
System.currentTimeMillis()));
// TimeDBUtil.instance.put(CMTables.LocalNodeLogDB.toString(), // TimeDBUtil.instance.put(CMTables.LocalNodeLogDB.toString(),
// sb.toString()); // sb.toString());
return flag; return flag;
@ -156,8 +137,7 @@ 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() ctx.channel().writeAndFlush(new TextWebSocketFrame(JsonUtil.toJson(response)));
.writeAndFlush(new TextWebSocketFrame(JsonUtil.toJson(response)));
return; return;
} else { } else {
if (dataCache.length() > 0) { if (dataCache.length() > 0) {
@ -170,17 +150,15 @@ 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) initActionExecutor(); if (ae == null)
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( ae.handle(action, map, new ResultCallback(ctx.channel()) {
action,
map,
new ResultCallback(ctx.channel()) {
@Override @Override
public void onResult(Map jo) { public void onResult(Map jo) {
if (jmap.has("requestID")) { if (jmap.has("requestID")) {
@ -239,7 +217,8 @@ public class ContractManagerFrameHandler extends SimpleChannelInboundHandler<Web
} }
ret.append(s); ret.append(s);
ret.append("\n"); ret.append("\n");
if (count++ > 5) break; if (count++ > 5)
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,13 +16,16 @@ 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>http://localhost:8080/websocket * <p>
* http://localhost:8080/websocket
* *
* <p>Open your browser at <a href="http://localhost:8080/">http://localhost:8080/</a>, then the * <p>
* demo page will be loaded and a Web Socket connection will be made automatically. * Open your browser at <a href="http://localhost:8080/">http://localhost:8080/</a>, then the demo
* page will be loaded and a Web Socket connection will be made automatically.
* *
* <p>This server illustrates support for the different web socket specification versions and will * <p>
* work with: * This server illustrates support for the different web socket specification versions and will work
* with:
* *
* <ul> * <ul>
* <li>Safari 5+ (draft-ietf-hybi-thewebsocketprotocol-00) * <li>Safari 5+ (draft-ietf-hybi-thewebsocketprotocol-00)
@ -35,7 +38,8 @@ import org.apache.logging.log4j.Logger;
*/ */
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 = Integer.parseInt(System.getProperty("port", SSL ? "8443" : "8080")); private static final int PORT =
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 {
@ -52,19 +56,14 @@ 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) b.group(bossGroup, workerGroup).channel(NioServerSocketChannel.class)
.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( LOGGER.info("Open your web browser and navigate to " + (SSL ? "https" : "http")
"Open your web browser and navigate to " + "://127.0.0.1:" + PORT + '/');
+ (SSL ? "https" : "http")
+ "://127.0.0.1:"
+ PORT
+ '/');
ch.closeFuture().sync(); ch.closeFuture().sync();
} finally { } finally {

View File

@ -41,10 +41,11 @@ 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 = new ConcurrentHashMap<>(); public static final Map<String, TCPServerFrameHandler> SERVER_CONNECTORS =
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<>();
@ -59,18 +60,13 @@ public class NetworkManager {
} }
public static void reconnectAgent(String master) { public static void reconnectAgent(String master) {
LOGGER.debug( LOGGER.debug(String.format("master=%s\t%s", master, JsonUtil.toJson(slaverRouter)));
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 conn.bootstrap.connect(ipAndPort[0], Integer.parseInt(ipAndPort[1])).sync()
.connect(ipAndPort[0], Integer.parseInt(ipAndPort[1]))
.sync()
.channel(); .channel();
} }
} }
@ -94,21 +90,18 @@ 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) b.channel(NioSocketChannel.class).handler(new ChannelInitializer<SocketChannel>() {
.handler(
new ChannelInitializer<SocketChannel>() {
@Override @Override
protected void initChannel(SocketChannel ch) { protected void initChannel(SocketChannel ch) {
ChannelPipeline p = ch.pipeline(); ChannelPipeline p = ch.pipeline();
p.addLast(new DelimiterCodec()).addLast(nodeCenterClientHandler); p.addLast(new DelimiterCodec()).addLast(nodeCenterClientHandler);
} }
}); });
ContractManager.scheduledThreadPool.scheduleWithFixedDelay( ContractManager.scheduledThreadPool.scheduleWithFixedDelay(() -> {
() -> {
try { try {
// manager.clearCache(); // manager.clearCache();
String URL = GlobalConf.getNodeCenterUrl(); String URL = GlobalConf.getNodeCenterUrl();
// LOGGER.debug("GlobalConf.getNodeCenterUrl() -> URL=" + URL); // LOGGER.debug("GlobalConf.getNodeCenterUrl() -> URL=" + URL);
URI uri = null; URI uri = null;
try { try {
uri = new URI(URL); uri = new URI(URL);
@ -120,20 +113,13 @@ public class NetworkManager {
nodeCenterClientHandler.close(); nodeCenterClientHandler.close();
assert null != uri; assert null != uri;
b.connect(uri.getHost(), uri.getPort()).sync().channel(); b.connect(uri.getHost(), uri.getPort()).sync().channel();
LOGGER.info( LOGGER.info("connect to node center: " + uri.getHost() + ":" + uri.getPort());
"connect to node center: "
+ uri.getHost()
+ ":"
+ uri.getPort());
} }
} catch (Exception e) { } catch (Exception e) {
// e.printStackTrace(); // e.printStackTrace();
LOGGER.warn("connecting to node center failed! " + e.getMessage()); LOGGER.warn("connecting to node center failed! " + e.getMessage());
} }
}, }, 0, 30 + (int) (20 * Math.random()), TimeUnit.SECONDS);
0,
30 + (int) (20 * Math.random()),
TimeUnit.SECONDS);
} }
@ -142,17 +128,13 @@ 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) b.group(bossGroup, workerGroup).channel(NioServerSocketChannel.class)
.channel(NioServerSocketChannel.class) .option(ChannelOption.SO_BACKLOG, 100).localAddress(port)
.option(ChannelOption.SO_BACKLOG, 100)
.localAddress(port)
.childOption(ChannelOption.SO_KEEPALIVE, true) .childOption(ChannelOption.SO_KEEPALIVE, true)
.childHandler( .childHandler(new ChannelInitializer<SocketChannel>() {
new ChannelInitializer<SocketChannel>() {
@Override @Override
protected void initChannel(SocketChannel arg0) { protected void initChannel(SocketChannel arg0) {
arg0.pipeline() arg0.pipeline().addLast(new DelimiterCodec())
.addLast(new DelimiterCodec())
.addLast(new TCPServerFrameHandler()); .addLast(new TCPServerFrameHandler());
} }
}); });
@ -164,7 +146,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);
} }
@ -174,9 +156,8 @@ public class NetworkManager {
} }
public void waitForNodeCenterConnected() { public void waitForNodeCenterConnected() {
for (int i = 0; for (int i = 0; i < 10 && null != nodeCenterClientHandler
i < 10 && null != nodeCenterClientHandler && !nodeCenterClientHandler.isConnected(); && !nodeCenterClientHandler.isConnected(); i++) {
i++) {
try { try {
Thread.sleep(200); Thread.sleep(200);
} catch (InterruptedException e) { } catch (InterruptedException e) {
@ -191,7 +172,7 @@ public class NetworkManager {
} }
} }
//----------AgentNetworkManagement // ----------AgentNetworkManagement
public void updateAgentRouter(String nodeID, String address) { public void updateAgentRouter(String nodeID, String address) {
@ -233,9 +214,7 @@ 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) b.channel(NioSocketChannel.class).handler(new ChannelInitializer<SocketChannel>() {
.handler(
new ChannelInitializer<SocketChannel>() {
@Override @Override
protected void initChannel(SocketChannel ch) { protected void initChannel(SocketChannel ch) {
ChannelPipeline p = ch.pipeline(); ChannelPipeline p = ch.pipeline();
@ -292,8 +271,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)) {
@ -306,13 +285,11 @@ 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) b.group(group).channel(NioSocketChannel.class)
.channel(NioSocketChannel.class)
.remoteAddress(new InetSocketAddress(host, port)) .remoteAddress(new InetSocketAddress(host, port))
.option(ChannelOption.TCP_NODELAY, true) .option(ChannelOption.TCP_NODELAY, true)
.handler( .handler(new ChannelInitializer<SocketChannel>() {
new ChannelInitializer<SocketChannel>() {
@Override @Override
public void initChannel(SocketChannel ch) throws Exception { public void initChannel(SocketChannel ch) throws Exception {
ch.pipeline() ch.pipeline()
@ -368,17 +345,16 @@ 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, null); // tcpClientFrameHandler = NetworkManager.instance.tcpClientMap.getOrDefault(peer,
// 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 = UnitMessage unitMessage = msg.toBuilder().clearReceiver().addReceiver(peer).build();
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 = UnitMessage unitMessage = msg.toBuilder().clearReceiver().addReceiver(peer).build();
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,6 +1,5 @@
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;
@ -11,29 +10,33 @@ 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,6 +4,7 @@ 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

@ -24,7 +24,7 @@ public class PBFTCenter implements ConsensusCenter {
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,32 +59,33 @@ 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 = MultiPointContractInfo contractInfo = JsonUtil
JsonUtil.fromJson(unitSequencingMessage.content, MultiPointContractInfo.class); .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:
@ -111,7 +112,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;
@ -138,7 +139,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:
@ -152,7 +153,8 @@ public class PBFTCenter implements ConsensusCenter {
} }
private void broadcast(UnitSequencingMessage msg) { private void broadcast(UnitSequencingMessage msg) {
SequencingManager.instance.send(JsonUtil.toJson(msg), contractInfo.getMembers().toArray(new String[0])); SequencingManager.instance.send(JsonUtil.toJson(msg),
contractInfo.getMembers().toArray(new String[0]));
} }
class PBFTInfo { class PBFTInfo {
@ -175,7 +177,8 @@ public class PBFTCenter implements ConsensusCenter {
isPrePrepareReceived = false; isPrePrepareReceived = false;
} }
public synchronized boolean updatePrepare(UnitSequencingMessage message, PBFTCenter center) { public synchronized boolean updatePrepare(UnitSequencingMessage message,
PBFTCenter center) {
if (isSendCommit) { if (isSendCommit) {
return false; return false;
} }
@ -209,18 +212,15 @@ public class PBFTCenter implements ConsensusCenter {
} }
public String getDisplayStr() { public String getDisplayStr() {
return String.format( return String.format("pSize=%d cSize=%d isSendCommit=%b isSendReply=%b buffSize=%d",
"pSize=%d cSize=%d isSendCommit=%b isSendReply=%b buffSize=%d", null == prepare ? -1 : prepare.size(), null == commit ? -1 : commit.size(),
null == prepare ? -1 : prepare.size(), isSendCommit, isSendReply, buff.size());
null == commit ? -1 : commit.size(),
isSendCommit,
isSendReply,
buff.size());
} }
public UnitSequencingMessage formPrepare(UnitSequencingMessage unitSequencingMessage) { public UnitSequencingMessage formPrepare(UnitSequencingMessage unitSequencingMessage) {
// UnitSequencingMessage prepareMsg = new UnitSequencingMessage(ConsensusStage.Prepare.toInt()); // UnitSequencingMessage prepareMsg = new
// prepareMsg.order = this.order; // UnitSequencingMessage(ConsensusStage.Prepare.toInt());
// 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,17 +228,19 @@ public class PBFTCenter implements ConsensusCenter {
} }
public void requestPrePrepareFromMaster() { public void requestPrePrepareFromMaster() {
UnitSequencingMessage requestMsg = new UnitSequencingMessage(ConsensusStage.ReSend.toInt()); UnitSequencingMessage requestMsg =
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(ConsensusStage.Commit.toInt()); // UnitSequencingMessage commitMsg = new
// unitSequencingMessage.order = this.order; // UnitSequencingMessage(ConsensusStage.Commit.toInt());
// 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();
@ -246,7 +248,8 @@ public class PBFTCenter implements ConsensusCenter {
} }
public void onCommit() { public void onCommit() {
UnitContractMessage unitContractMessage = JsonUtil.fromJson(request, UnitContractMessage.class); UnitContractMessage unitContractMessage =
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,8 +10,7 @@ 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 = MultiPointContractInfo contractInfo = JsonUtil
JsonUtil.fromJson(unitSequencingMessage.content, MultiPointContractInfo.class); .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,8 +102,7 @@ public class SingleCenter implements ConsensusCenter {
} }
private void broadcast(UnitSequencingMessage msg) { private void broadcast(UnitSequencingMessage msg) {
SequencingManager.instance.send( SequencingManager.instance.send(JsonUtil.toJson(msg),
JsonUtil.toJson(msg),
contractInfo.getMembers().toArray(new String[contractInfo.members.size()])); contractInfo.getMembers().toArray(new String[contractInfo.members.size()]));
} }
@ -116,7 +115,8 @@ public class SingleCenter implements ConsensusCenter {
isSendReply = false; isSendReply = false;
} }
public synchronized boolean updateCommit(UnitSequencingMessage message, SingleCenter center) { public synchronized boolean updateCommit(UnitSequencingMessage message,
SingleCenter center) {
if (isSendReply) { if (isSendReply) {
return false; return false;
} }
@ -126,7 +126,8 @@ public class SingleCenter implements ConsensusCenter {
} }
public void onCommit() { public void onCommit() {
UnitContractMessage unitContractMessage = JsonUtil.fromJson(request, UnitContractMessage.class); UnitContractMessage unitContractMessage =
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,7 +1,8 @@
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(7), AddMember(8); Init(0), Request(1), PrePrepare(2), Prepare(3), Commit(4), Reply(5), Unknown(6), ReSend(
7), AddMember(8);
private int type; private int type;

View File

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

View File

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

View File

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

View File

@ -26,7 +26,8 @@ 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 = this.addRequestIdAndGetMessage(requestId, msg, peers); BDLedgerContract.UnitMessage unitMessage =
this.addRequestIdAndGetMessage(requestId, msg, peers);
NetworkManager.instance.send(unitMessage); NetworkManager.instance.send(unitMessage);
} }
@ -39,7 +40,8 @@ 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 = this.addRequestIdAndGetMessage(requestId, msg, peers); BDLedgerContract.UnitMessage unitMessage =
this.addRequestIdAndGetMessage(requestId, msg, peers);
NetworkManager.instance.send(unitMessage); NetworkManager.instance.send(unitMessage);
requestCallbacks.put(requestId, resultCallback); requestCallbacks.put(requestId, resultCallback);
} }
@ -58,10 +60,8 @@ public class BaseFunctionManager {
System.out.println("[BaseFunctionManager] handleResponse null"); System.out.println("[BaseFunctionManager] handleResponse null");
return; return;
} }
if (responseCenter.updateReply( if (responseCenter.updateReply(arg.get("content").getAsString(),
arg.get("content").getAsString(), arg.get("sender").getAsString(), arg.get("pubkey").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, String[] peers) { private BDLedgerContract.UnitMessage addRequestIdAndGetMessage(String requestId, String msg,
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()) .setMsgType(getMessageType()).setSender(GlobalConf.instance.peerID)
.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,16 +87,12 @@ public class BaseFunctionManager {
return builder.build(); return builder.build();
} }
private BDLedgerContract.UnitMessage addRequestIdAndGetMessage( private BDLedgerContract.UnitMessage addRequestIdAndGetMessage(String requestId, String msg,
String requestId, String[] peers, BDLedgerContract.UnitMessageType unitMessageType) {
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) .setMsgType(unitMessageType).setSender(GlobalConf.instance.peerID)
.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,9 +34,10 @@ 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 = BDLedgerContract.UnitMessageType.UnitCommunicateMessage; private final BDLedgerContract.UnitMessageType UNIT_MESSAGE_TYPE =
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;
@ -49,11 +50,8 @@ 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>( instance.ae = new ActionExecutor<ResultCallback, JsonObject>(executorService,
executorService, instance.nodeCenterClientController, instance.communicationAction) {
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;
@ -67,11 +65,9 @@ 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() UnitMessage unitMessage = UnitMessage.newBuilder().setSender(GlobalConf.instance.peerID)
.setSender(GlobalConf.instance.peerID)
.setMsgType(BDLedgerContract.UnitMessageType.UnitCommunicateMessage) .setMsgType(BDLedgerContract.UnitMessageType.UnitCommunicateMessage)
.setContent(ByteString.copyFromUtf8(msg)) .setContent(ByteString.copyFromUtf8(msg)).build();
.build();
NetworkManager.instance.sendTo(unitMessage, symbol); NetworkManager.instance.sendTo(unitMessage, symbol);
} }
@ -81,39 +77,38 @@ 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, ae.handle(action, arg, new ResultCallback() {
new ResultCallback() {
@Override @Override
public void onResult(String arg) { public void onResult(String arg) {
System.out.println("[CommunicationManager] onResult"); System.out.println("[CommunicationManager] onResult");
// CommunicationManager.instance.send(arg, new String[]{sender}); // 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();
@ -124,12 +119,9 @@ 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") if (s.contains("sun.reflect") || s.contains("java.lang.reflect")
|| s.contains("java.lang.reflect") || s.contains("org.apache") || s.contains("java.util")
|| s.contains("org.apache") || s.contains("java.lang") || s.contains("io.netty")) {
|| s.contains("java.util")
|| s.contains("java.lang")
|| s.contains("io.netty")) {
continue; continue;
} }
ret.append(s); ret.append(s);
@ -149,11 +141,9 @@ 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() UnitMessage unitMessage = UnitMessage.newBuilder().setSender(GlobalConf.instance.peerID)
.setSender(GlobalConf.instance.peerID)
.setMsgType(BDLedgerContract.UnitMessageType.UnitCommunicateMessage) .setMsgType(BDLedgerContract.UnitMessageType.UnitCommunicateMessage)
.setContent(ByteString.copyFromUtf8(jsonObject.toString())) .setContent(ByteString.copyFromUtf8(jsonObject.toString())).build();
.build();
NetworkManager.instance.send(unitMessage, NetworkType.P2P); NetworkManager.instance.send(unitMessage, NetworkType.P2P);
} }
@ -186,11 +176,9 @@ 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() UnitMessage unitMessage = UnitMessage.newBuilder().setSender(GlobalConf.instance.peerID)
.setSender(GlobalConf.instance.peerID)
.setMsgType(BDLedgerContract.UnitMessageType.UnitCommunicateMessage) .setMsgType(BDLedgerContract.UnitMessageType.UnitCommunicateMessage)
.setContent(ByteString.copyFromUtf8(jsonObject.toString())) .setContent(ByteString.copyFromUtf8(jsonObject.toString())).build();
.build();
NetworkManager.instance.send(unitMessage, NetworkType.P2P); NetworkManager.instance.send(unitMessage, NetworkType.P2P);
} }
@ -206,5 +194,4 @@ public class CommunicationManager extends BaseFunctionManager {
} }

View File

@ -26,15 +26,17 @@ 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 = BDLedgerContract.UnitMessageType.UnitUnitMessage; // init after all static is inited final private BDLedgerContract.UnitMessageType UNIT_MESSAGE_TYPE =
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 = new ConcurrentHashMap<>(); private final Map<String, MultiPointContractInfo> contractID2Members =
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) {
@ -42,7 +44,8 @@ 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.unitsInfoActions) { instance.actionExecutor = new ActionExecutor<ResultCallback, JsonObject>(executorService,
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;
@ -62,18 +65,17 @@ public class ContractUnitManager extends BaseFunctionManager {
return; return;
} }
LOGGER.info("[ContractUnitManager] handle:" + arg); LOGGER.info("[ContractUnitManager] handle:" + arg);
actionExecutor.handle(action, arg, actionExecutor.handle(action, arg, new ResultCallback() {
new ResultCallback() {
@Override @Override
public void onResult(String arg) { public void onResult(String arg) {
ContractUnitManager.instance.send(arg, new String[]{sender}); 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();
@ -84,12 +86,9 @@ 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") if (s.contains("sun.reflect") || s.contains("java.lang.reflect")
|| s.contains("java.lang.reflect") || s.contains("org.apache") || s.contains("java.util")
|| s.contains("org.apache") || s.contains("java.lang") || s.contains("io.netty")) {
|| s.contains("java.util")
|| s.contains("java.lang")
|| s.contains("io.netty")) {
continue; continue;
} }
ret.append(s); ret.append(s);

View File

@ -54,8 +54,7 @@ public class ExecutionManager extends BaseFunctionManager {
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) {
@ -64,13 +63,11 @@ public class ExecutionManager extends BaseFunctionManager {
instance = new ExecutionManager(); instance = new ExecutionManager();
// instance.masterActions = new MasterServerTCPAction(); // instance.masterActions = new MasterServerTCPAction();
// instance.clientActions = new MasterClientTCPAction(); // instance.clientActions = new MasterClientTCPAction();
instance.actionExecutor = instance.actionExecutor = new ActionExecutor<ResultCallback, JsonObject>(executorService) { // ,
new ActionExecutor<ResultCallback, JsonObject>( // instance.masterActions,
executorService) { // , instance.masterActions,
// instance.clientActions) { // instance.clientActions) {
@Override @Override
public boolean checkPermission( public boolean checkPermission(Action a, final JsonObject args, long permission) {
Action a, final JsonObject args, long permission) {
return true; return true;
} }
}; };
@ -89,15 +86,11 @@ public class ExecutionManager extends BaseFunctionManager {
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( actionExecutor.handle(action, arg, new ResultCallback() {
action,
arg,
new ResultCallback() {
@Override @Override
public void onResult(String msg) { public void onResult(String msg) {
try { try {
UnitMessage unitMessage = UnitMessage unitMessage = UnitMessage.parseFrom(ByteUtil.decodeBASE64(msg));
UnitMessage.parseFrom(ByteUtil.decodeBASE64(msg));
NetworkManager.instance.send(unitMessage); NetworkManager.instance.send(unitMessage);
} catch (InvalidProtocolBufferException e) { } catch (InvalidProtocolBufferException e) {
e.printStackTrace(); e.printStackTrace();
@ -108,7 +101,7 @@ public class ExecutionManager extends BaseFunctionManager {
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();
@ -119,12 +112,9 @@ 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") if (s.contains("sun.reflect") || s.contains("java.lang.reflect")
|| s.contains("java.lang.reflect") || s.contains("org.apache") || s.contains("java.util")
|| s.contains("org.apache") || s.contains("java.lang") || s.contains("io.netty")) {
|| s.contains("java.util")
|| s.contains("java.lang")
|| s.contains("io.netty")) {
continue; continue;
} }
ret.append(s); ret.append(s);
@ -164,21 +154,15 @@ 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 = ResponseCenter responseCenter = new ResponseCenter(requestId, rc, peers.length,
new ResponseCenter( UnitContractRequestType.STOP, ResponseType.ALL.getValue());
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( new UnitContractMessage(UnitContractMessageType.ContractUnitRequest.getValue(),
UnitContractMessageType.ContractUnitRequest.getValue(),
UnitContractRequestType.STOP.getValue()); UnitContractRequestType.STOP.getValue());
unitContractMessage.action = "stopContractAtSlave"; unitContractMessage.action = "stopContractAtSlave";
unitContractMessage.requestID = requestId; unitContractMessage.requestID = requestId;
@ -190,43 +174,32 @@ 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( SequencingManager.instance.sequencingRequest(unitContractMessage.contractID,
unitContractMessage.contractID, unitContractMessage, peers, rc); unitContractMessage, peers, rc);
} else { } else {
String msgContent = JsonUtil.toJson(unitContractMessage); String msgContent = JsonUtil.toJson(unitContractMessage);
UnitMessage unitMessage; UnitMessage unitMessage;
unitMessage = unitMessage = UnitMessage.newBuilder()
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); NetworkManager.instance.send(unitMessage, networkType);
} }
} }
public void startContractRequest( public void startContractRequest(boolean tcpType, String contract, int num, String[] peers,
boolean tcpType, String content, int sequencing, int response, ResultCallback resultCallback) {
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 = ResponseCenter responseCenter = new ResponseCenter(requestId, resultCallback, num,
new ResponseCenter( UnitContractRequestType.START, response);
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( 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;
@ -242,22 +215,18 @@ 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 = UnitMessage.newBuilder()
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 {
// 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 = UnitMessage.newBuilder()
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 ? NetworkType.TCP : NetworkType.P2P); NetworkManager.instance.send(unitMessage, tcpType ? NetworkType.TCP : NetworkType.P2P);
} }
@ -272,14 +241,8 @@ public class ExecutionManager extends BaseFunctionManager {
nextContractID = content; nextContractID = content;
} }
public void executeContractRequest( public void executeContractRequest(String contract, String operation, String arg, int network,
String contract, int sequencing, int responseType, ResultCallback rc) {
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;
@ -287,17 +250,15 @@ 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 = ResponseCenter responseCenter = new ResponseCenter(requestId, rc, peers.length,
new ResponseCenter( UnitContractRequestType.EXECUTE, responseType);
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( 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;
@ -310,29 +271,22 @@ 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( SequencingManager.instance.sequencingRequest(unitContractMessage.contractID,
unitContractMessage.contractID, unitContractMessage, peers, rc); unitContractMessage, peers, rc);
} else { } else {
String msgContent = JsonUtil.toJson(unitContractMessage); String msgContent = JsonUtil.toJson(unitContractMessage);
UnitMessage unitMessage; UnitMessage unitMessage;
unitMessage = unitMessage = UnitMessage.newBuilder()
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 stopContractRequest( public void stopContractRequest(String contract, String operation, String arg, int network,
String contract, int sequencing, ResultCallback rc) {
String operation,
String arg,
int network,
int sequencing,
ResultCallback rc) {
// String requestId = getRequestId(); // String requestId = getRequestId();
//// this.requestCallbacks.put(requestId, resultCallback); //// this.requestCallbacks.put(requestId, resultCallback);
// MultiPointContractInfo info = // MultiPointContractInfo info =
@ -389,5 +343,4 @@ 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

@ -24,15 +24,14 @@ 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) {
@ -51,8 +50,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) {
@ -60,125 +59,124 @@ 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( public void sequencingRequest(String contractID, UnitContractMessage msg, String[] peers,
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 = new UnitSequencingMessage(ConsensusStage.Request.toInt()); UnitSequencingMessage sequencingMessage =
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, sequencing)); // new ResponseCenter(requestId, resultCallback, num, UnitContractRequestType.START,
//// respCaches.put(requestId, new RespCache(num)); // sequencing));
// UnitContractMessage unitContractMessage = new UnitContractMessage( //// respCaches.put(requestId, new RespCache(num));
// UnitContractMessageType.ContractUnitRequest.getValue(), // UnitContractMessage unitContractMessage = new UnitContractMessage(
// UnitContractRequestType.START.getValue()); // UnitContractMessageType.ContractUnitRequest.getValue(),
// unitContractMessage.action = "startContractAtSlave"; // UnitContractRequestType.START.getValue());
// unitContractMessage.requestID = requestId; // unitContractMessage.action = "startContractAtSlave";
//// unitContractMessage.contractID = contract; // unitContractMessage.requestID = requestId;
// unitContractMessage.content = content; //// unitContractMessage.contractID = contract;
// unitContractMessage.sequencing = sequencing; // unitContractMessage.content = content;
// unitContractMessage.num = num; // unitContractMessage.sequencing = sequencing;
// unitContractMessage.network = tcpType?0:1; // unitContractMessage.num = num;
// String msgContent = gson.toJson(unitContractMessage); // unitContractMessage.network = tcpType?0:1;
// BDLedgerContract.UnitMessage unitMessage; // String msgContent = gson.toJson(unitContractMessage);
// if (null != peers && peers.length > 0) { // BDLedgerContract.UnitMessage unitMessage;
// unitMessage = BDLedgerContract.UnitMessage.newBuilder() // if (null != peers && peers.length > 0) {
// .setMsgType(BDLedgerContract.UnitMessageType.UnitContractMessage) // unitMessage = BDLedgerContract.UnitMessage.newBuilder()
// .setContent(ByteString.copyFromUtf8(msgContent)) // .setMsgType(BDLedgerContract.UnitMessageType.UnitContractMessage)
// .addAllReceiver(Arrays.asList(peers)) // .setContent(ByteString.copyFromUtf8(msgContent))
// .setSender(GlobalConf.instance.peerID) // .addAllReceiver(Arrays.asList(peers))
// .build(); // .setSender(GlobalConf.instance.peerID)
// } else { // .build();
// // No specified receiver, send to p2p nodes randomly // } else {
// unitMessage = BDLedgerContract.UnitMessage.newBuilder() // // No specified receiver, send to p2p nodes randomly
// .setMsgType(BDLedgerContract.UnitMessageType.UnitContractMessage) // unitMessage = BDLedgerContract.UnitMessage.newBuilder()
// .setContent(ByteString.copyFromUtf8(msgContent)) // .setMsgType(BDLedgerContract.UnitMessageType.UnitContractMessage)
// .setSender(GlobalConf.instance.peerID) // .setContent(ByteString.copyFromUtf8(msgContent))
// .build(); // .setSender(GlobalConf.instance.peerID)
// } // .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) {
@ -195,19 +193,21 @@ 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 = ContractUnitManager.instance.getContractInfo(contractID); MultiPointContractInfo contractInfo =
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), send(JsonUtil.toJson(unitContractMessage), contractInfo.getMembers().toArray(new String[0]),
contractInfo.getMembers().toArray(new String[0]), BDLedgerContract.UnitMessageType.UnitUnitMessage); BDLedgerContract.UnitMessageType.UnitUnitMessage);
} }
public void updateConsensusCenter(String contractID, MultiPointContractInfo info) { public void updateConsensusCenter(String contractID, MultiPointContractInfo info) {
LOGGER.info("[updateConsensusCenter] consensusCenters " + contractID + " " + consensusCenters.size()); LOGGER.info("[updateConsensusCenter] consensusCenters " + contractID + " "
+ consensusCenters.size());
ConsensusCenter consensusCenter = consensusCenters.get(contractID); ConsensusCenter consensusCenter = consensusCenters.get(contractID);
while (null == consensusCenter) { while (null == consensusCenter) {
try { try {
@ -232,5 +232,4 @@ public class SequencingManager extends BaseFunctionManager {
} }

File diff suppressed because it is too large Load Diff

View File

@ -1,23 +1,13 @@
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( @javax.annotation.Generated(value = "by gRPC proto compiler (version 1.4.1-SNAPSHOT)",
value = "by gRPC proto compiler (version 1.4.1-SNAPSHOT)",
comments = "Source: BDLedgerContract.proto") comments = "Source: BDLedgerContract.proto")
public final class BDLedgerContractServiceGrpc { public final class BDLedgerContractServiceGrpc {
@ -27,16 +17,15 @@ public final class BDLedgerContractServiceGrpc {
// 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, public static final io.grpc.MethodDescriptor<BDLedgerContract.UnitMessage, BDLedgerContract.UnitMessage> METHOD_BDLEDGER_CONTRACT_STREAM =
BDLedgerContract.UnitMessage> METHOD_BDLEDGER_CONTRACT_STREAM =
io.grpc.MethodDescriptor.<BDLedgerContract.UnitMessage, BDLedgerContract.UnitMessage>newBuilder() io.grpc.MethodDescriptor.<BDLedgerContract.UnitMessage, BDLedgerContract.UnitMessage>newBuilder()
.setType(io.grpc.MethodDescriptor.MethodType.BIDI_STREAMING) .setType(io.grpc.MethodDescriptor.MethodType.BIDI_STREAMING)
.setFullMethodName(generateFullMethodName( .setFullMethodName(generateFullMethodName("BDLedgerContractService",
"BDLedgerContractService", "BDLedgerContractStream")) "BDLedgerContractStream"))
.setRequestMarshaller(io.grpc.protobuf.ProtoUtils.marshaller( .setRequestMarshaller(io.grpc.protobuf.ProtoUtils
BDLedgerContract.UnitMessage.getDefaultInstance())) .marshaller(BDLedgerContract.UnitMessage.getDefaultInstance()))
.setResponseMarshaller(io.grpc.protobuf.ProtoUtils.marshaller( .setResponseMarshaller(io.grpc.protobuf.ProtoUtils
BDLedgerContract.UnitMessage.getDefaultInstance())) .marshaller(BDLedgerContract.UnitMessage.getDefaultInstance()))
.build(); .build();
/** /**
@ -47,40 +36,38 @@ public final class BDLedgerContractServiceGrpc {
} }
/** /**
* Creates a new blocking-style stub that supports unary and streaming output calls on the service * Creates a new blocking-style stub that supports unary and streaming output calls on the
* service
*/ */
public static BDLedgerContractServiceBlockingStub newBlockingStub( public static BDLedgerContractServiceBlockingStub newBlockingStub(io.grpc.Channel channel) {
io.grpc.Channel channel) {
return new BDLedgerContractServiceBlockingStub(channel); return new BDLedgerContractServiceBlockingStub(channel);
} }
/** /**
* Creates a new ListenableFuture-style stub that supports unary calls on the service * Creates a new ListenableFuture-style stub that supports unary calls on the service
*/ */
public static BDLedgerContractServiceFutureStub newFutureStub( public static BDLedgerContractServiceFutureStub newFutureStub(io.grpc.Channel channel) {
io.grpc.Channel channel) {
return new BDLedgerContractServiceFutureStub(channel); return new BDLedgerContractServiceFutureStub(channel);
} }
/** /**
*/ */
public static abstract class BDLedgerContractServiceImplBase implements io.grpc.BindableService { public static abstract class BDLedgerContractServiceImplBase
implements io.grpc.BindableService {
/** /**
*/ */
public io.grpc.stub.StreamObserver<BDLedgerContract.UnitMessage> bDLedgerContractStream( public io.grpc.stub.StreamObserver<BDLedgerContract.UnitMessage> bDLedgerContractStream(
io.grpc.stub.StreamObserver<BDLedgerContract.UnitMessage> responseObserver) { io.grpc.stub.StreamObserver<BDLedgerContract.UnitMessage> responseObserver) {
return asyncUnimplementedStreamingCall(METHOD_BDLEDGER_CONTRACT_STREAM, responseObserver); return asyncUnimplementedStreamingCall(METHOD_BDLEDGER_CONTRACT_STREAM,
responseObserver);
} }
@Override public final io.grpc.ServerServiceDefinition bindService() { @Override
public final io.grpc.ServerServiceDefinition bindService() {
return io.grpc.ServerServiceDefinition.builder(getServiceDescriptor()) return io.grpc.ServerServiceDefinition.builder(getServiceDescriptor())
.addMethod( .addMethod(METHOD_BDLEDGER_CONTRACT_STREAM, asyncBidiStreamingCall(
METHOD_BDLEDGER_CONTRACT_STREAM, new MethodHandlers<BDLedgerContract.UnitMessage, BDLedgerContract.UnitMessage>(
asyncBidiStreamingCall(
new MethodHandlers<
BDLedgerContract.UnitMessage,
BDLedgerContract.UnitMessage>(
this, METHODID_BDLEDGER_CONTRACT_STREAM))) this, METHODID_BDLEDGER_CONTRACT_STREAM)))
.build(); .build();
} }
@ -88,7 +75,8 @@ public final class BDLedgerContractServiceGrpc {
/** /**
*/ */
public static final class BDLedgerContractServiceStub extends io.grpc.stub.AbstractStub<BDLedgerContractServiceStub> { public static final class BDLedgerContractServiceStub
extends io.grpc.stub.AbstractStub<BDLedgerContractServiceStub> {
private BDLedgerContractServiceStub(io.grpc.Channel channel) { private BDLedgerContractServiceStub(io.grpc.Channel channel) {
super(channel); super(channel);
} }
@ -109,13 +97,15 @@ public final class BDLedgerContractServiceGrpc {
public io.grpc.stub.StreamObserver<BDLedgerContract.UnitMessage> bDLedgerContractStream( public io.grpc.stub.StreamObserver<BDLedgerContract.UnitMessage> bDLedgerContractStream(
io.grpc.stub.StreamObserver<BDLedgerContract.UnitMessage> responseObserver) { io.grpc.stub.StreamObserver<BDLedgerContract.UnitMessage> responseObserver) {
return asyncBidiStreamingCall( return asyncBidiStreamingCall(
getChannel().newCall(METHOD_BDLEDGER_CONTRACT_STREAM, getCallOptions()), responseObserver); getChannel().newCall(METHOD_BDLEDGER_CONTRACT_STREAM, getCallOptions()),
responseObserver);
} }
} }
/** /**
*/ */
public static final class BDLedgerContractServiceBlockingStub extends io.grpc.stub.AbstractStub<BDLedgerContractServiceBlockingStub> { public static final class BDLedgerContractServiceBlockingStub
extends io.grpc.stub.AbstractStub<BDLedgerContractServiceBlockingStub> {
private BDLedgerContractServiceBlockingStub(io.grpc.Channel channel) { private BDLedgerContractServiceBlockingStub(io.grpc.Channel channel) {
super(channel); super(channel);
} }
@ -134,7 +124,8 @@ public final class BDLedgerContractServiceGrpc {
/** /**
*/ */
public static final class BDLedgerContractServiceFutureStub extends io.grpc.stub.AbstractStub<BDLedgerContractServiceFutureStub> { public static final class BDLedgerContractServiceFutureStub
extends io.grpc.stub.AbstractStub<BDLedgerContractServiceFutureStub> {
private BDLedgerContractServiceFutureStub(io.grpc.Channel channel) { private BDLedgerContractServiceFutureStub(io.grpc.Channel channel) {
super(channel); super(channel);
} }
@ -153,8 +144,8 @@ public final class BDLedgerContractServiceGrpc {
private static final int METHODID_BDLEDGER_CONTRACT_STREAM = 0; private static final int METHODID_BDLEDGER_CONTRACT_STREAM = 0;
private static final class MethodHandlers<Req, Resp> implements private static final class MethodHandlers<Req, Resp>
io.grpc.stub.ServerCalls.UnaryMethod<Req, Resp>, implements io.grpc.stub.ServerCalls.UnaryMethod<Req, Resp>,
io.grpc.stub.ServerCalls.ServerStreamingMethod<Req, Resp>, io.grpc.stub.ServerCalls.ServerStreamingMethod<Req, Resp>,
io.grpc.stub.ServerCalls.ClientStreamingMethod<Req, Resp>, io.grpc.stub.ServerCalls.ClientStreamingMethod<Req, Resp>,
io.grpc.stub.ServerCalls.BidiStreamingMethod<Req, Resp> { io.grpc.stub.ServerCalls.BidiStreamingMethod<Req, Resp> {
@ -189,7 +180,8 @@ public final class BDLedgerContractServiceGrpc {
} }
} }
private static final class BDLedgerContractServiceDescriptorSupplier implements io.grpc.protobuf.ProtoFileDescriptorSupplier { private static final class BDLedgerContractServiceDescriptorSupplier
implements io.grpc.protobuf.ProtoFileDescriptorSupplier {
@Override @Override
public com.google.protobuf.Descriptors.FileDescriptor getFileDescriptor() { public com.google.protobuf.Descriptors.FileDescriptor getFileDescriptor() {
return BDLedgerContract.getDescriptor(); return BDLedgerContract.getDescriptor();
@ -206,8 +198,7 @@ public final class BDLedgerContractServiceGrpc {
if (result == null) { if (result == null) {
serviceDescriptor = result = io.grpc.ServiceDescriptor.newBuilder(SERVICE_NAME) serviceDescriptor = result = io.grpc.ServiceDescriptor.newBuilder(SERVICE_NAME)
.setSchemaDescriptor(new BDLedgerContractServiceDescriptorSupplier()) .setSchemaDescriptor(new BDLedgerContractServiceDescriptorSupplier())
.addMethod(METHOD_BDLEDGER_CONTRACT_STREAM) .addMethod(METHOD_BDLEDGER_CONTRACT_STREAM).build();
.build();
} }
} }
} }

View File

@ -76,9 +76,7 @@ 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() Runtime.getRuntime().addShutdownHook(new Thread(() -> {
.addShutdownHook(
new Thread(() -> {
// Use stderr here since the logger may has been reset by its JVM // Use stderr here since the logger may has been reset by its JVM
// shutdown hook. // shutdown hook.
System.err.println("*** shutting down gRPC server since JVM is shutting down"); System.err.println("*** shutting down gRPC server since JVM is shutting down");
@ -111,7 +109,8 @@ public class JavaContractServiceGrpcServer {
/** /**
* Our implementation of RouteGuide service. * Our implementation of RouteGuide service.
* *
* <p>See route_guide.proto for details of the methods. * <p>
* See route_guide.proto for details of the methods.
*/ */
private static class JavaContractService private static class JavaContractService
extends BDLedgerContractServiceGrpc.BDLedgerContractServiceImplBase { extends BDLedgerContractServiceGrpc.BDLedgerContractServiceImplBase {
@ -134,7 +133,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);
} }

View File

@ -27,12 +27,8 @@ public class ResponseCenter {
long start; long start;
private ResponseType responseType; private ResponseType responseType;
public ResponseCenter( public ResponseCenter(String requestID, ResultCallback rc, int num,
String requestID, UnitContractRequestType cuType, int type) {
ResultCallback rc,
int num,
UnitContractRequestType cuType,
int type) {
this.requestID = requestID; this.requestID = requestID;
this.callback = rc; this.callback = rc;
this.isSendReply = false; this.isSendReply = false;
@ -72,8 +68,8 @@ public class ResponseCenter {
fails.put(sender, result.result.toString()); fails.put(sender, result.result.toString());
} }
int num = count.addAndGet(1); int num = count.addAndGet(1);
System.out.println( System.out
"---: updateReply, size:" + num + "/" + size + " --sender:" + sender); .println("---: updateReply, size:" + num + "/" + size + " --sender:" + sender);
} }
switch (this.responseType) { switch (this.responseType) {
case ALL: case ALL:
@ -130,7 +126,8 @@ public class ResponseCenter {
Map<String, String> data = new HashMap<>(); Map<String, String> data = new HashMap<>();
if (successes.size() > 0) { if (successes.size() > 0) {
data.put("status", "Success"); data.put("status", "Success");
result.append(successes.values().iterator().next()).append("(").append(successes.size()).append(") / "); result.append(successes.values().iterator().next()).append("(")
.append(successes.size()).append(") / ");
} else { // 结果不一致 } else { // 结果不一致
data.put("status", "Exception"); data.put("status", "Exception");
} }

View File

@ -11,32 +11,34 @@ import org.bdware.units.grpc.BDLedgerContract.UnitMessage;
/** /**
* 接收UnitMessage, 执行相应处理如合约启动执行定序等 * 接收UnitMessage, 执行相应处理如合约启动执行定序等
*
* @author oliveds * @author oliveds
*/ */
public class UnitMessageHandler { public class UnitMessageHandler {
private static final Logger LOGGER = LogManager.getLogger(UnitMessageHandler.class); private static final Logger LOGGER = LogManager.getLogger(UnitMessageHandler.class);
public static UnitMessageHandler instance = init(); public static UnitMessageHandler instance = init();
public UnitMessageHandler(){} public UnitMessageHandler() {}
public static UnitMessageHandler init() { public static UnitMessageHandler init() {
if(instance == null) { if (instance == null) {
instance = new UnitMessageHandler(); instance = new UnitMessageHandler();
} }
return instance; return instance;
} }
public void handle(UnitMessage msg) { public void handle(UnitMessage msg) {
String content = msg.getContent().toStringUtf8(); String content = msg.getContent().toStringUtf8();
String sender = msg.getSender(); String sender = msg.getSender();
// LOGGER.debug("[UnitMessageHandler] receive " + msg.toString()); // LOGGER.debug("[UnitMessageHandler] receive " + msg.toString());
handleInner(msg.getMsgType(),content,sender); handleInner(msg.getMsgType(), content, sender);
} }
public void handleWithSender(UnitMessage msg, String sender) { public void handleWithSender(UnitMessage msg, String sender) {
String content = msg.getContent().toStringUtf8(); String content = msg.getContent().toStringUtf8();
sender = sender.replace("/",""); sender = sender.replace("/", "");
LOGGER.debug("[UnitMessageHandler] receive " + msg.toString()); LOGGER.debug("[UnitMessageHandler] receive " + msg.toString());
handleInner(msg.getMsgType(),content,sender); handleInner(msg.getMsgType(), content, sender);
} }
private void handleInner(BDLedgerContract.UnitMessageType type, String content, String sender) { private void handleInner(BDLedgerContract.UnitMessageType type, String content, String sender) {
@ -51,13 +53,13 @@ public class UnitMessageHandler {
ContractUnitManager.instance.handle(content, sender); ContractUnitManager.instance.handle(content, sender);
break; break;
case UnitRecoverMessage: case UnitRecoverMessage:
// RecoveryManager.instance.handle(content,sender); // RecoveryManager.instance.handle(content,sender);
break; break;
case UnitSequencingMessage: case UnitSequencingMessage:
SequencingManager.instance.handle(content,sender); SequencingManager.instance.handle(content, sender);
break; break;
default: default:
// CommunicationManager.instance.handle(content, sender); // CommunicationManager.instance.handle(content, sender);
} }
} }
} }

View File

@ -25,11 +25,11 @@ public class TCPClientFrameHandler extends SimpleChannelInboundHandler<ByteBuf>
ChannelHandlerContext ctx; ChannelHandlerContext ctx;
private Channel channel; private Channel channel;
private String peer; private String peer;
// HeartBeatProtocol heartBeat; // HeartBeatProtocol heartBeat;
public TCPClientFrameHandler(String peerId) { public TCPClientFrameHandler(String peerId) {
peer = peerId; peer = peerId;
// heartBeat = new HeartBeatProtocol(peer); // heartBeat = new HeartBeatProtocol(peer);
for (String str : tcpPlugins) { for (String str : tcpPlugins) {
Object obj = createInstanceByClzName(str); Object obj = createInstanceByClzName(str);
ae.appendHandler(obj); ae.appendHandler(obj);
@ -50,11 +50,10 @@ public class TCPClientFrameHandler extends SimpleChannelInboundHandler<ByteBuf>
if (evt instanceof IdleStateEvent) { if (evt instanceof IdleStateEvent) {
IdleStateEvent idleStateEvent = (IdleStateEvent) evt; IdleStateEvent idleStateEvent = (IdleStateEvent) evt;
if (idleStateEvent.state() == IdleState.WRITER_IDLE) { if (idleStateEvent.state() == IdleState.WRITER_IDLE) {
// logger.info("[TCPClientFrameHandler] 5s msg"); // logger.info("[TCPClientFrameHandler] 5s msg");
//向服务端发送消息 // 向服务端发送消息
UnitMessage unitMessage = UnitMessage.newBuilder() UnitMessage unitMessage = UnitMessage.newBuilder()
.setMsgType(BDLedgerContract.UnitMessageType.UnitRecoverMessage) .setMsgType(BDLedgerContract.UnitMessageType.UnitRecoverMessage).build();
.build();
ByteBuf byteBuf = Unpooled.wrappedBuffer(unitMessage.toByteArray()); ByteBuf byteBuf = Unpooled.wrappedBuffer(unitMessage.toByteArray());
ctx.writeAndFlush(byteBuf).addListener(ChannelFutureListener.CLOSE_ON_FAILURE); ctx.writeAndFlush(byteBuf).addListener(ChannelFutureListener.CLOSE_ON_FAILURE);
} }
@ -83,7 +82,7 @@ public class TCPClientFrameHandler extends SimpleChannelInboundHandler<ByteBuf>
@Override @Override
protected void channelRead0(ChannelHandlerContext ctx, ByteBuf bb) { protected void channelRead0(ChannelHandlerContext ctx, ByteBuf bb) {
// ByteBuf bb = (ByteBuf) frame; // ByteBuf bb = (ByteBuf) frame;
UnitMessage unitMessage; UnitMessage unitMessage;
try { try {
byte[] bytes = new byte[bb.readableBytes()]; byte[] bytes = new byte[bb.readableBytes()];
@ -101,14 +100,14 @@ public class TCPClientFrameHandler extends SimpleChannelInboundHandler<ByteBuf>
ByteBuf byteBuf = Unpooled.wrappedBuffer(unitMessage.toByteArray()); ByteBuf byteBuf = Unpooled.wrappedBuffer(unitMessage.toByteArray());
ctx.writeAndFlush(byteBuf).addListener(ChannelFutureListener.CLOSE_ON_FAILURE); ctx.writeAndFlush(byteBuf).addListener(ChannelFutureListener.CLOSE_ON_FAILURE);
// if (isOpen()) { // if (isOpen()) {
// // ByteArrayOutputStream bos = new ByteArrayOutputStream(); // // ByteArrayOutputStream bos = new ByteArrayOutputStream();
//// unitMessage.writeTo(bos); //// unitMessage.writeTo(bos);
//// ctx.channel().writeAndFlush(bos); //// ctx.channel().writeAndFlush(bos);
//// bos.close(); //// bos.close();
// ByteBuf buf = Unpooled.wrappedBuffer(unitMessage.toByteArray()); // ByteBuf buf = Unpooled.wrappedBuffer(unitMessage.toByteArray());
// ctx.channel().writeAndFlush(buf); // ctx.channel().writeAndFlush(buf);
// } // }
} }
public boolean isOpen() { public boolean isOpen() {

View File

@ -8,21 +8,18 @@ import org.bdware.units.grpc.BDLedgerContract.UnitMessage;
import org.bdware.units.msghandler.UnitMessageHandler; import org.bdware.units.msghandler.UnitMessageHandler;
/** /**
* 节点间TCP建立通信传输 * 节点间TCP建立通信传输 1. 复杂情况组网 2. 自动选择网络方式
* 1. 复杂情况组网
* 2. 自动选择网络方式
*/ */
public class TCPServerFrameHandler extends SimpleChannelInboundHandler<ByteBuf> { public class TCPServerFrameHandler extends SimpleChannelInboundHandler<ByteBuf> {
// private static final Logger LOGGER = LogManager.getLogger(TCPServerFrameHandler.class); // private static final Logger LOGGER = LogManager.getLogger(TCPServerFrameHandler.class);
public ChannelHandlerContext ctx; public ChannelHandlerContext ctx;
public TCPServerFrameHandler() { public TCPServerFrameHandler() {}
}
@Override @Override
protected void channelRead0(ChannelHandlerContext ctx, ByteBuf bb) { protected void channelRead0(ChannelHandlerContext ctx, ByteBuf bb) {
this.ctx = ctx; this.ctx = ctx;
// ByteBuf bb = (ByteBuf) frame; // ByteBuf bb = (ByteBuf) frame;
UnitMessage msg; UnitMessage msg;
try { try {
byte[] bytes = new byte[bb.readableBytes()]; byte[] bytes = new byte[bb.readableBytes()];
@ -32,20 +29,20 @@ public class TCPServerFrameHandler extends SimpleChannelInboundHandler<ByteBuf>
e.printStackTrace(); e.printStackTrace();
return; return;
} }
// ByteBuf bb = (ByteBuf) frame; // ByteBuf bb = (ByteBuf) frame;
// byte[] bytes = new byte[bb.readableBytes()]; // byte[] bytes = new byte[bb.readableBytes()];
// logger.info("TCP server receive:" +bytes.toString()); // logger.info("TCP server receive:" +bytes.toString());
// bb.readBytes(bytes); // bb.readBytes(bytes);
// UnitMessage msg; // UnitMessage msg;
// try { // try {
// msg = UnitMessage.parseFrom(bytes); // msg = UnitMessage.parseFrom(bytes);
// logger.info("TCP receive:" + msg.toString()); // logger.info("TCP receive:" + msg.toString());
// //
// } catch (IOException e) { // } catch (IOException e) {
// logger.info("[TCPServerFrameHandler] bytes:" + new String(bytes)); // logger.info("[TCPServerFrameHandler] bytes:" + new String(bytes));
// e.printStackTrace(); // e.printStackTrace();
// return; // return;
// } // }
try { try {
UnitMessageHandler.instance.handleWithSender(msg, msg.getSender()); UnitMessageHandler.instance.handleWithSender(msg, msg.getSender());
} catch (Exception e) { } catch (Exception e) {
@ -57,16 +54,16 @@ public class TCPServerFrameHandler extends SimpleChannelInboundHandler<ByteBuf>
return ctx.channel().isOpen(); return ctx.channel().isOpen();
} }
// public void sendMsg(UnitMessage unitMsg) { // public void sendMsg(UnitMessage unitMsg) {
// if (ctx != null) { // if (ctx != null) {
// try { // try {
// ByteArrayOutputStream bos = new ByteArrayOutputStream(); // ByteArrayOutputStream bos = new ByteArrayOutputStream();
// unitMsg.writeTo(bos); // unitMsg.writeTo(bos);
// ctx.channel().writeAndFlush(bos); // ctx.channel().writeAndFlush(bos);
// bos.close(); // bos.close();
// } catch (IOException e) { // } catch (IOException e) {
// e.printStackTrace(); // e.printStackTrace();
// } // }
// } // }
// } // }
} }

View File

@ -1,14 +1,15 @@
package org.bdware.units.tcp; package org.bdware.units.tcp;
import jdk.nashorn.internal.runtime.regexp.joni.Regex;
import java.util.regex.Matcher; import java.util.regex.Matcher;
import java.util.regex.Pattern; import java.util.regex.Pattern;
public class TCPUtils { public class TCPUtils {
private static final String TCP_ADDRESS_PATTERN = "|((?:(?:25[0-5]|bai2[0-4]\\d|((1\\d{2})|([1-9]?\\d)))\\.){3}(?:25[0-5]|2[0-4]\\d|((1\\d{2})|([1-9]?[1-9])))(\\:\\d)*)"; private static final String TCP_ADDRESS_PATTERN =
"|((?:(?:25[0-5]|bai2[0-4]\\d|((1\\d{2})|([1-9]?\\d)))\\.){3}(?:25[0-5]|2[0-4]\\d|((1\\d{2})|([1-9]?[1-9])))(\\:\\d)*)";
private static final Pattern tcpAddressPattern = Pattern.compile(TCP_ADDRESS_PATTERN); private static final Pattern tcpAddressPattern = Pattern.compile(TCP_ADDRESS_PATTERN);
public static boolean isTCPAddress(String address) { public static boolean isTCPAddress(String address) {
Matcher m = tcpAddressPattern.matcher(address); Matcher m = tcpAddressPattern.matcher(address);
return m.find(); return m.find();

View File

@ -31,13 +31,15 @@ public class FuncInvokeInfo {
// invokeInfo.clear(); // invokeInfo.clear();
invokeInfoList.clear(); invokeInfoList.clear();
} }
// 以数组形式返回 // 以数组形式返回
public ArrayList<JsonObject> getOneFunction(String ContractName, String FunctionName) { public ArrayList<JsonObject> getOneFunction(String ContractName, String FunctionName) {
String Key = ContractName + "|" + FunctionName; String Key = ContractName + "|" + FunctionName;
// HashMap<String,JsonObject>Ret=invokeInfo.get(Key); // HashMap<String,JsonObject>Ret=invokeInfo.get(Key);
LinkedList<JsonObject> Ret = invokeInfoList.getValues(Key); LinkedList<JsonObject> Ret = invokeInfoList.getValues(Key);
if (Ret == null) return null; if (Ret == null)
return null;
ArrayList<JsonObject> ret = new ArrayList<JsonObject>(); ArrayList<JsonObject> ret = new ArrayList<JsonObject>();
for (int i = 0; i < Ret.size(); i++) { for (int i = 0; i < Ret.size(); i++) {
ret.add(Ret.get(i)); ret.add(Ret.get(i));
@ -51,30 +53,26 @@ public class FuncInvokeInfo {
; ;
} }
public void putOneInvoke( public void putOneInvoke(String ContractName, String FunctionName, String ResponseID,
String ContractName, String FunctionName, String ResponseID, JsonElement args, String res) { JsonElement args, String res) {
String Key1 = ContractName + "|" + FunctionName; String Key1 = ContractName + "|" + FunctionName;
String Key2 = ResponseID; String Key2 = ResponseID;
JsonObject Record =new JsonObject(); JsonObject Record = new JsonObject();
Record.add("args",args); Record.add("args", args);
Record.addProperty("res",res); Record.addProperty("res", res);
invokeInfoList.add(Key1, Record); invokeInfoList.add(Key1, Record);
// HashMap<String,JsonObject>OldRecordInfo=new HashMap<String ,JsonObject >(); // HashMap<String,JsonObject>OldRecordInfo=new HashMap<String ,JsonObject >();
/*OldRecordInfo=invokeInfo.get(Key1);//查看是否有这个合约的调用有就追加没有就新建 /*
if(OldRecordInfo==null){ * OldRecordInfo=invokeInfo.get(Key1);//查看是否有这个合约的调用有就追加没有就新建 if(OldRecordInfo==null){
HashMap<String,JsonObject>temp=new HashMap<String ,JsonObject >(); * HashMap<String,JsonObject>temp=new HashMap<String ,JsonObject >(); temp.put(Key2,Record);
temp.put(Key2,Record); * invokeInfo.put(Key1,temp); System.out.println(temp.size()); } else{
invokeInfo.put(Key1,temp); * OldRecordInfo.put(Key2,Record); //System.out.println("aaa"+OldRecordInfo);
System.out.println(temp.size()); *
} *
else{ * }
OldRecordInfo.put(Key2,Record); */
//System.out.println("aaa"+OldRecordInfo);
}*/
} }
} }

View File

@ -11,8 +11,7 @@ public class ContractInfoDBTest {
String pre = "CONTRACT_INFO_META_"; String pre = "CONTRACT_INFO_META_";
KeyValueDBUtil.setupCM(); KeyValueDBUtil.setupCM();
KeyValueDBUtil.instance.visitDB( KeyValueDBUtil.instance.visitDB(CMTables.ContractInfo.toString(),
CMTables.ContractInfo.toString(),
new Jedion.JedionVisitor() { new Jedion.JedionVisitor() {
@Override @Override
public void visit(String key, String value) { public void visit(String key, String value) {

View File

@ -10,9 +10,7 @@ public class DBTest {
public static void main(String[] arg) { public static void main(String[] arg) {
KeyValueDBUtil.setupCM(); KeyValueDBUtil.setupCM();
System.out.println(new File("./BDWareProjectDir/").getAbsolutePath()); System.out.println(new File("./BDWareProjectDir/").getAbsolutePath());
KeyValueDBUtil.instance.setValue( KeyValueDBUtil.instance.setValue(CMTables.ConfigDB.toString(), "projectDir",
CMTables.ConfigDB.toString(),
"projectDir",
new File("./BDWareProjectDir/").getAbsolutePath()); new File("./BDWareProjectDir/").getAbsolutePath());
} }
} }

View File

@ -17,8 +17,7 @@ public class DOIPOverHttpTest {
@Test @Test
public void retrieveYPK() throws CryptoException { public void retrieveYPK() throws CryptoException {
SM2KeyPair key = SM2KeyPair key = SM2KeyPair.fromJson(
SM2KeyPair.fromJson(
"{\"privateKey\":\"c1c6ff60964c3e9d3ca5dd241d1af98a2f72013aee00d1f7330bd56afdf9c086\",\"publicKey\":\"04fce45a4e5aafed640c77d940a99bc2e5c8649280a975cd1302783d3e74bb219482d706aa08ec3777a2bc1a0d279daecf7256cd50f968423deaa524b6877ffbbf\"}"); "{\"privateKey\":\"c1c6ff60964c3e9d3ca5dd241d1af98a2f72013aee00d1f7330bd56afdf9c086\",\"publicKey\":\"04fce45a4e5aafed640c77d940a99bc2e5c8649280a975cd1302783d3e74bb219482d706aa08ec3777a2bc1a0d279daecf7256cd50f968423deaa524b6877ffbbf\"}");
String path = "/DOIP/TrustedStorage/ypk?pubKey=" + key.getPublicKeyStr(); String path = "/DOIP/TrustedStorage/ypk?pubKey=" + key.getPublicKeyStr();
String sign = String sign =
@ -31,19 +30,16 @@ public class DOIPOverHttpTest {
@Test @Test
public void selfDefinedDOOp() throws CryptoException { public void selfDefinedDOOp() throws CryptoException {
SM2KeyPair key = SM2KeyPair key = SM2KeyPair.fromJson(
SM2KeyPair.fromJson(
"{\"privateKey\":\"589d94ee5688358a1c5c18430dd9c75097ddddebf769f139da36a807911d20f8\",\"publicKey\":\"04d1924329f72ced148f6f333fb985ccbaa31b1e3aacf10be5f43d4a4ff5ad88899a005e79e37fc06993e1d66ada8cf8b711cb36f59538bb7d3e39e70fa9360ddd\"}"); "{\"privateKey\":\"589d94ee5688358a1c5c18430dd9c75097ddddebf769f139da36a807911d20f8\",\"publicKey\":\"04d1924329f72ced148f6f333fb985ccbaa31b1e3aacf10be5f43d4a4ff5ad88899a005e79e37fc06993e1d66ada8cf8b711cb36f59538bb7d3e39e70fa9360ddd\"}");
String contractID = "AnnotationExample"; String contractID = "AnnotationExample";
String operation = "getDocument"; String operation = "getDocument";
String arg = ""; String arg = "";
String toSign = String toSign =
String.format("%s|%s|%s|%s", contractID, operation, arg, key.getPublicKeyStr()); String.format("%s|%s|%s|%s", contractID, operation, arg, key.getPublicKeyStr());
String sign = String sign = ByteUtils
ByteUtils.toHexString( .toHexString(SM2Util.sign(key.getPrivateKeyParameter(), toSign.getBytes()));
SM2Util.sign(key.getPrivateKeyParameter(), toSign.getBytes())); String url = String.format(
String url =
String.format(
"http://127.0.0.1:18000/DOIP/%s?operation=%s&arg=%s&pubkey=%s&signature=%s", "http://127.0.0.1:18000/DOIP/%s?operation=%s&arg=%s&pubkey=%s&signature=%s",
contractID, operation, arg, key.getPublicKeyStr(), sign); contractID, operation, arg, key.getPublicKeyStr(), sign);
System.out.println(new Gson().toJson(HttpUtil.httpGet(url))); System.out.println(new Gson().toJson(HttpUtil.httpGet(url)));

View File

@ -31,7 +31,8 @@ public class DoipClientTest {
LOGGER.info(msg); LOGGER.info(msg);
} }
}); });
for (; i.get() == 0; ) Thread.yield(); for (; i.get() == 0;)
Thread.yield();
} }
} }

View File

@ -13,8 +13,8 @@ public class GRPCPoolTest {
// 091119.23.207.45:18091 47.107.94.135:18091 120.79.215.187:18091 // 091119.23.207.45:18091 47.107.94.135:18091 120.79.215.187:18091
// 092 // 092
// 093 // 093
// String from = "0xadfadfadfa"; // String from = "0xadfadfadfa";
// String to = "0x3dafdsaf"; // String to = "0x3dafdsaf";
GRPCPool.loadConf("119.23.207.45:18091"); GRPCPool.loadConf("119.23.207.45:18091");
Client client = GRPCPool.grpcClients.get(0); Client client = GRPCPool.grpcClients.get(0);
@ -28,13 +28,10 @@ public class GRPCPoolTest {
QueryProto.GetTransactionByHashResponse trans = QueryProto.GetTransactionByHashResponse trans =
client.getTransactionByHashSync("test", "4eb1827bf18c96fd60d6fc787103639e14497885"); client.getTransactionByHashSync("test", "4eb1827bf18c96fd60d6fc787103639e14497885");
System.out.println(trans.getTransaction().getData().toStringUtf8()); System.out.println(trans.getTransaction().getData().toStringUtf8());
GRPCPool.instance.writeToChain( GRPCPool.instance.writeToChain((reqID, hashStr) -> {
(reqID, hashStr) -> {
System.out.println("[OnHashCallback] " + hashStr); System.out.println("[OnHashCallback] " + hashStr);
flag.notify(); flag.notify();
}, }, GRPCPool.mockedFrom, GRPCPool.mockedTo,
GRPCPool.mockedFrom,
GRPCPool.mockedTo,
"HeiHei dfadsfdfadf" + System.currentTimeMillis(), "HeiHei dfadsfdfadf" + System.currentTimeMillis(),
System.currentTimeMillis() + "__T", "test"); System.currentTimeMillis() + "__T", "test");
synchronized (flag) { synchronized (flag) {

View File

@ -73,7 +73,8 @@ public class MonitorTest {
sc2.close(); sc2.close();
port = line.substring(line.indexOf("-port=") + 6); port = line.substring(line.indexOf("-port=") + 6);
//System.out.println(pid + ", " + cpu + ", " + mem + ", " + vsz + ", " + rss + ", " + port); // System.out.println(pid + ", " + cpu + ", " + mem + ", " + vsz + ", " + rss + ", "
// + port);
Map<String, String> tmp = new HashMap<>(); Map<String, String> tmp = new HashMap<>();
tmp.put("pid", pid); tmp.put("pid", pid);
@ -116,7 +117,7 @@ public class MonitorTest {
LineNumberReader input = new LineNumberReader(ir); LineNumberReader input = new LineNumberReader(ir);
String line; String line;
while ((line = input.readLine()) != null) { while ((line = input.readLine()) != null) {
//System.out.println(line); // System.out.println(line);
if (line.contains("%Cpu(s):")) { if (line.contains("%Cpu(s):")) {
Scanner sc2 = new Scanner(new ByteArrayInputStream(line.getBytes())); Scanner sc2 = new Scanner(new ByteArrayInputStream(line.getBytes()));
if (sc2.hasNext()) { if (sc2.hasNext()) {
@ -140,7 +141,8 @@ public class MonitorTest {
if (sc2.hasNext()) { if (sc2.hasNext()) {
sc2.next(); sc2.next();
} }
if (sc2.hasNextFloat()) freeCPU = sc2.nextFloat() + "%"; if (sc2.hasNextFloat())
freeCPU = sc2.nextFloat() + "%";
sc2.close(); sc2.close();
} else if (line.contains("MiB Mem :")) { } else if (line.contains("MiB Mem :")) {
Scanner sc2 = new Scanner(new ByteArrayInputStream(line.getBytes())); Scanner sc2 = new Scanner(new ByteArrayInputStream(line.getBytes()));

View File

@ -19,9 +19,7 @@ public class NCTCPConnectTest {
b.option(ChannelOption.CONNECT_TIMEOUT_MILLIS, 5000); b.option(ChannelOption.CONNECT_TIMEOUT_MILLIS, 5000);
EventLoopGroup group = new NioEventLoopGroup(); EventLoopGroup group = new NioEventLoopGroup();
b.group(group); b.group(group);
b.channel(NioSocketChannel.class) b.channel(NioSocketChannel.class).handler(new ChannelInitializer<SocketChannel>() {
.handler(
new ChannelInitializer<SocketChannel>() {
@Override @Override
protected void initChannel(SocketChannel ch) { protected void initChannel(SocketChannel ch) {
ChannelPipeline p = ch.pipeline(); ChannelPipeline p = ch.pipeline();
@ -41,8 +39,8 @@ public class NCTCPConnectTest {
// setNodeID.put("nodeManager", value); // setNodeID.put("nodeManager", value);
System.out.println("Send getSessionID"); System.out.println("Send getSessionID");
ctx.channel().writeAndFlush("1123123123121231".getBytes()).addListener( ctx.channel().writeAndFlush("1123123123121231".getBytes())
future -> { .addListener(future -> {
System.out.println(future.isSuccess()); System.out.println(future.isSuccess());
future.cause().printStackTrace(); future.cause().printStackTrace();
}); });

View File

@ -19,8 +19,7 @@ import java.util.*;
public class PermissionHelper { public class PermissionHelper {
@Before @Before
public void init() { public void init() {}
}
@Test @Test
public void compareClientAndServer() { public void compareClientAndServer() {
@ -41,8 +40,7 @@ public class PermissionHelper {
} }
private List<Line> parseWithClzName( private List<Line> parseWithClzName(Map<String, ActionExecutor.Pair<Method, Object>> handlers) {
Map<String, ActionExecutor.Pair<Method, Object>> handlers) {
List<Line> lines = new ArrayList<>(); List<Line> lines = new ArrayList<>();
for (String str : handlers.keySet()) { for (String str : handlers.keySet()) {
Method m = handlers.get(str).first(); Method m = handlers.get(str).first();
@ -96,8 +94,8 @@ public class PermissionHelper {
parse(handler.ae.getHandlers(), false); parse(handler.ae.getHandlers(), false);
} }
private void parse( private void parse(Map<String, ActionExecutor.Pair<Method, Object>> handlers,
Map<String, ActionExecutor.Pair<Method, Object>> handlers, boolean checkHttpAccess) { boolean checkHttpAccess) {
List<Line> lines = new ArrayList<>(); List<Line> lines = new ArrayList<>();
EnumSet<Role> set = EnumSet.allOf(Role.class); EnumSet<Role> set = EnumSet.allOf(Role.class);
set.remove(Role.CenterManager); set.remove(Role.CenterManager);
@ -107,7 +105,8 @@ public class PermissionHelper {
Action a = m.getAnnotation(Action.class); Action a = m.getAnnotation(Action.class);
if (checkHttpAccess) { if (checkHttpAccess) {
if (!a.httpAccess()) continue; if (!a.httpAccess())
continue;
} }
Line l = new Line(); Line l = new Line();
lines.add(l); lines.add(l);
@ -121,7 +120,8 @@ public class PermissionHelper {
} }
l.roles = ""; l.roles = "";
for (Role r : set) for (Role r : set)
if ((r.getValue() & l.permission) == l.permission) l.roles += r.name() + ";"; if ((r.getValue() & l.permission) == l.permission)
l.roles += r.name() + ";";
if (l.roles.equals( if (l.roles.equals(
"NodeManager;ContractProvider;ContractInstanceManager;ContractUser;Anonymous;")) "NodeManager;ContractProvider;ContractInstanceManager;ContractUser;Anonymous;"))
l.roles = "任意角色"; l.roles = "任意角色";

View File

@ -32,9 +32,7 @@ public class SocketGetTest {
@Test @Test
public void setLogStage() { public void setLogStage() {
try { try {
URL url = URL url = new URL("http://127.0.0.1:18000/SCIDE/SCManager?action=setLogStage&logStage="
new URL(
"http://127.0.0.1:18000/SCIDE/SCManager?action=setLogStage&logStage="
+ logStage); + logStage);
HttpURLConnection connection = (HttpURLConnection) url.openConnection(); HttpURLConnection connection = (HttpURLConnection) url.openConnection();
InputStream input = connection.getInputStream(); InputStream input = connection.getInputStream();
@ -58,7 +56,8 @@ public class SocketGetTest {
cr.setContractID("ContractExecutor"); cr.setContractID("ContractExecutor");
cr.setAction("executeWithoutSig"); cr.setAction("executeWithoutSig");
String crStr = new Gson().toJson(cr); String crStr = new Gson().toJson(cr);
for (int i = 0; i < reqCount; i++) get.asyncGet("", "executeContract", crStr, c); for (int i = 0; i < reqCount; i++)
get.asyncGet("", "executeContract", crStr, c);
while (c.count.get() < reqCount) { while (c.count.get() < reqCount) {
Thread.yield(); Thread.yield();
} }
@ -74,7 +73,8 @@ public class SocketGetTest {
cr.setContractID("Hello"); cr.setContractID("Hello");
cr.setAction("hello"); cr.setAction("hello");
String crStr = new Gson().toJson(cr); String crStr = new Gson().toJson(cr);
for (int i = 0; i < reqCount; i++) get.asyncGet("", "executeContract", crStr, c); for (int i = 0; i < reqCount; i++)
get.asyncGet("", "executeContract", crStr, c);
while (c.count.get() < reqCount) { while (c.count.get() < reqCount) {
Thread.yield(); Thread.yield();
} }

View File

@ -25,7 +25,8 @@ public class BCOManagerTest {
// config.privateKey = key.getPrivateKeyStr(); // config.privateKey = key.getPrivateKeyStr();
// config.publicKey = key.getPublicKeyStr(); // config.publicKey = key.getPublicKeyStr();
this.bcoManager = new BCOManager("bdtest/CodeRepository", new File("./BDWareProjectDir/bco"), config.routerURI, key); this.bcoManager = new BCOManager("bdtest/CodeRepository",
new File("./BDWareProjectDir/bco"), config.routerURI, key);
} }
@Test @Test

View File

@ -5,85 +5,68 @@ import com.google.gson.JsonParser;
import org.bdware.sc.http.HttpUtil; import org.bdware.sc.http.HttpUtil;
import org.junit.Test; import org.junit.Test;
import java.io.File;
import java.net.URLEncoder;
import java.util.HashMap;
import java.util.Map;
import java.io.File;
import java.io.IOException;
import java.io.StringWriter;
import java.net.URLEncoder;
import java.sql.*; import java.sql.*;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
public class setMaskTest { public class setMaskTest {
@Test @Test
public void test1(){ public void test1() {
/*String baseUrl = "http://127.0.0.1:21030/SCIDE/CMManager?"; /*
StringBuilder url = new StringBuilder(baseUrl + "action=setMask"); * String baseUrl = "http://127.0.0.1:21030/SCIDE/CMManager?"; StringBuilder url = new
HashMap<String, String> param = new HashMap<>(); * StringBuilder(baseUrl + "action=setMask"); HashMap<String, String> param = new
HashMap<String,String> pa=new HashMap<String,String>(); * HashMap<>(); HashMap<String,String> pa=new HashMap<String,String>(); String contractName
String contractName = "Hello"; * = "Hello";
*
param.put("contractName", "Hello"); * param.put("contractName", "Hello"); param.put("defaultAccept", "true");
param.put("defaultAccept", "true"); * param.put("clientSecret", "abcdefg"); param.put("accessPolicy", "DAC");
param.put("clientSecret", "abcdefg"); * param.put("clientID", "abcd");
param.put("accessPolicy", "DAC"); *
param.put("clientID", "abcd"); * param.put("tableName", "student"); param.put("dbType", "PostgreSQL"); for (String key :
* param.keySet()) { url.append("&").append(key).append("=").append(param.get(key)); }
param.put("tableName", "student");
param.put("dbType", "PostgreSQL");
for (String key : param.keySet()) {
url.append("&").append(key).append("=").append(param.get(key));
}
*/ */
String url="http://127.0.0.1:21030/SCIDE/CMManager?action=setMask"; String url = "http://127.0.0.1:21030/SCIDE/CMManager?action=setMask";
String contractID="AAA12BMySQL"; String contractID = "AAA12BMySQL";
JsonElement maskInfo= JsonParser.parseString("{\n" + JsonElement maskInfo =
" \"name\": \"dx_md5\",\n" + JsonParser.parseString("{\n" + " \"name\": \"dx_md5\",\n"
" \"parameter\":\n" + + " \"parameter\":\n" + " {\n"
" {\n" + + " \"columnIndex\":1,\n"
" \"columnIndex\":1,\n" + + " \"paras\":[\"\"]\n" + " }\n"
" \"paras\":[\"\"]\n" + + " }");
" }\n" + String pubkey =
" }"); "04c111cde30c257eb9d891653e2a25eb15df5239dd9882389e8daeffd4b16f65f30b30688b58d3e2eaf25ce5a529a601e4924581b55cedf78d94d17864b73c51a7";
String pubkey="04c111cde30c257eb9d891653e2a25eb15df5239dd9882389e8daeffd4b16f65f30b30688b58d3e2eaf25ce5a529a601e4924581b55cedf78d94d17864b73c51a7";
System.out.println(url); System.out.println(url);
String sign="30440220138c8ae1956f6af19ddb24b9a0fe5cf9cc4f8ecd25537a8b5c4dcd5f30a4f985022026475279687ccdfb112cbcc307e573333d80f45386281def4df54b8b7532ed79"; String sign =
url+="&contractID="+contractID+"&maskInfo="+maskInfo+"&pubkey="+pubkey+"&signature="+sign; "30440220138c8ae1956f6af19ddb24b9a0fe5cf9cc4f8ecd25537a8b5c4dcd5f30a4f985022026475279687ccdfb112cbcc307e573333d80f45386281def4df54b8b7532ed79";
url += "&contractID=" + contractID + "&maskInfo=" + maskInfo + "&pubkey=" + pubkey
+ "&signature=" + sign;
url="http://127.0.0.1:21030/SCIDE/CMManager?action=setMask&&pubkey=04c111cde30c257eb9d891653e2a25eb15df5239dd9882389e8daeffd4b16f65f30b30688b58d3e2eaf25ce5a529a601e4924581b55cedf78d94d17864b73c51a7&signature=304602210082f33a4cdbf483428c701753eb08ca430f855d52df18547a367fe14ee638761f022100cab7fa189b03248b54f3cb679d7df6c2548f6743256cad6ee772c532bb34bdf9"; url = "http://127.0.0.1:21030/SCIDE/CMManager?action=setMask&&pubkey=04c111cde30c257eb9d891653e2a25eb15df5239dd9882389e8daeffd4b16f65f30b30688b58d3e2eaf25ce5a529a601e4924581b55cedf78d94d17864b73c51a7&signature=304602210082f33a4cdbf483428c701753eb08ca430f855d52df18547a367fe14ee638761f022100cab7fa189b03248b54f3cb679d7df6c2548f6743256cad6ee772c532bb34bdf9";
//url="http://127.0.0.1:21030/SCIDE/CMManager?action=ping"; // url="http://127.0.0.1:21030/SCIDE/CMManager?action=ping";
url="http://127.0.0.1:21030/SCIDE/CMManager?action=setMask"+"&contractID="+contractID+"&maskInfo="+maskInfo; url = "http://127.0.0.1:21030/SCIDE/CMManager?action=setMask" + "&contractID=" + contractID
+ "&maskInfo=" + maskInfo;
System.out.println(url); System.out.println(url);
String resp = HttpUtil.httpGet(url.toString()).get("response").toString(); String resp = HttpUtil.httpGet(url.toString()).get("response").toString();
System.out.println(resp); System.out.println(resp);
} }
@Test @Test
public void testgetMask(){ public void testgetMask() {
/*String baseUrl = "http://127.0.0.1:21030/SCIDE/CMManager?"; /*
StringBuilder url = new StringBuilder(baseUrl + "action=setMask"); * String baseUrl = "http://127.0.0.1:21030/SCIDE/CMManager?"; StringBuilder url = new
HashMap<String, String> param = new HashMap<>(); * StringBuilder(baseUrl + "action=setMask"); HashMap<String, String> param = new
HashMap<String,String> pa=new HashMap<String,String>(); * HashMap<>(); HashMap<String,String> pa=new HashMap<String,String>(); String contractName
String contractName = "Hello"; * = "Hello";
*
param.put("contractName", "Hello"); * param.put("contractName", "Hello"); param.put("defaultAccept", "true");
param.put("defaultAccept", "true"); * param.put("clientSecret", "abcdefg"); param.put("accessPolicy", "DAC");
param.put("clientSecret", "abcdefg"); * param.put("clientID", "abcd");
param.put("accessPolicy", "DAC"); *
param.put("clientID", "abcd"); * param.put("tableName", "student"); param.put("dbType", "PostgreSQL"); for (String key :
* param.keySet()) { url.append("&").append(key).append("=").append(param.get(key)); }
param.put("tableName", "student");
param.put("dbType", "PostgreSQL");
for (String key : param.keySet()) {
url.append("&").append(key).append("=").append(param.get(key));
}
*/ */
String contractID="AAA12BMySQL"; String contractID = "AAA12BMySQL";
String url="http://127.0.0.1:21030/SCIDE/CMManager?action=getMask"+"&contractID="+contractID+"&requestID=1"; String url = "http://127.0.0.1:21030/SCIDE/CMManager?action=getMask" + "&contractID="
+ contractID + "&requestID=1";
System.out.println(url); System.out.println(url);
String resp = HttpUtil.httpGet(url.toString()).get("response").toString(); String resp = HttpUtil.httpGet(url.toString()).get("response").toString();

View File

@ -15,8 +15,8 @@ public class MySQLTemplateTest {
@Test @Test
public void testManifest() { public void testManifest() {
VelocityEngine engine = new VelocityEngine(); VelocityEngine engine = new VelocityEngine();
engine.setProperty( engine.setProperty("file.resource.loader.path",
"file.resource.loader.path", new File("./ContractTemplate/").getAbsolutePath()); new File("./ContractTemplate/").getAbsolutePath());
VelocityContext ctx = new VelocityContext(); VelocityContext ctx = new VelocityContext();
ctx.put("ContractName", "ABCC"); ctx.put("ContractName", "ABCC");
Template script = engine.getTemplate("MySQLTemplate/manifest.vm"); Template script = engine.getTemplate("MySQLTemplate/manifest.vm");
@ -28,8 +28,7 @@ public class MySQLTemplateTest {
@Test @Test
public void testMySQLConf() { public void testMySQLConf() {
Map<String, String> str = new HashMap<>(); Map<String, String> str = new HashMap<>();
str.put( str.put("MySQLUrl",
"MySQLUrl",
"jdbc:mysql://127.0.0.1:3306/EcoData?useUnicode=yes&characterEncoding=UTF-8"); "jdbc:mysql://127.0.0.1:3306/EcoData?useUnicode=yes&characterEncoding=UTF-8");
str.put("MySQLName", "root"); str.put("MySQLName", "root");
str.put("MySQLPWD", "12qwas"); str.put("MySQLPWD", "12qwas");
@ -39,8 +38,8 @@ public class MySQLTemplateTest {
@Test @Test
public void testOneTableAllField() { public void testOneTableAllField() {
VelocityEngine engine = new VelocityEngine(); VelocityEngine engine = new VelocityEngine();
engine.setProperty( engine.setProperty("file.resource.loader.path",
"file.resource.loader.path", new File("./ContractTemplate/").getAbsolutePath()); new File("./ContractTemplate/").getAbsolutePath());
VelocityContext ctx = new VelocityContext(); VelocityContext ctx = new VelocityContext();
ctx.put("ContractName", "ABCC"); ctx.put("ContractName", "ABCC");