diff --git a/build.gradle b/build.gradle index 8cbbadb..ccd414a 100644 --- a/build.gradle +++ b/build.gradle @@ -5,6 +5,7 @@ plugins { mainClassName = 'org.bdware.server.CMHttpServer' +apply from: '../spotless.gradle' application { mainClass = mainClassName diff --git a/src/main/java/org/bdware/heartbeat/HeartBeatUtil.java b/src/main/java/org/bdware/heartbeat/HeartBeatUtil.java index 50e415a..9b94e28 100644 --- a/src/main/java/org/bdware/heartbeat/HeartBeatUtil.java +++ b/src/main/java/org/bdware/heartbeat/HeartBeatUtil.java @@ -41,9 +41,8 @@ public class HeartBeatUtil { if (recordedFuture.containsKey(checkAliveTask)) { cancel(checkAliveTask); } - ScheduledFuture future = - ContractManager.scheduledThreadPool.scheduleWithFixedDelay( - checkAliveTask, delay, period, TimeUnit.MILLISECONDS); + ScheduledFuture future = ContractManager.scheduledThreadPool + .scheduleWithFixedDelay(checkAliveTask, delay, period, TimeUnit.MILLISECONDS); recordedFuture.put(checkAliveTask, future); } catch (Exception e) { e.printStackTrace(); diff --git a/src/main/java/org/bdware/sc/udp/ContractExecuteInfo.java b/src/main/java/org/bdware/sc/udp/ContractExecuteInfo.java index 92bb3b4..71249d9 100644 --- a/src/main/java/org/bdware/sc/udp/ContractExecuteInfo.java +++ b/src/main/java/org/bdware/sc/udp/ContractExecuteInfo.java @@ -24,10 +24,8 @@ public class ContractExecuteInfo implements Serializable { public String invokeID; // TODO public ContractExecType type; public transient PriorityQueue queue; // contract request - public transient Map uniReqIDMap = - new ConcurrentHashMap<>(); // 用于请求 - public transient Map resultMap = - new ConcurrentHashMap<>(); // 用于请求 + public transient Map uniReqIDMap = new ConcurrentHashMap<>(); // 用于请求 + public transient Map resultMap = new ConcurrentHashMap<>(); // 用于请求 public transient PriorityQueue trans_queue; // transRecord private String contractID; private boolean isPrivate = false; @@ -44,10 +42,14 @@ public class ContractExecuteInfo implements Serializable { } public void init() { - if (queue == null) queue = new PriorityQueue(); - if (trans_queue == null) trans_queue = new PriorityQueue(); - if (uniReqIDMap == null) uniReqIDMap = new ConcurrentHashMap(); - if (resultMap == null) resultMap = new ConcurrentHashMap(); + if (queue == null) + queue = new PriorityQueue(); + if (trans_queue == null) + trans_queue = new PriorityQueue(); + if (uniReqIDMap == null) + uniReqIDMap = new ConcurrentHashMap(); + if (resultMap == null) + resultMap = new ConcurrentHashMap(); } public int getLastExeSeq() { @@ -56,15 +58,15 @@ public class ContractExecuteInfo implements Serializable { public void setLastExeSeq(int lastExeSeq) { this.lastExeSeq.set(lastExeSeq); - if (KeyValueDBUtil.instance.containsKey( - CMTables.LastExeSeq.toString(), contractID)) { // 如果现在是Stable模式就同步刷到磁盘 - KeyValueDBUtil.instance.setValue( - CMTables.LastExeSeq.toString(), contractID, lastExeSeq + ""); + if (KeyValueDBUtil.instance.containsKey(CMTables.LastExeSeq.toString(), contractID)) { // 如果现在是Stable模式就同步刷到磁盘 + KeyValueDBUtil.instance.setValue(CMTables.LastExeSeq.toString(), contractID, + lastExeSeq + ""); } } public boolean isSequent(int a) { - if (a - lastExeSeq.get() == 1) return true; + if (a - lastExeSeq.get() == 1) + return true; return false; } @@ -85,7 +87,8 @@ public class ContractExecuteInfo implements Serializable { } public String getPubKeyPath() { - if (!isPrivate) return null; + if (!isPrivate) + return null; return pubKeyPath; } @@ -136,7 +139,8 @@ public class ContractExecuteInfo implements Serializable { 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) { if (request.seq < lastExeSeq.get()) { if (request.getRequestID().endsWith("mul")) { diff --git a/src/main/java/org/bdware/server/CMHttpServer.java b/src/main/java/org/bdware/server/CMHttpServer.java index da7124c..7917516 100644 --- a/src/main/java/org/bdware/server/CMHttpServer.java +++ b/src/main/java/org/bdware/server/CMHttpServer.java @@ -57,9 +57,8 @@ public class CMHttpServer { private static final Logger LOGGER = LogManager.getLogger(CMHttpServer.class); private static final String CONFIG_PATH = "cmconfig.json"; public static EventLoopGroup workerGroup = new NioEventLoopGroup(); - public static MultiIndexTimeRocksDBUtil nodeLogDB = - new MultiIndexTimeRocksDBUtil( - "./ContractManagerDB", CMTables.LocalNodeLogDB.toString()); + public static MultiIndexTimeRocksDBUtil nodeLogDB = new MultiIndexTimeRocksDBUtil( + "./ContractManagerDB", CMTables.LocalNodeLogDB.toString()); public static URLClassLoader pluginLoader; private static SslContext sslContext = null; final String PATH = "/SCIDE/SCExecutor"; @@ -88,23 +87,21 @@ public class CMHttpServer { GlobalConf.initDOAConfig(doaConf); if (cmdConf.withBdledgerServer) { - ContractManager.threadPool.execute( - () -> NetworkManager.instance.initP2P(cmdConf.servicePort + 4)); + ContractManager.threadPool + .execute(() -> NetworkManager.instance.initP2P(cmdConf.servicePort + 4)); } // 可自动运行bdledger可执行文件,也可在shell脚步中运行和停止 if (!cmdConf.withBdledgerClient.isEmpty()) { - ContractManager.scheduledThreadPool.schedule( - () -> { - File ledgerClient = new File(cmdConf.withBdledgerClient); - LOGGER.debug("canRead=" + ledgerClient.canRead() + - " path=" + ledgerClient.getAbsolutePath()); - try { - Runtime.getRuntime().exec(ledgerClient.getAbsolutePath()); - } catch (IOException e) { - LOGGER.warn("start bdledger client failed: " + e.getMessage()); - } - }, - 1, TimeUnit.SECONDS); + ContractManager.scheduledThreadPool.schedule(() -> { + File ledgerClient = new File(cmdConf.withBdledgerClient); + LOGGER.debug("canRead=" + ledgerClient.canRead() + " path=" + + ledgerClient.getAbsolutePath()); + try { + Runtime.getRuntime().exec(ledgerClient.getAbsolutePath()); + } catch (IOException e) { + LOGGER.warn("start bdledger client failed: " + e.getMessage()); + } + }, 1, TimeUnit.SECONDS); } if (cmdConf.enableEventPersistence) { ContractManager.eventPersistenceEnabled = true; @@ -114,15 +111,12 @@ public class CMHttpServer { String[] filePaths = cmdConf.enableSsl.split(":"); File chainedFile = new File(filePaths[0]), keyFile = new File(filePaths[1]); if (chainedFile.exists() && keyFile.exists()) { - sslContext = - SslContextBuilder.forServer(chainedFile, keyFile) - .ciphers( - null, - (ciphers, defaultCiphers, supportedCiphers) -> - defaultCiphers.stream() - .filter(x -> null != x && !x.contains("RC4")) - .toArray(String[]::new)) - .build(); + sslContext = SslContextBuilder.forServer(chainedFile, keyFile) + .ciphers(null, + (ciphers, defaultCiphers, supportedCiphers) -> defaultCiphers + .stream().filter(x -> null != x && !x.contains("RC4")) + .toArray(String[]::new)) + .build(); LOGGER.info("openssl isAvailable:" + OpenSsl.isAvailable()); } } catch (Exception e) { @@ -142,7 +136,8 @@ public class CMHttpServer { // plugins CMHttpHandler.wsPluginActions = parseStrAsList(cmdConf.wsPluginActions); TCPClientFrameHandler.clientToAgentPlugins = parseStrAsList(cmdConf.clientToAgentPlugins); - NodeCenterClientHandler.clientToClusterPlugins = parseStrAsList(cmdConf.clientToClusterPlugins); + NodeCenterClientHandler.clientToClusterPlugins = + parseStrAsList(cmdConf.clientToClusterPlugins); org.bdware.units.tcp.TCPClientFrameHandler.tcpPlugins = parseStrAsList(cmdConf.tcpPlugins); if (!StringUtil.isNullOrEmpty(cmdConf.debug)) { try { @@ -161,37 +156,36 @@ public class CMHttpServer { } if (cmdConf.startContract != null && cmdConf.startContract.size() > 0) { - ContractManager.scheduledThreadPool.schedule( - () -> { - try { - for (JsonElement je : cmdConf.startContract) { - JsonObject jo = je.getAsJsonObject(); - if (!jo.has("path")) - continue; + ContractManager.scheduledThreadPool.schedule(() -> { + try { + for (JsonElement je : cmdConf.startContract) { + JsonObject jo = je.getAsJsonObject(); + if (!jo.has("path")) + continue; - String path = jo.get("path").getAsString(); - File f = new File(path); - if (!f.getName().endsWith(".ypk") || !f.exists()) - continue; - Contract c = new Contract(); - c.setScript(f.getAbsolutePath()); - c.setType(ContractExecType.Sole); - if (jo.has("killBeforeStart")) { - ContractManager.instance.stopContract(jo.get("killBeforeStart").getAsString()); - } - if (jo.has("owner")) - c.setOwner(jo.get("owner").getAsString()); - else - c.setOwner(UserManagerAction.getNodeManager()); - if (jo.has("createParam")) - c.setCreateParam(jo.get("createParam")); - ContractManager.instance.startContract(c); - } - } catch (Exception e) { - e.printStackTrace(); + String path = jo.get("path").getAsString(); + File f = new File(path); + if (!f.getName().endsWith(".ypk") || !f.exists()) + continue; + Contract c = new Contract(); + c.setScript(f.getAbsolutePath()); + c.setType(ContractExecType.Sole); + if (jo.has("killBeforeStart")) { + ContractManager.instance + .stopContract(jo.get("killBeforeStart").getAsString()); } - }, - 10, TimeUnit.SECONDS); + if (jo.has("owner")) + c.setOwner(jo.get("owner").getAsString()); + else + c.setOwner(UserManagerAction.getNodeManager()); + if (jo.has("createParam")) + c.setCreateParam(jo.get("createParam")); + ContractManager.instance.startContract(c); + } + } catch (Exception e) { + e.printStackTrace(); + } + }, 10, TimeUnit.SECONDS); } if (cmdConf.datachainConf != null) { GlobalConf.resetDataChain(cmdConf.datachainConf); @@ -204,7 +198,7 @@ public class CMHttpServer { private static String[] parseStrAsList(String str) { if (str == null) { - return new String[]{}; + return new String[] {}; } return str.split(","); } @@ -212,7 +206,7 @@ public class CMHttpServer { private static void addDirToPath(String s) { try { LOGGER.info("add to path: " + s); - // Field field = ClassLoader.class.getDeclaredField("sys_paths"); + // Field field = ClassLoader.class.getDeclaredField("sys_paths"); Field field = ClassLoader.class.getDeclaredField("usr_paths"); field.setAccessible(true); String[] path = (String[]) field.get(null); @@ -262,19 +256,15 @@ public class CMHttpServer { try { BufferedReader br = new BufferedReader(new FileReader(keyFile)); String pubKey = br.readLine(); - String nowManager = - KeyValueDBUtil.instance.getValue( - CMTables.ConfigDB.toString(), "__NodeManager__"); + String nowManager = KeyValueDBUtil.instance.getValue(CMTables.ConfigDB.toString(), + "__NodeManager__"); // manager.key is used when node manager isn' set if (null == nowManager || nowManager.isEmpty()) { - KeyValueDBUtil.instance.setValue( - CMTables.ConfigDB.toString(), "__NodeManager__", pubKey); - KeyValueDBUtil.instance.setValue( - CMTables.NodeRole.toString(), pubKey, + KeyValueDBUtil.instance.setValue(CMTables.ConfigDB.toString(), + "__NodeManager__", pubKey); + KeyValueDBUtil.instance.setValue(CMTables.NodeRole.toString(), pubKey, "NodeManager,ContractProvider,ContractUser,ContractInstanceManager"); - KeyValueDBUtil.instance.setValue( - CMTables.NodeTime.toString(), - pubKey, + KeyValueDBUtil.instance.setValue(CMTables.NodeTime.toString(), pubKey, Long.toString(new Date().getTime())); LOGGER.info("set node manager from manager.key"); } @@ -290,7 +280,7 @@ public class CMHttpServer { LOGGER.info("start server at:" + port); LOGGER.debug("dir:" + new File("./").getAbsolutePath()); new CMHttpServer(port).start(); - //never reach here!! + // never reach here!! } /** @@ -301,9 +291,9 @@ public class CMHttpServer { // EpollEventLoopGroup // EpollServerSocketChannel // ContractManager.reconnectPort = (port - 18000) * 30 + 1630; - // if (ContractManager.reconnectPort < 0) ContractManager.reconnectPort = 1630; - File[] pluginJar = new File("./pluginLib/") - .listFiles(pathname -> pathname.getName().endsWith(".jar")); + // if (ContractManager.reconnectPort < 0) ContractManager.reconnectPort = 1630; + File[] pluginJar = + new File("./pluginLib/").listFiles(pathname -> pathname.getName().endsWith(".jar")); URL[] urls; if (pluginJar != null && pluginJar.length > 0) { urls = new URL[pluginJar.length]; @@ -316,7 +306,7 @@ public class CMHttpServer { } } } else { - urls = new URL[]{}; + urls = new URL[] {}; } pluginLoader = new URLClassLoader(urls, CMHttpServer.class.getClassLoader()); if (port >= 18000 && port < 18100) { @@ -332,28 +322,20 @@ public class CMHttpServer { try { ServerBootstrap b1 = new ServerBootstrap(); b1.option(ChannelOption.ALLOCATOR, PooledByteBufAllocator.DEFAULT); - b1.group(bossGroup, workerGroup) - .channel(NioServerSocketChannel.class) - .localAddress(port) - .childHandler( - new ChannelInitializer() { - @Override - protected void initChannel(SocketChannel arg0) { - if (sslContext != null) { - arg0.pipeline().addLast(new OptionalSslHandler(sslContext)); - } - arg0.pipeline() - .addLast(trafficSharp) - .addLast(new HttpServerCodec()) - .addLast(new HttpObjectAggregator(10 * 1024 * 1024)) - .addLast( - new WebSocketServerProtocolHandler( - PATH, null, true)) - .addLast(new ChunkedWriteHandler()) - .addLast(serverHandler) - .addLast(new ContractManagerFrameHandler()); - } - }); + b1.group(bossGroup, workerGroup).channel(NioServerSocketChannel.class) + .localAddress(port).childHandler(new ChannelInitializer() { + @Override + protected void initChannel(SocketChannel arg0) { + if (sslContext != null) { + arg0.pipeline().addLast(new OptionalSslHandler(sslContext)); + } + arg0.pipeline().addLast(trafficSharp).addLast(new HttpServerCodec()) + .addLast(new HttpObjectAggregator(10 * 1024 * 1024)) + .addLast(new WebSocketServerProtocolHandler(PATH, null, true)) + .addLast(new ChunkedWriteHandler()).addLast(serverHandler) + .addLast(new ContractManagerFrameHandler()); + } + }); final Channel ch = b1.bind(port).sync().channel(); LOGGER.debug("[CMHttpServer] listen master port at:" + port); new HTTPServer(port + 3); @@ -370,8 +352,7 @@ public class CMHttpServer { @Sharable public static class NettyConnectServerHandler extends ChannelInboundHandlerAdapter { - public NettyConnectServerHandler(AtomicInteger connectNum) { - } + public NettyConnectServerHandler(AtomicInteger connectNum) {} @Override public void channelRegistered(ChannelHandlerContext ctx) throws Exception { diff --git a/src/main/java/org/bdware/server/GRPCPool.java b/src/main/java/org/bdware/server/GRPCPool.java index b881710..a77c032 100644 --- a/src/main/java/org/bdware/server/GRPCPool.java +++ b/src/main/java/org/bdware/server/GRPCPool.java @@ -68,11 +68,12 @@ public class GRPCPool implements ChainOpener { private String dataNodeIP; private int dataNodePort; static final String DBDir = "ContractManagerDB/GRPCPool"; - // public static OnHashCallback callback; //for CM write on chain + + // public static OnHashCallback callback; //for CM write on chain GRPCPool() { - logIndex = new LenVarTimeSerialIndex("./"+DBDir+"/hashToData.index", 20); - requestID2Hash = openDB("./"+DBDir+"/requestIDToHash", "req2Hash"); - hash2Data = openDB("./"+DBDir+"/hashToData", "hash2Data"); + logIndex = new LenVarTimeSerialIndex("./" + DBDir + "/hashToData.index", 20); + requestID2Hash = openDB("./" + DBDir + "/requestIDToHash", "req2Hash"); + hash2Data = openDB("./" + DBDir + "/hashToData", "hash2Data"); contractName2LogIndex = new HashMap<>(); instances = new ArrayList<>(); for (int i = 0; i < WORKER_COUNT; ++i) { @@ -112,15 +113,12 @@ public class GRPCPool implements ChainOpener { params.put("DOI", "86.5000.470/" + sucFix); params.put("Description", "DataWare Contract Info"); params.put("Interface", ""); - params.put( - "Address", + params.put("Address", "http://39.106.6.6:8080/SCIDE/CMManager?action=queryDataByHash&hash=" + hash); byte[] signature; try { - signature = - SM2Util.sign( - GlobalConf.instance.keyPair.getPrivateKeyParameter(), - origin.getBytes()); + signature = SM2Util.sign(GlobalConf.instance.keyPair.getPrivateKeyParameter(), + origin.getBytes()); } catch (Exception e) { signature = "no signature".getBytes(); } @@ -130,14 +128,8 @@ public class GRPCPool implements ChainOpener { HttpPostForm.postForm(url, params); } - private static Line wrapperLine( - OnHashCallback cb, - String from, - String to, - String data, - String requestID, - String contractName, - String namedLedger) { + private static Line wrapperLine(OnHashCallback cb, String from, String to, String data, + String requestID, String contractName, String namedLedger) { Line l = new Line(); l.cb = cb; l.from = from; @@ -150,24 +142,15 @@ public class GRPCPool implements ChainOpener { } public static void updateContractInfo(String contractName, long times, long traffic) { - KeyValueDBUtil.instance.setValue( - CMTables.ContractInfo.toString(), contractName + "-Times", times + ""); - KeyValueDBUtil.instance.setValue( - CMTables.ContractInfo.toString(), contractName + "-Traffic", traffic + ""); + KeyValueDBUtil.instance.setValue(CMTables.ContractInfo.toString(), contractName + "-Times", + times + ""); + KeyValueDBUtil.instance.setValue(CMTables.ContractInfo.toString(), + contractName + "-Traffic", traffic + ""); } - public static void addLocalContractLog( - String action, - String contractID, - String contractName, - String pubKey, - String function, - long startTime, - long costTime, - long totalGas, - long executionGas, - long extraGas, - Map logType) { + public static void addLocalContractLog(String action, String contractID, String contractName, + String pubKey, String function, long startTime, long costTime, long totalGas, + long executionGas, long extraGas, Map logType) { // if (disable) return; JsonObject jo = new JsonObject(); jo.addProperty("action", action); @@ -191,8 +174,7 @@ public class GRPCPool implements ChainOpener { } @Override - protected void finalize() { - } + protected void finalize() {} public void reloadConf(String confFile) { loadConf(confFile); @@ -222,25 +204,14 @@ public class GRPCPool implements ChainOpener { } @Override - public void writeToChain( - OnHashCallback callback, - String from, - String to, - String data, - String requestID, - String namedLedger) { + public void writeToChain(OnHashCallback callback, String from, String to, String data, + String requestID, String namedLedger) { writeToChainWithContract(callback, from, to, data, requestID, null, namedLedger); } @Override - public void writeToChainWithContract( - OnHashCallback cb, - String from, - String to, - String data, - String requestID, - String contractName, - String namedLedger) { + public void writeToChainWithContract(OnHashCallback cb, String from, String to, String data, + String requestID, String contractName, String namedLedger) { Line l = wrapperLine(cb, from, to, data, requestID, contractName, namedLedger); WorkerThread t = getNextWorkerThread(); if (t != null) { @@ -271,7 +242,7 @@ public class GRPCPool implements ChainOpener { @Override public void reRegister(String doid) { - //TODO just success + // TODO just success // throw new IllegalStateException("TODO"); } @@ -280,13 +251,8 @@ public class GRPCPool implements ChainOpener { } @Override - public void writeContractResultToLocalAndLedger( - String result, - ContractClient client, - ContractRequest contractRequest, - OnHashCallback cb, - long start, - long time) { + public void writeContractResultToLocalAndLedger(String result, ContractClient client, + ContractRequest contractRequest, OnHashCallback cb, long start, long time) { ContractResultLine l = new ContractResultLine(); l.client = client; l.contractRequest = contractRequest; @@ -343,21 +309,14 @@ public class GRPCPool implements ChainOpener { ret.put("action", "onQueryHashByReqID"); if (args.has("requestID")) { try { - ret.put( - "data", - new String( - requestID2Hash.get( - args.get("requestID").getAsString().getBytes()))); + ret.put("data", new String( + requestID2Hash.get(args.get("requestID").getAsString().getBytes()))); } catch (Exception e) { - ret.put( - "data", - "Match failed! " - + "Can't find hash by this requestID " - + args.get("requestID").getAsString()); + ret.put("data", "Match failed! " + "Can't find hash by this requestID " + + args.get("requestID").getAsString()); } } else { - ret.put( - "data", + ret.put("data", "Can't find hash by this requestID " + args.get("requestID").getAsString()); } resultCallback.onResult(JsonUtil.toJson(ret)); @@ -384,13 +343,16 @@ public class GRPCPool implements ChainOpener { index = createIndexIfNotExist(args.get("contractName").getAsString()); } - //根据事务类型查找 + // 根据事务类型查找 else if (args.has("type")) { index = createIndexIfNotExist(args.get("type").getAsString()); - } else index = logIndex; + } else + index = logIndex; List result; - if (offset < 0) result = index.requestLast(count); - else result = index.request(offset, count); + if (offset < 0) + result = index.requestLast(count); + else + result = index.request(offset, count); for (byte[] data : result) { long date = HashUtil.bytes2Long(data); String hash = HashUtil.byteArray2Str(data, 8); @@ -419,12 +381,10 @@ public class GRPCPool implements ChainOpener { ret.put("action", "onQueryDataByHash"); if (args.has("hash")) { try { - JsonObject jo = - JsonParser.parseString( - new String( - hash2Data.get( - args.get("hash").getAsString().getBytes()))) - .getAsJsonObject(); + JsonObject jo = JsonParser + .parseString(new String( + hash2Data.get(args.get("hash").getAsString().getBytes()))) + .getAsJsonObject(); jo.addProperty("action", "onQueryDataByHash"); resultCallback.onResult(JsonUtil.toJson(jo)); return; @@ -457,19 +417,16 @@ public class GRPCPool implements ChainOpener { ret.put("action", "onQueryDataByHash"); if (args.has("hash")) { try { - JsonObject jo = - JsonParser.parseString( - new String( - hash2Data.get( - args.get("hash").getAsString().getBytes()))) - .getAsJsonObject(); + JsonObject jo = JsonParser + .parseString(new String( + hash2Data.get(args.get("hash").getAsString().getBytes()))) + .getAsJsonObject(); jo.addProperty("action", "onQueryDataByHash"); resultCallback.onResult(JsonUtil.toJson(jo)); return; } catch (Exception e) { e.printStackTrace(); - ret.put( - "data", + ret.put("data", "!!! " + "Can't find data by hash " + args.get("hash").getAsString()); } } else { @@ -485,7 +442,8 @@ public class GRPCPool implements ChainOpener { LenVarTimeSerialIndex index = null; if (args.has("contractName")) index = createIndexIfNotExist(args.get("contractName").getAsString()); - if (index == null) index = logIndex; + if (index == null) + index = logIndex; ret.put("count", index.size() + ""); resultCallback.onResult(JsonUtil.toJson(ret)); } @@ -512,11 +470,8 @@ public class GRPCPool implements ChainOpener { obj.put("hash", hash); obj.put("date", date); try { - obj.put( - "data", - JsonParser.parseString( - new String( - hash2Data.get(args.get("hash").getAsString().getBytes())))); + obj.put("data", JsonParser.parseString( + new String(hash2Data.get(args.get("hash").getAsString().getBytes())))); } catch (Exception e) { e.printStackTrace(); } @@ -547,11 +502,8 @@ public class GRPCPool implements ChainOpener { obj.put("hash", hash); obj.put("date", date); try { - obj.put( - "data", - shortStr( - new String( - hash2Data.get(args.get("hash").getAsString().getBytes())))); + obj.put("data", shortStr( + new String(hash2Data.get(args.get("hash").getAsString().getBytes())))); } catch (Exception e) { e.printStackTrace(); } @@ -561,8 +513,10 @@ public class GRPCPool implements ChainOpener { } private String shortStr(String str) { - if (str != null && str.length() > 50) return str.substring(0, 50); - else return str; + if (str != null && str.length() > 50) + return str.substring(0, 50); + else + return str; } @Action(async = true, userPermission = 1L << 24) @@ -575,7 +529,7 @@ public class GRPCPool implements ChainOpener { RocksIterator iter = hash2Data.newIterator(); iter.seekToFirst(); List hashes = new ArrayList<>(); - for (; iter.isValid(); ) { + for (; iter.isValid();) { iter.value(); hashes.add(new String(iter.value())); iter.next(); @@ -584,7 +538,8 @@ public class GRPCPool implements ChainOpener { List times = new ArrayList<>(); for (String str : hashes) { Long time = getDataTime(str); - if (time < 0) continue; + if (time < 0) + continue; times.add(time); memoryIndex.put(time, str); } @@ -602,8 +557,7 @@ public class GRPCPool implements ChainOpener { try { String obj = new String(hash2Data.get(key.getBytes())); Map parsedObj = - JsonUtil.fromJson(obj, new TypeToken>() { - }.getType()); + JsonUtil.fromJson(obj, new TypeToken>() {}.getType()); String data = parsedObj.get("data"); int len = "1575452533275".length(); @@ -620,9 +574,8 @@ public class GRPCPool implements ChainOpener { private synchronized LenVarTimeSerialIndex createIndexIfNotExist(String contractName) { LenVarTimeSerialIndex index = contractName2LogIndex.get(contractName); if (index == null) { - index = - new LenVarTimeSerialIndex( - "./"+DBDir+"/hashByContract/" + contractName + ".index", 20); + index = new LenVarTimeSerialIndex( + "./" + DBDir + "/hashByContract/" + contractName + ".index", 20); contractName2LogIndex.put(contractName, index); } return index; @@ -647,8 +600,7 @@ public class GRPCPool implements ChainOpener { static SecureRandom random = new SecureRandom((System.currentTimeMillis() + "").getBytes()); boolean exit = false; - WorkerThread() { - } + WorkerThread() {} public static byte[] getRandomByte(int len) { Random random = new Random(); @@ -662,7 +614,7 @@ public class GRPCPool implements ChainOpener { public void run() { while (true) { - // System.out.println("[GRPCPool] for circleing"); + // System.out.println("[GRPCPool] for circleing"); Line l = uploadContent.poll(); if (l != null) { if (l instanceof ContractResultLine) { @@ -711,65 +663,50 @@ public class GRPCPool implements ChainOpener { ListenableFuture ret2; if (l.ledgerName != null && !l.ledgerName.equals("")) { - ret2 = - client.sendTransaction( - l.ledgerName, - CommonProto.TransactionType.MESSAGE, - l.from, - random.nextLong(), - l.to, - l.data.getBytes(StandardCharsets.UTF_8)); + ret2 = client.sendTransaction(l.ledgerName, CommonProto.TransactionType.MESSAGE, + l.from, random.nextLong(), l.to, + l.data.getBytes(StandardCharsets.UTF_8)); } else { - ret2 = - client.sendTransaction( - LEDGER_NAME, - CommonProto.TransactionType.MESSAGE, - l.from, random.nextLong(), - l.to, - l.data.getBytes(StandardCharsets.UTF_8)); + ret2 = client.sendTransaction(LEDGER_NAME, CommonProto.TransactionType.MESSAGE, + l.from, random.nextLong(), l.to, + l.data.getBytes(StandardCharsets.UTF_8)); } if (ret2 != null) - ret2.addListener( - new Runnable() { - @Override - public void run() { - try { - ByteString hash = ret2.get().getHash(); - String hashStr; - if (hash == null) { - hash = ByteString.copyFrom(getRandomByte(20)); - hashStr = HashUtil.byteArray2Str(hash.toByteArray()); - LOGGER.info("generate fake hash: " + hashStr); - } else { - hashStr = HashUtil.byteArray2Str(hash.toByteArray()); - } - if (!l.data.startsWith("MockTransaction_")) { - if (null != l.cb) { - l.cb.publishHash(l.requestID, hashStr); - } - instance.logIndex.index(HashUtil.str16ToBytes(hashStr)); - if (null != l.contractName) { - LenVarTimeSerialIndex index = - instance.createIndexIfNotExist( - l.contractName); - index.index(HashUtil.str16ToBytes(hashStr)); - } - instance.hash2Data.put( - hashStr.getBytes(), JsonUtil.toJson(l).getBytes()); - instance.requestID2Hash.put( - l.requestID.getBytes(), hashStr.getBytes()); - LOGGER.debug( - "put requestID: " - + l.requestID - + " hash: " - + hashStr); - } - } catch (Exception e) { - LOGGER.warn(e.getMessage()); - } + ret2.addListener(new Runnable() { + @Override + public void run() { + try { + ByteString hash = ret2.get().getHash(); + String hashStr; + if (hash == null) { + hash = ByteString.copyFrom(getRandomByte(20)); + hashStr = HashUtil.byteArray2Str(hash.toByteArray()); + LOGGER.info("generate fake hash: " + hashStr); + } else { + hashStr = HashUtil.byteArray2Str(hash.toByteArray()); } - }, - executorService); + if (!l.data.startsWith("MockTransaction_")) { + if (null != l.cb) { + l.cb.publishHash(l.requestID, hashStr); + } + instance.logIndex.index(HashUtil.str16ToBytes(hashStr)); + if (null != l.contractName) { + LenVarTimeSerialIndex index = + instance.createIndexIfNotExist(l.contractName); + index.index(HashUtil.str16ToBytes(hashStr)); + } + instance.hash2Data.put(hashStr.getBytes(), + JsonUtil.toJson(l).getBytes()); + instance.requestID2Hash.put(l.requestID.getBytes(), + hashStr.getBytes()); + LOGGER.debug( + "put requestID: " + l.requestID + " hash: " + hashStr); + } + } catch (Exception e) { + LOGGER.warn(e.getMessage()); + } + } + }, executorService); // ByteString hash = ByteString.copyFrom(new byte[] { 1, 2, 2, 2 }); } catch (Exception e) { @@ -779,8 +716,8 @@ public class GRPCPool implements ChainOpener { } } - public Map analysisLocalContractLog( - String data2, ContractRequest c, String detail) { + public Map analysisLocalContractLog(String data2, ContractRequest c, + String detail) { // 本地日志 JsonObject jo = JsonParser.parseString(data2).getAsJsonObject(); Map logType = new HashMap<>(); @@ -844,7 +781,7 @@ public class GRPCPool implements ChainOpener { ContractClient client = l.client; cr = JsonUtil.fromJson(l.data, ContractResult.class); // updateContractInfo( - // client.getContractName(), client.getTimes(), client.getTraffic()); + // client.getContractName(), client.getTimes(), client.getTraffic()); String detail = client.getLogType(l.contractRequest.getAction()); Map logType = analysisLocalContractLog(l.data, l.contractRequest, detail); @@ -870,32 +807,14 @@ public class GRPCPool implements ChainOpener { // LOGGER.debug("type: " + JsonUtil.toJson(logType) + " | detail: " + // detail); - addLocalContractLog( - "executeContract", - contractID, - contractName, - l.contractRequest.getPublicKey(), - l.contractRequest.getAction(), - l.start, - l.costTime, - cr.totalGas, - cr.executionGas, - cr.extraGas, - logType); + addLocalContractLog("executeContract", contractID, contractName, + l.contractRequest.getPublicKey(), l.contractRequest.getAction(), l.start, + l.costTime, cr.totalGas, cr.executionGas, cr.extraGas, logType); // 929 1277 1448 1417 1507 if (l.contractRequest.fromContract != null) { - addLocalContractLog( - "executeContract", - contractID, - contractName, - l.contractRequest.fromContract, - l.contractRequest.getAction(), - l.start, - l.costTime, - cr.totalGas, - cr.executionGas, - cr.extraGas, - logType); + addLocalContractLog("executeContract", contractID, contractName, + l.contractRequest.fromContract, l.contractRequest.getAction(), l.start, + l.costTime, cr.totalGas, cr.executionGas, cr.extraGas, logType); } // 1027 1563 1461 1519 1501 if (toBDContract || toNamedLedger) { @@ -910,29 +829,17 @@ public class GRPCPool implements ChainOpener { // 1025 1422 1497 1447 1445 if (toBDContract) { - Line l1 = - wrapperLine( - l.cb, - l.contractRequest.getPublicKey(), - "executeContract", - JsonUtil.toJson(logType), - l.contractRequest.getRequestID(), - contractName, - ""); + Line l1 = wrapperLine(l.cb, l.contractRequest.getPublicKey(), "executeContract", + JsonUtil.toJson(logType), l.contractRequest.getRequestID(), + contractName, ""); writeChain(l1); } - // 1424 1421 1443 1160 1611 + // 1424 1421 1443 1160 1611 if (toNamedLedger) { for (String name : namedLedger) { - Line l2 = - wrapperLine( - l.cb, - l.contractRequest.getPublicKey(), - "executeContract", - JsonUtil.toJson(logType), - l.contractRequest.getRequestID(), - contractName, - name); + Line l2 = wrapperLine(l.cb, l.contractRequest.getPublicKey(), + "executeContract", JsonUtil.toJson(logType), + l.contractRequest.getRequestID(), contractName, name); writeChain(l2); } } diff --git a/src/main/java/org/bdware/server/GlobalConf.java b/src/main/java/org/bdware/server/GlobalConf.java index 6451776..7700a7e 100644 --- a/src/main/java/org/bdware/server/GlobalConf.java +++ b/src/main/java/org/bdware/server/GlobalConf.java @@ -17,7 +17,6 @@ import org.zz.gmhelper.SM2KeyPair; import org.zz.gmhelper.SM2Util; import java.io.File; -import java.net.URL; import java.util.logging.Level; public class GlobalConf { @@ -64,14 +63,11 @@ public class GlobalConf { private static GlobalConf init() { java.util.logging.Logger.getLogger(org.bdware.bdledger.api.grpc.Client.class.getName()) .setLevel(Level.OFF); - Configurator.setLevel( - "io.netty.handler.codec.http.websocketx.WebSocket08FrameEncoder", + Configurator.setLevel("io.netty.handler.codec.http.websocketx.WebSocket08FrameEncoder", org.apache.logging.log4j.Level.OFF); - Configurator.setLevel( - "io.netty.handler.codec.http.websocketx.WebSocket08FrameDecoder", + Configurator.setLevel("io.netty.handler.codec.http.websocketx.WebSocket08FrameDecoder", org.apache.logging.log4j.Level.OFF); - Configurator.setLevel( - "io.netty.handler.codec.http.websocketx.WebSocketServerHandshaker", + Configurator.setLevel("io.netty.handler.codec.http.websocketx.WebSocketServerHandshaker", org.apache.logging.log4j.Level.OFF); KeyValueDBUtil.setupCM(); @@ -83,19 +79,17 @@ public class GlobalConf { String dbName = CMTables.ConfigDB.toString(); if (!KeyValueDBUtil.instance.getKeys(dbName).contains("hasInited")) { KeyValueDBUtil.instance.setValue(dbName, "hasInited", "true"); - KeyValueDBUtil.instance.setValue( - dbName, "projectDir", new File("./BDWareProjectDir/").getAbsolutePath()); - KeyValueDBUtil.instance.setValue( - dbName, - "ADSPDir", + KeyValueDBUtil.instance.setValue(dbName, "projectDir", + new File("./BDWareProjectDir/").getAbsolutePath()); + KeyValueDBUtil.instance.setValue(dbName, "ADSPDir", new File("./BDWareProjectDir/ADSPDir/").getAbsolutePath()); File f = new File("./yjs.jar"); if (f.exists()) { - KeyValueDBUtil.instance.setValue( - dbName, "yjsPath", new File("./yjs.jar").getAbsolutePath()); + KeyValueDBUtil.instance.setValue(dbName, "yjsPath", + new File("./yjs.jar").getAbsolutePath()); } else { - KeyValueDBUtil.instance.setValue( - dbName, "yjsPath", new File("./cp/yjs.jar").getAbsolutePath()); + KeyValueDBUtil.instance.setValue(dbName, "yjsPath", + new File("./cp/yjs.jar").getAbsolutePath()); } conf.keyPairStr = SM2Util.generateSM2KeyPair().toJson(); @@ -111,40 +105,27 @@ public class GlobalConf { // long time = System.currentTimeMillis()+15811200000; String licence = - ByteHexUtil.encode( - SM2Util.encrypt( - conf.keyPair.getPublicKey(), - (HardwareInfo.getCPUID() - + "==" - + (System.currentTimeMillis() - + 15811200000L)) - .getBytes())); + ByteHexUtil + .encode(SM2Util.encrypt(conf.keyPair.getPublicKey(), + (HardwareInfo.getCPUID() + "==" + + (System.currentTimeMillis() + 15811200000L)) + .getBytes())); LOGGER.debug("licence:" + licence); - LOGGER.debug( - String.format( - "deviceName %s license %s %s==%d", - deviceName, - licence, - HardwareInfo.getCPUID(), - (System.currentTimeMillis() + 15811200000L))); + LOGGER.debug(String.format("deviceName %s license %s %s==%d", deviceName, licence, + HardwareInfo.getCPUID(), (System.currentTimeMillis() + 15811200000L))); KeyValueDBUtil.instance.setValue(dbName, "licence", licence); KeyValueDBUtil.instance.setValue(dbName, "nodeName", deviceName.substring(0, 10)); KeyValueDBUtil.instance.setValue(dbName, "masterAddress", "null"); KeyValueDBUtil.instance.setValue(dbName, "ipPort", "null"); KeyValueDBUtil.instance.setValue(dbName, "nodeCenter", "ws://127.0.0.1:18005"); - KeyValueDBUtil.instance.setValue( - dbName, - "datachainConf", - "39.104.70.160:18091\n" - + "47.98.247.70:18091\n" - + "47.98.248.208:18091\n" - + "39.104.77.165:18091\n" - + "47.98.249.131:18091"); + KeyValueDBUtil.instance.setValue(dbName, "datachainConf", + "39.104.70.160:18091\n" + "47.98.247.70:18091\n" + "47.98.248.208:18091\n" + + "39.104.77.165:18091\n" + "47.98.249.131:18091"); } conf.projectDir = KeyValueDBUtil.instance.getValue(dbName, "projectDir"); - conf.bcoDir = conf.projectDir+"/bco"; + conf.bcoDir = conf.projectDir + "/bco"; conf.publicDir = KeyValueDBUtil.instance.getValue(dbName, "projectDir") + "/public"; conf.ADSPDir = KeyValueDBUtil.instance.getValue(dbName, "projectDir") + "/ADSPDir"; conf.publicCompiledDir = @@ -211,9 +192,8 @@ public class GlobalConf { 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.ADSPDir).getAbsolutePath()); - LOGGER.debug( - "[GlobalConf] publicDirCompiled Path:" - + new File(conf.publicCompiledDir).getAbsolutePath()); + LOGGER.debug("[GlobalConf] publicDirCompiled Path:" + + new File(conf.publicCompiledDir).getAbsolutePath()); LOGGER.debug( "[GlobalConf] PersonalDir Path:" + new File(conf.privateDir).getAbsolutePath()); LOGGER.debug("[GlobalConf] memorytDir Path:" + new File(conf.memoryDir).getAbsolutePath()); @@ -250,16 +230,17 @@ public class GlobalConf { private static void verifyLicence(GlobalConf conf) { try { -// String pubkey = -// "OTIzNmUzMGNmOGI1ZjFkMDBjZjEyMWY4OThmM2ZmYTIwNjE2ODYxOWNiMDNhMTVlM2FiZTA0OThhNTlkZDg1MmRi" + -// "MjA5Njc1NmM3ZDBhOWM3YTNkOTg2NWVlYzk2YzM1MmY0MDdkMGMyOTA4M2NkNDI4YmY1YjM5M2U5OTA1" + -// "NWE0MzM0MTJhM2Y2ZDhkZWVmZDk4MmI4NmZiZTMyYjhlMGE3ZWFmZmE5ODM3M2E4ZTRmNTYyNDgxNTY0" + -// "Yjk2ZjFkMTZiODk2MGRhZDAwMTNjZDYwOGZmOTcxNjdiOWI1MDU1MjJlMzk0ODhmODczNDJjNWUwOGRj" + -// "ZjFhZjFkYzBjODUxZjRlNDg2ZWIyOTM5NDI3MDc4MjA5NDg5ODliODVhZDNlOGJlNWJiYWEzZDUyMWU2" + -// "MjdmZjE3NGY4Y2ZlZDk3NTY4OWNlNDEzOGYyMTgyOWIwMDVmMzE0YjM3MmNlZmFkZjBkNmUyOTY4ZGUz" + -// "ZmFlNGUxNTFkMWFmNWE4Mjc4ZjQ2MDI5ODBjY2JkMDM0ZDE0YWRjZDk1ZjI1MjY3NmRlODRjYzdkNzU5" + -// "NGYyYTAxMTliYWJmYjgyMGRjMWNjZWZjNThjNWUwYWRjMDQyM2MzYzA1ODNhZTU1MWZlN2Y5YTYwYjkx" + -// "Zjg2YWViNDNlMzU0NzlhYWI5YmFjOTAwN2IsMTAwMDEsMA=="; + // String pubkey = + // "OTIzNmUzMGNmOGI1ZjFkMDBjZjEyMWY4OThmM2ZmYTIwNjE2ODYxOWNiMDNhMTVlM2FiZTA0OThhNTlkZDg1MmRi" + // + + // "MjA5Njc1NmM3ZDBhOWM3YTNkOTg2NWVlYzk2YzM1MmY0MDdkMGMyOTA4M2NkNDI4YmY1YjM5M2U5OTA1" + + // "NWE0MzM0MTJhM2Y2ZDhkZWVmZDk4MmI4NmZiZTMyYjhlMGE3ZWFmZmE5ODM3M2E4ZTRmNTYyNDgxNTY0" + + // "Yjk2ZjFkMTZiODk2MGRhZDAwMTNjZDYwOGZmOTcxNjdiOWI1MDU1MjJlMzk0ODhmODczNDJjNWUwOGRj" + + // "ZjFhZjFkYzBjODUxZjRlNDg2ZWIyOTM5NDI3MDc4MjA5NDg5ODliODVhZDNlOGJlNWJiYWEzZDUyMWU2" + + // "MjdmZjE3NGY4Y2ZlZDk3NTY4OWNlNDEzOGYyMTgyOWIwMDVmMzE0YjM3MmNlZmFkZjBkNmUyOTY4ZGUz" + + // "ZmFlNGUxNTFkMWFmNWE4Mjc4ZjQ2MDI5ODBjY2JkMDM0ZDE0YWRjZDk1ZjI1MjY3NmRlODRjYzdkNzU5" + + // "NGYyYTAxMTliYWJmYjgyMGRjMWNjZWZjNThjNWUwYWRjMDQyM2MzYzA1ODNhZTU1MWZlN2Y5YTYwYjkx" + + // "Zjg2YWViNDNlMzU0NzlhYWI5YmFjOTAwN2IsMTAwMDEsMA=="; LOGGER.debug("beforedecode:" + conf.licence); if (conf.licence != null && conf.licence.length() > 8) { @@ -267,11 +248,8 @@ public class GlobalConf { try { // byte[] arr = key.encode(new BASE64Decoder().decodeBuffer(conf.licence)); // String actualKey = new String(arr); - String arr = - new String( - SM2Util.decrypt( - conf.keyPair.getPrivateKeyParameter(), - ByteHexUtil.decode(conf.licence))); + String arr = new String(SM2Util.decrypt(conf.keyPair.getPrivateKeyParameter(), + ByteHexUtil.decode(conf.licence))); LOGGER.debug("[GlobalConf] actualKey:" + arr); @@ -326,7 +304,8 @@ public class GlobalConf { } 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); } } diff --git a/src/main/java/org/bdware/server/SDKContext.java b/src/main/java/org/bdware/server/SDKContext.java index 3a7c6aa..468d063 100644 --- a/src/main/java/org/bdware/server/SDKContext.java +++ b/src/main/java/org/bdware/server/SDKContext.java @@ -28,7 +28,8 @@ public class SDKContext implements ISDKContext { ICMActions cmActionsProxy = new CMActionsProxy(); - IMasterServerRecoverMechAction masterServerRecoverMechActionProxy = new MasterServerRecoverMechActionProxy(); + IMasterServerRecoverMechAction masterServerRecoverMechActionProxy = + new MasterServerRecoverMechActionProxy(); IGlobalConf globalConfProxy = new GlobalProxy(); @@ -81,9 +82,7 @@ public class SDKContext implements ISDKContext { @Override public void asyncExecuteContractLocally(JsonObject jo, ResultCallback rc) { - executorService.execute( - () -> _masterClientTCPAction.executeContractLocally(jo, rc) - ); + executorService.execute(() -> _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 public Map> getRecoverStatusMap() { return MasterServerRecoverMechAction.recoverStatus; diff --git a/src/main/java/org/bdware/server/action/CMActions.java b/src/main/java/org/bdware/server/action/CMActions.java index 5ede0cd..0fc0e6b 100644 --- a/src/main/java/org/bdware/server/action/CMActions.java +++ b/src/main/java/org/bdware/server/action/CMActions.java @@ -40,8 +40,8 @@ public class CMActions implements OnHashCallback { private static final JsonObject MISSING_ARGUMENT = JsonUtil.parseStringAsJsonObject("{\"action\":\"onExecuteResult\",\"executeTime\":-1," + "\"status\":\"Error\",\"result\":\"missing arguments\"}"); - private static final JsonObject INVALID_DOI = JsonUtil.parseStringAsJsonObject( - "{\"action\":\"onExecuteResult\",\"executeTime\":-1," + private static final JsonObject INVALID_DOI = + JsonUtil.parseStringAsJsonObject("{\"action\":\"onExecuteResult\",\"executeTime\":-1," + "\"status\":\"Error\",\"result\":\"invalid contract doi\"}"); private static final Logger LOGGER = LogManager.getLogger(CMActions.class); public static ContractManager manager = initManager(); @@ -66,32 +66,31 @@ public class CMActions implements OnHashCallback { contractManager.chainOpener = GRPCPool.instance; GRPCPool.logsDB = ContractManager.logsDB; // expiredDate = Long.parseLong(GlobalConf.instance.licence); - ContractManager.threadPool.execute( - () -> { - long start = System.currentTimeMillis(); - contractManager.reconnectContractProcess(); - // 重启动时所有合约都不是master - // contractManager.initAnalysisClient(); - List contractIDS = new ArrayList<>(); - for (ContractMeta meta : contractManager.statusRecorder.getStatus().values()) { - if (meta.getStatus() == ContractStatusEnum.RUNNING) { - contractIDS.add(meta.getID()); - if (meta.contract.getType().needSeq()) - contractManager.setContractIsMaster(meta.getID(), "false"); - } - } + ContractManager.threadPool.execute(() -> { + long start = System.currentTimeMillis(); + contractManager.reconnectContractProcess(); + // 重启动时所有合约都不是master + // contractManager.initAnalysisClient(); + List contractIDS = new ArrayList<>(); + for (ContractMeta meta : contractManager.statusRecorder.getStatus().values()) { + if (meta.getStatus() == ContractStatusEnum.RUNNING) { + contractIDS.add(meta.getID()); + if (meta.contract.getType().needSeq()) + contractManager.setContractIsMaster(meta.getID(), "false"); + } + } - NetworkManager.instance.waitForNodeCenterConnected(); - ExecutionManager.instance.updateLocalContractToNodeCenter(); - }); + NetworkManager.instance.waitForNodeCenterConnected(); + ExecutionManager.instance.updateLocalContractToNodeCenter(); + }); RecoverMechTimeRecorder.startFinish = System.currentTimeMillis(); return contractManager; } - public static void listContractProcessWithFirstWithOwner( - String owner, String id, ResultCallback resultCallback) { + public static void listContractProcessWithFirstWithOwner(String owner, String id, + ResultCallback resultCallback) { LOGGER.debug("[CMActions listContractProcessWithFirstWithOwner] id=" + id); String data = manager.listContractsWithOwner(owner, id, 1 << 1); ReplyUtil.simpleReply(resultCallback, "onListContractProcess", data); @@ -112,14 +111,10 @@ public class CMActions implements OnHashCallback { return sb.toString(); } - public static void executeContractInternal( - final JsonObject args, - final ResultCallback resultCallback, - final OnHashCallback hashcb) { + public static void executeContractInternal(final JsonObject args, + final ResultCallback resultCallback, final OnHashCallback hashcb) { final ContractRequest cReq = 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); return; } @@ -130,7 +125,7 @@ public class CMActions implements OnHashCallback { if (args.has("contractID")) { cReq.setContractID(args.get("contractID").getAsString()); } - + if (args.has("isDebug")) { cReq.setFromDebug(args.get("isDebug").getAsBoolean()); } @@ -185,39 +180,32 @@ public class CMActions implements OnHashCallback { } cReq.setRequestID(reqID); long start = System.currentTimeMillis(); - manager.executeContractInternal( - cReq, - new ResultCallback() { - @Override - public void onResult(JsonObject ret) { - ret.addProperty("responseID", cReq.getRequestID()); - ret.addProperty("action", "onExecuteResult"); - String costTime = (System.currentTimeMillis() - start) + ""; - ret.addProperty("executeTime", costTime); - ContractMeta meta = - manager.statusRecorder.getContractMeta(cReq.getContractID()); - if (meta != null && meta.getIsDebug()) { - FUNCINVOKEINFO.putOneInvoke( - cReq.getContractID(), - cReq.getAction(), - cReq.getRequestID(), - cReq.getArg(), - ret.has("result") ? ret.get("result").toString() : ""); - } - LOGGER.debug("result of request " + cReq.getRequestID() + ": " + ret); - resultCallback.onResult(ret); - } + manager.executeContractInternal(cReq, new ResultCallback() { + @Override + public void onResult(JsonObject ret) { + ret.addProperty("responseID", cReq.getRequestID()); + ret.addProperty("action", "onExecuteResult"); + String costTime = (System.currentTimeMillis() - start) + ""; + ret.addProperty("executeTime", costTime); + ContractMeta meta = manager.statusRecorder.getContractMeta(cReq.getContractID()); + if (meta != null && meta.getIsDebug()) { + FUNCINVOKEINFO.putOneInvoke(cReq.getContractID(), cReq.getAction(), + cReq.getRequestID(), cReq.getArg(), + ret.has("result") ? ret.get("result").toString() : ""); + } + LOGGER.debug("result of request " + cReq.getRequestID() + ": " + ret); + resultCallback.onResult(ret); + } - @Override - public void onResult(String str) { - throw new IllegalStateException("Can't reach here"); - } - }, - hashcb); + @Override + public void onResult(String str) { + throw new IllegalStateException("Can't reach here"); + } + }, hashcb); } - public static void generateReadmeInternal( - JsonObject args, final ResultCallback resultCallback, final OnHashCallback hashcb) { + public static void generateReadmeInternal(JsonObject args, final ResultCallback resultCallback, + final OnHashCallback hashcb) { final ContractRequest c = new ContractRequest(); if (!args.has("contractName") && !args.has("contractID") && !args.has("contractDOI")) { resultCallback.onResult(MISSING_ARGUMENT); @@ -231,12 +219,12 @@ public class CMActions implements OnHashCallback { c.setContractID(args.get("contractID").getAsString()); } - // JsonObject jo = + // JsonObject jo = // JsonParser.parseString(args.get("arg").getAsString()).getAsJsonObject(); - // if (!jo.has("action")) { - // resultCallback.onResult(MISSING_ARGUMENT); - // return; - // } + // if (!jo.has("action")) { + // resultCallback.onResult(MISSING_ARGUMENT); + // return; + // } long start = System.currentTimeMillis(); @@ -248,23 +236,23 @@ public class CMActions implements OnHashCallback { String argSchema = ""; String resSchema = ""; String argTemplate = ""; - //String resTemplate = ""; + // String resTemplate = ""; String descStr = null; String invokeRocords = null; if (desp.annotations != null) { for (AnnotationNode node : desp.annotations) { LOGGER.debug("AnnotationNode Type:" + node.getType()); // if (node.getType().equals("Param")) - // if (node.getArgs() != null && node.getArgs().size() > 0) - // paramStr = node.getArgs().get(0); - // else paramStr = "无需参数"; - // if (node.getType().equals("Result") && node.getArgs().size() > 0) - // resultStr = node.getArgs().get(0); + // if (node.getArgs() != null && node.getArgs().size() > 0) + // paramStr = node.getArgs().get(0); + // else paramStr = "无需参数"; + // if (node.getType().equals("Result") && node.getArgs().size() > 0) + // resultStr = node.getArgs().get(0); if (node.getType().equals("Description") && node.getArgs().size() > 0) descStr = node.getArgs().get(0); - // if (node.getType().equals("MockTemplate") && node.getArgs().size() > + // if (node.getType().equals("MockTemplate") && node.getArgs().size() > // 0) - // mockStr = node.getArgs().get(0); + // mockStr = node.getArgs().get(0); } } @@ -295,17 +283,12 @@ public class CMActions implements OnHashCallback { } - ReadmeGenerator.ReadmeFunction joFunction = - new ReadmeGenerator.ReadmeFunction( - // new ReadmeGenerator.ReadmeFunc + ReadmeGenerator.ReadmeFunction joFunction = new ReadmeGenerator.ReadmeFunction( + // new ReadmeGenerator.ReadmeFunc - desp.functionName, - descStr, - argSchema, - argTemplate, - resSchema, - //resTemplate, - invokeRocords); // 第二个参数是调用结果的一个集合 + desp.functionName, descStr, argSchema, argTemplate, resSchema, + // resTemplate, + invokeRocords); // 第二个参数是调用结果的一个集合 // 注入之后将该函数的记录清空 FUNCINVOKEINFO.clearOneFunction(c.getContractID(), desp.functionName); @@ -342,19 +325,18 @@ public class CMActions implements OnHashCallback { } } generator.setContractDescription(contractDesp.toString()); - ResultCallback rb = - new ResultCallback() { - @Override - public void onResult(String str) { - final Map ret = new HashMap<>(); - ret.put("responseID", c.getRequestID()); - ret.put("action", "onGenerateReadme"); - ret.put("data", str); - String costTime = (System.currentTimeMillis() - start) + ""; - ret.put("executeTime", costTime); - resultCallback.onResult(ret); - } - }; + ResultCallback rb = new ResultCallback() { + @Override + public void onResult(String str) { + final Map ret = new HashMap<>(); + ret.put("responseID", c.getRequestID()); + ret.put("action", "onGenerateReadme"); + ret.put("data", str); + String costTime = (System.currentTimeMillis() - start) + ""; + ret.put("executeTime", costTime); + resultCallback.onResult(ret); + } + }; rb.onResult(generator.generate(targetPath)); } catch (Exception e) { ByteArrayOutputStream bo = new ByteArrayOutputStream(); @@ -367,28 +349,30 @@ public class CMActions implements OnHashCallback { } private static String truncQuotation(String str) { - if (str.startsWith("\"")) str = str.substring(1); - if (str.endsWith("\"")) str = str.substring(0, str.length() - 1); + if (str.startsWith("\"")) + str = str.substring(1); + if (str.endsWith("\"")) + str = str.substring(0, str.length() - 1); return str; } - public static void killContractByMaster( - String contractID, JsonObject request, ResultCallback rc) { + public static void killContractByMaster(String contractID, JsonObject request, + ResultCallback rc) { LOGGER.info("[MasterClientTCPAction] killContract : "); try { - MasterClientTCPAction.killUnitContractMap.put( - request.get("requestID").getAsString(), + MasterClientTCPAction.killUnitContractMap.put(request.get("requestID").getAsString(), 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)); } catch (Exception e) { e.printStackTrace(); } finally { - CMActions.manager.stopContractWithOwner( - request.get("verifiedPubKey").getAsString(), contractID); + CMActions.manager.stopContractWithOwner(request.get("verifiedPubKey").getAsString(), + contractID); ContractMeta meta = manager.statusRecorder.getContractMeta(contractID); if (null != meta && meta.contractExecutor != null) { - //TODO why close? + // TODO why close? // meta.contractExecutor.close(); } } @@ -428,7 +412,7 @@ public class CMActions implements OnHashCallback { String data = "failed"; String contractID = ""; String operation = ""; - //String mock = ""; + // String mock = ""; if (args.has("contractID") && args.has("operation") && args.has("arg")) { contractID = args.get("contractID").getAsString(); System.out.println(contractID); @@ -480,7 +464,7 @@ public class CMActions implements OnHashCallback { String data = "failed"; String contractID; String operation; - //JsonElement mask = JsonUtil.parseString(""); + // JsonElement mask = JsonUtil.parseString(""); if (args.has("contractID") && args.has("operation") && args.has("arg")) { contractID = args.get("contractID").getAsString(); System.out.println(contractID); @@ -509,14 +493,12 @@ public class CMActions implements OnHashCallback { // 目前没有验签!前置的handler中统一验还是方法内自己验? @Action(async = true, userPermission = 0) public void executeContract(JsonObject args, final ResultCallback resultCallback) { - // String sequencing = args.get("sequencing").getAsString(); + // String sequencing = args.get("sequencing").getAsString(); if (!args.has("useP2P") || !args.get("useP2P").getAsBoolean()) { executeContractInternal(args, resultCallback, this); } else { - resultCallback.onResult( - JsonUtil.toJson( - new ContractResult( - ContractResult.Status.Error, new JsonPrimitive("noResult")))); + resultCallback.onResult(JsonUtil.toJson(new ContractResult(ContractResult.Status.Error, + new JsonPrimitive("noResult")))); } } @@ -544,16 +526,14 @@ public class CMActions implements OnHashCallback { resultCallback.onResult(jo); } }; - // String sequencing = args.get("sequencing").getAsString(); + // String sequencing = args.get("sequencing").getAsString(); if (args.has("shortId")) args.add("contractID", args.get("shortId")); if (!args.has("useP2P") || !args.get("useP2P").getAsBoolean()) { executeContractInternal(args, wrapped, this); } else { - wrapped.onResult( - JsonUtil.toJson( - new ContractResult( - ContractResult.Status.Error, new JsonPrimitive("noResult")))); + wrapped.onResult(JsonUtil.toJson(new ContractResult(ContractResult.Status.Error, + new JsonPrimitive("noResult")))); } } @@ -568,9 +548,7 @@ public class CMActions implements OnHashCallback { public void listContractProcess(JsonObject args, ResultCallback resultCallback) { String data; if (args.has("verifiedPubKey")) { - data = manager.listContractsWithOwner( - args.get("verifiedPubKey").getAsString(), - null, + data = manager.listContractsWithOwner(args.get("verifiedPubKey").getAsString(), null, args.has("filters") ? args.get("filters").getAsInt() : 0); ReplyUtil.simpleReply(resultCallback, "onListContractProcess", data); } else { @@ -603,12 +581,14 @@ public class CMActions implements OnHashCallback { @Action(userPermission = 1L << 16) public void queryContractResourceInfo(JsonObject args, ResultCallback resultCallback) { - ReplyUtil.simpleReply(resultCallback, "onQueryContractResourceInfo", manager.getContractResourceInfo()); + ReplyUtil.simpleReply(resultCallback, "onQueryContractResourceInfo", + manager.getContractResourceInfo()); } @Action(userPermission = 1L << 16) 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); resultCallback.onResult(data2); } 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) { Map ret = new HashMap<>(); ret.put("action", "onStartContract"); - JsonArray array = - JsonUtil.parseString(args.get("fileList").getAsString()).getAsJsonArray(); + JsonArray array = JsonUtil.parseString(args.get("fileList").getAsString()).getAsJsonArray(); for (int i = 0; i < array.size(); i++) { String fileName = array.get(i).getAsString(); Contract c = new Contract(); @@ -713,19 +693,19 @@ public class CMActions implements OnHashCallback { @Action(async = true) public void startContractByYPKAtNode(JsonObject args, ResultCallback resultCallback) { - // String nodeID = args.get("nodeID").getAsString(); - // SM2KeyPair keyPair = GlobalConf.instance.keyPair; - // json.addProperty("sponsorPubkey", keyPair.getPublicKeyStr()); // 节点 - // json.addProperty("pubkey", handler.getPubKey()); // 用户 - // String reqID = - // System.currentTimeMillis() + "_" + (int) (Math.random() * 10000) + + // String nodeID = args.get("nodeID").getAsString(); + // SM2KeyPair keyPair = GlobalConf.instance.keyPair; + // json.addProperty("sponsorPubkey", keyPair.getPublicKeyStr()); // 节点 + // json.addProperty("pubkey", handler.getPubKey()); // 用户 + // String reqID = + // System.currentTimeMillis() + "_" + (int) (Math.random() * 10000) + // "_distribute"; - // json.addProperty("distributeID", reqID); - // LOGGER.info("[FileActions] distributeContract : "); - // LOGGER.info(JsonUtil.toJson(json)); - // NetworkManager.instance.getNCClientHandler().distributeReqMap.put(reqID, + // json.addProperty("distributeID", reqID); + // LOGGER.info("[FileActions] distributeContract : "); + // LOGGER.info(JsonUtil.toJson(json)); + // NetworkManager.instance.getNCClientHandler().distributeReqMap.put(reqID, // resultCallback); - // NetworkManager.instance.sendToNodeCenter(JsonUtil.toJson(json)); + // NetworkManager.instance.sendToNodeCenter(JsonUtil.toJson(json)); } @Action(userPermission = 1L << 26, async = true) @@ -773,7 +753,8 @@ public class CMActions implements OnHashCallback { try { // TODO script should encoded!! 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) { e.printStackTrace(); } @@ -785,10 +766,8 @@ public class CMActions implements OnHashCallback { LOGGER.info("handler is null " + (handler == null)); LOGGER.info(args.get("verifiedPubKey").getAsString()); if (handler != null) { - listContractProcessWithFirstWithOwner( - args.get("verifiedPubKey").getAsString(), - c.getID(), - new ResultCallback() { + listContractProcessWithFirstWithOwner(args.get("verifiedPubKey").getAsString(), + c.getID(), new ResultCallback() { @Override public void onResult(String str) { handler.sendMsg(str); @@ -878,10 +857,8 @@ public class CMActions implements OnHashCallback { ret.put("executeTime", System.currentTimeMillis() - start); resultCallback.onResult(ret); if (handler != null) { - listContractProcessWithFirstWithOwner( - args.get("verifiedPubKey").getAsString(), - c.getID(), - new ResultCallback() { + listContractProcessWithFirstWithOwner(args.get("verifiedPubKey").getAsString(), + c.getID(), new ResultCallback() { @Override public void onResult(String str) { handler.sendMsg(str); @@ -894,14 +871,16 @@ public class CMActions implements OnHashCallback { manager.changeDumpPeriod(c.getID(), args.get("dumpPeriod").getAsString()); } } else { - ReplyUtil.replyWithStatus(resultCallback, "onStartContract", false, "Failed: Illegal user"); + ReplyUtil.replyWithStatus(resultCallback, "onStartContract", false, + "Failed: Illegal user"); } ExecutionManager.instance.updateLocalContractToNodeCenter(); } private String getLoginPubkey(JsonObject args) { try { - if (handler != null) return handler.getPubKey(); + if (handler != null) + return handler.getPubKey(); return args.get("pubKey").getAsString(); } catch (Exception e) { e.printStackTrace(); @@ -946,11 +925,11 @@ public class CMActions implements OnHashCallback { // 上面那些。。有空再整理一下 c.setOwner(args.get("verifiedPubKey").getAsString()); - // if (!c.verifySignature()) { - // ret.put("data", "verify failed"); - // resultCallback.onResult(gson.toJson(ret)); - // return; - // } + // if (!c.verifySignature()) { + // ret.put("data", "verify failed"); + // resultCallback.onResult(gson.toJson(ret)); + // return; + // } if (path != null && path.startsWith("/")) { String parPath; @@ -981,29 +960,17 @@ public class CMActions implements OnHashCallback { c.setScript(ypkPath); /* - if (DoConfig.openContractDORegister) { - File file = new File(dir.getAbsolutePath() + "/manifest.json"); - if (file.isFile() && file.exists()) { - try { - InputStream manifestInput = new FileInputStream(file); - ContractManifest cm = - JsonUtil - .fromJson( - new InputStreamReader(manifestInput), - ContractManifest.class); - 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); - } - */ + * if (DoConfig.openContractDORegister) { File file = new + * File(dir.getAbsolutePath() + "/manifest.json"); if (file.isFile() && + * file.exists()) { try { InputStream manifestInput = new FileInputStream(file); + * ContractManifest cm = JsonUtil .fromJson( new + * InputStreamReader(manifestInput), ContractManifest.class); + * 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) { e.printStackTrace(); } @@ -1017,10 +984,8 @@ public class CMActions implements OnHashCallback { resultCallback.onResult(ret); ExecutionManager.instance.updateLocalContractToNodeCenter(); if (handler != null) { - listContractProcessWithFirstWithOwner( - args.get("verifiedPubKey").getAsString(), - c.getID(), - new ResultCallback() { + listContractProcessWithFirstWithOwner(args.get("verifiedPubKey").getAsString(), + c.getID(), new ResultCallback() { @Override public void onResult(String str) { handler.sendMsg(str); @@ -1107,8 +1072,8 @@ public class CMActions implements OnHashCallback { } SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd.HH_mm_ss"); // 设置日期格式 - File f = - new File(GlobalConf.instance.memoryDir + "/" + contractName, df.format(new Date())); + File f = new File(GlobalConf.instance.memoryDir + "/" + contractName, + df.format(new Date())); File parent = f.getParentFile(); if (!parent.exists()) { parent.mkdirs(); @@ -1204,17 +1169,11 @@ public class CMActions implements OnHashCallback { } ContractClient cl = manager.getClient(rc.getContractID()); if (null == cl) { - String ret = - manager.stopContractWithOwner( - args.get("verifiedPubKey").getAsString(), rc.getContractID()); + String ret = manager.stopContractWithOwner(args.get("verifiedPubKey").getAsString(), + rc.getContractID()); - GRPCPool.instance.writeToChain( - this, - rc.getContractID(), - "stopContract", - ret, - args.has("requestID") ? args.get("requestID").getAsString() : null, - ""); + GRPCPool.instance.writeToChain(this, rc.getContractID(), "stopContract", ret, + args.has("requestID") ? args.get("requestID").getAsString() : null, ""); Map r = new HashMap<>(); r.put("action", "onKillContractProcess"); r.put("data", ret); @@ -1229,16 +1188,10 @@ public class CMActions implements OnHashCallback { killContractByMaster(rc.getContractID(), args, resultCallback); } else { - String ret = - manager.stopContractWithOwner( - args.get("verifiedPubKey").getAsString(), rc.getContractID()); - GRPCPool.instance.writeToChain( - this, - rc.getContractID(), - "stopContract", - ret, - args.has("requestID") ? args.get("requestID").getAsString() : null, - ""); + String ret = manager.stopContractWithOwner(args.get("verifiedPubKey").getAsString(), + rc.getContractID()); + GRPCPool.instance.writeToChain(this, rc.getContractID(), "stopContract", ret, + args.has("requestID") ? args.get("requestID").getAsString() : null, ""); JsonObject r = new JsonObject(); r.addProperty("action", "onKillContractProcess"); r.addProperty("data", ret); @@ -1247,7 +1200,8 @@ public class CMActions implements OnHashCallback { ExecutionManager.instance.updateLocalContractToNodeCenter(); } } 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; killContractProcess(args, resultCallback); manager.startContract(contract); - String data = manager.listContractsWithOwner( - args.get("verifiedPubKey").getAsString(), - null, - args.has("filters") ? args.get("filters").getAsInt() : 0); + String data = manager.listContractsWithOwner(args.get("verifiedPubKey").getAsString(), + null, args.has("filters") ? args.get("filters").getAsInt() : 0); ReplyUtil.simpleReply(resultCallback, "onListContractProcess", data); } 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()); for (ContractMeta key : toRemove) { 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); } resultCallback.onResult("size:" + toRemove.size()); @@ -1383,7 +1337,8 @@ public class CMActions implements OnHashCallback { String dirPath; if (args.has("isPrivate") && args.get("isPrivate").getAsBoolean()) dirPath = GlobalConf.instance.privateDir; - else dirPath = GlobalConf.instance.publicDir; + else + dirPath = GlobalConf.instance.publicDir; String ypkPath = FileActions.autoCompile(dirPath, project); Contract c = new Contract(); c.setScript(ypkPath); @@ -1418,7 +1373,8 @@ public class CMActions implements OnHashCallback { if (sc2.hasNext()) { sc2.next(); - if (sc2.hasNextInt()) pid = sc2.nextInt() + ""; + if (sc2.hasNextInt()) + pid = sc2.nextInt() + ""; } sc2.close(); if (pid != null) { @@ -1443,7 +1399,8 @@ public class CMActions implements OnHashCallback { ReplyUtil.replyWithStatus(resultCallback, "onKillAllContract", true, "Success"); } } 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); Map ret = new HashMap<>(); ret.put("status", cr.status.toString()); - ret.put( - "result", - JsonUtil.fromJson( - cr.result, new TypeToken>>() { - }.getType())); + ret.put("result", JsonUtil.fromJson(cr.result, + new TypeToken>>() {}.getType())); resultCallback.onResult(ret); } @@ -1535,10 +1489,8 @@ public class CMActions implements OnHashCallback { Map ret = new HashMap<>(); ret.put("status", cr.status.toString()); try { - Object obj = - JsonUtil.fromJson( - cr.result, new TypeToken>>() { - }.getType()); + Object obj = JsonUtil.fromJson(cr.result, + new TypeToken>>() {}.getType()); ret.put("result", obj); } catch (Exception e) { e.printStackTrace(); @@ -1552,12 +1504,12 @@ public class CMActions implements OnHashCallback { @Action(async = true, userPermission = 0L) public void getP2PNodes(JsonObject args, ResultCallback rc) { LOGGER.debug("getP2PNodes"); - // String peers = CommunicationManager.instance.getCachedP2PNodes(); - // if(peers == null) { + // String peers = CommunicationManager.instance.getCachedP2PNodes(); + // if(peers == null) { CommunicationManager.instance.getP2PNodes(rc); - // return; - // } - // rc.onResult(peers); + // return; + // } + // rc.onResult(peers); } @Action(async = true, userPermission = 0L) @@ -1572,7 +1524,8 @@ public class CMActions implements OnHashCallback { String nodeName; for (JsonElement jsonElement : jsonArray) { jsonObject = jsonElement.getAsJsonObject(); - unitPeers = JsonUtil.parseString(jsonObject.get("value").getAsString()).getAsJsonArray(); + unitPeers = + JsonUtil.parseString(jsonObject.get("value").getAsString()).getAsJsonArray(); for (JsonElement jsonElemenPeer : unitPeers) { jsonPeer = jsonElemenPeer.getAsJsonObject(); if (jsonPeer.has("nodeName")) @@ -1581,16 +1534,16 @@ public class CMActions implements OnHashCallback { peerID = jsonPeer.get("peerID").getAsString(); if (jsonPeer.has("ipPort")) ipPort = jsonPeer.get("ipPort").getAsString(); - // NetworkManager.instance.peerID2TCPAddress.put(peer, ipPort); -// try { -// NetworkManager.instance.createTCPClient(peerID, ipPort); -// } catch (InterruptedException e) { -// e.printStackTrace(); -// JsonObject ret = new JsonObject(); -// ret.addProperty("status", "Error"); -// ret.addProperty("result", "Cannot form TCP connection to " + nodeName); -// rc.onResult(ret); -// } + // NetworkManager.instance.peerID2TCPAddress.put(peer, ipPort); + // try { + // NetworkManager.instance.createTCPClient(peerID, ipPort); + // } catch (InterruptedException e) { + // e.printStackTrace(); + // JsonObject ret = new JsonObject(); + // ret.addProperty("status", "Error"); + // ret.addProperty("result", "Cannot form TCP connection to " + nodeName); + // rc.onResult(ret); + // } } } } @@ -1730,64 +1683,64 @@ public class CMActions implements OnHashCallback { resultCallback.onResult(ret); } - // @Action(userPermission = 1L << 26, async = true) - // public void queryContractInstanceInfoByDOI(JsonObject args, ResultCallback resultCallback) + // @Action(userPermission = 1L << 26, async = true) + // public void queryContractInstanceInfoByDOI(JsonObject args, ResultCallback resultCallback) // { - // long s = System.currentTimeMillis(); - // String ret; - // try { - // String contractDOI = args.get("doi").getAsString(); - // DigitalObject contractDO; - // DoipClient doipClient = - // DoipClient.createByRepoUrlAndMsgFmt( - // DOIPMainServer.repoUrl, DoipMessageFormat.PACKET.getName()); - // DoMessage response = doipClient.retrieve(contractDOI, null, null); - // if (response.parameters.response == DoResponse.Success) { - // contractDO = DigitalObject.parse(response.body); - // } else { - // DoMessage resp = DOAClient.getGlobalInstance().retrieve(contractDOI, null, + // long s = System.currentTimeMillis(); + // String ret; + // try { + // String contractDOI = args.get("doi").getAsString(); + // DigitalObject contractDO; + // DoipClient doipClient = + // DoipClient.createByRepoUrlAndMsgFmt( + // DOIPMainServer.repoUrl, DoipMessageFormat.PACKET.getName()); + // DoMessage response = doipClient.retrieve(contractDOI, null, null); + // if (response.parameters.response == DoResponse.Success) { + // contractDO = DigitalObject.parse(response.body); + // } else { + // DoMessage resp = DOAClient.getGlobalInstance().retrieve(contractDOI, null, // null); - // contractDO = DigitalObject.parse(resp.body); - // } - // ContractInstanceDO contractInstanceDO = - // (ContractInstanceDO) - // ContractManager.toObject(contractDO.elements.get(0).getData()); - // // Dictionary contractInfo = JsonUtil.fromJson(new - // // String(contractDO.getData()), new Hashtable().getClass()); + // contractDO = DigitalObject.parse(resp.body); + // } + // ContractInstanceDO contractInstanceDO = + // (ContractInstanceDO) + // ContractManager.toObject(contractDO.elements.get(0).getData()); + // // Dictionary contractInfo = JsonUtil.fromJson(new + // // String(contractDO.getData()), new Hashtable().getClass()); // - // ret = - // String.format( - // "Contract ID: %s\nContract PublicKey: %s", - // contractInstanceDO.id, contractInstanceDO.publicKey); - // } catch (Exception e) { - // ByteArrayOutputStream bo = new ByteArrayOutputStream(); - // e.printStackTrace(new PrintStream(bo)); - // ret = bo.toString(); - // } - // Map r = new HashMap<>(); - // r.put("action", "onQueryContractInstanceInfoByDOI"); - // r.put("data", ret); - // r.put("executeTime", System.currentTimeMillis() - s); - // resultCallback.onResult(JsonUtil.toJson(r)); - // if (client != null && client.controller != null) { - // client.controller.updateContract(); - // } - // } + // ret = + // String.format( + // "Contract ID: %s\nContract PublicKey: %s", + // contractInstanceDO.id, contractInstanceDO.publicKey); + // } catch (Exception e) { + // ByteArrayOutputStream bo = new ByteArrayOutputStream(); + // e.printStackTrace(new PrintStream(bo)); + // ret = bo.toString(); + // } + // Map r = new HashMap<>(); + // r.put("action", "onQueryContractInstanceInfoByDOI"); + // r.put("data", ret); + // r.put("executeTime", System.currentTimeMillis() - s); + // resultCallback.onResult(JsonUtil.toJson(r)); + // if (client != null && client.controller != null) { + // client.controller.updateContract(); + // } + // } /* - * @Action(userPermission = 1 << 19, async = true) public void - * staticVerify(JsonObject args, ResultCallback resultCallback) { Map r = new HashMap<>(); r.put("action", "onStaticVerifyResult"); + * @Action(userPermission = 1 << 19, async = true) public void staticVerify(JsonObject args, + * ResultCallback resultCallback) { Map r = new HashMap<>(); r.put("action", + * "onStaticVerifyResult"); * - * long start = System.currentTimeMillis(); Map ret = new - * HashMap<>(); Contract c = new Contract(); // c.setType(Type.Algorithm); - * c.setType(ContractType.Sole); ret.put("action", "onStartContract"); String path = - * null; if (args.has("path")) path = args.get("path").getAsString(); if (path - * != null && path.startsWith("/")) c.setScript(args.get("path").getAsString()); - * else c.setScript(args.get("script").getAsString()); if - * (args.has("publicKey")) { c.setOwner(args.get("publicKey").getAsString()); - * c.setSignature(args.get("signature").getAsString()); } else if - * (args.has("owner")) { c.setOwner(args.get("owner").getAsString()); + * long start = System.currentTimeMillis(); Map ret = new HashMap<>(); Contract + * c = new Contract(); // c.setType(Type.Algorithm); c.setType(ContractType.Sole); + * ret.put("action", "onStartContract"); String path = null; if (args.has("path")) path = + * args.get("path").getAsString(); if (path != null && path.startsWith("/")) + * c.setScript(args.get("path").getAsString()); else + * c.setScript(args.get("script").getAsString()); if (args.has("publicKey")) { + * c.setOwner(args.get("publicKey").getAsString()); + * c.setSignature(args.get("signature").getAsString()); } else if (args.has("owner")) { + * c.setOwner(args.get("owner").getAsString()); * c.setSignature(args.get("signature").getAsString()); * * } else { c.setOwner(GlobalConf.instance.keyPair.getPublicKeyStr()); @@ -1796,27 +1749,23 @@ public class CMActions implements OnHashCallback { * if (!c.verifySignature()) { ret.put("data", "verify failed"); * resultCallback.onResult(gson.toJson(ret)); return; } if (path != null && * path.startsWith("/")) { String parPath; if (args.has("isPrivate") && - * args.get("isPrivate").getAsBoolean()) { parPath = - * GlobalConf.instance.privateDir + "/" + handler.pubKey; } else { parPath = - * GlobalConf.instance.publicDir; } try { String[] pp = path.split("/"); String - * parentPath = path; for (int i = 0; i < pp.length && i < 2; i++) { parentPath - * += pp[i] + "/"; } System.out.println("[CMActions] pack Dir, from:" + path + + * args.get("isPrivate").getAsBoolean()) { parPath = GlobalConf.instance.privateDir + "/" + + * handler.pubKey; } else { parPath = GlobalConf.instance.publicDir; } try { String[] pp = + * path.split("/"); String parentPath = path; for (int i = 0; i < pp.length && i < 2; i++) { + * parentPath += pp[i] + "/"; } System.out.println("[CMActions] pack Dir, from:" + path + * " --> " + parentPath); byte[] bb = YJSPacker.pack(new File(parPath, - * parentPath).getAbsolutePath()); File temp = File.createTempFile(pp[pp.length - * - 1], ".zip"); FileOutputStream fout = new FileOutputStream(temp); - * fout.write(bb); fout.close(); System.out.println("StartContract, zipPath:" + - * temp.getAbsolutePath()); // TODO script should encoded!! - * c.setScript(temp.getAbsolutePath()); } catch (Exception e) { - * e.printStackTrace(); } } + * parentPath).getAbsolutePath()); File temp = File.createTempFile(pp[pp.length - 1], ".zip"); + * FileOutputStream fout = new FileOutputStream(temp); fout.write(bb); fout.close(); + * System.out.println("StartContract, zipPath:" + temp.getAbsolutePath()); // TODO script should + * encoded!! c.setScript(temp.getAbsolutePath()); } catch (Exception e) { e.printStackTrace(); } + * } * - * System.out.println("[CMActions] verifyContract: " + gson.toJson(c)); - * r.put("data", manager.staticVerify(c)); r.put("cid", c.getID()); - * r.put("executeTime", System.currentTimeMillis() - start); // - * GRPCPool.writeToChain(c.getOwner(), privKey, gson.toJson(r), // - * json.getString("requestID")); + * System.out.println("[CMActions] verifyContract: " + gson.toJson(c)); r.put("data", + * manager.staticVerify(c)); r.put("cid", c.getID()); r.put("executeTime", + * System.currentTimeMillis() - start); // GRPCPool.writeToChain(c.getOwner(), privKey, + * gson.toJson(r), // json.getString("requestID")); * - * //addLocalContractLog("staticVerify", c.getID(), path.split("/")[1], - * c.getOwner(),null); + * //addLocalContractLog("staticVerify", c.getID(), path.split("/")[1], c.getOwner(),null); * * resultCallback.onResult(gson.toJson(r)); } */ @@ -1870,10 +1819,10 @@ public class CMActions implements OnHashCallback { @Action(async = true, userPermission = 1L << 12) public void startContractConfig(JsonObject args, ResultCallback rc) { LOGGER.debug("startContractConfig"); - // TODO private contract - // if (args.has("isPrivate") && args.get("isPrivate").getAsBoolean()) { - // args.add("pubkey", JsonParser.parseString(handler.getPubKey())); - // } + // TODO private contract + // if (args.has("isPrivate") && args.get("isPrivate").getAsBoolean()) { + // args.add("pubkey", JsonParser.parseString(handler.getPubKey())); + // } boolean type = args.get("type").getAsString().equalsIgnoreCase("TCP"); String contract = args.get("contractName").getAsString(); String content = args.get("path").getAsString(); @@ -1899,8 +1848,8 @@ public class CMActions implements OnHashCallback { old_num = peers.length; } } - ExecutionManager.instance.startContractRequest( - type, contract, old_num, peers, content, sequencing, response, rc); + ExecutionManager.instance.startContractRequest(type, contract, old_num, peers, content, + sequencing, response, rc); } static class WSPrintStream extends PrintStream { @@ -1932,4 +1881,4 @@ public class CMActions implements OnHashCallback { } } } -} \ No newline at end of file +} diff --git a/src/main/java/org/bdware/server/action/CMLogAction.java b/src/main/java/org/bdware/server/action/CMLogAction.java index c259c8f..b136dca 100644 --- a/src/main/java/org/bdware/server/action/CMLogAction.java +++ b/src/main/java/org/bdware/server/action/CMLogAction.java @@ -17,7 +17,7 @@ import java.util.Map; import java.util.Random; public class CMLogAction { -// static SocketGet get; + // static SocketGet get; @Action(async = true, userPermission = 0) public void setLogStage(JsonObject json, ResultCallback result) { @@ -49,7 +49,8 @@ public class CMLogAction { if (json.has("contractName")) { 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) @@ -220,12 +221,8 @@ public class CMLogAction { JsonObject ret = new JsonObject(); ret.addProperty("action", "onQueryAEState"); if (json.has("caller")) { - ret.add( - "result", - JsonParser.parseString( - JsonUtil.toJson( - ActionExecutor.getStatistic( - json.get("caller").getAsString())))); + ret.add("result", JsonParser.parseString(JsonUtil + .toJson(ActionExecutor.getStatistic(json.get("caller").getAsString())))); } else { ret.add("result", JsonParser.parseString(JsonUtil.toJson(ActionExecutor.getAllData()))); } @@ -244,17 +241,15 @@ public class CMLogAction { public void checkIsContract(JsonObject json, ResultCallback rc) { String requestID = new Random().nextLong() + "_" + System.currentTimeMillis(); 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.add("result", ret); json.addProperty("action", "onCheckIsContract"); rc.onResult(json.toString()); } - private void queryLogSize( - MultiIndexTimeDBUtilIntf db, - String action, - String label, + private void queryLogSize(MultiIndexTimeDBUtilIntf db, String action, String label, ResultCallback result) { try { JsonObject ret = new JsonObject(); @@ -274,20 +269,14 @@ public class CMLogAction { } - private void queryByDate( - MultiIndexTimeDBUtilIntf db, - String action, - String label, - JsonObject json, - ResultCallback result) { + private void queryByDate(MultiIndexTimeDBUtilIntf db, String action, String label, + JsonObject json, ResultCallback result) { // TODO FixMe // Caused by: com.google.gson.stream.MalformedJsonException: Unterminated object at line 1 // column 240 path $.function if (!json.has("start")) { - result.onResult( - "{\"action\":\"" - + action - + "\",\"status\":\"failed\",\"data\":\"missing start\"}"); + result.onResult("{\"action\":\"" + action + + "\",\"status\":\"failed\",\"data\":\"missing start\"}"); return; } long date = json.get("start").getAsLong(); @@ -307,17 +296,11 @@ public class CMLogAction { result.onResult(JsonUtil.toJson(ret)); } - private void queryByOffset( - MultiIndexTimeDBUtilIntf db, - String action, - String label, - JsonObject json, - ResultCallback result) { + private void queryByOffset(MultiIndexTimeDBUtilIntf db, String action, String label, + JsonObject json, ResultCallback result) { if (!json.has("count")) { - result.onResult( - "{\"action\":\"" - + action - + "\",\"status\":\"failed\",\"data\":\"missing count\"}"); + result.onResult("{\"action\":\"" + action + + "\",\"status\":\"failed\",\"data\":\"missing count\"}"); return; } int count = json.get("count").getAsInt(); diff --git a/src/main/java/org/bdware/server/action/CheckPointCallback.java b/src/main/java/org/bdware/server/action/CheckPointCallback.java index 28c102a..bf98890 100644 --- a/src/main/java/org/bdware/server/action/CheckPointCallback.java +++ b/src/main/java/org/bdware/server/action/CheckPointCallback.java @@ -9,8 +9,8 @@ import java.util.HashMap; import java.util.Map; import java.util.concurrent.ConcurrentHashMap; -//UNUSED -//TO Merge +// UNUSED +// TO Merge public class CheckPointCallback implements OnHashCallback { public static Map lastHash = new ConcurrentHashMap<>(); // contractID,hash @@ -23,11 +23,11 @@ public class CheckPointCallback implements OnHashCallback { reqStr.put("contractID", contractID); reqStr.put("hash", hashStr); String sendStr = JsonUtil.toJson(reqStr); - MultiContractMeta info = CMActions.manager.multiContractRecorder.getMultiContractMeta(contractID); + MultiContractMeta info = + CMActions.manager.multiContractRecorder.getMultiContractMeta(contractID); for (String node : info.getMembers()) { NetworkManager.instance.sendToAgent(node, sendStr); - System.out.println( - "发送请求给 " + node.substring(0, 5) + " 更新ledger中最新检查点的hash!"); + System.out.println("发送请求给 " + node.substring(0, 5) + " 更新ledger中最新检查点的hash!"); } } } diff --git a/src/main/java/org/bdware/server/action/EventActions.java b/src/main/java/org/bdware/server/action/EventActions.java index b13ad9b..272740c 100644 --- a/src/main/java/org/bdware/server/action/EventActions.java +++ b/src/main/java/org/bdware/server/action/EventActions.java @@ -8,7 +8,7 @@ import org.bdware.sc.util.JsonUtil; public class EventActions { @Action(async = true, userPermission = 0) public void deliverEvent(JsonObject args, final ResultCallback rcb) { - CMActions.manager.deliverEvent( - JsonUtil.fromJson(args.get("data").getAsString(), REvent.class)); + CMActions.manager + .deliverEvent(JsonUtil.fromJson(args.get("data").getAsString(), REvent.class)); } } diff --git a/src/main/java/org/bdware/server/action/EventWSActions.java b/src/main/java/org/bdware/server/action/EventWSActions.java index dc7a4c1..1248874 100644 --- a/src/main/java/org/bdware/server/action/EventWSActions.java +++ b/src/main/java/org/bdware/server/action/EventWSActions.java @@ -52,13 +52,11 @@ public class EventWSActions { rcb.onResult(ret); return; } - String requestID = args.has("requestID") ? - args.get("requestID").getAsString() : - HashUtil.sha3(String.valueOf(System.currentTimeMillis()), "_", String.valueOf(Math.random())); - REvent event = new REvent(args.get("topic").getAsString(), - PUBLISH, - args.get("content").getAsString(), - requestID); + String requestID = args.has("requestID") ? args.get("requestID").getAsString() + : HashUtil.sha3(String.valueOf(System.currentTimeMillis()), "_", + String.valueOf(Math.random())); + REvent event = new REvent(args.get("topic").getAsString(), PUBLISH, + args.get("content").getAsString(), requestID); if (args.has("semantics")) { try { event.setSemantics(valueOf(args.get("semantics").getAsString())); diff --git a/src/main/java/org/bdware/server/action/FileActions.java b/src/main/java/org/bdware/server/action/FileActions.java index d5f4d7a..617d7ad 100644 --- a/src/main/java/org/bdware/server/action/FileActions.java +++ b/src/main/java/org/bdware/server/action/FileActions.java @@ -49,7 +49,7 @@ import java.util.concurrent.TimeUnit; import static io.netty.handler.codec.http.HttpResponseStatus.OK; public class FileActions { - // private static final String PARAM_ACTION = "action"; + // private static final String PARAM_ACTION = "action"; private static final Logger LOGGER = LogManager.getLogger(FileActions.class); private static final Set TEXT_FILE_SUFFIXES = new HashSet<>(); static Set changeSet = ConcurrentHashMap.newKeySet(); @@ -59,14 +59,13 @@ public class FileActions { ContractManagerFrameHandler handler; static { - clearUploadFailed = - new TimerTask() { - @Override - public void run(Timeout arg0) { - clearUploadFailed(); - SyncResult.timer.newTimeout(this, 5, TimeUnit.MINUTES); - } - }; + clearUploadFailed = new TimerTask() { + @Override + public void run(Timeout arg0) { + clearUploadFailed(); + SyncResult.timer.newTimeout(this, 5, TimeUnit.MINUTES); + } + }; SyncResult.timer.newTimeout(clearUploadFailed, 5, TimeUnit.MINUTES); } @@ -85,11 +84,8 @@ public class FileActions { String fileName = compileInternal(parentPath, projectName, isPrivate, true); File dir; if (isPrivate) { - dir = - new File( - parentPath.replace( - GlobalConf.instance.privateDir, - GlobalConf.instance.privateCompiledDir)); + dir = new File(parentPath.replace(GlobalConf.instance.privateDir, + GlobalConf.instance.privateCompiledDir)); } else { dir = new File(GlobalConf.instance.publicCompiledDir); } @@ -107,9 +103,7 @@ public class FileActions { return ret != null && ret.equals("locked"); } - @URIPath( - method = org.bdware.server.http.HttpMethod.POST, - value = {"/SCIDE/Upload", "/Upload"}) + @URIPath(method = org.bdware.server.http.HttpMethod.POST, value = {"/SCIDE/Upload", "/Upload"}) public static void handleUploadRequest(ChannelHandlerContext ctx, FullHttpRequest request) { // logger.info("[CMHttpHandler] handleUploadRequest : "); // Upload method is POST @@ -124,20 +118,16 @@ public class FileActions { } } - if (!transformedParam.containsKey("path") - || !transformedParam.containsKey("fileName") + if (!transformedParam.containsKey("path") || !transformedParam.containsKey("fileName") || !transformedParam.containsKey("isPrivate") - || !transformedParam.containsKey("order") - || !transformedParam.containsKey("count") + || !transformedParam.containsKey("order") || !transformedParam.containsKey("count") || !transformedParam.containsKey("pubKey") || !transformedParam.containsKey("sign")) { - DefaultFullHttpResponse fullResponse = - new DefaultFullHttpResponse( - request.protocolVersion(), - OK, - Unpooled.wrappedBuffer( - "{\"status\":\"false\",\"data\":\"Missing argument, please check: path, fileName, isPrivate, order, count, pubKey, sign!\"}" - .getBytes())); + DefaultFullHttpResponse fullResponse = new DefaultFullHttpResponse( + request.protocolVersion(), OK, + Unpooled.wrappedBuffer( + "{\"status\":\"false\",\"data\":\"Missing argument, please check: path, fileName, isPrivate, order, count, pubKey, sign!\"}" + .getBytes())); ChannelFuture f = addCrossOriginHeaderAndWrite(ctx, fullResponse); @@ -146,10 +136,8 @@ public class FileActions { } // 验签 - // HttpMethod method = request.method(); - String uri = - URLDecoder.decode(request.uri()) - .split("\\?")[1]; // http请求中规定签名必须是最后一个且公钥名必须为pubKey,否则验签失败 + // HttpMethod method = request.method(); + String uri = URLDecoder.decode(request.uri()).split("\\?")[1]; // http请求中规定签名必须是最后一个且公钥名必须为pubKey,否则验签失败 int index = uri.lastIndexOf('&'); String str = uri.substring(0, index); // logger.info("uri=" + uri); @@ -183,9 +171,8 @@ public class FileActions { Method mm; Action a = null; try { - mm = - FileActions.class.getDeclaredMethod( - "uploadFile", JsonObject.class, ResultCallback.class); + mm = FileActions.class.getDeclaredMethod("uploadFile", JsonObject.class, + ResultCallback.class); a = mm.getAnnotation(Action.class); } catch (SecurityException | NoSuchMethodException e1) { // TODO Auto-generated catch block @@ -215,28 +202,17 @@ public class FileActions { status = "accept"; } - TimeDBUtil.instance.put( - CMTables.LocalNodeLogDB.toString(), - "{\"action\":\"" - + action - + "\",\"pubKey\":\"" - + transformedParam.get("pubKey") - + "\",\"status\":\"" - + status - + "\",\"date\":" - + System.currentTimeMillis() + TimeDBUtil.instance.put(CMTables.LocalNodeLogDB.toString(), + "{\"action\":\"" + action + "\",\"pubKey\":\"" + transformedParam.get("pubKey") + + "\",\"status\":\"" + status + "\",\"date\":" + System.currentTimeMillis() + "}"); // logger.info("[CMHttpHandler] flag = " + flag + " flag2 = " + flag2); if (!flag || !flag2) { - DefaultFullHttpResponse fullResponse = - new DefaultFullHttpResponse( - request.protocolVersion(), - OK, - Unpooled.wrappedBuffer( - "{\"status\":\"false\",\"data\":\"Permission denied!\"}" - .getBytes())); + DefaultFullHttpResponse fullResponse = new DefaultFullHttpResponse( + request.protocolVersion(), OK, Unpooled.wrappedBuffer( + "{\"status\":\"false\",\"data\":\"Permission denied!\"}".getBytes())); ChannelFuture f = addCrossOriginHeaderAndWrite(ctx, fullResponse); f.addListener(ChannelFutureListener.CLOSE); @@ -256,9 +232,7 @@ public class FileActions { ContractMeta meta = CMActions.manager.statusRecorder.getContractMeta(contractID); if (meta == null) { DefaultFullHttpResponse fullResponse = - new DefaultFullHttpResponse( - request.protocolVersion(), - OK, + new DefaultFullHttpResponse(request.protocolVersion(), OK, Unpooled.wrappedBuffer( "{\"status\":\"false\",\"data\":\"no such contract!\"}" .getBytes())); @@ -267,24 +241,20 @@ public class FileActions { return; } if (!meta.contract.getOwner().equals(pubkey)) { - DefaultFullHttpResponse fullResponse = - new DefaultFullHttpResponse( - request.protocolVersion(), - OK, - Unpooled.wrappedBuffer( - "{\"status\":\"false\",\"data\":\"not owner!\"}" - .getBytes())); + DefaultFullHttpResponse fullResponse = new DefaultFullHttpResponse( + request.protocolVersion(), OK, Unpooled.wrappedBuffer( + "{\"status\":\"false\",\"data\":\"not owner!\"}".getBytes())); ChannelFuture f = addCrossOriginHeaderAndWrite(ctx, fullResponse); f.addListener(ChannelFutureListener.CLOSE); return; } dir = new File(GlobalConf.instance.getDBPath(), meta.getName()); dir = new File(dir, dirName); - if (!dir.exists()) dir.mkdirs(); + if (!dir.exists()) + dir.mkdirs(); } else { - boolean isPrivate = - transformedParam.containsKey("isPrivate") - && Boolean.parseBoolean(transformedParam.get("isPrivate")); + boolean isPrivate = transformedParam.containsKey("isPrivate") + && Boolean.parseBoolean(transformedParam.get("isPrivate")); // TODO verify signature and if (isPrivate) { String pub = "/" + transformedParam.get("pubKey"); @@ -298,27 +268,24 @@ public class FileActions { } File target = new File(dir, fileName); if (fileName.contains("..")) { - DefaultFullHttpResponse fullResponse = - new DefaultFullHttpResponse( - request.protocolVersion(), - OK, - Unpooled.wrappedBuffer( - "{\"status\":\"false\",\"data\":\"FileName illegal!\"}" - .getBytes())); + DefaultFullHttpResponse fullResponse = new DefaultFullHttpResponse( + request.protocolVersion(), OK, Unpooled.wrappedBuffer( + "{\"status\":\"false\",\"data\":\"FileName illegal!\"}".getBytes())); ChannelFuture f = addCrossOriginHeaderAndWrite(ctx, fullResponse); f.addListener(ChannelFutureListener.CLOSE); return; } - // LOGGER.info(request.refCnt()); - // httpDecoder.offer(request); - // LOGGER.info(request.refCnt()); + // LOGGER.info(request.refCnt()); + // httpDecoder.offer(request); + // LOGGER.info(request.refCnt()); FileOutputStream fout; if (order == 0) { try { LOGGER.debug("Path:" + target.getAbsolutePath()); - if (!target.getParentFile().exists()) target.getParentFile().mkdirs(); + if (!target.getParentFile().exists()) + target.getParentFile().mkdirs(); fout = new FileOutputStream(target, false); fileMap.put(target.getAbsolutePath(), fout); } catch (FileNotFoundException e) { @@ -339,24 +306,24 @@ public class FileActions { } fileMap.remove(target.getAbsolutePath()); updateTime.remove(target.getAbsolutePath()); - boolean isDebug = - transformedParam.containsKey("isDebug") - && Boolean.parseBoolean(transformedParam.get("isDebug")); + boolean isDebug = transformedParam.containsKey("isDebug") + && Boolean.parseBoolean(transformedParam.get("isDebug")); 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); if (null != doi) { retStr = retStr.replaceFirst("null", doi); } } - DefaultFullHttpResponse fullResponse = - new DefaultFullHttpResponse( - request.protocolVersion(), OK, Unpooled.wrappedBuffer(retStr.getBytes())); + DefaultFullHttpResponse fullResponse = new DefaultFullHttpResponse( + request.protocolVersion(), OK, Unpooled.wrappedBuffer(retStr.getBytes())); ChannelFuture f = addCrossOriginHeaderAndWrite(ctx, fullResponse); 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-Methods", "*"); return ctx.write(fullResponse); @@ -374,15 +341,12 @@ public class FileActions { } private static String unzipIfYpk(File target, File dir, boolean isDebug) { - // [FileAction] unzipIfYpk, - // target:/data/bdwaas/bdcontract/./BDWareProjectDir/private/045eeda3a001faad9d636ab1e973599ea87338a9576756eb10ceeca6083c1f76aac5cd201eab21c41342eb8aac40e9b283f0b6eae019644cdcc0a9f9aeb73de8fc/ContractUNknown.ypk targetDir:/data/bdwaas/bdcontract/./BDWareProjectDir/private/045eeda3a001faad9d636ab1e973599ea87338a9576756eb10ceeca6083c1f76aac5cd201eab21c41342eb8aac40e9b283f0b6eae019644cdcc0a9f9aeb73de8fc/ContractUNknown - LOGGER.info( - "[FileAction] unzipIfYpk, date:" - + new SimpleDateFormat("MM-dd hh:mm:ss").format(new Date()) - + " -> target:" - + target.getAbsolutePath() - + " dir:" - + dir.getAbsolutePath()); + // [FileAction] unzipIfYpk, + // target:/data/bdwaas/bdcontract/./BDWareProjectDir/private/045eeda3a001faad9d636ab1e973599ea87338a9576756eb10ceeca6083c1f76aac5cd201eab21c41342eb8aac40e9b283f0b6eae019644cdcc0a9f9aeb73de8fc/ContractUNknown.ypk + // targetDir:/data/bdwaas/bdcontract/./BDWareProjectDir/private/045eeda3a001faad9d636ab1e973599ea87338a9576756eb10ceeca6083c1f76aac5cd201eab21c41342eb8aac40e9b283f0b6eae019644cdcc0a9f9aeb73de8fc/ContractUNknown + LOGGER.info("[FileAction] unzipIfYpk, date:" + + new SimpleDateFormat("MM-dd hh:mm:ss").format(new Date()) + " -> target:" + + target.getAbsolutePath() + " dir:" + dir.getAbsolutePath()); if (target.getParentFile().equals(dir)) { if (target.getName().endsWith(".ypk")) { String dirName = target.getName().substring(0, target.getName().length() - 4); @@ -396,11 +360,8 @@ public class FileActions { } } targetDir.mkdirs(); - LOGGER.info( - "[FileAction] unzipIfYpk, target:" - + target.getAbsolutePath() - + " targetDir:" - + targetDir.getAbsolutePath()); + LOGGER.info("[FileAction] unzipIfYpk, target:" + target.getAbsolutePath() + + " targetDir:" + targetDir.getAbsolutePath()); YJSPacker.unpack(target.getAbsolutePath(), targetDir.getAbsolutePath()); final File tempDir = targetDir; ContractManager.threadPool.execute(() -> startIfManifestDetected(tempDir, isDebug)); @@ -418,14 +379,13 @@ public class FileActions { String doi = "86.5000.470/do." + geneRandomID(); jo.addProperty("doi", doi); } - ContractManager.threadPool.execute( - () -> { - try { - GRPCPool.instance.reRegister(jo.get("doi").getAsString()); - } catch (Exception e) { - LOGGER.warn("unable to connect LHS: " + e.getMessage()); - } - }); + ContractManager.threadPool.execute(() -> { + try { + GRPCPool.instance.reRegister(jo.get("doi").getAsString()); + } catch (Exception e) { + LOGGER.warn("unable to connect LHS: " + e.getMessage()); + } + }); FileWriter fw = new FileWriter(manifestFile); fw.write(JsonUtil.toJson(jo)); fw.close(); @@ -450,9 +410,8 @@ public class FileActions { LOGGER.info("startContractProcess:" + targetDir); Contract c = new Contract(); c.setType(ContractExecType.Sole); - String ypkPath = - FileActions.autoCompile( - targetDir.getParentFile().getAbsolutePath(), contractName); + String ypkPath = FileActions + .autoCompile(targetDir.getParentFile().getAbsolutePath(), contractName); c.setScript(ypkPath); c.setOwner(owner); c.setDebug(isDebug); @@ -487,8 +446,8 @@ public class FileActions { } } - private static void writeChunk( - ChannelHandlerContext ctx, HttpPostRequestDecoder httpDecoder, File file) { + private static void writeChunk(ChannelHandlerContext ctx, HttpPostRequestDecoder httpDecoder, + File file) { try { if (!file.exists()) { file.createNewFile(); @@ -521,8 +480,8 @@ public class FileActions { } } - private static String compileInternal( - String parPath, String projectName, boolean isPrivate, boolean isAuto) { + private static String compileInternal(String parPath, String projectName, boolean isPrivate, + boolean isAuto) { File project = new File(parPath, projectName); try { if (project.isDirectory()) { @@ -534,24 +493,18 @@ public class FileActions { File dir; if (isPrivate) { - dir = - new File( - parPath.replace( - GlobalConf.instance.privateDir, - GlobalConf.instance.privateCompiledDir)); + dir = new File(parPath.replace(GlobalConf.instance.privateDir, + GlobalConf.instance.privateCompiledDir)); } else { dir = new File(GlobalConf.instance.publicCompiledDir); } tempZip = new File(dir, projectName + "_" + time + isAutoStr + ".ypk"); if (isAuto) { - File[] files = - dir.listFiles( - pathname -> - pathname.getName().startsWith(projectName + "_") - && pathname.getName().endsWith("_Auto.ypk")); - if (files != null - && files.length == 1 + File[] files = dir + .listFiles(pathname -> pathname.getName().startsWith(projectName + "_") + && pathname.getName().endsWith("_Auto.ypk")); + if (files != null && files.length == 1 && !changeSet.contains(project.getAbsolutePath())) { return files[0].getName(); } else if (files != null) { @@ -576,8 +529,7 @@ public class FileActions { Map header = new HashMap<>(); header.put("accept", "*/*"); header.put("connection", "Keep-Alive"); - header.put( - "user-agent", + header.put("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)"); // header.put("Content-Type", "application/json"); return header; @@ -652,7 +604,8 @@ public class FileActions { } private static String toProjectName(String path) { - if (path.startsWith("/")) path = path.substring(1); + if (path.startsWith("/")) + path = path.substring(1); return path.replaceAll("/.*$", ""); } @@ -771,9 +724,7 @@ public class FileActions { int counter = 0; while ((s = br.readLine()) != null) { - if (s.equals("{") - || s.equals("}") - || s.equals("") + if (s.equals("{") || s.equals("}") || s.equals("") || s.trim().startsWith("\"doi\":\"") || s.trim().startsWith("\"doipFlag\":\"")) { continue; @@ -852,8 +803,8 @@ public class FileActions { returnFileListResponse(resultCallback, response, dirs, f); } - private void returnFileListResponse( - ResultCallback resultCallback, Response response, List dirs, File f) { + private void returnFileListResponse(ResultCallback resultCallback, Response response, + List dirs, File f) { if (f.exists() && f.isDirectory()) { for (File subFile : f.listFiles()) { dirs.add(subFile.getName()); @@ -895,7 +846,8 @@ public class FileActions { String fileName = subFile.getName(); dirs.add(fileName); } - } else dirs.add(project); + } else + dirs.add(project); } response.data = JsonUtil.toJson(dirs); } @@ -995,20 +947,20 @@ public class FileActions { response.isPrivate = true; String strr = "/" + getPubkey(args); projectDir = GlobalConf.instance.privateDir + strr; - // url = - // "http://" - // + mainHost - // + "/SCIDE/CMManager?action=downloadContract&projectName=" - // + projectName - // + "&pubkey=" - // + json.get("pubkey").getAsString(); + // url = + // "http://" + // + mainHost + // + "/SCIDE/CMManager?action=downloadContract&projectName=" + // + projectName + // + "&pubkey=" + // + json.get("pubkey").getAsString(); } else { projectDir = GlobalConf.instance.publicDir; - // url = - // "http://" - // + mainHost - // + "/SCIDE/CMManager?action=downloadContract&projectName=" - // + projectName; + // url = + // "http://" + // + mainHost + // + "/SCIDE/CMManager?action=downloadContract&projectName=" + // + projectName; } url = "http://127.0.0.1:18000/Users/zhangyixuan/Grade2/temp65/TEST.txt"; @@ -1077,7 +1029,7 @@ public class FileActions { long downloaded = 0; byte[] buff = new byte[1024 * 100 * 4]; int d = 5; - for (int k; (k = input.read(buff)) > 0; ) { + for (int k; (k = input.read(buff)) > 0;) { fout.write(buff, 0, k); downloaded += k; response.data = "downloading"; @@ -1179,89 +1131,72 @@ public class FileActions { case "Data Sharing Project": // 注册一个用于授权状态持久化的DO,并设置到manifest String authInfoPersistDOI = null; - // try { + // try { // - // HandleService hs = - // new + // HandleService hs = + // new // HandleService(HandleServiceUtils.hrRegister); - // authInfoPersistDOI = + // authInfoPersistDOI = // // hs.registerContract(DOIPMainServer.repoIdentifier, ""); - // DigitalObject contractDO = - // new + // DigitalObject contractDO = + // new // DigitalObject(authInfoPersistDOI, DoType.Json); - // Element e = new + // Element e = new // Element("contract", "JsonString"); - // e.setData("{}".getBytes()); - // contractDO.addElements(e); - // // - // DOAClient.getGlobalInstance().create(DOIPMainServer.repoIdentifier, contractDO); - // DoipClient doipClient = + // e.setData("{}".getBytes()); + // contractDO.addElements(e); + // // + // DOAClient.getGlobalInstance().create(DOIPMainServer.repoIdentifier, + // contractDO); + // DoipClient doipClient = // // DoipClient.createByRepoUrlAndMsgFmt( // // DOIPMainServer.repoUrl, // // DoipMessageFormat.PACKET.getName()); - // DoMessage response = - // doipClient.create( + // DoMessage response = + // doipClient.create( // // DOIPMainServer.repoIdentifier, contractDO); - // if (authInfoPersistDOI == + // if (authInfoPersistDOI == // null) return; - // } catch (Exception ex) { - // ex.printStackTrace(); - // return; - // } + // } catch (Exception ex) { + // ex.printStackTrace(); + // return; + // } if (args.has("projectDOI")) - manifestFout.write( - ("{\n \"main\":\"" - + fileName - + ".yjs\",\n" - + " \"doipFlag\":true,\n" - + " \"doi\":\"" - + args.get("projectDOI").getAsString() - + "\",\n" - + " \"authInfoPersistDOI\":\"" - + authInfoPersistDOI - + "\"\n}") - .getBytes()); + manifestFout.write(("{\n \"main\":\"" + fileName + ".yjs\",\n" + + " \"doipFlag\":true,\n" + " \"doi\":\"" + + args.get("projectDOI").getAsString() + "\",\n" + + " \"authInfoPersistDOI\":\"" + authInfoPersistDOI + + "\"\n}").getBytes()); else - manifestFout.write( - ("{\n \"main\":\"" - + fileName - + ".yjs\",\n" - + " \"authInfoPersistDOI\":\"" - + authInfoPersistDOI - + "\"\n}") - .getBytes()); + manifestFout.write(("{\n \"main\":\"" + fileName + ".yjs\",\n" + + " \"authInfoPersistDOI\":\"" + authInfoPersistDOI + + "\"\n}").getBytes()); YJSPacker.unpack( new File("./WebContent/ProjectTemplate/naiveDAC.zip") .getAbsolutePath(), newFile.getPath() + "/naiveDAC"); - mainyjsFout.write( - ("import \"naiveDAC/naiveDAC.yjs\"\n\n").getBytes()); - mainyjsFout.write( - ("contract " - + fileName - + "{\n function onCreate(){\n initDAC(requester);\n }\n}") + mainyjsFout + .write(("import \"naiveDAC/naiveDAC.yjs\"\n\n").getBytes()); + mainyjsFout.write(("contract " + fileName + + "{\n function onCreate(){\n initDAC(requester);\n }\n}") .getBytes()); break; default: if (args.has("projectDOI")) - manifestFout.write( - ("{\n \"main\":\"" - + fileName - + ".yjs\",\n \"doipFlag\":true,\n \"doi\":\"" - + args.get("projectDOI").getAsString() - + "\"\n}") + manifestFout.write(("{\n \"main\":\"" + fileName + + ".yjs\",\n \"doipFlag\":true,\n \"doi\":\"" + + args.get("projectDOI").getAsString() + "\"\n}") .getBytes()); else - manifestFout.write( - ("{\n \"main\":\"" + fileName + ".yjs\"\n}") - .getBytes()); + manifestFout.write(("{\n \"main\":\"" + fileName + ".yjs\"\n}") + .getBytes()); mainyjsFout.write(("contract " + fileName + "{\n\n}").getBytes()); } } @@ -1323,11 +1258,8 @@ public class FileActions { File f = new File(parPath + "/" + oldFile); if (!oldFile.contains("..") && f.exists()) { - LOGGER.debug( - "[FileController] delete:" - + f.getAbsolutePath() - + " exists:" - + f.exists()); + LOGGER.debug("[FileController] delete:" + f.getAbsolutePath() + " exists:" + + f.exists()); if (f.isDirectory()) { deleteDir(f); } else { @@ -1465,10 +1397,8 @@ public class FileActions { // 文本文件 if (!path.contains("..") && isTextFile(path)) { LOGGER.debug("[FileActions] 上传文本文件类型 : "); - BufferedWriter bw = - new BufferedWriter( - new FileWriter( - target.getAbsolutePath() + "/" + fileName, isAppend)); + BufferedWriter bw = new BufferedWriter( + new FileWriter(target.getAbsolutePath() + "/" + fileName, isAppend)); bw.write(content); bw.close(); } else { // 其他类型文件 @@ -1505,7 +1435,8 @@ public class FileActions { private String getPubkey(JsonObject args) { try { - if (handler != null) return handler.getPubKey(); + if (handler != null) + return handler.getPubKey(); return args.get("pubKey").getAsString(); } catch (Exception e) { e.printStackTrace(); @@ -1558,59 +1489,59 @@ public class FileActions { resultCallback.onResult(JsonUtil.toJson(response)); } - // @Action(userPermission = 1 << 14, async = true) - // public void importContractInstanceCodeByDOI(JsonObject args, ResultCallback + // @Action(userPermission = 1 << 14, async = true) + // public void importContractInstanceCodeByDOI(JsonObject args, ResultCallback // resultCallback) { - // long s = System.currentTimeMillis(); - // String ret; - // try { - // String contractDOI = args.get("doi").getAsString(); - // DigitalObject contractDO; - // DoipClient doipClient = - // DoipClient.createByRepoUrlAndMsgFmt( - // DOIPMainServer.repoUrl, DoipMessageFormat.PACKET.getName()); - // DoMessage response = doipClient.retrieve(contractDOI, null, null); - // if (response.parameters.response == DoResponse.Success) { - // contractDO = DigitalObject.parse(response.body); - // } else { - // DoMessage resp = DOAClient.getGlobalInstance().retrieve(contractDOI, null, + // long s = System.currentTimeMillis(); + // String ret; + // try { + // String contractDOI = args.get("doi").getAsString(); + // DigitalObject contractDO; + // DoipClient doipClient = + // DoipClient.createByRepoUrlAndMsgFmt( + // DOIPMainServer.repoUrl, DoipMessageFormat.PACKET.getName()); + // DoMessage response = doipClient.retrieve(contractDOI, null, null); + // if (response.parameters.response == DoResponse.Success) { + // contractDO = DigitalObject.parse(response.body); + // } else { + // DoMessage resp = DOAClient.getGlobalInstance().retrieve(contractDOI, null, // null); - // contractDO = DigitalObject.parse(resp.body); - // } - // // Dictionary contractInfo = JsonUtil.fromJson(new - // // String(contractDO.getData()), - // // new Hashtable().getClass()); - // ContractInstanceDO contractInstanceDO = - // (ContractInstanceDO) - // ContractManager.toObject(contractDO.elements.get(0).getData()); - // String projectName = contractDOI.replace('/', '_'); - // String projectDirStr = - // GlobalConf.instance.privateDir + "/" + getPubkey(args) + "/" + + // contractDO = DigitalObject.parse(resp.body); + // } + // // Dictionary contractInfo = JsonUtil.fromJson(new + // // String(contractDO.getData()), + // // new Hashtable().getClass()); + // ContractInstanceDO contractInstanceDO = + // (ContractInstanceDO) + // ContractManager.toObject(contractDO.elements.get(0).getData()); + // String projectName = contractDOI.replace('/', '_'); + // String projectDirStr = + // GlobalConf.instance.privateDir + "/" + getPubkey(args) + "/" + // projectName; - // File projectDir = new File(projectDirStr); - // if (projectDir.isDirectory()) { - // deleteDir(projectDir); - // } - // YJSPacker.unpack(contractInstanceDO.script, projectDirStr); - // ret = - // "Import project successfully." - // + "\nProject Name: " - // + projectName - // + "\nContract ID: " - // + contractInstanceDO.id - // + "\nContract PublicKey: " - // + contractInstanceDO.publicKey; - // } catch (Exception e) { - // ByteArrayOutputStream bo = new ByteArrayOutputStream(); - // e.printStackTrace(new PrintStream(bo)); - // ret = bo.toString(); - // } - // Map r = new HashMap<>(); - // r.put("action", "onImportContractInstanceCodeByDOI"); - // r.put("data", ret); - // r.put("executeTime", System.currentTimeMillis() - s); - // resultCallback.onResult(JsonUtil.toJson(r)); - // } + // File projectDir = new File(projectDirStr); + // if (projectDir.isDirectory()) { + // deleteDir(projectDir); + // } + // YJSPacker.unpack(contractInstanceDO.script, projectDirStr); + // ret = + // "Import project successfully." + // + "\nProject Name: " + // + projectName + // + "\nContract ID: " + // + contractInstanceDO.id + // + "\nContract PublicKey: " + // + contractInstanceDO.publicKey; + // } catch (Exception e) { + // ByteArrayOutputStream bo = new ByteArrayOutputStream(); + // e.printStackTrace(new PrintStream(bo)); + // ret = bo.toString(); + // } + // Map r = new HashMap<>(); + // r.put("action", "onImportContractInstanceCodeByDOI"); + // r.put("data", ret); + // r.put("executeTime", System.currentTimeMillis() - s); + // resultCallback.onResult(JsonUtil.toJson(r)); + // } private boolean isTextFile(String path) { return TEXT_FILE_SUFFIXES.contains(path.substring(path.lastIndexOf("."))); @@ -1648,9 +1579,8 @@ public class FileActions { if (null != ypkPath) { try { ret.put("ypk", new File(ypkPath).getName()); - ret.put( - "permissions", - JsonUtil.parseStringAsJsonObject(CMActions.manager.parseYpkPermissions(ypkPath))); + ret.put("permissions", JsonUtil + .parseStringAsJsonObject(CMActions.manager.parseYpkPermissions(ypkPath))); } catch (Exception e) { ByteArrayOutputStream bo = new ByteArrayOutputStream(); e.printStackTrace(new PrintStream(bo)); diff --git a/src/main/java/org/bdware/server/action/HttpFileAction.java b/src/main/java/org/bdware/server/action/HttpFileAction.java index 276de4a..5e34c33 100644 --- a/src/main/java/org/bdware/server/action/HttpFileAction.java +++ b/src/main/java/org/bdware/server/action/HttpFileAction.java @@ -18,25 +18,17 @@ public class HttpFileAction { LOGGER.debug("[HttpFileAction] donwloadContract : "); try { - /* already verified before into downloadContract! - String arg = "action=" + json.get("action").getAsString(); - arg += "&projectName=" + json.get("projectName").getAsString(); - arg += "&isPrivate=" + json.get("isPrivate").getAsString(); - arg += "&pubKey=" + json.get("pubKey").getAsString(); - arg += "×tamp=" + json.get("timestamp").getAsString(); - ECPoint pubKey = SM2KeyPair.publicKeyStr2ECPoint(json.get("pubKey").getAsString()); - boolean verify = - new SM2() - .verify( - arg, - SM2.Signature.loadFromString(json.get("sign").getAsString()), - "", - pubKey); - if (!verify) { - result.onResult("/dev/null/2"); - return; - } - */ + /* + * already verified before into downloadContract! String arg = "action=" + + * json.get("action").getAsString(); arg += "&projectName=" + + * json.get("projectName").getAsString(); arg += "&isPrivate=" + + * json.get("isPrivate").getAsString(); arg += "&pubKey=" + + * json.get("pubKey").getAsString(); arg += "×tamp=" + + * json.get("timestamp").getAsString(); ECPoint pubKey = + * SM2KeyPair.publicKeyStr2ECPoint(json.get("pubKey").getAsString()); boolean verify = + * new SM2() .verify( arg, SM2.Signature.loadFromString(json.get("sign").getAsString()), + * "", pubKey); if (!verify) { result.onResult("/dev/null/2"); return; } + */ String projectName = json.get("projectName").getAsString(); if (projectName.contains("..")) { diff --git a/src/main/java/org/bdware/server/action/LedgerActions.java b/src/main/java/org/bdware/server/action/LedgerActions.java index 366dbf0..6053207 100644 --- a/src/main/java/org/bdware/server/action/LedgerActions.java +++ b/src/main/java/org/bdware/server/action/LedgerActions.java @@ -24,41 +24,41 @@ import java.util.Map; public class LedgerActions { public static LedgerActions instance = new LedgerActions(); - // @Action - // private void sendMockTransaction(JsonObject args, ResultCallback resultCallback) { - // Result r = new Result(); - // r.data = "TODO"; - // r.status = true; - // r.msg = null; - // resultCallback.onResult(gson.toJson(r)); - // } + // @Action + // private void sendMockTransaction(JsonObject args, ResultCallback resultCallback) { + // Result r = new Result(); + // r.data = "TODO"; + // r.status = true; + // r.msg = null; + // resultCallback.onResult(gson.toJson(r)); + // } // - // @Action - // private void queryTransByHash(JsonObject args, ResultCallback resultCallback) { - // Result r = new Result(); - // r.data = "TODO"; - // r.status = true; - // r.msg = null; - // resultCallback.onResult(gson.toJson(r)); - // } + // @Action + // private void queryTransByHash(JsonObject args, ResultCallback resultCallback) { + // Result r = new Result(); + // r.data = "TODO"; + // r.status = true; + // r.msg = null; + // resultCallback.onResult(gson.toJson(r)); + // } - // @Action - // private void queryHash(JsonObject args, ResultCallback resultCallback) { - // Result r = new Result(); - // r.data = "TODO"; - // r.status = true; - // r.msg = null; - // resultCallback.onResult(gson.toJson(r)); - // } + // @Action + // private void queryHash(JsonObject args, ResultCallback resultCallback) { + // Result r = new Result(); + // r.data = "TODO"; + // r.status = true; + // r.msg = null; + // resultCallback.onResult(gson.toJson(r)); + // } // - // @Action - // private void queryRecent(JsonObject args, ResultCallback resultCallback) { - // Result r = new Result(); - // r.data = "TODO"; - // r.status = true; - // r.msg = null; - // resultCallback.onResult(gson.toJson(r)); - // } + // @Action + // private void queryRecent(JsonObject args, ResultCallback resultCallback) { + // Result r = new Result(); + // r.data = "TODO"; + // r.status = true; + // r.msg = null; + // resultCallback.onResult(gson.toJson(r)); + // } @Action public void queryLedgers(JsonObject jo, ResultCallback resultCallback) { @@ -69,7 +69,8 @@ public class LedgerActions { LedgerProto.GetLedgersResponse ledgers = wt.getLedgersSync(); List array = new ArrayList<>(); 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)); } catch (Exception e) { ByteArrayOutputStream bo = new ByteArrayOutputStream(); @@ -99,67 +100,61 @@ public class LedgerActions { public void sendTransaction(JsonObject jo, ResultCallback resultCallback) { Client wt = GRPCPool.grpcClients.get(0); 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 to = jo.get("to").getAsString(); String data = jo.get("data").getAsString(); ListenableFuture future = - wt.sendTransaction( - ledgerName, - CommonProto.TransactionType.MESSAGE, - from, - random.nextLong(), - to, - data.getBytes()); - future.addListener( - () -> { - try { - ByteString hash = future.get().getHash(); - ReplyUtil.replyWithStatus(resultCallback, "onSendTransaction", true, HashUtil.byteArray2Str(hash.toByteArray())); - } catch (Exception e) { - ByteArrayOutputStream bo = new ByteArrayOutputStream(); - String dataStr = bo.toString(); - ReplyUtil.replyWithStatus(resultCallback, "onSendTransaction", false, dataStr); - e.printStackTrace(); - } - }, - ContractManager.threadPool); + wt.sendTransaction(ledgerName, CommonProto.TransactionType.MESSAGE, from, + random.nextLong(), to, data.getBytes()); + future.addListener(() -> { + try { + ByteString hash = future.get().getHash(); + ReplyUtil.replyWithStatus(resultCallback, "onSendTransaction", true, + HashUtil.byteArray2Str(hash.toByteArray())); + } catch (Exception e) { + ByteArrayOutputStream bo = new ByteArrayOutputStream(); + String dataStr = bo.toString(); + ReplyUtil.replyWithStatus(resultCallback, "onSendTransaction", false, dataStr); + e.printStackTrace(); + } + }, ContractManager.threadPool); } @Action public void queryTransactionByHash(JsonObject jo, ResultCallback resultCallback) { String hash = jo.get("hash").getAsString(); 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); if (wt == null) { - resultCallback.onResult( - "{\"status\":\"Exception\",\"data\":\"no available worker thread\"}"); + resultCallback + .onResult("{\"status\":\"Exception\",\"data\":\"no available worker thread\"}"); return; } ListenableFuture future = wt.getTransactionByHash(ledgerName, hash); - future.addListener( - () -> { - try { - CommonProto.Transaction trans = future.get().getTransaction(); - Map ret = new HashMap<>(); - ret.put("from", HashUtil.byteArray2Str(trans.getFrom().toByteArray())); - ret.put("to", HashUtil.byteArray2Str(trans.getTo().toByteArray())); - ret.put("data", trans.getData().toStringUtf8()); - ret.put("action", "onQueryTransactionByHash"); - ret.put("type", trans.getType().name()); - resultCallback.onResult(JsonUtil.toJson(ret)); - } catch (Exception e) { - ByteArrayOutputStream bo = new ByteArrayOutputStream(); - Map ret = new HashMap<>(); - ret.put("action", "onQueryTransactionByHash"); - e.printStackTrace(new PrintStream(bo)); - ret.put("data", bo.toString()); - resultCallback.onResult(JsonUtil.toJson(ret)); - e.printStackTrace(); - } - }, - ContractManager.threadPool); + future.addListener(() -> { + try { + CommonProto.Transaction trans = future.get().getTransaction(); + Map ret = new HashMap<>(); + ret.put("from", HashUtil.byteArray2Str(trans.getFrom().toByteArray())); + ret.put("to", HashUtil.byteArray2Str(trans.getTo().toByteArray())); + ret.put("data", trans.getData().toStringUtf8()); + ret.put("action", "onQueryTransactionByHash"); + ret.put("type", trans.getType().name()); + resultCallback.onResult(JsonUtil.toJson(ret)); + } catch (Exception e) { + ByteArrayOutputStream bo = new ByteArrayOutputStream(); + Map ret = new HashMap<>(); + ret.put("action", "onQueryTransactionByHash"); + e.printStackTrace(new PrintStream(bo)); + ret.put("data", bo.toString()); + resultCallback.onResult(JsonUtil.toJson(ret)); + e.printStackTrace(); + } + }, ContractManager.threadPool); } } diff --git a/src/main/java/org/bdware/server/action/ManagerActions.java b/src/main/java/org/bdware/server/action/ManagerActions.java index 9be40d2..a8f4477 100644 --- a/src/main/java/org/bdware/server/action/ManagerActions.java +++ b/src/main/java/org/bdware/server/action/ManagerActions.java @@ -42,7 +42,8 @@ public class ManagerActions { public void getEncodedUUID(JsonObject args, ResultCallback resultCallback) { String data = null; 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) { e.printStackTrace(); } @@ -51,7 +52,8 @@ public class ManagerActions { @Action(userPermission = 1 << 10) 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); } @@ -98,7 +100,8 @@ public class ManagerActions { return; } catch (Exception e) { 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 data = new HashMap<>(); data.put("projectDir", GlobalConf.instance.projectDir); 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("licence", GlobalConf.instance.licence); 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("peerID", GlobalConf.instance.peerID); 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("masterAddress", GlobalConf.instance.masterAddress); data.put("nodeCenterWS", GlobalConf.getNodeCenterWSUrl()); @@ -157,14 +162,16 @@ public class ManagerActions { public void changeNodeCenter(JsonObject args, ResultCallback resultCallback) { String val = args.get("data").getAsString(); 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) public void changeNodeCenterWS(JsonObject args, ResultCallback resultCallback) { String val = args.get("data").getAsString(); LOGGER.debug(JsonUtil.toJson(args)); - ReplyUtil.replyWithStatus(resultCallback, "onChangeNodeCenter", true, GlobalConf.resetNodeCenterWS(val)); + ReplyUtil.replyWithStatus(resultCallback, "onChangeNodeCenter", true, + GlobalConf.resetNodeCenterWS(val)); } @@ -173,37 +180,43 @@ public class ManagerActions { String val = args.get("data").getAsString(); String lines = val.replace(" ", "\n"); LOGGER.debug("changeBDledger " + lines); - ReplyUtil.replyWithStatus(resultCallback, "onChangeBDledger", true, GlobalConf.resetDataChain(lines)); + ReplyUtil.replyWithStatus(resultCallback, "onChangeBDledger", true, + GlobalConf.resetDataChain(lines)); } @Action(userPermission = 1 << 10) public void changeNodeName(JsonObject args, ResultCallback resultCallback) { 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) public void changeIpPort(JsonObject args, ResultCallback resultCallback) { 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) public void changeDOIPConfig(JsonObject args, ResultCallback resultCallback) { 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) public void changeYJSPath(JsonObject args, ResultCallback resultCallback) { 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) public void uploadLicence(JsonObject args, ResultCallback resultCallback) { 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) @@ -215,9 +228,11 @@ public class ManagerActions { public void applyNodeRoleDeprecated(JsonObject json, ResultCallback resultCallback) { try { String pubKey = null; - if (json.has("verifiedPubKey")) pubKey = json.get("verifiedPubKey").getAsString(); + if (json.has("verifiedPubKey")) + pubKey = json.get("verifiedPubKey").getAsString(); if (pubKey == null) { - resultCallback.onResult("{\"action\":\"onApplyNodeRole\",\"data\":\"Failed: Illegal user\"}"); + resultCallback.onResult( + "{\"action\":\"onApplyNodeRole\",\"data\":\"Failed: Illegal user\"}"); return; } String ro = json.get("role").getAsString(); @@ -225,21 +240,26 @@ public class ManagerActions { LOGGER.debug("[role]" + ro); Role role = Role.parse(json.get("role").getAsString()); if (role != Role.Anonymous) { - String str = KeyValueDBUtil.instance.getValue(CMTables.ApplyRole.toString(), pubKey); - String already = KeyValueDBUtil.instance.getValue(CMTables.NodeRole.toString(), pubKey); + String str = + KeyValueDBUtil.instance.getValue(CMTables.ApplyRole.toString(), pubKey); + String already = + KeyValueDBUtil.instance.getValue(CMTables.NodeRole.toString(), pubKey); if (already != null && already.contains(role.toString())) { ReplyUtil.simpleReply(resultCallback, "onApplyNodeRole", "already has!"); return; } 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 { 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"); return; @@ -253,7 +273,8 @@ public class ManagerActions { } catch (Exception e) { e.printStackTrace(); - resultCallback.onResult("{\"action\":\"onApplyNodeRole\",\"data\":\"Failed: Exception happened\"}"); + resultCallback.onResult( + "{\"action\":\"onApplyNodeRole\",\"data\":\"Failed: Exception happened\"}"); } } } diff --git a/src/main/java/org/bdware/server/action/MasterWSAction.java b/src/main/java/org/bdware/server/action/MasterWSAction.java index ece937d..c4da06e 100644 --- a/src/main/java/org/bdware/server/action/MasterWSAction.java +++ b/src/main/java/org/bdware/server/action/MasterWSAction.java @@ -13,7 +13,6 @@ import org.bdware.sc.db.CMTables; import org.bdware.sc.db.KeyValueDBUtil; import org.bdware.sc.units.RecoverFlag; import org.bdware.sc.util.JsonUtil; -import org.bdware.server.GRPCPool; import org.bdware.server.GlobalConf; import org.bdware.server.action.p2p.MasterServerRecoverMechAction; import org.bdware.server.action.p2p.MasterServerTCPAction; @@ -105,34 +104,36 @@ public class MasterWSAction { } else if (args.has("projectName")) { 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"); // String toVerify = - // "MultiPoint|" - // + args.get("type").getAsString() - // + "|" - // + contract.getScriptStr() - // + "|" - // + managerAction.getPubKey(); - // boolean verify = - // SM2Util.plainStrVerify( - // managerAction.getPubKey(), toVerify, + // "MultiPoint|" + // + args.get("type").getAsString() + // + "|" + // + contract.getScriptStr() + // + "|" + // + managerAction.getPubKey(); + // boolean verify = + // SM2Util.plainStrVerify( + // managerAction.getPubKey(), toVerify, // args.get("sign").getAsString()); // - // if (!verify) { - // Map ret = new HashMap<>(); - // ret.put("action", "onStartContractTrustfullyResult"); - // ret.put("data", "verify signature failed"); - // ret.put("status", "Error"); - // rc.onResult(JsonUtil.toJson(ret)); - // return; - // } + // if (!verify) { + // Map ret = new HashMap<>(); + // ret.put("action", "onStartContractTrustfullyResult"); + // ret.put("data", "verify signature failed"); + // ret.put("status", "Error"); + // rc.onResult(JsonUtil.toJson(ret)); + // return; + // } SM2KeyPair sm2Key; String parPath = GlobalConf.instance.publicCompiledDir; 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(); @@ -140,7 +141,8 @@ public class MasterWSAction { scriptOrPath = parPath + contract.getScriptStr(); } 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) { privateKeyStr = SM2Util.generateSM2KeyPair().toJson(); KeyValueDBUtil.instance.setValue(CMTables.ContractInfo.toString(), key, privateKeyStr); @@ -152,48 +154,40 @@ public class MasterWSAction { contract.setPublicKey(sm2Key.getPublicKeyStr()); // TODO - // contract.setNodeCenterRepoDOI(DOIPMainServer4NC.repoIdentifier); + // contract.setNodeCenterRepoDOI(DOIPMainServer4NC.repoIdentifier); // 多点合约部署时,由NC预先注册一个DOI以备使用 /* - if (DoConfig.openContractDORegister) { - try { - HandleService hs = new HandleService(HandleServiceUtils.hrRegister); - String tmpDOI = hs.registerContract(DOIPMainServer4NC.repoIdentifier); - if (tmpDOI == "" || tmpDOI == null) - contract.setDOI("RegisterFailed"); - else - contract.setDOI(tmpDOI); - } - catch (Exception e) { - e.printStackTrace(); - contract.setDOI("RegisterFailed"); - } - } - */ + * if (DoConfig.openContractDORegister) { try { HandleService hs = new + * HandleService(HandleServiceUtils.hrRegister); String tmpDOI = + * hs.registerContract(DOIPMainServer4NC.repoIdentifier); if (tmpDOI == "" || tmpDOI == + * null) contract.setDOI("RegisterFailed"); else contract.setDOI(tmpDOI); } catch (Exception + * e) { e.printStackTrace(); contract.setDOI("RegisterFailed"); } } + */ List nodeNames; // nodes' peerID -// if (contract.getType().equals(ContractExecType.SelfAdaptiveSharding)) { -// if (ContractManager.instance.nodeCenterConn.listNodes().length < 3) { -// rc.onResult( -// "{\"status\":\"Error\",\"result\":\"No enough nodes!\"," -// + "\"action\":\"onStartTrustfulContract\"}"); -// return; -// } -// int unitSize = args.get("selectUnitNum").getAsInt(); -// nodeNames = -// Arrays.asList(ContractManager.instance.nodeCenterConn.getClusterByKey( -// contractID, -// Math.max(unitSize, 3))); -// } else { + // if (contract.getType().equals(ContractExecType.SelfAdaptiveSharding)) { + // if (ContractManager.instance.nodeCenterConn.listNodes().length < 3) { + // rc.onResult( + // "{\"status\":\"Error\",\"result\":\"No enough nodes!\"," + // + "\"action\":\"onStartTrustfulContract\"}"); + // return; + // } + // int unitSize = args.get("selectUnitNum").getAsInt(); + // nodeNames = + // Arrays.asList(ContractManager.instance.nodeCenterConn.getClusterByKey( + // contractID, + // Math.max(unitSize, 3))); + // } else { // all nodes' peerID in the unit String[] nodeNamesStr = args.get("peersID").getAsString().split(","); // 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; String masterNode = keyPair.getPublicKeyStr(); assert nodeNames.contains(masterNode); - //nodeNames.add(masterNode); + // nodeNames.add(masterNode); int nodeSize = nodeNames.size(); // 方式一向NodeCenter发,要求Slave节点主动连接到Master节点. Map requestConnect = new HashMap<>(); @@ -204,8 +198,8 @@ public class MasterWSAction { if (contract.getType() == ContractExecType.Sharding) { requestConnect.put("connectAll", true); } - // NetworkManager.instance.sendToNodeCenter(JsonUtil.toJson(requestConnect)); // 向NC发 - //waitForConnection(nodeNames); + // NetworkManager.instance.sendToNodeCenter(JsonUtil.toJson(requestConnect)); // 向NC发 + // waitForConnection(nodeNames); LOGGER.debug(JsonUtil.toPrettyJson(requestConnect)); final long curr = System.currentTimeMillis(); String requestID = curr + "_" + (int) (Math.random() * 10000); @@ -247,7 +241,7 @@ public class MasterWSAction { contract.setNumOfCopies(nodeSize); break; default: - contract.setNumOfCopies(1); // TODO copies是1? + contract.setNumOfCopies(1); // TODO copies是1? break; } LOGGER.debug("contract " + contract.getID() + " has been added into contractID2Members"); @@ -270,14 +264,17 @@ public class MasterWSAction { if (!MasterServerRecoverMechAction.recoverStatus.containsKey(nodeID)) { 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!"); } public String getPubKey(JsonObject jo) { - if (handler != null) return handler.getPubKey(); + if (handler != null) + return handler.getPubKey(); return jo.get("pubKey").getAsString(); } } diff --git a/src/main/java/org/bdware/server/action/MultiRequestInfo.java b/src/main/java/org/bdware/server/action/MultiRequestInfo.java index e48481f..4f643c7 100644 --- a/src/main/java/org/bdware/server/action/MultiRequestInfo.java +++ b/src/main/java/org/bdware/server/action/MultiRequestInfo.java @@ -18,13 +18,14 @@ import java.util.concurrent.atomic.AtomicInteger; public class MultiRequestInfo { public static final Object lock = new Object(); private static final Logger LOGGER = LogManager.getLogger(MultiRequestInfo.class); - public static Map reqInfos = new ConcurrentHashMap(); //key为requestID + public static Map reqInfos = + new ConcurrentHashMap(); // key为requestID public final String requestID; public final int seq; private final int total; private final AtomicInteger count = new AtomicInteger(0); - private final Map flag = new HashMap<>(); //uniID是否执行 - public Map callbackMap = new ConcurrentHashMap<>(); //key是uniqueID,这个map中存的是第2个及之后的请求的callback第1个请求的callback在正常的请求队列中 + private final Map flag = new HashMap<>(); // uniID是否执行 + public Map callbackMap = new ConcurrentHashMap<>(); // key是uniqueID,这个map中存的是第2个及之后的请求的callback第1个请求的callback在正常的请求队列中 public MultiRequestInfo(String id, int t) { requestID = id; @@ -32,41 +33,47 @@ public class MultiRequestInfo { total = Integer.parseInt(id.split("_")[1]); } - //交给线程池中线程完成,不能是同一个线程跑 + // 交给线程池中线程完成,不能是同一个线程跑 public static void exeMultiReq(ContractRequest request, String uniID) { - ContractManagerFrameHandler.executorService.execute( - () -> { - exeMultiReqInternal(request, uniID); - } - ); + ContractManagerFrameHandler.executorService.execute(() -> { + exeMultiReqInternal(request, 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(); - //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()); - //logger.info("【exeMultiReqInternal】 uniID=" + uniID + " Thread-id=" + Thread.currentThread().getId() + " ---3 " + (reqInfos.containsKey(request.getRequestID()))); + MultiContractMeta cei = CMActions.manager.multiContractRecorder + .getMultiContractMeta(request.getContractID()); + // logger.info("【exeMultiReqInternal】 uniID=" + uniID + " Thread-id=" + + // Thread.currentThread().getId() + " ---3 " + + // (reqInfos.containsKey(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) { - //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) { - // logger.info("还未执行到 " + mri.seq + " 当前序号是 " + cei.curExeSeq); + // logger.info("还未执行到 " + mri.seq + " 当前序号是 " + cei.curExeSeq); return; } if (mri.flag.get(uniID)) { - //logger.info("uniID=" + uniID + " 已执行过 " + " Thread-id=" + Thread.currentThread().getId()); + // logger.info("uniID=" + uniID + " 已执行过 " + " Thread-id=" + + // Thread.currentThread().getId()); return; } else { mri.flag.put(uniID, true); @@ -75,7 +82,8 @@ public class MultiRequestInfo { if (-1 == cei.curExeSeq) 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() { @Override public void onResult(String str) { @@ -89,7 +97,7 @@ public class MultiRequestInfo { ret.put("executeTime", (System.currentTimeMillis() - start) + ""); ret.put("data", str); mri.countIncrease(); - //logger.info("返回 uniID=" + uniID + " 的结果"); + // logger.info("返回 uniID=" + uniID + " 的结果"); mri.callbackMap.get(uniID).onResult(JsonUtil.toJson(ret)); } }, null); @@ -97,7 +105,7 @@ public class MultiRequestInfo { public synchronized void countIncrease() { int tmp = count.incrementAndGet(); - //logger.info("【MultiRequestInfo】 countIncrease tmp=" + tmp + " total=" + total); + // logger.info("【MultiRequestInfo】 countIncrease tmp=" + tmp + " total=" + total); if (tmp == total) { reqInfos.remove(requestID); } diff --git a/src/main/java/org/bdware/server/action/ProcessAction.java b/src/main/java/org/bdware/server/action/ProcessAction.java index 9fc46c8..8d62541 100644 --- a/src/main/java/org/bdware/server/action/ProcessAction.java +++ b/src/main/java/org/bdware/server/action/ProcessAction.java @@ -76,7 +76,8 @@ public class ProcessAction { sc.nextLine(); while (sc.hasNextLine()) { 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); Scanner sc2 = new Scanner(new ByteArrayInputStream(line.getBytes())); sc2.next(); diff --git a/src/main/java/org/bdware/server/action/ReadmeGenerator.java b/src/main/java/org/bdware/server/action/ReadmeGenerator.java index ea423f5..ea054a5 100644 --- a/src/main/java/org/bdware/server/action/ReadmeGenerator.java +++ b/src/main/java/org/bdware/server/action/ReadmeGenerator.java @@ -23,8 +23,7 @@ public class ReadmeGenerator { private String generateReadme() { VelocityEngine engine = new VelocityEngine(); - engine.setProperty( - "file.resource.loader.path", + engine.setProperty("file.resource.loader.path", new File(templatePath, "ReadmeTemplate").getAbsolutePath()); createREADMEIfNotExists(new File(templatePath, "ReadmeTemplate")); VelocityContext ctx = new VelocityContext(); @@ -32,18 +31,17 @@ public class ReadmeGenerator { readmeFuncs = new ArrayList<>(); } for (ReadmeFunction rm : readmeFuncs) { - /*if (rm.funcDefaultArg == null) { - rm.funcDefaultArg = "未提供默认参数"; - } - if (rm.funcDefaultResult == null) { - rm.funcDefaultResult = "暂无返回结果示例"; - }*/ + /* + * if (rm.funcDefaultArg == null) { rm.funcDefaultArg = "未提供默认参数"; } if + * (rm.funcDefaultResult == null) { rm.funcDefaultResult = "暂无返回结果示例"; } + */ if (rm.funcDescription == null) { rm.funcDescription = "暂无描述"; } - /*if (rm.funcMockTemplate == null) { - rm.funcMockTemplate = "{\"result\":\"emptyMock\"}"; - }*/ + /* + * if (rm.funcMockTemplate == null) { rm.funcMockTemplate = + * "{\"result\":\"emptyMock\"}"; } + */ if (rm.funcArgTemplate == null) { rm.funcArgTemplate = "暂无参数模板"; } @@ -76,63 +74,24 @@ public class ReadmeGenerator { readmeTemplate.mkdirs(); File content = new File(readmeTemplate, "README.md.vm"); try { - FileUtils.writeStringToFile( - content, - /*"# 简介\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" - + "```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", + FileUtils.writeStringToFile(content, + /* + * "# 简介\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" + "```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); } catch (IOException e) { e.printStackTrace(); @@ -149,7 +108,8 @@ public class ReadmeGenerator { if (!name.exists()) { FileUtils.writeStringToFile(name, generateReadme(), StandardCharsets.UTF_8); return "生成文档 " + name.getName(); - } else return "请删除已有README.md"; + } else + return "请删除已有README.md"; } catch (Exception e) { e.printStackTrace(); return "生成文档异常"; @@ -170,19 +130,19 @@ public class ReadmeGenerator { public String funcDescription; public String funcDefaultArg; public String funcDefaultResult; - //public String funcMockTemplate; + // public String funcMockTemplate; public String funcRecordsString; public String funcArgTemplate; public String funcArgSchema; public String funcResultSchema; public String funcResultTemplate; - public ReadmeFunction( - String name, String description, String argSchema, String argTemplate, String resultSchema, String recordsString) { + public ReadmeFunction(String name, String description, String argSchema, String argTemplate, + String resultSchema, String recordsString) { funcName = name; funcDescription = description; funcArgTemplate = argTemplate; - //funcResultTemplate = resTemplate; + // funcResultTemplate = resTemplate; funcRecordsString = recordsString; funcArgSchema = argSchema; funcResultSchema = resultSchema; @@ -205,9 +165,9 @@ public class ReadmeGenerator { return funcDefaultResult.replace("\\\"", "\""); } - /*public String getFuncMockTemplate() { - return funcMockTemplate; - }*/ + /* + * public String getFuncMockTemplate() { return funcMockTemplate; } + */ public String getFuncArgTemplate() { return funcArgTemplate; diff --git a/src/main/java/org/bdware/server/action/RequestToMaster.java b/src/main/java/org/bdware/server/action/RequestToMaster.java index 6cd02f1..d5252ac 100644 --- a/src/main/java/org/bdware/server/action/RequestToMaster.java +++ b/src/main/java/org/bdware/server/action/RequestToMaster.java @@ -1,11 +1,12 @@ package org.bdware.server.action; + import org.bdware.sc.bean.ContractRequest; public class RequestToMaster { long requestTime; ContractRequest cr; - public RequestToMaster(ContractRequest c){ + public RequestToMaster(ContractRequest c) { requestTime = System.currentTimeMillis(); cr = c; } diff --git a/src/main/java/org/bdware/server/action/TemporyTestAction.java b/src/main/java/org/bdware/server/action/TemporyTestAction.java index b6ca3f8..149819c 100644 --- a/src/main/java/org/bdware/server/action/TemporyTestAction.java +++ b/src/main/java/org/bdware/server/action/TemporyTestAction.java @@ -84,25 +84,22 @@ public class TemporyTestAction { @Action(async = true) public void batchCompile(JsonObject args, ResultCallback resultCallback) { - ContractManagerFrameHandler.executorService.execute( - () -> { - File privateDir = new File(GlobalConf.instance.privateDir); - File[] list = - privateDir.listFiles( - new FileFilter() { - @Override - public boolean accept(File pathname) { - return pathname.isDirectory(); - } - }); - totalCompile = list.length; - compileProgress = 0; - if (list != null) - for (File userDir : list) { - compileProgress++; - compileAllUserProject(userDir); - } - }); + ContractManagerFrameHandler.executorService.execute(() -> { + File privateDir = new File(GlobalConf.instance.privateDir); + File[] list = privateDir.listFiles(new FileFilter() { + @Override + public boolean accept(File pathname) { + return pathname.isDirectory(); + } + }); + totalCompile = list.length; + compileProgress = 0; + if (list != null) + for (File userDir : list) { + compileProgress++; + compileAllUserProject(userDir); + } + }); peekComplieProgress(args, resultCallback); } @@ -189,8 +186,8 @@ public class TemporyTestAction { reconnectVisitor.visit(host, args.get("port").getAsInt()); else reconnectVisitor.visit(args.get("port").getAsInt()); - String data = ContractManager.instance.listContractsWithOwner( - args.get("owner").getAsString(), null, 0); + String data = ContractManager.instance + .listContractsWithOwner(args.get("owner").getAsString(), null, 0); JsonObject ret = new JsonObject(); ret.addProperty("data", data); ret.addProperty("action", "onReconnectAll"); diff --git a/src/main/java/org/bdware/server/action/UserManagerAction.java b/src/main/java/org/bdware/server/action/UserManagerAction.java index 6fc06dc..2db2d94 100644 --- a/src/main/java/org/bdware/server/action/UserManagerAction.java +++ b/src/main/java/org/bdware/server/action/UserManagerAction.java @@ -21,11 +21,8 @@ import java.util.concurrent.ConcurrentLinkedQueue; // 节点管理员用户管理页面 public class UserManagerAction { public static final String NodeManager = "__NodeManager__"; - static final Counter counter = - Counter.build() - .name("contract_login_counter") - .help("contract login counter") - .register(); + static final Counter counter = Counter.build().name("contract_login_counter") + .help("contract login counter").register(); private static final Logger LOGGER = LogManager.getLogger(UserManagerAction.class); public static ConcurrentLinkedQueue contractInstanceMangerPool = new ConcurrentLinkedQueue<>(); @@ -50,18 +47,22 @@ public class UserManagerAction { if (str.contains("NodeManager")) { if (json.has("newPubKey")) { String newPubKey = json.get("newPubKey").getAsString(); - KeyValueDBUtil.instance.setValue(CMTables.ConfigDB.toString(), NodeManager, newPubKey); - KeyValueDBUtil.instance.setValue( - CMTables.NodeRole.toString(), newPubKey, "NodeManager"); - resultCallback.onResult("{\"action\":\"onResetNodeManager\",\"data\":\"success\",\"pubKey\":\"" - + newPubKey + "\"}"); + KeyValueDBUtil.instance.setValue(CMTables.ConfigDB.toString(), NodeManager, + newPubKey); + KeyValueDBUtil.instance.setValue(CMTables.NodeRole.toString(), newPubKey, + "NodeManager"); + resultCallback.onResult( + "{\"action\":\"onResetNodeManager\",\"data\":\"success\",\"pubKey\":\"" + + newPubKey + "\"}"); } else { - //just keep the same - resultCallback.onResult("{\"action\":\"onResetNodeManager\",\"data\":\"success\",\"pubKey\":\"" - + getPubKey(json) + "\"}"); + // just keep the same + resultCallback.onResult( + "{\"action\":\"onResetNodeManager\",\"data\":\"success\",\"pubKey\":\"" + + getPubKey(json) + "\"}"); } } 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) public void login(JsonObject json, ResultCallback resultCallback) { if (sessionID == null) { - resultCallback.onResult("{\"action\":\"onLogin\",\"status\":\"failed, no session\"," + - "\"data\":\"" + Role.Anonymous.name() + "\"}"); + resultCallback.onResult("{\"action\":\"onLogin\",\"status\":\"failed, no session\"," + + "\"data\":\"" + Role.Anonymous.name() + "\"}"); } LOGGER.debug("[NodeManagerAction] session:" + (sessionID)); String pubKey = json.get("pubKey").getAsString(); @@ -95,15 +96,15 @@ public class UserManagerAction { } else { setHandlerPermission(0); - resultCallback.onResult( - "{\"action\":\"onLogin\",\"status\":\"verify sign failed\"," + - "\"data\":\"" + Role.Anonymous.name() + "\"}"); + resultCallback.onResult("{\"action\":\"onLogin\",\"status\":\"verify sign failed\"," + + "\"data\":\"" + Role.Anonymous.name() + "\"}"); } } private void setHandlerPermission(long i) { - if (handler != null) handler.setPermission(i); + if (handler != null) + handler.setPermission(i); } public void getNodeRole(JsonObject json, ResultCallback resultCallback) { @@ -122,12 +123,12 @@ public class UserManagerAction { if (isNodeManager) { if (ret != null && ret.length() > 0) { setHandlerPermission(0x86000f41L | Role.compoundValue(ret.split(","))); - resultCallback.onResult( - "{\"action\":\"onLogin\",\"data\":\"" + ret + "\"}"); + resultCallback + .onResult("{\"action\":\"onLogin\",\"data\":\"" + ret + "\"}"); } else { setHandlerPermission(0x86000f41L); - resultCallback.onResult( - "{\"action\":\"onLogin\",\"data\":\"NodeManager\"}"); + resultCallback + .onResult("{\"action\":\"onLogin\",\"data\":\"NodeManager\"}"); } } else { if (ret == null || ret.equals("")) { @@ -140,10 +141,10 @@ public class UserManagerAction { } } else { KeyValueDBUtil.instance.setValue(CMTables.ConfigDB.toString(), NodeManager, pubKey); - KeyValueDBUtil.instance.setValue( - CMTables.NodeRole.toString(), pubKey, "NodeManager"); - KeyValueDBUtil.instance.setValue( - CMTables.NodeTime.toString(), pubKey, Long.toString(new Date().getTime())); + KeyValueDBUtil.instance.setValue(CMTables.NodeRole.toString(), pubKey, + "NodeManager"); + KeyValueDBUtil.instance.setValue(CMTables.NodeTime.toString(), pubKey, + Long.toString(new Date().getTime())); setHandlerPermission(0x86000d41L); resultCallback.onResult("{\"action\":\"onLogin\",\"data\":\"NodeManager\"}"); } @@ -186,11 +187,11 @@ public class UserManagerAction { } else { 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())); resultCallback.onResult("{\"action\":\"onApplyRole\",\"data\":\"success\"}"); } @@ -270,8 +271,8 @@ public class UserManagerAction { if (roString.length() > 0) { roString = new StringBuilder(roString.subSequence(0, roString.length() - 1).toString()); - KeyValueDBUtil.instance.setValue( - CMTables.NodeRole.toString(), pubKey, roString.toString()); + KeyValueDBUtil.instance.setValue(CMTables.NodeRole.toString(), pubKey, + roString.toString()); } else { KeyValueDBUtil.instance.delete(CMTables.NodeRole.toString(), pubKey); KeyValueDBUtil.instance.delete(CMTables.NodeTime.toString(), pubKey); @@ -312,8 +313,8 @@ public class UserManagerAction { already = roles; } KeyValueDBUtil.instance.setValue(CMTables.NodeRole.toString(), pubKey, already); - KeyValueDBUtil.instance.setValue( - CMTables.NodeTime.toString(), pubKey, Long.toString(new Date().getTime())); + KeyValueDBUtil.instance.setValue(CMTables.NodeTime.toString(), pubKey, + Long.toString(new Date().getTime())); KeyValueDBUtil.instance.delete(CMTables.ApplyRole.toString(), pubKey); KeyValueDBUtil.instance.delete(CMTables.ApplyTime.toString(), pubKey); resultCallback.onResult("{\"action\":\"onAuthNodeRole\",\"data\":\"success\"}"); @@ -336,7 +337,8 @@ public class UserManagerAction { private String getPubKey(JsonObject json) { try { - if (this.publicKey != null) return this.publicKey; + if (this.publicKey != null) + return this.publicKey; return json.get("pubKey").getAsString(); } catch (Exception e) { return null; diff --git a/src/main/java/org/bdware/server/action/p2p/AliveCheckClientAction.java b/src/main/java/org/bdware/server/action/p2p/AliveCheckClientAction.java index df9d2d4..ad0a7b3 100644 --- a/src/main/java/org/bdware/server/action/p2p/AliveCheckClientAction.java +++ b/src/main/java/org/bdware/server/action/p2p/AliveCheckClientAction.java @@ -57,76 +57,65 @@ public class AliveCheckClientAction { public void checkMasterAlive(ResultCallback rc) { if (sendPingTask == null) - sendPingTask = - new TimerTask() { - @Override - public void run() { - try { - LOGGER.debug( - String.format( - "f %s", - DATE_FORMAT - .format(System.currentTimeMillis()))); - Map ping = new HashMap<>(); - ping.put("action", "masterPing"); - rc.onResult(JsonUtil.toJson(ping)); - } catch (Throwable t) { - t.printStackTrace(); - } - } - }; + sendPingTask = new TimerTask() { + @Override + public void run() { + try { + LOGGER.debug(String.format("f %s", + DATE_FORMAT.format(System.currentTimeMillis()))); + Map ping = new HashMap<>(); + ping.put("action", "masterPing"); + rc.onResult(JsonUtil.toJson(ping)); + } catch (Throwable t) { + t.printStackTrace(); + } + } + }; if (null == checkAliveTask) - checkAliveTask = - new TimerTask() { - @Override - public void run() { - try { - run1(); - } catch (Throwable t) { - t.printStackTrace(); - HeartBeatUtil.getInstance().cancel(this); + checkAliveTask = new TimerTask() { + @Override + public void run() { + try { + run1(); + } catch (Throwable t) { + t.printStackTrace(); + HeartBeatUtil.getInstance().cancel(this); + } + } + + public void run1() { + long cur = System.currentTimeMillis(); + if (cur - lastMasterPongTime >= (2 * sendDelay)) { + LOGGER.info("master maybe crash down, because lastMasterPongTime=" + + DATE_FORMAT.format(lastMasterPongTime) + "!"); + + // 向NC发通知重新选举master,如果NC没有收到所有节点的重选请求,就认为是这个节点和master连接断开 + // 这个节点需要重连master + Map request = new HashMap<>(); + request.put("action", "electMaster"); + SM2KeyPair keyPair = GlobalConf.instance.keyPair; + request.put("nodeID", keyPair.getPublicKeyStr()); + for (MultiContractMeta meta : CMActions.manager.multiContractRecorder + .getStatus().values()) { + if (meta.getMasterNode().equals(masterPubkey)) { + LOGGER.info("master of contract " + meta.getContractID() + + " maybe crash down! master=" + masterPubkey); + request.put("contractID", meta.getContractID()); + int lastSeq = meta.getLastExeSeq(); + request.put("lastExe", lastSeq + ""); + request.put("master", masterPubkey); + request.put("members", meta.joinMembers(",")); + NetworkManager.instance.sendToNodeCenter(JsonUtil.toJson(request)); + MasterElectTimeRecorder.findMasterCrash = + System.currentTimeMillis(); } } - - public void run1() { - long cur = System.currentTimeMillis(); - if (cur - lastMasterPongTime >= (2 * sendDelay)) { - LOGGER.info( - "master maybe crash down, because lastMasterPongTime=" - + DATE_FORMAT.format(lastMasterPongTime) - + "!"); - - // 向NC发通知重新选举master,如果NC没有收到所有节点的重选请求,就认为是这个节点和master连接断开 - // 这个节点需要重连master - Map request = new HashMap<>(); - request.put("action", "electMaster"); - SM2KeyPair keyPair = GlobalConf.instance.keyPair; - request.put("nodeID", keyPair.getPublicKeyStr()); - for (MultiContractMeta meta : CMActions.manager.multiContractRecorder.getStatus().values()) { - if (meta.getMasterNode().equals(masterPubkey)) { - LOGGER.info( - "master of contract " - + meta.getContractID() - + " maybe crash down! master=" - + masterPubkey); - request.put("contractID", meta.getContractID()); - int lastSeq = meta.getLastExeSeq(); - request.put("lastExe", lastSeq + ""); - request.put("master", masterPubkey); - request.put("members", meta.joinMembers(",")); - NetworkManager.instance.sendToNodeCenter( - JsonUtil.toJson(request)); - MasterElectTimeRecorder.findMasterCrash = - System.currentTimeMillis(); - } - } - NetworkManager.instance.closeAgent(masterPubkey); - } // if - } - }; + NetworkManager.instance.closeAgent(masterPubkey); + } // if + } + }; lastMasterPongTime = System.currentTimeMillis(); - LOGGER.info( - "lastMasterPongTime=" + DATE_FORMAT.format(lastMasterPongTime)); + LOGGER.info("lastMasterPongTime=" + DATE_FORMAT.format(lastMasterPongTime)); HeartBeatUtil.getInstance().schedule(sendPingTask, sendDelay / 2, checkDelay); HeartBeatUtil.getInstance().schedule(checkAliveTask, sendDelay, checkDelay); } @@ -138,7 +127,8 @@ public class AliveCheckClientAction { public void waitForSetNodeID() { for (int i = 0; i < 100; i++) { - if (waitForSetNode) return; + if (waitForSetNode) + return; try { Thread.sleep(30); } catch (InterruptedException e) { @@ -150,9 +140,9 @@ public class AliveCheckClientAction { public void init() { LOGGER.info("init nodeID:"); assert masterPubkey != null; - NetworkManager.instance.sendToAgent(masterPubkey, "{\"action\":\"setNodeInfo\",\"pubKey\":\"" - + GlobalConf.instance.keyPair.getPublicKeyStr() - + "\"}"); + NetworkManager.instance.sendToAgent(masterPubkey, + "{\"action\":\"setNodeInfo\",\"pubKey\":\"" + + GlobalConf.instance.keyPair.getPublicKeyStr() + "\"}"); } } diff --git a/src/main/java/org/bdware/server/action/p2p/AliveCheckServerAction.java b/src/main/java/org/bdware/server/action/p2p/AliveCheckServerAction.java index 38532b5..e5ed63e 100644 --- a/src/main/java/org/bdware/server/action/p2p/AliveCheckServerAction.java +++ b/src/main/java/org/bdware/server/action/p2p/AliveCheckServerAction.java @@ -22,18 +22,12 @@ public class AliveCheckServerAction { public String pubKey; public AliveCheckServerAction(TCPServerFrameHandler handler) { - lastSlavePingTime = - System.currentTimeMillis() - + 5000L - + AliveCheckClientAction.sendDelay - + AliveCheckClientAction.checkDelay; + lastSlavePingTime = System.currentTimeMillis() + 5000L + AliveCheckClientAction.sendDelay + + AliveCheckClientAction.checkDelay; checkAliveTask = new HeartBeatTask(AliveCheckClientAction.sendDelay); - HeartBeatUtil.getInstance() - .schedule( - checkAliveTask, - AliveCheckClientAction.sendDelay, - AliveCheckClientAction.checkDelay); + HeartBeatUtil.getInstance().schedule(checkAliveTask, AliveCheckClientAction.sendDelay, + AliveCheckClientAction.checkDelay); this.handler = handler; } @@ -56,10 +50,10 @@ public class AliveCheckServerAction { try { long cur = System.currentTimeMillis(); if (cur - lastSlavePingTime >= (2L * delay)) { -// LOGGER.info( -// new SimpleDateFormat("yyyy-MM-dd.HH:mm:ss").format(lastSlavePingTime) -// + " " -// + delay); + // LOGGER.info( + // new SimpleDateFormat("yyyy-MM-dd.HH:mm:ss").format(lastSlavePingTime) + // + " " + // + delay); Set contracts = new HashSet<>(); String nodeID = pubKey; if (nodeID == null) { @@ -67,21 +61,17 @@ public class AliveCheckServerAction { HeartBeatUtil.getInstance().cancel(this); return; } - LOGGER.info( - "Master心跳机制发现节点 " - + nodeID.substring(0, 5) - + " 下线! " - + this.toString()); + LOGGER.info("Master心跳机制发现节点 " + nodeID.substring(0, 5) + " 下线! " + + this.toString()); HeartBeatUtil.getInstance().cancel(this); - for (String contractID : - MasterServerRecoverMechAction.recoverStatus.get(nodeID).keySet()) { - // RecoverFlag flag = + for (String contractID : MasterServerRecoverMechAction.recoverStatus.get(nodeID) + .keySet()) { + // RecoverFlag flag = // // MasterServerRecoverMechAction.recoverStatus.get(nodeID).get(contractID); - // if (flag == RecoverFlag.Fine) - MasterServerRecoverMechAction.recoverStatus - .get(nodeID) - .put(contractID, RecoverFlag.ToRecover); + // if (flag == RecoverFlag.Fine) + MasterServerRecoverMechAction.recoverStatus.get(nodeID).put(contractID, + RecoverFlag.ToRecover); contracts.add(contractID); MasterServerTCPAction.notifyNodeOffline(contractID, nodeID); } diff --git a/src/main/java/org/bdware/server/action/p2p/CommunicationAction.java b/src/main/java/org/bdware/server/action/p2p/CommunicationAction.java index c28bd1b..47f556d 100644 --- a/src/main/java/org/bdware/server/action/p2p/CommunicationAction.java +++ b/src/main/java/org/bdware/server/action/p2p/CommunicationAction.java @@ -14,8 +14,7 @@ import java.util.HashMap; import java.util.Map; public class CommunicationAction implements OnHashCallback { - public CommunicationAction() { - } + public CommunicationAction() {} @Action(async = true) public void updatePeerID(JsonObject jsonObject, final ResultCallback callback) { @@ -26,13 +25,14 @@ public class CommunicationAction implements OnHashCallback { @Action(async = true) public void updateContractID(JsonObject jsonObject, final ResultCallback callback) { 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) public void onGetP2PNodes(JsonObject args, final ResultCallback rc) { String requestID = args.get(BaseFunctionManager.REQUEST_ID).getAsString(); - ResultCallback resultCallback = CommunicationManager.instance.requestCallbacks.remove(requestID); + ResultCallback resultCallback = + CommunicationManager.instance.requestCallbacks.remove(requestID); String allPeers; allPeers = args.get("content").getAsString(); System.out.println("String coding " + allPeers); @@ -46,6 +46,6 @@ public class CommunicationAction implements OnHashCallback { r.put("action", "onHashResult"); r.put("responseID", reqID); r.put("data", hashStr); - CommunicationManager.instance.send(JsonUtil.toJson(r), new String[]{}); + CommunicationManager.instance.send(JsonUtil.toJson(r), new String[] {}); } } diff --git a/src/main/java/org/bdware/server/action/p2p/MasterClientRecoverMechAction.java b/src/main/java/org/bdware/server/action/p2p/MasterClientRecoverMechAction.java index 322aac2..5978248 100644 --- a/src/main/java/org/bdware/server/action/p2p/MasterClientRecoverMechAction.java +++ b/src/main/java/org/bdware/server/action/p2p/MasterClientRecoverMechAction.java @@ -34,26 +34,24 @@ import java.util.zip.GZIPOutputStream; public class MasterClientRecoverMechAction { private static final Logger LOGGER = LogManager.getLogger(MasterClientRecoverMechAction.class); - public static Set recoverSet = - new ConcurrentSkipListSet<>(); // contracts which don't finish recoverRestart - public static Map> - requestsToMaster; // when master is re-electing,client node cache ites received requests + public static Set recoverSet = new ConcurrentSkipListSet<>(); // contracts which don't + // finish recoverRestart + public static Map> requestsToMaster; // when master is + // re-electing,client node + // cache ites received + // requests private final Map stateFileMap = new HashMap<>(); private final Map transFileMap = new HashMap<>(); - public MasterClientRecoverMechAction() { - } + public MasterClientRecoverMechAction() {} // 告知master自己需要恢复,携带之前的运行模式,如果是StableMode需要携带lastExeSeq信息 public static void askForRecover(String contractID, String masterID, String nodeID) { RecoverMechTimeRecorder.startRecover = System.currentTimeMillis(); - // recoverSet.add(contractID); - LOGGER.info( - "[MasterClientRecoverMechAction] askForRecover contractID=" - + contractID - + " masterID=" - + masterID.substring(0, 5)); + // recoverSet.add(contractID); + LOGGER.info("[MasterClientRecoverMechAction] askForRecover contractID=" + contractID + + " masterID=" + masterID.substring(0, 5)); TCPClientFrameHandler master = AgentManager.getHandler(masterID); Map ret = new HashMap(); @@ -61,27 +59,22 @@ public class MasterClientRecoverMechAction { ret.put("contractID", contractID); ret.put("nodeID", nodeID); - /* //没有这个合约进程 - if(!MasterClientTCPAction.requests.containsKey(contractID)){ - if(KeyValueDBUtil.instance.containsKey(CMTables.LastExeSeq.toString(),contractID)){ - logger.info("[MasterClientRecoverMechAction] delete database lastExeSeq"); - KeyValueDBUtil.instance.delete(CMTables.LastExeSeq.toString(),contractID); - } - }else{ - ContractClient client = CMActions.manager.getClient(contractID); - ContractExecuteInfo cei = MasterClientTCPAction.requests.get(contractID); - if (client == null || !client.getContractType().equals(cei.type)){ - if(KeyValueDBUtil.instance.containsKey(CMTables.LastExeSeq.toString(),contractID)){ - logger.info("[MasterClientRecoverMechAction] delete database lastExeSeq"); - KeyValueDBUtil.instance.delete(CMTables.LastExeSeq.toString(),contractID); - } - } - }*/ + /* + * //没有这个合约进程 if(!MasterClientTCPAction.requests.containsKey(contractID)){ + * if(KeyValueDBUtil.instance.containsKey(CMTables.LastExeSeq.toString(),contractID)){ + * logger.info("[MasterClientRecoverMechAction] delete database lastExeSeq"); + * KeyValueDBUtil.instance.delete(CMTables.LastExeSeq.toString(),contractID); } }else{ + * ContractClient client = CMActions.manager.getClient(contractID); ContractExecuteInfo cei + * = MasterClientTCPAction.requests.get(contractID); if (client == null || + * !client.getContractType().equals(cei.type)){ + * if(KeyValueDBUtil.instance.containsKey(CMTables.LastExeSeq.toString(),contractID)){ + * logger.info("[MasterClientRecoverMechAction] delete database lastExeSeq"); + * KeyValueDBUtil.instance.delete(CMTables.LastExeSeq.toString(),contractID); } } } + */ if (KeyValueDBUtil.instance.containsKey(CMTables.LastExeSeq.toString(), contractID)) { ret.put("mode", ContractUnitStatus.StableMode.toString()); - ret.put( - "lastExeSeq", + ret.put("lastExeSeq", KeyValueDBUtil.instance.getValue(CMTables.LastExeSeq.toString(), contractID)); } else { ret.put("mode", ContractUnitStatus.CommonMode.toString()); @@ -98,20 +91,17 @@ public class MasterClientRecoverMechAction { public static void stableModeCheckpoint(String contractID) { LOGGER.info("设置合约" + contractID + " stable模式下的 checkpoint"); final MultiContractMeta cei; - synchronized ( - cei = CMActions.manager.multiContractRecorder.getMultiContractMeta(contractID)) { - KeyValueDBUtil.instance.setValue( - CMTables.LastExeSeq.toString(), contractID, cei.getLastExeSeq() + ""); + synchronized (cei = + CMActions.manager.multiContractRecorder.getMultiContractMeta(contractID)) { + KeyValueDBUtil.instance.setValue(CMTables.LastExeSeq.toString(), contractID, + cei.getLastExeSeq() + ""); CMActions.manager.clearSyncFiles(contractID); // TODO 将ContractExecuteInfo持久化 SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd-HH:mm:ss"); - String fileName = - "ContractExecuteInfo_" - + format.format(new Date()) - + "_" - + new Random().nextInt(); + String fileName = "ContractExecuteInfo_" + format.format(new Date()) + "_" + + new Random().nextInt(); String parPath = GlobalConf.instance.ADSPDir + "/" + contractID + "/cr"; File file = new File(parPath + "/" + fileName); try { @@ -135,7 +125,8 @@ public class MasterClientRecoverMechAction { public void saveStateFile(String path, ContractRecord record) { File file = new File(GlobalConf.instance.projectDir + "/stateFiles/" + path); File parent = file.getParentFile(); - if (!parent.exists()) parent.mkdirs(); + if (!parent.exists()) + parent.mkdirs(); ObjectOutputStream writer; try { FileOutputStream fileout = new FileOutputStream(file); @@ -170,7 +161,8 @@ public class MasterClientRecoverMechAction { } catch (FileNotFoundException e) { e.printStackTrace(); } - } else fout = (FileOutputStream) stateFileMap.get(fileName); + } else + fout = (FileOutputStream) stateFileMap.get(fileName); String data = args.get("data").getAsString(); try { @@ -205,27 +197,27 @@ public class MasterClientRecoverMechAction { recoverFromCommonMode(path, false, rc); } - // //无状态合约同步lastExeSeq之后发送恢复完成 - // public void statelessContract(String contractID){ - // logger.info("无状态合约请求unitLastExeSeq"); - // Map ret = new HashMap(); - // ret.put("action", "statelessUnitLastExe"); - // ret.put("contractID", contractID); - // ret.put("nodeID",GlobalConf.instance.keyPair.getPublicKeyStr()); - // handler.sendMsg(JsonUtil.toJson(ret)); - // } + // //无状态合约同步lastExeSeq之后发送恢复完成 + // public void statelessContract(String contractID){ + // logger.info("无状态合约请求unitLastExeSeq"); + // Map ret = new HashMap(); + // ret.put("action", "statelessUnitLastExe"); + // ret.put("contractID", contractID); + // ret.put("nodeID",GlobalConf.instance.keyPair.getPublicKeyStr()); + // handler.sendMsg(JsonUtil.toJson(ret)); + // } // - // @Action(async = true) - // public void statelessReceiveLastExe(JsonObject args, final ResultCallback rc) { - // String contractID = args.get("contractID").getAsString(); - // int unitLast = args.get("unitLastExe").getAsInt(); + // @Action(async = true) + // public void statelessReceiveLastExe(JsonObject args, final ResultCallback rc) { + // String contractID = args.get("contractID").getAsString(); + // int unitLast = args.get("unitLastExe").getAsInt(); // - // ContractExecuteInfo cei = MasterClientTCPAction.requests.get(contractID); - // synchronized(cei){ - // cei.setLastExeSeq(unitLast); - // } - // sendRecoverFinish(contractID,"stateless"); - // } + // ContractExecuteInfo cei = MasterClientTCPAction.requests.get(contractID); + // synchronized(cei){ + // cei.setLastExeSeq(unitLast); + // } + // sendRecoverFinish(contractID,"stateless"); + // } // 普通节点从CommonMode恢复 public void recoverFromCommonMode(String path, boolean isMaster, ResultCallback rc) { @@ -252,9 +244,8 @@ public class MasterClientRecoverMechAction { } // cei.printContent(); if (cei.queue == null) { - cei.init( - CMActions.manager.multiContractRecorder.getMultiContractMeta( - cei.getContractID())); + cei.init(CMActions.manager.multiContractRecorder + .getMultiContractMeta(cei.getContractID())); } recoverSet.add(cei.getContractID()); @@ -264,12 +255,12 @@ public class MasterClientRecoverMechAction { return; } - // //无状态合约 - // String stateful = CMActions.manager.getContractStateful(cei.getContractID()); - // if(stateful.equals("false")){ - // statelessContract(cei.getContractID()); - // return; - // } + // //无状态合约 + // String stateful = CMActions.manager.getContractStateful(cei.getContractID()); + // if(stateful.equals("false")){ + // statelessContract(cei.getContractID()); + // return; + // } if (isMaster) { CMActions.manager.setContractIsMaster(cei.getContractID(), "true"); @@ -298,12 +289,9 @@ public class MasterClientRecoverMechAction { try { LOGGER.info(" 开始等待 checkAndRestart锁 : "); time1 = System.currentTimeMillis(); - LOGGER.info( - "time1=" - + new SimpleDateFormat("yyyy-MM-dd HH:mm:ss") - .format(new Date(time1)) - + " " - + time1); + LOGGER.info("time1=" + + new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(new Date(time1)) + + " " + time1); ContractManager.checkAndStartLock.wait(10000); } catch (InterruptedException e) { e.printStackTrace(); @@ -312,10 +300,8 @@ public class MasterClientRecoverMechAction { long time2 = System.currentTimeMillis(); LOGGER.info( - "time2=" - + new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(new Date(time2)) - + " " - + time2); + "time2=" + new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(new Date(time2)) + + " " + time2); LOGGER.info("等待 checkAndRestart锁 结束 "); if (time2 - time1 >= 10000) { LOGGER.info("[ADSP]CheckAndStart 锁 等待超时"); @@ -333,31 +319,27 @@ public class MasterClientRecoverMechAction { if (client == null) { System.out.println("恢复 checkAndRestart client == null\n"); } else { - System.out.println( - "恢复 checkAndRestart client == null: false" - + " client.getContractType=" - + client.getContractType() - + "\n"); + System.out.println("恢复 checkAndRestart client == null: false" + + " client.getContractType=" + client.getContractType() + "\n"); } ContractMeta meta = CMActions.manager.statusRecorder.getContractMeta(cei.getContractID()); - meta.setContractExecutor( - MasterClientTCPAction.createContractExecutor(meta.contract, contractID, cei.getMasterNode(), cei.getMembers())); + meta.setContractExecutor(MasterClientTCPAction.createContractExecutor(meta.contract, + contractID, cei.getMasterNode(), cei.getMembers())); Map args = new HashMap<>(); args.put("ceiLastExeSeq", cei.getLastExeSeq()); meta.contractExecutor.onRecover(args); // 认为contractID不会重 - if (client != null - && client.isProcessAlive() + if (client != null && client.isProcessAlive() && client.getContractType().equals(cei.type)) { LOGGER.info("恢复节点已有这个合约进程!"); - if (!KeyValueDBUtil.instance.containsKey( - CMTables.UnitContracts.toString(), cei.getContractID())) { - KeyValueDBUtil.instance.setValue( - CMTables.UnitContracts.toString(), cei.getContractID(), "exist"); + if (!KeyValueDBUtil.instance.containsKey(CMTables.UnitContracts.toString(), + cei.getContractID())) { + KeyValueDBUtil.instance.setValue(CMTables.UnitContracts.toString(), + cei.getContractID(), "exist"); } CMActions.manager.multiContractRecorder.updateValue(cei); - //MasterClientTCPAction.contractID2MasterInfo.put(contractID, clientAction); + // MasterClientTCPAction.contractID2MasterInfo.put(contractID, clientAction); CMActions.manager.setContractIsMaster(contractID, "false"); } else { LOGGER.info("[MasterClientRecoverMechAction] 恢复节点没有这个合约进程 : "); @@ -373,22 +355,18 @@ public class MasterClientRecoverMechAction { contract.setPublicKey(cei.publicKey); int copies = cei.getMembers().length; contract.setNumOfCopies(copies); - if (!KeyValueDBUtil.instance.containsKey( - CMTables.UnitContracts.toString(), cei.getContractID())) { - KeyValueDBUtil.instance.setValue( - CMTables.UnitContracts.toString(), cei.getContractID(), "exist"); + if (!KeyValueDBUtil.instance.containsKey(CMTables.UnitContracts.toString(), + cei.getContractID())) { + KeyValueDBUtil.instance.setValue(CMTables.UnitContracts.toString(), + cei.getContractID(), "exist"); } CMActions.manager.multiContractRecorder.updateValue(cei); - //MasterClientTCPAction.contractID2MasterInfo.put(contractID, clientAction); + // MasterClientTCPAction.contractID2MasterInfo.put(contractID, clientAction); parPath = GlobalConf.instance.publicCompiledDir + "/" + cei.getYpkName(); if (cei.isPrivate()) { - parPath = - GlobalConf.instance.privateCompiledDir - + "/" - + cei.getPubKeyPath() - + "/" - + cei.getYpkName(); + parPath = GlobalConf.instance.privateCompiledDir + "/" + cei.getPubKeyPath() + + "/" + cei.getYpkName(); } } @@ -454,7 +432,8 @@ public class MasterClientRecoverMechAction { String path = contractID + "_temp_stateFile_" + new Random().nextLong(); File file = new File(GlobalConf.instance.projectDir + "/stateFiles/" + path); File parent = file.getParentFile(); - if (!parent.exists()) parent.mkdirs(); + if (!parent.exists()) + parent.mkdirs(); ObjectOutputStream writer; try { FileOutputStream fileout = new FileOutputStream(file); @@ -491,7 +470,7 @@ public class MasterClientRecoverMechAction { LOGGER.info("times=" + times); 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); String data = ByteUtil.encodeBASE64(buff, len); req.put("data", data); @@ -511,9 +490,9 @@ public class MasterClientRecoverMechAction { } fin.close(); - // req.put("isDone", "true"); - // req.remove("data"); - // handler.sendMsg(JsonUtil.toJson(req)); + // req.put("isDone", "true"); + // req.remove("data"); + // handler.sendMsg(JsonUtil.toJson(req)); // delete state file if (file.isFile() && file.exists()) { @@ -534,17 +513,12 @@ public class MasterClientRecoverMechAction { int unitLastExeSeq = json.get("unitLastExeSeq").getAsInt(); recoverSet.add(contractID); // 查看自己和master的lastExeSeq差距 - int lastExeSeq = - Integer.parseInt( - KeyValueDBUtil.instance.getValue( - CMTables.LastExeSeq.toString(), contractID)); + int lastExeSeq = Integer.parseInt( + KeyValueDBUtil.instance.getValue(CMTables.LastExeSeq.toString(), contractID)); LOGGER.info("unitLastExeSeq=" + unitLastExeSeq + " lastExeSeq=" + lastExeSeq); - LOGGER.info( - "从StableMode恢复,采用先从本地load的方式 unitLastExeSeq=" - + unitLastExeSeq - + " lastExeDeq=" - + lastExeSeq); + LOGGER.info("从StableMode恢复,采用先从本地load的方式 unitLastExeSeq=" + unitLastExeSeq + + " lastExeDeq=" + lastExeSeq); // Step 1 查看最新的sync file String parPath = GlobalConf.instance.ADSPDir + "/" + contractID + "/sync"; @@ -600,9 +574,8 @@ public class MasterClientRecoverMechAction { } // record.printContent(); if (cei.queue == null) { - cei.init( - CMActions.manager.multiContractRecorder.getMultiContractMeta( - cei.getContractID())); + cei.init(CMActions.manager.multiContractRecorder + .getMultiContractMeta(cei.getContractID())); } CMActions.manager.multiContractRecorder.updateValue(cei); ContractMeta meta = CMActions.manager.statusRecorder.getContractMeta(contractID); @@ -615,24 +588,18 @@ public class MasterClientRecoverMechAction { return; } // 无状态合约 - // String stateful = CMActions.manager.getContractStateful(cei.getContractID()); - // if(stateful.equals("false")){ - // statelessContract(cei.getContractID()); - // return; - // } + // String stateful = CMActions.manager.getContractStateful(cei.getContractID()); + // if(stateful.equals("false")){ + // statelessContract(cei.getContractID()); + // return; + // } - // step3 loadMemory + // step3 loadMemory String memoryFileName = content[1].split(";")[1]; ContractClient client = ContractManager.instance.getClient(cei.getContractID()); - String temp1 = - CMActions.manager.loadMemory( - client, - GlobalConf.instance.ADSPDir - + "/" - + contractID - + "/memory/" - + memoryFileName); + String temp1 = CMActions.manager.loadMemory(client, + GlobalConf.instance.ADSPDir + "/" + contractID + "/memory/" + memoryFileName); LOGGER.info("loadMemory结果" + temp1); // logger.info("测试位置 333 step3结束后状态为\n" + CMActions.manager.dumpContract(contractID, "")); @@ -640,10 +607,8 @@ public class MasterClientRecoverMechAction { // step4 redo local trans String transFileName = content[2].split(";")[1]; - String temp = - CMActions.manager.redo( - contractID, - GlobalConf.instance.ADSPDir + "/" + contractID + "/trans/" + transFileName); + String temp = CMActions.manager.redo(contractID, + GlobalConf.instance.ADSPDir + "/" + contractID + "/trans/" + transFileName); LOGGER.info("redo from local结果" + temp); synchronized (cei) { cei.setLastExeSeq(lastExeSeq); // 通过数据库中值设置lastExeSeq,和本地记录的ContractRecord是同步的 @@ -708,13 +673,12 @@ public class MasterClientRecoverMechAction { SM2KeyPair keyPair = GlobalConf.instance.keyPair; JsonObject jo = new JsonObject(); jo.addProperty("action", "onQueryUnitStatus"); - LOGGER.info( - "恢复节点查看自己的状态 " - + KeyValueDBUtil.instance.containsKey( - CMTables.LastExeSeq.toString(), contractID)); + LOGGER.info("恢复节点查看自己的状态 " + + KeyValueDBUtil.instance.containsKey(CMTables.LastExeSeq.toString(), contractID)); if (KeyValueDBUtil.instance.containsKey(CMTables.LastExeSeq.toString(), contractID)) jo.addProperty("mode", ContractUnitStatus.StableMode.toString()); - else jo.addProperty("mode", ContractUnitStatus.CommonMode.toString()); + else + jo.addProperty("mode", ContractUnitStatus.CommonMode.toString()); // jo.addProperty("mode", // KeyValueDBUtil.instance.getValue(CMTables.UnitStatus.toString(),contractID)); jo.addProperty("nodeID", keyPair.getPublicKeyStr()); @@ -729,7 +693,8 @@ public class MasterClientRecoverMechAction { ContractUnitStatus cur_mode; if (KeyValueDBUtil.instance.containsKey(CMTables.LastExeSeq.toString(), contractID)) cur_mode = ContractUnitStatus.StableMode; - else cur_mode = ContractUnitStatus.CommonMode; + else + cur_mode = ContractUnitStatus.CommonMode; LOGGER.info("合约" + contractID + "当前模式为" + cur_mode + " 期望设置为" + mode); if (cur_mode == ContractUnitStatus.CommonMode && mode.equals(ContractUnitStatus.StableMode.toString())) { @@ -743,10 +708,10 @@ public class MasterClientRecoverMechAction { KeyValueDBUtil.instance.delete(CMTables.LastExeSeq.toString(), contractID); } } - // else if(cur_mode == ContractUnitStatus.StableMode && + // else if(cur_mode == ContractUnitStatus.StableMode && // mode.equals(ContractUnitStatus.StableMode.toString())){ - // stableModeCheckpoint(contractID); - // } + // stableModeCheckpoint(contractID); + // } } @Action(async = true) @@ -779,7 +744,8 @@ public class MasterClientRecoverMechAction { } catch (FileNotFoundException e) { e.printStackTrace(); } - } else fout = (FileOutputStream) transFileMap.get(fileName); + } else + fout = (FileOutputStream) transFileMap.get(fileName); String data = args.get("data").getAsString(); try { diff --git a/src/main/java/org/bdware/server/action/p2p/MasterClientTCPAction.java b/src/main/java/org/bdware/server/action/p2p/MasterClientTCPAction.java index 02200b5..10bff01 100644 --- a/src/main/java/org/bdware/server/action/p2p/MasterClientTCPAction.java +++ b/src/main/java/org/bdware/server/action/p2p/MasterClientTCPAction.java @@ -49,35 +49,40 @@ public class MasterClientTCPAction { SM2KeyPair keyPair = GlobalConf.instance.keyPair; request.put("nodeID", keyPair.getPublicKeyStr()); -// if (!contractID2MasterInfo.containsKey(contractID)) { -// contractID = cc.getContractID(); -// } -// -// MasterClientTCPAction mcta = contractID2MasterInfo.get(contractID); -// if (mcta != null) { -// mcta.closeMaster(); -// } + // if (!contractID2MasterInfo.containsKey(contractID)) { + // contractID = cc.getContractID(); + // } + // + // MasterClientTCPAction mcta = contractID2MasterInfo.get(contractID); + // if (mcta != null) { + // mcta.closeMaster(); + // } 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("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); NetworkManager.instance.sendToNodeCenter(JsonUtil.toJson(request)); 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 args = new HashMap<>(); args.put("contractID", contractID); args.put("nodeSize", contract.getNumOfCopies()); args.put("masterPubkey", masterPubkey); 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) { @@ -107,7 +112,8 @@ public class MasterClientTCPAction { if (isMultiReq) { // 开始执行多点合约请求,需要将缓存的其他节点发来的同requestID的请求也触发调用 LOGGER.info("开始执行多点合约请求,需要将缓存的其他节点发来的同requestID的请求也触发调用"); - MultiRequestInfo mri = MultiRequestInfo.reqInfos.get(request.getRequestID()); + MultiRequestInfo mri = + MultiRequestInfo.reqInfos.get(request.getRequestID()); for (String uniID : mri.callbackMap.keySet()) { LOGGER.info("触发 uniID=" + uniID); MultiRequestInfo.exeMultiReq(request, uniID); @@ -134,18 +140,22 @@ public class MasterClientTCPAction { LOGGER.info("返回 uniID=" + cei.uniReqIDMap.get(seq) + " 的结果"); cei.resultMap.get(seq).onResult(JsonUtil.toJson(ret)); cei.setLastExeSeq(seq); - if (KeyValueDBUtil.instance.containsKey(CMTables.LastExeSeq.toString(), contractID)) { - KeyValueDBUtil.instance.setValue(CMTables.LastExeSeq.toString(), contractID, seq + ""); + if (KeyValueDBUtil.instance.containsKey(CMTables.LastExeSeq.toString(), + 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; //账本检查点 if (seq % 100 == 0) { LOGGER.info("遇到ledger检查点 seq=" + cei.getLastExeSeq()); boolean isMaster = CMActions.manager.getContractIsMaster(contractID); if (isMaster) { String lastHash; - if (KeyValueDBUtil.instance.containsKey(CMTables.CheckPointLastHash.toString(), contractID)) { - lastHash = KeyValueDBUtil.instance.getValue(CMTables.CheckPointLastHash.toString(), contractID); + if (KeyValueDBUtil.instance.containsKey( + CMTables.CheckPointLastHash.toString(), contractID)) { + lastHash = KeyValueDBUtil.instance.getValue( + CMTables.CheckPointLastHash.toString(), contractID); } else { lastHash = "firstCheckPoint"; } @@ -154,7 +164,8 @@ public class MasterClientTCPAction { map.put("state", state); map.put("lastHash", lastHash); String data = JsonUtil.toJson(map); - String requestID = contractID + "_" + "checkPoint_" + new Random().nextInt(); + String requestID = + contractID + "_" + "checkPoint_" + new Random().nextInt(); CheckPointCallback cb = new CheckPointCallback(); ContractManager.checkPointToLedger(cb, contractID, data, requestID); } else { @@ -180,7 +191,8 @@ public class MasterClientTCPAction { SM2KeyPair keyPair = GlobalConf.instance.keyPair; ret.put("nodeID", keyPair.getPublicKeyStr()); 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)); cb.onResult(JsonUtil.toJson(ret)); } @@ -233,10 +245,12 @@ public class MasterClientTCPAction { 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()); } - 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()); } File file = new File(GlobalConf.instance.ADSPDir + "/" + cc.getContractID()); @@ -276,9 +290,10 @@ public class MasterClientTCPAction { // 需要计算出自己的ShardingID?路由规则(id/requester/arg-->shardingId), // 也在MultiPointCooperationExecutor中实现 } - //TODO master连接 + // TODO master连接 // contractID2MasterInfo.put(contractID, this); // 记录contractID 和 master之间的对应关系 - MultiContractMeta multiContractMeta = CMActions.manager.multiContractRecorder.createIfNotExist(contractID); + MultiContractMeta multiContractMeta = + CMActions.manager.multiContractRecorder.createIfNotExist(contractID); multiContractMeta.setLastExeSeq(-1); if (!contract.getScriptStr().startsWith("/")) { contract.setScript(dumpToDisk(contract, jo)); @@ -287,7 +302,7 @@ public class MasterClientTCPAction { String[] pp = contract.getScriptStr().split("/"); String parPath = GlobalConf.instance.publicCompiledDir; - //TODO 第一次来的meta没有cid!!! + // TODO 第一次来的meta没有cid!!! synchronized (multiContractMeta) { // 合约执行信息 multiContractMeta.setYpkName(pp[pp.length - 1]); multiContractMeta.setMembers(jo.get("members").getAsJsonArray()); @@ -295,7 +310,8 @@ public class MasterClientTCPAction { multiContractMeta.key = contract.getKey(); multiContractMeta.publicKey = contract.getPublicKey(); 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.setPubKeyPath(jo.get("pubKey").getAsString()); @@ -306,7 +322,11 @@ public class MasterClientTCPAction { try { File temp = new File(parPath, pp[pp.length - 1]); 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; } contract.setScript(temp.getAbsolutePath()); @@ -316,7 +336,8 @@ public class MasterClientTCPAction { // 这个地方判定,从参数中的master数据 和 globalConf中的数据 进行对比,如果一致的话,说明该节点为master multiContractMeta.setMaster(jo.get("master").getAsString()); if (contract.getType().needSeq()) - multiContractMeta.setIsMaster(GlobalConf.getNodeID().equals(jo.get("master").getAsString())); + multiContractMeta + .setIsMaster(GlobalConf.getNodeID().equals(jo.get("master").getAsString())); else { multiContractMeta.setIsMaster(true); } @@ -324,15 +345,19 @@ public class MasterClientTCPAction { LOGGER.info("startup arguments: " + JsonUtil.toJson(contract)); String ret = CMActions.manager.startContract(contract); // 调用CMActions 里的启动合约的方法,启动结果 LOGGER.info("startup result: " + ret); - //IMPORTANT!!!!!!!!!! + // IMPORTANT!!!!!!!!!! // meta should get after manger.startContract, because startContract reInitilized it! ContractMeta meta = CMActions.manager.statusRecorder.getContractMeta(contractID); - //IMPORTANT!!!!!!!!!! - meta.setContractExecutor(createContractExecutor(contract, contractID, jo.get("master").getAsString(), multiContractMeta.getMembers())); // 分配不同的Executor - // TODO 合约终止后从数据库中移除,但是为了测试可以人为制造合约终止但不从数据库中移除(异常停止) + // IMPORTANT!!!!!!!!!! + meta.setContractExecutor(createContractExecutor(contract, contractID, + jo.get("master").getAsString(), multiContractMeta.getMembers())); // 分配不同的Executor + // TODO 合约终止后从数据库中移除,但是为了测试可以人为制造合约终止但不从数据库中移除(异常停止) KeyValueDBUtil.instance.setValue(CMTables.UnitContracts.toString(), contractID, "exist"); 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(); } else { Map resultMap = new HashMap<>(); @@ -343,23 +368,26 @@ public class MasterClientTCPAction { resultMap.put("pubKey", GlobalConf.instance.keyPair.getPublicKeyStr()); result.onResult(JsonUtil.toJson(resultMap)); } -// if (contract.getType() == ContractExecType.Sharding) { -// for (String str : cei.getMembers()) { -// NetworkManager.instance.getNCClientHandler().controller.connectToMaster(str, null); -// } -// } + // if (contract.getType() == ContractExecType.Sharding) { + // for (String str : cei.getMembers()) { + // NetworkManager.instance.getNCClientHandler().controller.connectToMaster(str, null); + // } + // } } 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 { 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()) { 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); zout.putNextEntry(new ZipEntry("/manifest.json")); zout.write(("{\"main\":\"" + scriptName + ".yjs\"}").getBytes()); @@ -376,7 +404,7 @@ public class MasterClientTCPAction { return "/" + scriptName + ".ypk"; } - //TODO 这个奇怪的action可以放到这个SelfAdaptiveSharding的相关类里 + // TODO 这个奇怪的action可以放到这个SelfAdaptiveSharding的相关类里 @Action(async = true) public void deliverBlock(JsonObject jo, ResultCallback result) { if (jo.has("contractID") && jo.has("data")) { @@ -390,10 +418,12 @@ public class MasterClientTCPAction { @Action(async = true) public void executeContractLocally(JsonObject jo, ResultCallback result) { - final ContractRequest request = JsonUtil.fromJson(jo.get("data").toString(), ContractRequest.class); - // LOGGER.info("[MasterCientTCPAction] executeContractLocally " + JsonUtil.toJson(jo)); + final ContractRequest request = + JsonUtil.fromJson(jo.get("data").toString(), ContractRequest.class); + // 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 if (!request.needSeq) { @@ -411,7 +441,8 @@ public class MasterClientTCPAction { result.onResult(JsonUtil.toJson(ret)); } else { // reqeust all response all need seq String contractID = request.getContractID(); - MultiContractMeta cei = CMActions.manager.multiContractRecorder.getMultiContractMeta(contractID); + MultiContractMeta cei = + CMActions.manager.multiContractRecorder.getMultiContractMeta(contractID); boolean putToQueue = false; // 对于多点合约的请求 if (request.getRequestID().endsWith("_mul")) { @@ -419,24 +450,27 @@ public class MasterClientTCPAction { boolean isFirst = false; synchronized (MultiRequestInfo.lock) { // 加锁,防止同时放入多个同requestID的请求到cei的队列中 if (MultiRequestInfo.reqInfos.containsKey(request.getRequestID())) { - // logger.info("【收到多点合约请求】request.seq=" + request.seq + " cei.curExeSeq=" + - // cei.curExeSeq + " cei.getLastExeSeq()=" + cei.getLastExeSeq() + " + // logger.info("【收到多点合约请求】request.seq=" + request.seq + " cei.curExeSeq=" + + // 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) { // 正在执行多点请求时收到多点请求,说明这个请求不是第一个到的同requestID的请求s mri.callbackMap.put(jo.get("uniReqID").getAsString(), result); 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.putFlag(jo.get("uniReqID").getAsString(), false); } } else { - // logger.info("【收到多点合约请求】request.seq=" + request.seq + " cei.curExeSeq=" + - // cei.curExeSeq + " cei.getLastExeSeq()=" + cei.getLastExeSeq() + " + // logger.info("【收到多点合约请求】request.seq=" + request.seq + " cei.curExeSeq=" + + // 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); cei.addRequestQueue(request, jo.get("uniReqID").getAsString(), result); LOGGER.info("队列中加入请求 " + request.seq); @@ -451,7 +485,8 @@ public class MasterClientTCPAction { } } else { synchronized (cei) { - LOGGER.info("合约" + contractID + " 请求序号为 " + request.seq + " 上一次执行请求序号为 " + cei.getLastExeSeq()); + LOGGER.info("合约" + contractID + " 请求序号为 " + request.seq + " 上一次执行请求序号为 " + + cei.getLastExeSeq()); // cei.printContent(); if (request.seq <= cei.getLastExeSeq()) { @@ -484,14 +519,17 @@ public class MasterClientTCPAction { } @Action(async = true) - public void receiveContractExecutionServer(JsonObject jsonObject, ResultCallback resultCallback) { - MasterServerTCPAction.sync.wakeUp(jsonObject.get("responseID").getAsString(), jsonObject.get("data").getAsString()); + public void receiveContractExecutionServer(JsonObject jsonObject, + ResultCallback resultCallback) { + MasterServerTCPAction.sync.wakeUp(jsonObject.get("responseID").getAsString(), + jsonObject.get("data").getAsString()); } @Action(async = true) public void contractSyncMessage(JsonObject jsonObject, ResultCallback resultCallback) { 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); byte[] data = ByteUtil.decodeBASE64(jsonObject.get("data").getAsString()); PubKeyNode node = new PubKeyNode(); @@ -505,55 +543,69 @@ public class MasterClientTCPAction { @Action(async = true) public void reRouteContract(JsonObject jo, ResultCallback result) { LOGGER.info("Receive Reroute Info:" + jo.toString()); - MasterServerTCPAction.sync.instrumentWakeUp(jo.get("responseID").getAsString(), (resultCallback, result1) -> { - resultCallback.cancelTimeOut(); - LOGGER.info("try To reRoute"); + MasterServerTCPAction.sync.instrumentWakeUp(jo.get("responseID").getAsString(), + (resultCallback, result1) -> { + resultCallback.cancelTimeOut(); + LOGGER.info("try To reRoute"); - JsonObject cr = result1.get("data").getAsJsonObject(); - if (resultCallback instanceof SyncResult.ContractResultCallback) { - SyncResult.ContractResultCallback cb = (SyncResult.ContractResultCallback) resultCallback; - if (cb.getReRouteCount() > 0) { - 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)); - return; - } else cb.incReRouteCount(); - LOGGER.info("inc reRoute:" + cb.getReRouteCount()); - } - String pubkey = CMActions.manager.nodeCenterConn.reRouteContract(cr.get("contractID").getAsString()); - LOGGER.info("ReRoute Result:" + cr.get("contractID").getAsString() + " pubKey:" + pubkey); + JsonObject cr = result1.get("data").getAsJsonObject(); + if (resultCallback instanceof SyncResult.ContractResultCallback) { + SyncResult.ContractResultCallback cb = + (SyncResult.ContractResultCallback) resultCallback; + if (cb.getReRouteCount() > 0) { + 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)); + return; + } else + cb.incReRouteCount(); + LOGGER.info("inc reRoute:" + cb.getReRouteCount()); + } + String pubkey = CMActions.manager.nodeCenterConn + .reRouteContract(cr.get("contractID").getAsString()); + LOGGER.info("ReRoute Result:" + cr.get("contractID").getAsString() + " pubKey:" + + pubkey); - 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")); - resultCallback.onResult(JsonUtil.toJson(contractResult)); - return; - } - LOGGER.debug("Receive Reroute Result:" + pubkey); - ContractRequest contractRequest = JsonUtil.fromJson(cr, ContractRequest.class); - CMActions.manager.masterStub.executeByOtherNodeAsync(pubkey, contractRequest, resultCallback); - }, jo); + 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")); + resultCallback.onResult(JsonUtil.toJson(contractResult)); + return; + } + LOGGER.debug("Receive Reroute Result:" + pubkey); + ContractRequest contractRequest = JsonUtil.fromJson(cr, ContractRequest.class); + CMActions.manager.masterStub.executeByOtherNodeAsync(pubkey, contractRequest, + resultCallback); + }, jo); } -// public String requestContractExecution(ContractRequest c) { -// try { -// LOGGER.info("[MasterClientTCPAction] requestContractExecution " + JsonUtil.toJson(c)); -// Map req = new HashMap<>(); -// req.put("action", "requestContractExecution"); -// req.put("requestID", c.getRequestID()); -// req.put("data", c); -// handler.sendMsg(JsonUtil.toJson(req)); -// // 这里可能出错。是不是在这里校验CollectResult? -// ContractResult str = MasterServerTCPAction.sync.syncSleep(c.getRequestID()); -// LOGGER.info("[RequestContractGet]" + JsonUtil.toJson(str)); -// return JsonUtil.toJson(str); -// } catch (Exception e) { -// ByteArrayOutputStream bo = new ByteArrayOutputStream(); -// e.printStackTrace(new PrintStream(bo)); -// ContractResult cr = -// new ContractResult( -// ContractResult.Status.Exception, new JsonPrimitive(bo.toString())); -// return JsonUtil.toJson(cr); -// } -// } + // public String requestContractExecution(ContractRequest c) { + // try { + // LOGGER.info("[MasterClientTCPAction] requestContractExecution " + JsonUtil.toJson(c)); + // Map req = new HashMap<>(); + // req.put("action", "requestContractExecution"); + // req.put("requestID", c.getRequestID()); + // req.put("data", c); + // handler.sendMsg(JsonUtil.toJson(req)); + // // 这里可能出错。是不是在这里校验CollectResult? + // ContractResult str = MasterServerTCPAction.sync.syncSleep(c.getRequestID()); + // LOGGER.info("[RequestContractGet]" + JsonUtil.toJson(str)); + // return JsonUtil.toJson(str); + // } catch (Exception e) { + // ByteArrayOutputStream bo = new ByteArrayOutputStream(); + // e.printStackTrace(new PrintStream(bo)); + // ContractResult cr = + // new ContractResult( + // ContractResult.Status.Exception, new JsonPrimitive(bo.toString())); + // return JsonUtil.toJson(cr); + // } + // } } diff --git a/src/main/java/org/bdware/server/action/p2p/MasterClientTransferAction.java b/src/main/java/org/bdware/server/action/p2p/MasterClientTransferAction.java index b22fd1b..dee1667 100644 --- a/src/main/java/org/bdware/server/action/p2p/MasterClientTransferAction.java +++ b/src/main/java/org/bdware/server/action/p2p/MasterClientTransferAction.java @@ -25,15 +25,14 @@ public class MasterClientTransferAction { private final Map id2Memory = new HashMap<>(); - private MasterClientTransferAction() { - } + private MasterClientTransferAction() {} public void transferInstance(String agentPubkey, String contractID) { LOGGER.info("transferInstance contractID=" + contractID); - //step2 save state + // step2 save state String mem = CMActions.manager.dumpContract(contractID, ""); 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); } @@ -48,7 +47,7 @@ public class MasterClientTransferAction { String script = cc.contractMeta.contract.getScriptStr(); ContractStartInfo csi = cc.contractMeta.contract.startInfo; - //kill + // kill LOGGER.info("sendAndRestart stopContract"); CMActions.manager.stopContract(contractID); @@ -66,7 +65,8 @@ public class MasterClientTransferAction { File file; String path; 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; } else { file = new File(GlobalConf.instance.publicCompiledDir + "/" + csi.ypkName); @@ -90,7 +90,7 @@ public class MasterClientTransferAction { long count = 0; 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); req.put("data", data); count += len; @@ -116,7 +116,7 @@ public class MasterClientTransferAction { @Action(async = true) public void onSendAndStart(JsonObject jo, ResultCallback result) { - //step4 send memory + // step4 send memory String contractID = jo.get("contractID").getAsString(); LOGGER.info("onSendAndStart contractID=" + contractID); String mem = id2Memory.get(contractID); @@ -130,11 +130,13 @@ public class MasterClientTransferAction { public boolean sendMemory(String contractID, String memory, ResultCallback cb) { 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); LOGGER.info(file.getAbsolutePath()); File parent = file.getParentFile(); - if (!parent.exists()) parent.mkdirs(); + if (!parent.exists()) + parent.mkdirs(); ObjectOutputStream writer; try { FileOutputStream fileout = new FileOutputStream(file); @@ -160,7 +162,7 @@ public class MasterClientTransferAction { byte[] buff = new byte[30 * 1024]; 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); req.put("data", data); count += len; @@ -175,7 +177,7 @@ public class MasterClientTransferAction { req.put("contractID", contractID); req.remove("data"); cb.onResult(JsonUtil.toJson(req)); - //delete state file + // delete state file if (file.isFile() && file.exists()) { file.delete(); } @@ -190,16 +192,16 @@ public class MasterClientTransferAction { @Action(async = true) public void onSendMemory(JsonObject jo, ResultCallback result) { - //step5 close connect + // step5 close connect LOGGER.info("onSendMemory done"); -// if (handler != null) { -// LOGGER.info("handler close"); -// NetworkManager.instance.closeAgent(master); -// -// } -// if (NetworkManager.CONNECTORS.containsKey(master)) { -// NetworkManager.CONNECTORS.remove(master); -// } + // if (handler != null) { + // LOGGER.info("handler close"); + // NetworkManager.instance.closeAgent(master); + // + // } + // if (NetworkManager.CONNECTORS.containsKey(master)) { + // NetworkManager.CONNECTORS.remove(master); + // } LOGGER.info("transfer contract instance finished."); } } diff --git a/src/main/java/org/bdware/server/action/p2p/MasterServerRecoverMechAction.java b/src/main/java/org/bdware/server/action/p2p/MasterServerRecoverMechAction.java index 9fc4c61..06c3ef0 100644 --- a/src/main/java/org/bdware/server/action/p2p/MasterServerRecoverMechAction.java +++ b/src/main/java/org/bdware/server/action/p2p/MasterServerRecoverMechAction.java @@ -30,8 +30,7 @@ public class MasterServerRecoverMechAction { public static Map> recoverStatus = new ConcurrentHashMap<>(); private final Map stateFileMap = new HashMap<>(); - public MasterServerRecoverMechAction() { - } + public MasterServerRecoverMechAction() {} // 从disk-durable恢复 public static void restartContractFromStableMode(String nodeID, String contractID) { @@ -46,8 +45,8 @@ public class MasterServerRecoverMechAction { Map request = new HashMap(); request.put("action", "recoverFromStableMode"); request.put("contractID", contractID); - int temp = - CMActions.manager.multiContractRecorder.getMultiContractMeta(contractID).getCurSeqAtMaster(); + int temp = CMActions.manager.multiContractRecorder.getMultiContractMeta(contractID) + .getCurSeqAtMaster(); request.put("unitLastExeSeq", temp + ""); NetworkManager.instance.sendToAgent(nodeID, JsonUtil.toJson(request)); } @@ -81,15 +80,15 @@ public class MasterServerRecoverMechAction { RecoverMechTimeRecorder.writeCEIStart.put(nodeID, System.currentTimeMillis()); MultiContractMeta cei = - CMActions.manager.multiContractRecorder.getMultiContractMeta( - contractID); // master的server直接调client端,因为master自己的client端就在自己本地 + CMActions.manager.multiContractRecorder.getMultiContractMeta(contractID); // master的server直接调client端,因为master自己的client端就在自己本地 cei.memory = CMActions.manager.dumpContract(contractID, ""); // cei.printContent(); String path = contractID + "_temp_stateFile_" + new Random().nextLong(); File file = new File(GlobalConf.instance.projectDir + "/stateFiles/" + path); File parent = file.getParentFile(); - if (!parent.exists()) parent.mkdirs(); + if (!parent.exists()) + parent.mkdirs(); ObjectOutputStream writer; try { FileOutputStream fileout = new FileOutputStream(file); @@ -125,7 +124,7 @@ public class MasterServerRecoverMechAction { times++; LOGGER.info("times=" + times); 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); String data = ByteUtil.encodeBASE64(buff, len); req.put("data", data); @@ -143,10 +142,10 @@ public class MasterServerRecoverMechAction { // Thread.sleep(300); } fin.close(); - // req.put("isDone", "true"); - // req.remove("data"); + // req.put("isDone", "true"); + // req.remove("data"); // - // node.connection.sendMsg(JsonUtil.toJson(req)); + // node.connection.sendMsg(JsonUtil.toJson(req)); // master delete state file if (file.isFile() && file.exists()) { @@ -163,8 +162,8 @@ public class MasterServerRecoverMechAction { public static void masterRestartFromOther(String contractID) { LOGGER.info("Master从别的节点load当前状态"); - String masterID = - CMActions.manager.multiContractRecorder.getMultiContractMeta(contractID).getMasterNode(); + String masterID = CMActions.manager.multiContractRecorder.getMultiContractMeta(contractID) + .getMasterNode(); if (recoverStatus.get(masterID).get(contractID) != RecoverFlag.ToRecover) { return; } @@ -172,15 +171,15 @@ public class MasterServerRecoverMechAction { // 找一个普通节点来dump String relyNode = null; - for (String nodeID : - CMActions.manager.multiContractRecorder.getMultiContractMeta(contractID).getMembers()) { + for (String nodeID : CMActions.manager.multiContractRecorder + .getMultiContractMeta(contractID).getMembers()) { if (nodeID.equals(masterID)) { continue; } if (recoverStatus.get(nodeID).get(contractID) != RecoverFlag.Fine) { continue; } - //TODO????似乎人重连接? + // TODO????似乎人重连接? if (NetworkManager.instance.hasAgentConnection(nodeID)) { relyNode = nodeID; break; @@ -202,14 +201,16 @@ public class MasterServerRecoverMechAction { public static void unitModeCheck(String contractID) { String stateful = CMActions.manager.getContractStateful(contractID); - //just disable unitModeCheck - if (stateful!=null) return; + // just disable unitModeCheck + if (stateful != null) + return; if (stateful.equals("false")) { LOGGER.info("无状态集群合约无需运行模式检查及切换!"); return; } - MultiContractMeta mpci = CMActions.manager.multiContractRecorder.getMultiContractMeta(contractID); + MultiContractMeta mpci = + CMActions.manager.multiContractRecorder.getMultiContractMeta(contractID); synchronized (mpci) { int total = 0, fineNum = 0; for (String nodeId : mpci.getMembers()) { @@ -223,27 +224,17 @@ public class MasterServerRecoverMechAction { total++; } - LOGGER.info( - "合约" - + contractID - + "的集群,正常运行的节点有" - + 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); + LOGGER.info("合约" + contractID + "的集群,正常运行的节点有" + 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; if (fineNum <= Math.ceil((double) total / 2)) { unitStatus = ContractUnitStatus.StableMode; } - LOGGER.info( - "合约" + contractID + "的集群更改模式为" + unitStatus); + LOGGER.info("合约" + contractID + "的集群更改模式为" + unitStatus); Map req = new HashMap(); req.put("action", "changeUnitStatus"); @@ -251,12 +242,8 @@ public class MasterServerRecoverMechAction { req.put("mode", unitStatus.toString()); for (String nodeId : mpci.getMembers()) { NetworkManager.instance.sendToAgentIfConnected(nodeId, JsonUtil.toJson(req)); - LOGGER.info( - "发消息给节点 " - + nodeId.substring(0, 5) - + " 设置合约" - + contractID - + "的集群模式为StableMode"); + LOGGER.info("发消息给节点 " + nodeId.substring(0, 5) + " 设置合约" + contractID + + "的集群模式为StableMode"); } @@ -265,14 +252,15 @@ public class MasterServerRecoverMechAction { } // 新选出的Master恢复 - public static void newMasterRecover( - String contractID, String allMembers, List onlineMembers) { + public static void newMasterRecover(String contractID, String allMembers, + List onlineMembers) { LOGGER.info("[MasterServerRecoverMechAction] 新master开始恢复 : "); MasterElectTimeRecorder.masterStartRecover = System.currentTimeMillis(); - // step1 恢复MultiContractInfo - MultiContractMeta cei = CMActions.manager.multiContractRecorder.getMultiContractMeta(contractID); + // step1 恢复MultiContractInfo + MultiContractMeta cei = + CMActions.manager.multiContractRecorder.getMultiContractMeta(contractID); synchronized (cei) { cei.setSeqAtMaster(cei.getLastExeSeq()); } @@ -294,8 +282,8 @@ public class MasterServerRecoverMechAction { } ContractMeta meta = CMActions.manager.statusRecorder.getContractMeta(contractID); - meta.setContractExecutor( - MasterClientTCPAction.createContractExecutor(meta.contract, contractID, cei.getMasterNode(), cei.getMembers())); + meta.setContractExecutor(MasterClientTCPAction.createContractExecutor(meta.contract, + contractID, cei.getMasterNode(), cei.getMembers())); Map args = new HashMap<>(); args.put("ceiLastExeSeq", cei.getLastExeSeq()); meta.contractExecutor.onRecover(args); @@ -305,7 +293,7 @@ public class MasterServerRecoverMechAction { LOGGER.info( "[MasterServerRecoverMechAction] step1 新master恢复 MultiPointContractInfo 完成! \n"); - // step2 恢复recoverStatues这个map + // step2 恢复recoverStatues这个map for (String nodeID : nodeNames) { if (onlineMembers.contains(nodeID)) { // 设置所有在线的节点Fine状态 if (!recoverStatus.containsKey(nodeID)) { @@ -319,12 +307,8 @@ public class MasterServerRecoverMechAction { recoverStatus.put(nodeID, new ConcurrentHashMap<>()); } recoverStatus.get(nodeID).put(contractID, RecoverFlag.ToRecover); - LOGGER.info( - "新master设置 合约 " - + contractID - + " 节点 " - + nodeID.substring(0, 5) - + " 为ToRecover"); + LOGGER.info("新master设置 合约 " + contractID + " 节点 " + nodeID.substring(0, 5) + + " 为ToRecover"); } } LOGGER.info("新master恢复 recoverStatus map 完成!"); @@ -332,7 +316,7 @@ public class MasterServerRecoverMechAction { MasterElectTimeRecorder.masterRecoverFinish = System.currentTimeMillis(); - // step3 告知NC更新路由信息 + // step3 告知NC更新路由信息 Map re = new HashMap<>(); re.put("action", "changeMaster"); re.put("contractID", contractID); @@ -340,35 +324,35 @@ public class MasterServerRecoverMechAction { NetworkManager.instance.sendToNodeCenter(JsonUtil.toJson(re)); LOGGER.info("[MasterServerRecoverMechAction] step3 告知NC更新路由信息! \n"); - // step4 查看集群当前状态 + // step4 查看集群当前状态 unitModeCheck(contractID); LOGGER.info("新master 查看当前集群状态 完成!"); LOGGER.info("[MasterServerRecoverMechAction] step4 新master查看当前集群状态 完成!"); - // step5 向其他可能和旧的master断连,但和NC连接的节点发请求让连新的master - // String off = ""; - // for (String str : offlines) { - // if (off.equals("")) { - // off = str; - // } else { - // off += ","; - // off += str; - // } - // } + // step5 向其他可能和旧的master断连,但和NC连接的节点发请求让连新的master + // String off = ""; + // for (String str : offlines) { + // if (off.equals("")) { + // off = str; + // } else { + // off += ","; + // off += str; + // } + // } // - // Map request = new HashMap<>(); - // request.put("action", "updateFormerMaster"); - // request.put("contractID", contractID); - // request.put("offlines", off); - // request.put("master", mpci.masterNode); - // CMActions.client.sendMsg(JsonUtil.toJson(request)); + // Map request = new HashMap<>(); + // request.put("action", "updateFormerMaster"); + // request.put("contractID", contractID); + // request.put("offlines", off); + // request.put("master", mpci.masterNode); + // CMActions.client.sendMsg(JsonUtil.toJson(request)); LOGGER.info("新的master恢复完毕!"); LOGGER.info("[MasterServerRecoverMechAction] 新master恢复完成!"); } - public String judegeRecoverMethod( - String contractID, String nodeMode, String unitMode, int nodeLastExe, int unitLastExe) { + public String judegeRecoverMethod(String contractID, String nodeMode, String unitMode, + int nodeLastExe, int unitLastExe) { if (nodeMode.equals(ContractUnitStatus.CommonMode.toString()) && nodeLastExe == unitLastExe) { return ""; @@ -405,13 +389,14 @@ public class MasterServerRecoverMechAction { String unitMode; if (KeyValueDBUtil.instance.containsKey(CMTables.LastExeSeq.toString(), contractID)) unitMode = ContractUnitStatus.StableMode.toString(); - else unitMode = ContractUnitStatus.CommonMode.toString(); + else + unitMode = ContractUnitStatus.CommonMode.toString(); int nodeLastExe = Integer.MIN_VALUE; if (jo.has("lastExeSeq")) { nodeLastExe = jo.get("lastExeSeq").getAsInt(); } - int unitLastExe = - CMActions.manager.multiContractRecorder.getMultiContractMeta(contractID).getCurSeqAtMaster(); + int unitLastExe = CMActions.manager.multiContractRecorder.getMultiContractMeta(contractID) + .getCurSeqAtMaster(); RecoverMechTimeRecorder.startJudgeRecoverMethod.put(nodeID, System.currentTimeMillis()); @@ -420,15 +405,8 @@ public class MasterServerRecoverMechAction { RecoverMechTimeRecorder.judgeRecoverMethodFinish.put(nodeID, System.currentTimeMillis()); - LOGGER.info( - "[MasterServerRecoverMechAciton] askForRecover mode=" - + nodeMode - + " contractID=" - + contractID - + " nodeID=" - + nodeID - + " method=" - + method); + LOGGER.info("[MasterServerRecoverMechAciton] askForRecover mode=" + nodeMode + + " contractID=" + contractID + " nodeID=" + nodeID + " method=" + method); if (method.equals("common")) { LOGGER.info("restartContractFromCommonMode"); restartContractFromCommonMode(nodeID, contractID); @@ -447,8 +425,8 @@ public class MasterServerRecoverMechAction { @Action(async = true) public void restartContractFromCommonMode(JsonObject jo, ResultCallback cb) { - restartContractFromCommonMode( - jo.get("nodeID").getAsString(), jo.get("contractID").getAsString()); + restartContractFromCommonMode(jo.get("nodeID").getAsString(), + jo.get("contractID").getAsString()); } @Action(async = true) @@ -457,7 +435,8 @@ public class MasterServerRecoverMechAction { LOGGER.info("master查询缓存的 trans records 从 " + startSeq + " 开始"); String nodeId = jo.get("nodeID").getAsString(); String contractID = jo.get("contractID").getAsString(); - MultiContractMeta mpci = CMActions.manager.multiContractRecorder.getMultiContractMeta(contractID); + MultiContractMeta mpci = + CMActions.manager.multiContractRecorder.getMultiContractMeta(contractID); synchronized (mpci) { if (mpci.unitStatus == ContractUnitStatus.CommonMode) { restartContractFromCommonMode(nodeId, contractID); @@ -477,7 +456,8 @@ public class MasterServerRecoverMechAction { String path = contractID + "_temp_TransFile_" + new Random().nextLong(); File file = new File(GlobalConf.instance.projectDir + "/stateFiles/" + path); File parent = file.getParentFile(); - if (!parent.exists()) parent.mkdirs(); + if (!parent.exists()) + parent.mkdirs(); try { FileWriter fw = new FileWriter(file, true); @@ -516,7 +496,7 @@ public class MasterServerRecoverMechAction { int index = 1; // 数据包序号 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); String data = ByteUtil.encodeBASE64(buff, len); req.put("data", data); @@ -537,12 +517,12 @@ public class MasterServerRecoverMechAction { } fin.close(); - // req.put("isDone", "true"); - // req.put("contractID", contractID); - // req.put("last", last); - // req.remove("data"); + // req.put("isDone", "true"); + // req.put("contractID", contractID); + // req.put("last", last); + // req.remove("data"); // - // node.connection.sendMsg(JsonUtil.toJson(req)); + // node.connection.sendMsg(JsonUtil.toJson(req)); // master delete state file if (file.isFile() && file.exists()) { @@ -599,7 +579,8 @@ public class MasterServerRecoverMechAction { } catch (FileNotFoundException e) { e.printStackTrace(); } - } else fout = (FileOutputStream) stateFileMap.get(fileName); + } else + fout = (FileOutputStream) stateFileMap.get(fileName); String data = args.get("data").getAsString(); try { @@ -620,25 +601,26 @@ public class MasterServerRecoverMechAction { req.put("isMaster", "true"); req.put("filePath", dir.getAbsolutePath()); SM2KeyPair keyPair = GlobalConf.instance.keyPair; - NetworkManager.instance.sendToAgent(keyPair.getPublicKeyStr(), JsonUtil.toJson(req)); + NetworkManager.instance.sendToAgent(keyPair.getPublicKeyStr(), + JsonUtil.toJson(req)); } } catch (IOException e) { e.printStackTrace(); } } - // @Action(async = true) - // public void statelessUnitLastExe(JsonObject jo, ResultCallback cb) { - // String contractID = jo.get("contractID").getAsString(); - // String unitLastExe = + // @Action(async = true) + // public void statelessUnitLastExe(JsonObject jo, ResultCallback cb) { + // String contractID = jo.get("contractID").getAsString(); + // String unitLastExe = // MasterServerTCPAction.contractID2Members.get(contractID).getCurSeq() + ""; - // String nodeID = jo.get("nodeID").getAsString(); + // String nodeID = jo.get("nodeID").getAsString(); // - // Map request = new HashMap(); - // request.put("action", "statelessReceiveLastExe"); - // request.put("contractID", contractID); - // request.put("unitLastExe", unitLastExe); - // SlaveNode node = MasterServerTCPAction.id2Slaves.get(nodeID); - // node.connection.sendMsg(JsonUtil.toJson(request)); - // } + // Map request = new HashMap(); + // request.put("action", "statelessReceiveLastExe"); + // request.put("contractID", contractID); + // request.put("unitLastExe", unitLastExe); + // SlaveNode node = MasterServerTCPAction.id2Slaves.get(nodeID); + // node.connection.sendMsg(JsonUtil.toJson(request)); + // } } diff --git a/src/main/java/org/bdware/server/action/p2p/MasterServerTCPAction.java b/src/main/java/org/bdware/server/action/p2p/MasterServerTCPAction.java index 348b287..a0a3aa4 100644 --- a/src/main/java/org/bdware/server/action/p2p/MasterServerTCPAction.java +++ b/src/main/java/org/bdware/server/action/p2p/MasterServerTCPAction.java @@ -19,7 +19,6 @@ import org.bdware.server.CongestionControl; import org.bdware.server.action.Action; import org.bdware.server.action.CMActions; import org.bdware.server.action.SyncResult; -import org.bdware.server.executor.consistency.RequestAllExecutor; import org.bdware.server.trustedmodel.KillUnitContractResultCollector; import org.bdware.server.trustedmodel.ResultCollector; import org.bdware.units.NetworkManager; @@ -40,26 +39,21 @@ public class MasterServerTCPAction { static { final Object flag = new Object(); - ContractManager.scheduledThreadPool.scheduleWithFixedDelay( - () -> { - boolean cleared = clearCache(); - if (cleared) { - try { - synchronized (flag) { - flag.wait(14000L); - } - } catch (InterruptedException e) { - e.printStackTrace(); - } + ContractManager.scheduledThreadPool.scheduleWithFixedDelay(() -> { + boolean cleared = clearCache(); + if (cleared) { + try { + synchronized (flag) { + flag.wait(14000L); } - }, - 0, - 1, - TimeUnit.SECONDS); + } catch (InterruptedException e) { + e.printStackTrace(); + } + } + }, 0, 1, TimeUnit.SECONDS); } - public MasterServerTCPAction() { - } + public MasterServerTCPAction() {} public static void notifyNodeOffline(String contractID, String nodeID) { synchronized (sync) { @@ -68,23 +62,21 @@ public class MasterServerTCPAction { if (cb instanceof ResultCollector) { ResultCollector rc = (ResultCollector) cb; if (rc.getCommitter() instanceof NotifiableResultMerger) { - NotifiableResultMerger merger = - (NotifiableResultMerger) rc.getCommitter(); + NotifiableResultMerger merger = (NotifiableResultMerger) rc.getCommitter(); if (merger.getContractID().equals(contractID)) { - LOGGER.info("node " + nodeID + " offline! in the cluster of contract " + contractID); - LOGGER.debug("nodeID=" + nodeID + " contractID=" + contractID + - ": " + merger.getInfo()); - ContractResult cr = - new ContractResult( - ContractResult.Status.Exception, - new JsonPrimitive("node offline")); + LOGGER.info("node " + nodeID + " offline! in the cluster of contract " + + contractID); + LOGGER.debug("nodeID=" + nodeID + " contractID=" + contractID + ": " + + merger.getInfo()); + ContractResult cr = new ContractResult(ContractResult.Status.Exception, + new JsonPrimitive("node offline")); JsonObject jo = new JsonObject(); jo.addProperty("data", JsonUtil.toJson(cr)); jo.addProperty("responseID", requestID); jo.addProperty("action", "receiveTrustfullyResult"); jo.addProperty("nodeID", nodeID); - LOGGER.debug("[cb] nodeID=" + nodeID + " contractID=" + contractID + - ": " + jo); + LOGGER.debug("[cb] nodeID=" + nodeID + " contractID=" + contractID + + ": " + jo); sync.wakeUp(requestID, jo.toString()); } } @@ -96,7 +88,8 @@ public class MasterServerTCPAction { static RequestCache getCache(String contractID) { if (contractID != null) { RequestCache cache = requestCache.get(contractID); - if (cache != null) return cache; + if (cache != null) + return cache; else { LOGGER.info("[MasterServerTCPAction] create requestcache:" + contractID); RequestCache reqc = new RequestCache(); @@ -108,17 +101,18 @@ public class MasterServerTCPAction { } static boolean clearCache() { - if (requestCache.isEmpty()) return true; + if (requestCache.isEmpty()) + return true; - // final long time = System.currentTimeMillis() - 120000L; // 120s - // requestCache - // .entrySet() - // .removeIf( - // entry -> { - // RequestCache cache = entry.getValue(); - // if (cache == null) return true; - // return cache.getTime() < time; - // }); + // final long time = System.currentTimeMillis() - 120000L; // 120s + // requestCache + // .entrySet() + // .removeIf( + // entry -> { + // RequestCache cache = entry.getValue(); + // if (cache == null) return true; + // return cache.getTime() < time; + // }); for (RequestCache cache : requestCache.values()) { cache.decSize(); @@ -130,9 +124,7 @@ public class MasterServerTCPAction { ContractMeta meta = CMActions.manager.statusRecorder.getContractMeta(contractID); MultiContractMeta ret = CMActions.manager.multiContractRecorder.getMultiContractMeta(contractID); - LOGGER.debug(String.format("getCMInfo: %s %s %s", - meta.getName(), - meta.getID(), + LOGGER.debug(String.format("getCMInfo: %s %s %s", meta.getName(), meta.getID(), meta.getStatus())); return ret; } @@ -172,9 +164,8 @@ public class MasterServerTCPAction { jo.addProperty("action", "killContractProcessAtSlave"); MultiContractMeta contractMeta = CMActions.manager.multiContractRecorder.getMultiContractMeta(cl.getContractID()); - KillUnitContractResultCollector collector = - new KillUnitContractResultCollector( - jo.get("requestID").getAsString(), cb, contractMeta.getMembers().length); + KillUnitContractResultCollector collector = new KillUnitContractResultCollector( + jo.get("requestID").getAsString(), cb, contractMeta.getMembers().length); sync.sleep(jo.get("requestID").getAsString(), collector); for (String member : contractMeta.getMembers()) { NetworkManager.instance.sendToAgent(member, jo.toString()); @@ -184,27 +175,27 @@ public class MasterServerTCPAction { @Action(async = true) public void receiveTrustfullyResult(JsonObject jo, ResultCallback cb) { String responseID = jo.get("responseID").getAsString(); - // LOGGER.info("========== ExecuteContractLocally wakeUp:" + responseID); + // LOGGER.info("========== ExecuteContractLocally wakeUp:" + responseID); MasterServerTCPAction.sync.wakeUp(responseID, jo.toString()); } -// TODO to Remove -// @Action(async = true) -// // 假设该结点有运行这个合约调用的合约 -// public void executeContractLocallyServer(JsonObject jo, ResultCallback cb) { -// final ContractRequest request = -// JsonUtil.fromJson(jo.get("data").toString(), ContractRequest.class); -// long start = System.currentTimeMillis(); -// String data2 = CMActions.manager.executeLocally(request, null); -// Map ret = new HashMap<>(); -// ret.put("action", "receiveTrustfullyResultServer"); -// SM2KeyPair keyPair = GlobalConf.instance.keyPair; -// ret.put("nodeID", keyPair.getPublicKeyStr()); -// ret.put("responseID", jo.get("uniReqID").getAsString()); -// ret.put("executeTime", (System.currentTimeMillis() - start) + ""); -// ret.put("data", data2); -// cb.onResult(JsonUtil.toJson(ret)); -// } + // TODO to Remove + // @Action(async = true) + // // 假设该结点有运行这个合约调用的合约 + // public void executeContractLocallyServer(JsonObject jo, ResultCallback cb) { + // final ContractRequest request = + // JsonUtil.fromJson(jo.get("data").toString(), ContractRequest.class); + // long start = System.currentTimeMillis(); + // String data2 = CMActions.manager.executeLocally(request, null); + // Map ret = new HashMap<>(); + // ret.put("action", "receiveTrustfullyResultServer"); + // SM2KeyPair keyPair = GlobalConf.instance.keyPair; + // ret.put("nodeID", keyPair.getPublicKeyStr()); + // ret.put("responseID", jo.get("uniReqID").getAsString()); + // ret.put("executeTime", (System.currentTimeMillis() - start) + ""); + // ret.put("data", data2); + // cb.onResult(JsonUtil.toJson(ret)); + // } @Action(async = true) @@ -224,8 +215,8 @@ public class MasterServerTCPAction { // 调用方向为MasterClient->MasterServer, // 如果为多节点,则为MasterServer executeLocally-> MasterClient // executeLocally,否则为MasterServer->Local - // LOGGER.info("[requestContractExecution]:" + jo.toString()); - // loggger.bug + // LOGGER.info("[requestContractExecution]:" + jo.toString()); + // loggger.bug JsonObject cr = jo.get("data").getAsJsonObject(); String requestID = cr.get("requestID").getAsString(); String contractID = cr.get("contractID").getAsString(); @@ -242,22 +233,20 @@ public class MasterServerTCPAction { return; } MultiContractMeta info = MasterServerTCPAction.getMPCInfo(contractMeta.getID()); - // LOGGER.info("[MasterServerTCPAction] requestContractExecution " + new + // LOGGER.info("[MasterServerTCPAction] requestContractExecution " + new // Gson().toJson(jo)); - // LOGGER.info("MultiPointContractInfo info=" + (info == null ? "null" : "not + // LOGGER.info("MultiPointContractInfo info=" + (info == null ? "null" : "not // null") + // "\n"); - if (info != null && - ContractExecType.Sharding != contractMeta.contract.getType() - && !ContractExecType.SelfAdaptiveSharding.equals(contractMeta.contract.getType())) { + if (info != null && ContractExecType.Sharding != contractMeta.contract.getType() + && !ContractExecType.SelfAdaptiveSharding + .equals(contractMeta.contract.getType())) { // 这个是个多节点的合约 // Just forward it to the correct Node // Master节点直接发3个,聚合后返回结果。 - contractMeta.contractExecutor.execute( - requestID, - JsonUtil.fromJson(cr, ContractRequest.class), - new ResultCallback() { + contractMeta.contractExecutor.execute(requestID, + JsonUtil.fromJson(cr, ContractRequest.class), new ResultCallback() { @Override public void onResult(String str) { Map result = new HashMap<>(); @@ -279,17 +268,18 @@ public class MasterServerTCPAction { // 这个是个单节点的合约 // executeContract(CacheTest应该要有多个进来。 if (null != client && !client.getContractType().needSeq()) { - contractMeta.contractExecutor.execute(requestID, contractRequest, new ResultCallback() { - @Override - public void onResult(String str) { - Map result = new HashMap<>(); - result.put("action", "receiveContractExecutionServer"); - result.put("responseID", cr.get("requestID").getAsString()); - result.put("data", str); - cb.onResult(JsonUtil.toJson(result)); - CongestionControl.masterServerLoad.decrementAndGet(); - } - }, null); + contractMeta.contractExecutor.execute(requestID, contractRequest, + new ResultCallback() { + @Override + public void onResult(String str) { + Map result = new HashMap<>(); + result.put("action", "receiveContractExecutionServer"); + result.put("responseID", cr.get("requestID").getAsString()); + result.put("data", str); + cb.onResult(JsonUtil.toJson(result)); + CongestionControl.masterServerLoad.decrementAndGet(); + } + }, null); } else { LOGGER.debug("send ReRoute response:" + cr); JsonObject result = new JsonObject(); diff --git a/src/main/java/org/bdware/server/action/p2p/MasterServerTransferAction.java b/src/main/java/org/bdware/server/action/p2p/MasterServerTransferAction.java index f8cdfdf..f1271a4 100644 --- a/src/main/java/org/bdware/server/action/p2p/MasterServerTransferAction.java +++ b/src/main/java/org/bdware/server/action/p2p/MasterServerTransferAction.java @@ -22,8 +22,7 @@ public class MasterServerTransferAction { private static final Logger LOGGER = LogManager.getLogger(MasterServerTransferAction.class); private Map fileMap = new HashMap<>(); - public MasterServerTransferAction() { - } + public MasterServerTransferAction() {} @Action(async = true) public void transferByYPK(JsonObject args, ResultCallback cb) { @@ -54,7 +53,8 @@ public class MasterServerTransferAction { } catch (FileNotFoundException e) { e.printStackTrace(); } - } else fout = (FileOutputStream) fileMap.get(fileKey); + } else + fout = (FileOutputStream) fileMap.get(fileKey); if (isDone) { if (fout != null) try { @@ -90,7 +90,8 @@ public class MasterServerTransferAction { c.setOwner(GlobalConf.instance.keyPair.getPublicKeyStr()); try { 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) { e.printStackTrace(); } @@ -142,7 +143,8 @@ public class MasterServerTransferAction { } catch (FileNotFoundException e) { e.printStackTrace(); } - } else fout = (FileOutputStream) fileMap.get(fileName); + } else + fout = (FileOutputStream) fileMap.get(fileName); if (isDone) { if (fout != null) try { diff --git a/src/main/java/org/bdware/server/action/p2p/UnitsInfoAction.java b/src/main/java/org/bdware/server/action/p2p/UnitsInfoAction.java index 4aeb182..a31a42a 100644 --- a/src/main/java/org/bdware/server/action/p2p/UnitsInfoAction.java +++ b/src/main/java/org/bdware/server/action/p2p/UnitsInfoAction.java @@ -4,20 +4,17 @@ import com.google.gson.JsonObject; import org.bdware.sc.conn.ResultCallback; import org.bdware.sc.util.JsonUtil; import org.bdware.server.action.Action; -import org.bdware.units.NetworkManager; import org.bdware.units.beans.MultiPointContractInfo; import org.bdware.units.function.ContractUnitManager; import org.bdware.units.function.ExecutionManager; import org.bdware.units.function.SequencingManager; /** - * 负责集群信息的方法 - * 如获取集群信息,master信息等 + * 负责集群信息的方法 如获取集群信息,master信息等 */ public class UnitsInfoAction { - public UnitsInfoAction() { - } + public UnitsInfoAction() {} @Action(async = true) public void getContractUnit(String contractId, final ResultCallback callback) { @@ -29,7 +26,8 @@ public class UnitsInfoAction { JsonObject jsonObject = new JsonObject(); jsonObject.addProperty("action", "getContractUnit"); 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.addProperty("action", "getContractUnitMaster"); 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) public void updateContractStartInfo(JsonObject args, final ResultCallback callback) { 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(); ContractUnitManager.instance.addContractInfo(contractID, contractInfo); SequencingManager.instance.updateConsensusCenter(contractID, contractInfo); diff --git a/src/main/java/org/bdware/server/action/p2p/_UNUSED_ExecutionAction.java b/src/main/java/org/bdware/server/action/p2p/_UNUSED_ExecutionAction.java index 1e8e38b..ca66dec 100644 --- a/src/main/java/org/bdware/server/action/p2p/_UNUSED_ExecutionAction.java +++ b/src/main/java/org/bdware/server/action/p2p/_UNUSED_ExecutionAction.java @@ -35,8 +35,7 @@ import java.io.File; public class _UNUSED_ExecutionAction implements OnHashCallback { private static final Logger LOGGER = LogManager.getLogger(_UNUSED_ExecutionAction.class); - public _UNUSED_ExecutionAction() { - } + public _UNUSED_ExecutionAction() {} // TODO TOMerge @Action(async = true) @@ -71,23 +70,18 @@ public class _UNUSED_ExecutionAction implements OnHashCallback { } else { unitContractMessage.msgType = UnitContractMessageType.ContractUnitResponse.getValue(); - // unitContractMessage.cuType = + // unitContractMessage.cuType = // UnitContractRequestType.START.getValue(); unitContractMessage.action = "startContractResponse"; unitContractMessage.content = - JsonUtil.toJson( - new ContractResult( - ContractResult.Status.Exception, - new JsonPrimitive("Contract not found"))); - reply = - UnitMessage.newBuilder() - .setMsgType(BDLedgerContract.UnitMessageType.UnitContractMessage) - .setSender(GlobalConf.instance.peerID) - .addReceiver(sender) - .setContent( - ByteString.copyFromUtf8(JsonUtil.toJson(unitContractMessage))) - .build(); - // byte[] bytes = reply.toByteArray(); + JsonUtil.toJson(new ContractResult(ContractResult.Status.Exception, + new JsonPrimitive("Contract not found"))); + reply = UnitMessage.newBuilder() + .setMsgType(BDLedgerContract.UnitMessageType.UnitContractMessage) + .setSender(GlobalConf.instance.peerID).addReceiver(sender) + .setContent(ByteString.copyFromUtf8(JsonUtil.toJson(unitContractMessage))) + .build(); + // byte[] bytes = reply.toByteArray(); callback.onResult(JsonUtil.toJson(reply)); return; } @@ -100,20 +94,17 @@ public class _UNUSED_ExecutionAction implements OnHashCallback { LOGGER.info("[START] result: " + content); result = JsonUtil.fromJson(content, ContractResult.class); unitContractMessage.msgType = UnitContractMessageType.ContractUnitResponse.getValue(); - // unitContractMessage.statusType = result.status == + // unitContractMessage.statusType = result.status == // ContractResult.Status.Success?0:1; unitContractMessage.action = "startContractResponse"; // Collector investigates success or fail unitContractMessage.content = JsonUtil.toJson(result); // TODO save privKey in contractClient unitContractMessage.pubkey = ""; - reply = - UnitMessage.newBuilder() - .setMsgType(BDLedgerContract.UnitMessageType.UnitContractMessage) - .setSender(GlobalConf.instance.peerID) - .addReceiver(sender) - .setContent(ByteString.copyFromUtf8(JsonUtil.toJson(unitContractMessage))) - .build(); + reply = UnitMessage.newBuilder() + .setMsgType(BDLedgerContract.UnitMessageType.UnitContractMessage) + .setSender(GlobalConf.instance.peerID).addReceiver(sender) + .setContent(ByteString.copyFromUtf8(JsonUtil.toJson(unitContractMessage))).build(); byte[] bytes = reply.toByteArray(); callback.onResult(ByteUtil.encodeBASE64(bytes)); if (result.status == ContractResult.Status.Success) { @@ -130,10 +121,8 @@ public class _UNUSED_ExecutionAction implements OnHashCallback { System.out.println("[BaseFunctionManager] handleResponse null"); return; } - if (responseCenter.updateReply( - arg.get("content").getAsString(), - arg.get("sender").getAsString(), - arg.get("pubkey").getAsString())) { + if (responseCenter.updateReply(arg.get("content").getAsString(), + arg.get("sender").getAsString(), arg.get("pubkey").getAsString())) { // save contractInfo String contractID = arg.get("contractID").getAsString(); int sequencing = arg.get("sequencing").getAsInt(); @@ -158,62 +147,54 @@ public class _UNUSED_ExecutionAction implements OnHashCallback { @Action(async = true) public void executeContractAtSlave(JsonObject args, final ResultCallback callback) { String sender = args.get("sender").getAsString(); - UnitContractMessage unitContractMessage = JsonUtil.fromJson(args, UnitContractMessage.class); + UnitContractMessage unitContractMessage = + JsonUtil.fromJson(args, UnitContractMessage.class); String requestID = unitContractMessage.requestID; int sequencing = unitContractMessage.sequencing; int network = unitContractMessage.network; - // int rcheck = unitContractMessage.rcheck; + // int rcheck = unitContractMessage.rcheck; String contractID = unitContractMessage.contractID; String operation = unitContractMessage.operation; String arg = unitContractMessage.arg; - // String content = unitContractMessage.content; + // String content = unitContractMessage.content; LOGGER.info("[executeContractAtSlave] [EXECUTE] " + args); final ContractRequest c = new ContractRequest(); c.setContractID(contractID); c.setRequestID(requestID); - // c.withDynamicAnalysis = args.get("withDynamicAnalysis").getAsBoolean(); - // c.withEvaluatesAnalysis = args.get("withEvaluatesAnalysis").getAsBoolean(); + // c.withDynamicAnalysis = args.get("withDynamicAnalysis").getAsBoolean(); + // c.withEvaluatesAnalysis = args.get("withEvaluatesAnalysis").getAsBoolean(); c.setAction(operation); c.setArg(arg); - // if (c.withEvaluatesAnalysis) { - // c.setValue(jo.get("hasValue").getAsLong()); - // } - // if (jo.has("gasLimit")) { - // c.setGasLimit(jo.get("gasLimit").getAsLong()); - // } - // if (args.has("requester")) { - // c.setPublicKey(args.get("requester").getAsString()); - // c.setSignature(args.get("signature").getAsString()); - // } - // c.setPublicKey(args.get("pubkey").getAsString()); - // c.setSignature(args.get("signature").getAsString()); + // if (c.withEvaluatesAnalysis) { + // c.setValue(jo.get("hasValue").getAsLong()); + // } + // if (jo.has("gasLimit")) { + // c.setGasLimit(jo.get("gasLimit").getAsLong()); + // } + // if (args.has("requester")) { + // c.setPublicKey(args.get("requester").getAsString()); + // c.setSignature(args.get("signature").getAsString()); + // } + // c.setPublicKey(args.get("pubkey").getAsString()); + // c.setSignature(args.get("signature").getAsString()); String reqID; long start = System.currentTimeMillis(); - CMActions.manager.executeContractInternal( - c, - new ResultCallback() { - @Override - public void onResult(String str) { - // TODO qianming - unitContractMessage.signature = str; - unitContractMessage.action = "executeContractResponse"; - unitContractMessage.content = str; - UnitMessage unitMessage = - UnitMessage.newBuilder() - .setMsgType( - BDLedgerContract.UnitMessageType - .UnitContractMessage) - .setSender(GlobalConf.instance.peerID) - .addReceiver(sender) - .setContent( - ByteString.copyFromUtf8( - JsonUtil.toJson(unitContractMessage))) - .build(); - byte[] bytes = unitMessage.toByteArray(); - callback.onResult(ByteUtil.encodeBASE64(bytes)); - } - }, - null); + CMActions.manager.executeContractInternal(c, new ResultCallback() { + @Override + public void onResult(String str) { + // TODO qianming + unitContractMessage.signature = str; + unitContractMessage.action = "executeContractResponse"; + unitContractMessage.content = str; + UnitMessage unitMessage = UnitMessage.newBuilder() + .setMsgType(BDLedgerContract.UnitMessageType.UnitContractMessage) + .setSender(GlobalConf.instance.peerID).addReceiver(sender) + .setContent(ByteString.copyFromUtf8(JsonUtil.toJson(unitContractMessage))) + .build(); + byte[] bytes = unitMessage.toByteArray(); + callback.onResult(ByteUtil.encodeBASE64(bytes)); + } + }, null); } @Action(async = true) @@ -225,10 +206,8 @@ public class _UNUSED_ExecutionAction implements OnHashCallback { System.out.println("[BaseFunctionManager] responseCenter null"); return; } - if (responseCenter.updateReply( - arg.get("content").getAsString(), - arg.get("sender").getAsString(), - arg.get("signature").getAsString())) { + if (responseCenter.updateReply(arg.get("content").getAsString(), + arg.get("sender").getAsString(), arg.get("signature").getAsString())) { // call back responseCenter.formReply(); ExecutionManager.instance.responseCenters.remove(requestID); @@ -238,38 +217,30 @@ public class _UNUSED_ExecutionAction implements OnHashCallback { @Action(async = true) public void stopContractAtSlave(JsonObject args, final ResultCallback callback) { String sender = args.get("sender").getAsString(); - UnitContractMessage unitContractMessage = JsonUtil.fromJson(args, UnitContractMessage.class); + UnitContractMessage unitContractMessage = + JsonUtil.fromJson(args, UnitContractMessage.class); String requestID = unitContractMessage.requestID; int sequencing = unitContractMessage.sequencing; int network = unitContractMessage.network; - // int rcheck = unitContractMessage.rcheck; + // int rcheck = unitContractMessage.rcheck; String contractID = unitContractMessage.contractID; LOGGER.info("[stopContractAtSlave] [EXECUTE] " + args); final ContractRequest c = new ContractRequest(); c.setContractID(contractID); c.setRequestID(requestID); - String ret = - CMActions.manager.stopContractWithOwner( - GlobalConf.instance.keyPair.getPublicKeyStr(), contractID); - GRPCPool.instance.writeToChain( - this, - contractID, - "stopContract", - ret, - args.has("requestID") ? args.get("requestID").getAsString() : null, - ""); + String ret = CMActions.manager + .stopContractWithOwner(GlobalConf.instance.keyPair.getPublicKeyStr(), contractID); + GRPCPool.instance.writeToChain(this, contractID, "stopContract", ret, + args.has("requestID") ? args.get("requestID").getAsString() : null, ""); ContractResult contractResult = new ContractResult(ContractResult.Status.Success, new JsonPrimitive("success")); unitContractMessage.signature = ret; unitContractMessage.action = "stopContractResponse"; unitContractMessage.content = JsonUtil.toJson(contractResult); - UnitMessage unitMessage = - UnitMessage.newBuilder() - .setMsgType(BDLedgerContract.UnitMessageType.UnitContractMessage) - .setSender(GlobalConf.instance.peerID) - .addReceiver(sender) - .setContent(ByteString.copyFromUtf8(JsonUtil.toJson(unitContractMessage))) - .build(); + UnitMessage unitMessage = UnitMessage.newBuilder() + .setMsgType(BDLedgerContract.UnitMessageType.UnitContractMessage) + .setSender(GlobalConf.instance.peerID).addReceiver(sender) + .setContent(ByteString.copyFromUtf8(JsonUtil.toJson(unitContractMessage))).build(); byte[] bytes = unitMessage.toByteArray(); callback.onResult(ByteUtil.encodeBASE64(bytes)); } @@ -284,10 +255,8 @@ public class _UNUSED_ExecutionAction implements OnHashCallback { System.out.println("[BaseFunctionManager] responseCenter null"); return; } - if (responseCenter.updateReply( - arg.get("content").getAsString(), - arg.get("sender").getAsString(), - arg.get("signature").getAsString())) { + if (responseCenter.updateReply(arg.get("content").getAsString(), + arg.get("sender").getAsString(), arg.get("signature").getAsString())) { // call back boolean allSuccess = responseCenter.isAllSuccess(); responseCenter.formReply(); @@ -299,6 +268,5 @@ public class _UNUSED_ExecutionAction implements OnHashCallback { } @Override - public void publishHash(String reqID, String hashStr) { - } + public void publishHash(String reqID, String hashStr) {} } diff --git a/src/main/java/org/bdware/server/doip/BCOManager.java b/src/main/java/org/bdware/server/doip/BCOManager.java index 66895ae..89685e4 100644 --- a/src/main/java/org/bdware/server/doip/BCOManager.java +++ b/src/main/java/org/bdware/server/doip/BCOManager.java @@ -46,7 +46,8 @@ public class BCOManager { String body = doipMessage.body.getDataAsJsonString(); LOGGER.info("Retrieve " + bCoId + " Result:" + body); YPKInfo parsed = new Gson().fromJson(body, YPKInfo.class); - if (parsed != null && parsed.md5 != null && parsed.status == UploadingStatus.Finished) { + if (parsed != null && parsed.md5 != null + && parsed.status == UploadingStatus.Finished) { ypkInfo.copyFrom(parsed); } synchronized (ypkInfo) { @@ -65,7 +66,8 @@ public class BCOManager { if (ypkInfo.status == UploadingStatus.Finished) { 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(); DownloadProgressChecker checker = new DownloadProgressChecker(); client.downloadYPK(bCoId, checker, target); @@ -109,7 +111,8 @@ public class BCOManager { synchronized (this) { this.notify(); } - LOGGER.info("[Download error]" + s + " doipMessage:" + doipMessage.body.getDataAsJsonString()); + LOGGER.info("[Download error]" + s + " doipMessage:" + + doipMessage.body.getDataAsJsonString()); } diff --git a/src/main/java/org/bdware/server/doip/ContractRepositoryHandler.java b/src/main/java/org/bdware/server/doip/ContractRepositoryHandler.java index e788df6..c7c92a7 100644 --- a/src/main/java/org/bdware/server/doip/ContractRepositoryHandler.java +++ b/src/main/java/org/bdware/server/doip/ContractRepositoryHandler.java @@ -41,7 +41,8 @@ import java.util.ArrayList; import java.util.List; @ChannelHandler.Sharable -public class ContractRepositoryHandler extends RepositoryHandlerBase implements DefaultRepoHandlerInjector { +public class ContractRepositoryHandler extends RepositoryHandlerBase + implements DefaultRepoHandlerInjector { BCOManager bcoManager; static Logger LOGGER = LogManager.getLogger(ContractRepositoryHandler.class); @@ -49,7 +50,8 @@ public class ContractRepositoryHandler extends RepositoryHandlerBase implements super(info); GlobalConf.DOAConf doaConf = GlobalConf.instance.doaConf; String bcoDir = GlobalConf.instance.bcoDir; - bcoManager = new BCOManager(doaConf.repoDoid, new File(bcoDir), doaConf.lhsAddress, GlobalConf.instance.keyPair); + bcoManager = new BCOManager(doaConf.repoDoid, new File(bcoDir), doaConf.lhsAddress, + GlobalConf.instance.keyPair); } @Override @@ -60,7 +62,9 @@ public class ContractRepositoryHandler extends RepositoryHandlerBase implements @Override public DoipMessage handleListOps(DoipMessage doipMessage) { if (!GlobalConf.instance.doaConf.repoDoid.equals(doipMessage.header.parameters.id)) { - return replyStringWithStatus(doipMessage, "unsupported doid:" + doipMessage.header.parameters.id, DoipResponseCode.DoNotFound); + return replyStringWithStatus(doipMessage, + "unsupported doid:" + doipMessage.header.parameters.id, + DoipResponseCode.DoNotFound); } JsonArray ops = new JsonArray(); ops.add(BasicOperations.Hello.getName()); @@ -71,13 +75,17 @@ public class ContractRepositoryHandler extends RepositoryHandlerBase implements @Override public DoipMessage handleCreate(DoipMessage doipMessage) { 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) { - 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")) { - return replyStringWithStatus(doipMessage, "permission denied, role:" + permissions, DoipResponseCode.Declined); + return replyStringWithStatus(doipMessage, "permission denied, role:" + permissions, + DoipResponseCode.Declined); } } DigitalObject digitalObject = null; @@ -87,7 +95,8 @@ public class ContractRepositoryHandler extends RepositoryHandlerBase implements } catch (Exception e) { ByteArrayOutputStream bo = new ByteArrayOutputStream(); 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()); 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); Contract c = new Contract(); if (digitalObject.attributes.has("contractExecType")) - c.setType(ContractExecType.valueOf(digitalObject.attributes.get("contractExecType").getAsString())); - else c.setType(ContractExecType.Sole); + c.setType(ContractExecType + .valueOf(digitalObject.attributes.get("contractExecType").getAsString())); + else + c.setType(ContractExecType.Sole); if (digitalObject.attributes.has("shardingId")) - c.setShardingId(Integer.valueOf(digitalObject.attributes.get("shardingId").getAsString())); - else c.setShardingId(-1); + c.setShardingId( + Integer.valueOf(digitalObject.attributes.get("shardingId").getAsString())); + else + c.setShardingId(-1); c.setScript(path); c.setOwner(doipMessage.credential.getSigner()); if (digitalObject.attributes.has("createParam")) { @@ -116,25 +132,28 @@ public class ContractRepositoryHandler extends RepositoryHandlerBase implements } SM2KeyPair sm2Key; if (digitalObject.attributes.has("sm2KeyPair")) - sm2Key = SM2KeyPair.fromJson(digitalObject.attributes.get("sm2KeyPair").getAsJsonObject().toString()); - else sm2Key = SM2Util.generateSM2KeyPair(); + sm2Key = SM2KeyPair.fromJson( + digitalObject.attributes.get("sm2KeyPair").getAsJsonObject().toString()); + else + sm2Key = SM2Util.generateSM2KeyPair(); String contractID = String.valueOf(sm2Key.getPublicKeyStr().hashCode()); c.setID(contractID); // contractID是根据hash算出来的 c.setKey(sm2Key.getPrivateKeyStr()); c.setPublicKey(sm2Key.getPublicKeyStr()); 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); 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); } private void registerBDOID(String contractID) { - //TODO + // TODO } @Override @@ -147,13 +166,15 @@ public class ContractRepositoryHandler extends RepositoryHandlerBase implements String id = doipMessage.header.parameters.attributes.get("elementId").getAsString(); id = id.replaceAll(".*/", ""); LOGGER.info("handleDelete:" + id); - //TODO judge whethere the do exists + // TODO judge whethere the do exists ContractMeta meta = CMActions.manager.statusRecorder.getContractMeta(id); if (meta == null) { - return replyStringWithStatus(doipMessage, "can't locate do", DoipResponseCode.DoNotFound); + return replyStringWithStatus(doipMessage, "can't locate do", + DoipResponseCode.DoNotFound); } if (meta.getStatus() == ContractStatusEnum.KILLED) { - return replyStringWithStatus(doipMessage, "already deleted!", DoipResponseCode.Declined); + return replyStringWithStatus(doipMessage, "already deleted!", + DoipResponseCode.Declined); } DoipMessage[] content = new DoipMessage[1]; JsonObject jo = new JsonObject(); @@ -172,11 +193,13 @@ public class ContractRepositoryHandler extends RepositoryHandlerBase implements if (client == null) { String doid = doipMessage.header.parameters.id; 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); } 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(); @@ -213,7 +236,8 @@ public class ContractRepositoryHandler extends RepositoryHandlerBase implements result.add(new JsonPrimitive("Timeout!")); 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("result", result.get(0)); @@ -224,7 +248,7 @@ public class ContractRepositoryHandler extends RepositoryHandlerBase implements private DigitalObject contract2DigitalObject(ContractClient contractClient) { DigitalObject contractDO = new DigitalObject(contractClient.getContractID(), DoType.DO); contractDO.addAttribute("contractName", contractClient.getContractName()); - // contractDO.addAttribute("script",contract.contract.getScriptStr()); + // contractDO.addAttribute("script",contract.contract.getScriptStr()); contractDO.addAttribute("owner", contractClient.contractMeta.contract.getOwner()); for (FunctionDesp f : contractClient.getExportedFunctions()) { Element fe = new Element(f.functionName, "function"); @@ -236,29 +260,35 @@ public class ContractRepositoryHandler extends RepositoryHandlerBase implements @Op(op = BasicOperations.Extension, name = "call") 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) - return replyStringWithStatus(doipMessage, "Contract instance not exist!", DoipResponseCode.DoNotFound); + return replyStringWithStatus(doipMessage, "Contract instance not exist!", + DoipResponseCode.DoNotFound); // todo transform doipMessage to args JsonObject args = doipMessage.header.parameters.attributes; ContractRequest cr = new ContractRequest(); 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")) cr.withEvaluatesAnalysis = args.get("withEvaluatesAnalysis").getAsBoolean(); 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()); - 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) cr.setRequesterDOI(doipMessage.credential.getSigner()); String reqID; - if (args.has("requestID")) reqID = args.get("requestID").getAsString(); + if (args.has("requestID")) + reqID = args.get("requestID").getAsString(); else { reqID = System.currentTimeMillis() + "_" + (int) (Math.random() * 1000); args.addProperty("requestID", reqID); @@ -267,8 +297,8 @@ public class ContractRepositoryHandler extends RepositoryHandlerBase implements String resp = CMActions.manager.execute(cr, null); - // StringContainer sc = new StringContainer(); - // SyncContainer sync = new SyncContainer(sc); + // StringContainer sc = new StringContainer(); + // SyncContainer sync = new SyncContainer(sc); return replyString(doipMessage, resp); } @@ -285,22 +315,25 @@ public class ContractRepositoryHandler extends RepositoryHandlerBase implements } @Override - public void injectListOps(DoipMessage doipMessage, DoipMessageFactory.DoipMessageBuilder builder) { + public void injectListOps(DoipMessage doipMessage, + DoipMessageFactory.DoipMessageBuilder builder) { builder.setDoipMessage(handleListOps(doipMessage)); } @Override public void injectUpdate(DoipMessage request, DoipMessageFactory.DoipMessageBuilder builder) { - // use default behavior + // use default behavior } @Override - public void injectRetrieve(DoipMessage doipMessage, DoipMessageFactory.DoipMessageBuilder builder) { + public void injectRetrieve(DoipMessage doipMessage, + DoipMessageFactory.DoipMessageBuilder builder) { builder.setDoipMessage(handleRetrieve(doipMessage)); } @Override - public void injectDelete(DoipMessage doipMessage, DoipMessageFactory.DoipMessageBuilder builder) { + public void injectDelete(DoipMessage doipMessage, + DoipMessageFactory.DoipMessageBuilder builder) { builder.setDoipMessage(handleDelete(doipMessage)); } } diff --git a/src/main/java/org/bdware/server/doip/ContractRepositoryMain.java b/src/main/java/org/bdware/server/doip/ContractRepositoryMain.java index 4fccc85..2cccdd6 100644 --- a/src/main/java/org/bdware/server/doip/ContractRepositoryMain.java +++ b/src/main/java/org/bdware/server/doip/ContractRepositoryMain.java @@ -34,7 +34,8 @@ public class ContractRepositoryMain { String url = GlobalConf.instance.doaConf.doipAddress; forwarder = new LocalDoipFrowarder(); 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; } if (currentServer != null) { @@ -42,7 +43,8 @@ public class ContractRepositoryMain { } List infos = new ArrayList<>(); 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(); config.publicKey = GlobalConf.instance.keyPair.getPublicKeyStr(); config.privateKey = GlobalConf.instance.keyPair.getPrivateKeyStr(); @@ -55,8 +57,10 @@ public class ContractRepositoryMain { SM2Signer signer = new SM2Signer(SM2KeyPair.fromJson(new Gson().toJson(config))); DelegateDoipHandler delegateHandler = new DelegateDoipHandler(requestCallback) { @Override - protected DoipMessage delegateMessage(ChannelHandlerContext context, DoipMessage message) { - DoipMessageFactory.DoipMessageBuilder builder = new DoipMessageFactory.DoipMessageBuilder(); + protected DoipMessage delegateMessage(ChannelHandlerContext context, + DoipMessage message) { + DoipMessageFactory.DoipMessageBuilder builder = + new DoipMessageFactory.DoipMessageBuilder(); builder.createResponse(DoipResponseCode.DelegateRequired, message); String id = message.header.parameters.id; id = id.replaceAll(".*/", ""); @@ -64,7 +68,7 @@ public class ContractRepositoryMain { if (enableDelegate(meta)) { 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()); DoipMessage ret; ret = builder.create(); diff --git a/src/main/java/org/bdware/server/doip/DelegateDoipHandler.java b/src/main/java/org/bdware/server/doip/DelegateDoipHandler.java index 5da9d76..c9a1460 100644 --- a/src/main/java/org/bdware/server/doip/DelegateDoipHandler.java +++ b/src/main/java/org/bdware/server/doip/DelegateDoipHandler.java @@ -14,9 +14,12 @@ public abstract class DelegateDoipHandler implements DoipRequestHandler { public DoipMessage onRequest(ChannelHandlerContext context, DoipMessage doipMessage) { if (accept(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); } diff --git a/src/main/java/org/bdware/server/doip/LocalDoipFrowarder.java b/src/main/java/org/bdware/server/doip/LocalDoipFrowarder.java index 5820f47..4ac3066 100644 --- a/src/main/java/org/bdware/server/doip/LocalDoipFrowarder.java +++ b/src/main/java/org/bdware/server/doip/LocalDoipFrowarder.java @@ -27,10 +27,12 @@ public class LocalDoipFrowarder { connection = connections.get(meta.contract.getDoipPort()); } else { 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); } - if (!connection.isConnected()) connection.reconnect(); + if (!connection.isConnected()) + connection.reconnect(); DoipMessage[] result = new DoipMessage[1]; connection.sendRawMessage(message, new DoipMessageCallback() { @Override @@ -49,7 +51,8 @@ public class LocalDoipFrowarder { } catch (Exception e) { ByteArrayOutputStream bo = new ByteArrayOutputStream(); e.printStackTrace(new PrintStream(bo)); - DoipMessageFactory.DoipMessageBuilder builder = new DoipMessageFactory.DoipMessageBuilder(); + DoipMessageFactory.DoipMessageBuilder builder = + new DoipMessageFactory.DoipMessageBuilder(); builder.createResponse(DoipResponseCode.UnKnownError, message); builder.setBody(bo.toByteArray()); return builder.create(); diff --git a/src/main/java/org/bdware/server/executor/consistency/PBFTExecutor.java b/src/main/java/org/bdware/server/executor/consistency/PBFTExecutor.java index 76d254c..80c7342 100644 --- a/src/main/java/org/bdware/server/executor/consistency/PBFTExecutor.java +++ b/src/main/java/org/bdware/server/executor/consistency/PBFTExecutor.java @@ -1,375 +1,378 @@ -//package org.bdware.server.executor.consistency; +// package org.bdware.server.executor.consistency; // -//import com.google.gson.JsonObject; -//import com.google.gson.JsonParser; -//import com.google.gson.JsonPrimitive; -//import org.apache.logging.log4j.LogManager; -//import org.apache.logging.log4j.Logger; -//import org.bdware.sc.ComponedContractResult; -//import org.bdware.sc.ContractResult; -//import org.bdware.sc.bean.ContractRequest; -//import org.bdware.sc.conn.Node; -//import org.bdware.sc.conn.OnHashCallback; -//import org.bdware.sc.conn.ResultCallback; -//import org.bdware.sc.consistency.Committer; -//import org.bdware.sc.consistency.pbft.PBFTAlgorithm; -//import org.bdware.sc.consistency.pbft.PBFTMember; -//import org.bdware.sc.consistency.pbft.PBFTMessage; -//import org.bdware.sc.consistency.pbft.PBFTType; -//import org.bdware.sc.units.*; -//import org.bdware.sc.util.JsonUtil; -//import org.bdware.server.GlobalConf; -//import org.bdware.server.action.CMActions; -//import org.bdware.server.action.p2p.MasterServerRecoverMechAction; -//import org.bdware.server.action.p2p.MasterServerTCPAction; -//import org.bdware.server.trustedmodel.ContractCluster; -//import org.bdware.server.trustedmodel.ContractExecutor; -//import org.bdware.server.trustedmodel.MultiReqSeq; -//import org.bdware.server.trustedmodel.ResultCollector; -//import org.bdware.units.NetworkManager; -//import org.zz.gmhelper.SM2KeyPair; +// import com.google.gson.JsonObject; +// import com.google.gson.JsonParser; +// import com.google.gson.JsonPrimitive; +// import org.apache.logging.log4j.LogManager; +// import org.apache.logging.log4j.Logger; +// import org.bdware.sc.ComponedContractResult; +// import org.bdware.sc.ContractResult; +// import org.bdware.sc.bean.ContractRequest; +// import org.bdware.sc.conn.Node; +// import org.bdware.sc.conn.OnHashCallback; +// import org.bdware.sc.conn.ResultCallback; +// import org.bdware.sc.consistency.Committer; +// import org.bdware.sc.consistency.pbft.PBFTAlgorithm; +// import org.bdware.sc.consistency.pbft.PBFTMember; +// import org.bdware.sc.consistency.pbft.PBFTMessage; +// import org.bdware.sc.consistency.pbft.PBFTType; +// import org.bdware.sc.units.*; +// import org.bdware.sc.util.JsonUtil; +// import org.bdware.server.GlobalConf; +// import org.bdware.server.action.CMActions; +// import org.bdware.server.action.p2p.MasterServerRecoverMechAction; +// import org.bdware.server.action.p2p.MasterServerTCPAction; +// import org.bdware.server.trustedmodel.ContractCluster; +// import org.bdware.server.trustedmodel.ContractExecutor; +// import org.bdware.server.trustedmodel.MultiReqSeq; +// import org.bdware.server.trustedmodel.ResultCollector; +// import org.bdware.units.NetworkManager; +// import org.zz.gmhelper.SM2KeyPair; // -//import java.util.*; -//import java.util.concurrent.ConcurrentHashMap; -//import java.util.concurrent.atomic.AtomicInteger; +// import java.util.*; +// import java.util.concurrent.ConcurrentHashMap; +// import java.util.concurrent.atomic.AtomicInteger; // -////TODO 追赶差下的调用 -//public class PBFTExecutor implements ContractExecutor { -// private static final Logger LOGGER = LogManager.getLogger(PBFTExecutor.class); -// final Object lock = new Object(); -// private final List members; -// int resultCount; +//// TODO 追赶差下的调用 +// public class PBFTExecutor implements ContractExecutor { +// private static final Logger LOGGER = LogManager.getLogger(PBFTExecutor.class); +// final Object lock = new Object(); +// private final List members; +// int resultCount; // -// AtomicInteger request_index = new AtomicInteger(0); -// // key为requestID,value为其seq -// Map seqMap = new ConcurrentHashMap<>(); -// Map resultCache = new ConcurrentHashMap<>(); -// // MultiPointContractInfo info; -// String contractID; -// PBFTAlgorithm pbft; -// ContractCluster contractCluster; -// boolean isMaster; +// AtomicInteger request_index = new AtomicInteger(0); +// // key为requestID,value为其seq +// Map seqMap = new ConcurrentHashMap<>(); +// Map resultCache = new ConcurrentHashMap<>(); +// // MultiPointContractInfo info; +// String contractID; +// PBFTAlgorithm pbft; +// ContractCluster contractCluster; +// boolean isMaster; // -// public PBFTExecutor( -// int c, String con_id, final String masterPubkey, String[] members) { -// resultCount = c; -// contractID = con_id; -// this.members = new ArrayList<>(); -// isMaster = GlobalConf.getNodeID().equals(masterPubkey); -// pbft = new PBFTAlgorithm(isMaster); -// int count = 0; -// for (String mem : members) { -// PubKeyNode pubkeyNode = new PubKeyNode(); -// pubkeyNode.pubkey = mem; -// PBFTMember pbftMember = new PBFTMember(); -// pbftMember.isMaster = mem.equals(masterPubkey); -// pbft.addMember(pubkeyNode, pbftMember); -// this.members.add(pubkeyNode); -// if (GlobalConf.getNodeID().equals(mem)) { -// pbft.setSendID(count); -// } -// count++; -// } -// contractCluster = new ContractCluster(contractID, this.members); -// pbft.setConnection(contractCluster); -// final MultiContractMeta cei = CMActions.manager.multiContractRecorder.getMultiContractMeta(contractID); -// pbft.setCommitter(new Committer() { -// @Override -// public void onCommit(ContractRequest data) { -// ResultCallback ret = null; -// final long startTime = System.currentTimeMillis(); -// ret = new ResultCallback() { -// @Override -// public void onResult(String str) { -// Map ret = new HashMap<>(); -// ret.put("action", "receiveTrustfullyResult"); -// SM2KeyPair keyPair = GlobalConf.instance.keyPair; -// ret.put("nodeID", keyPair.getPublicKeyStr()); -// ret.put("responseID", data.getRequestID()); -// ret.put("executeTime", (System.currentTimeMillis() - startTime) + ""); -// ret.put("data", str); -// cei.setLastExeSeq(data.seq); -// NetworkManager.instance.sendToAgent(masterPubkey, JsonUtil.toJson(ret)); -// } -// }; -// CMActions.manager.executeLocallyAsync(data, ret, null); -// } -// }); -// } +// public PBFTExecutor( +// int c, String con_id, final String masterPubkey, String[] members) { +// resultCount = c; +// contractID = con_id; +// this.members = new ArrayList<>(); +// isMaster = GlobalConf.getNodeID().equals(masterPubkey); +// pbft = new PBFTAlgorithm(isMaster); +// int count = 0; +// for (String mem : members) { +// PubKeyNode pubkeyNode = new PubKeyNode(); +// pubkeyNode.pubkey = mem; +// PBFTMember pbftMember = new PBFTMember(); +// pbftMember.isMaster = mem.equals(masterPubkey); +// pbft.addMember(pubkeyNode, pbftMember); +// this.members.add(pubkeyNode); +// if (GlobalConf.getNodeID().equals(mem)) { +// pbft.setSendID(count); +// } +// count++; +// } +// contractCluster = new ContractCluster(contractID, this.members); +// pbft.setConnection(contractCluster); +// final MultiContractMeta cei = +// CMActions.manager.multiContractRecorder.getMultiContractMeta(contractID); +// pbft.setCommitter(new Committer() { +// @Override +// public void onCommit(ContractRequest data) { +// ResultCallback ret = null; +// final long startTime = System.currentTimeMillis(); +// ret = new ResultCallback() { +// @Override +// public void onResult(String str) { +// Map ret = new HashMap<>(); +// ret.put("action", "receiveTrustfullyResult"); +// SM2KeyPair keyPair = GlobalConf.instance.keyPair; +// ret.put("nodeID", keyPair.getPublicKeyStr()); +// ret.put("responseID", data.getRequestID()); +// ret.put("executeTime", (System.currentTimeMillis() - startTime) + ""); +// ret.put("data", str); +// cei.setLastExeSeq(data.seq); +// NetworkManager.instance.sendToAgent(masterPubkey, JsonUtil.toJson(ret)); +// } +// }; +// CMActions.manager.executeLocallyAsync(data, ret, null); +// } +// }); +// } // -// public void onSyncMessage(Node node, byte[] data) { +// public void onSyncMessage(Node node, byte[] data) { // -// pbft.onMessage(node, data); -// } +// pbft.onMessage(node, data); +// } // -// public void setSeq(int seq) { -// request_index = new AtomicInteger(seq); -// pbft.setAtomSeq(request_index.get()); -// } +// public void setSeq(int seq) { +// request_index = new AtomicInteger(seq); +// pbft.setAtomSeq(request_index.get()); +// } // -// public ResultCallback createResultCallback( -// final String requestID, -// final ResultCallback originalCb, -// final int count, -// final int request_seq, -// final String contractID) { -// ComponedContractResult componedContractResult = new ComponedContractResult(count); -// // TODO 加对应的超时? -// return new ResultCollector( -// requestID, new ResultMerger(originalCb, count, request_seq, contractID), count); -// } +// public ResultCallback createResultCallback( +// final String requestID, +// final ResultCallback originalCb, +// final int count, +// final int request_seq, +// final String contractID) { +// ComponedContractResult componedContractResult = new ComponedContractResult(count); +// // TODO 加对应的超时? +// return new ResultCollector( +// requestID, new ResultMerger(originalCb, count, request_seq, contractID), count); +// } // -// public void sendRequest(String id, ContractRequest req, ResultCallback collector) { -//// Map reqStr = new HashMap<>(); -//// reqStr.put("uniReqID", id); -//// reqStr.put("data", req); -//// reqStr.put("action", "executeContractLocally"); -// ContractRequest cr2 = ContractRequest.parse(req.toByte()); -// cr2.setRequestID(id); -// PBFTMessage request = new PBFTMessage(); -// request.setOrder(req.seq); -// request.setType(PBFTType.Request); -// request.setContent(cr2.toByte()); -// for (PubKeyNode node : members) { -// if (!NetworkManager.instance.hasAgentConnection(node.pubkey)) { -// LOGGER.warn("cmNode " + node.pubkey.substring(0, 5) + " is null"); -// collector.onResult( -// "{\"status\":\"Error\",\"result\":\"node offline\"," -// + "\"nodeID\":\"" -// + node -// + "\"," -// + "\"action\":\"onExecuteContractTrustfully\"}"); -//// } else if (MasterServerRecoverMechAction.recoverStatus.get(node).get(contractID) -//// != RecoverFlag.Fine) { -//// collector.onResult( -//// "{\"status\":\"Error\",\"result\":\"node recovering\"," -//// + "\"nodeID\":\"" -//// + node -//// + "\"," -//// + "\"action\":\"onExecuteContractTrustfully\"}"); -//// contractCluster.sendMessage(node, request.getBytes()); -// } else { -// contractCluster.sendMessage(node, request.getBytes()); -// } -// } -// // master负责缓存请求 -// if (!MasterServerTCPAction.requestCache.containsKey(contractID)) { -// MasterServerTCPAction.requestCache.put(contractID, new RequestCache()); -// } -// // TODO 多调多统一个seq的有多个请求,这个需要改 -// String[] nodes = -// CMActions.manager.multiContractRecorder.getMultiContractMeta(contractID).getMembers(); -// LOGGER.info("cluster size=" + nodes.length + " contract " + req.getContractID()); -// LOGGER.debug("contract " + req.getContractID() + " cluster: " + JsonUtil.toJson(nodes)); +// public void sendRequest(String id, ContractRequest req, ResultCallback collector) { +//// Map reqStr = new HashMap<>(); +//// reqStr.put("uniReqID", id); +//// reqStr.put("data", req); +//// reqStr.put("action", "executeContractLocally"); +// ContractRequest cr2 = ContractRequest.parse(req.toByte()); +// cr2.setRequestID(id); +// PBFTMessage request = new PBFTMessage(); +// request.setOrder(req.seq); +// request.setType(PBFTType.Request); +// request.setContent(cr2.toByte()); +// for (PubKeyNode node : members) { +// if (!NetworkManager.instance.hasAgentConnection(node.pubkey)) { +// LOGGER.warn("cmNode " + node.pubkey.substring(0, 5) + " is null"); +// collector.onResult( +// "{\"status\":\"Error\",\"result\":\"node offline\"," +// + "\"nodeID\":\"" +// + node +// + "\"," +// + "\"action\":\"onExecuteContractTrustfully\"}"); +//// } else if (MasterServerRecoverMechAction.recoverStatus.get(node).get(contractID) +//// != RecoverFlag.Fine) { +//// collector.onResult( +//// "{\"status\":\"Error\",\"result\":\"node recovering\"," +//// + "\"nodeID\":\"" +//// + node +//// + "\"," +//// + "\"action\":\"onExecuteContractTrustfully\"}"); +//// contractCluster.sendMessage(node, request.getBytes()); +// } else { +// contractCluster.sendMessage(node, request.getBytes()); +// } +// } +// // master负责缓存请求 +// if (!MasterServerTCPAction.requestCache.containsKey(contractID)) { +// MasterServerTCPAction.requestCache.put(contractID, new RequestCache()); +// } +// // TODO 多调多统一个seq的有多个请求,这个需要改 +// String[] nodes = +// CMActions.manager.multiContractRecorder.getMultiContractMeta(contractID).getMembers(); +// LOGGER.info("cluster size=" + nodes.length + " contract " + req.getContractID()); +// LOGGER.debug("contract " + req.getContractID() + " cluster: " + JsonUtil.toJson(nodes)); // -// } +// } // // -// public boolean checkCurNodeNumValid() { -// return true; -// } +// public boolean checkCurNodeNumValid() { +// return true; +// } // -// @Override -// public void execute(String requestID, ContractRequest req, ResultCallback rc, OnHashCallback hcb) { -// LOGGER.debug(JsonUtil.toJson(req)); -// MultiContractMeta meta = CMActions.manager.multiContractRecorder.getMultiContractMeta(req.getContractID()); -// if (meta == null || !meta.isMaster()) { -// CMActions.manager.executeContractOnOtherNodes(req, rc); -// return; -// } -// req.setContractID(CMActions.manager.getContractIDByName(req.getContractID())); +// @Override +// public void execute(String requestID, ContractRequest req, ResultCallback rc, OnHashCallback hcb) +// { +// LOGGER.debug(JsonUtil.toJson(req)); +// MultiContractMeta meta = +// CMActions.manager.multiContractRecorder.getMultiContractMeta(req.getContractID()); +// if (meta == null || !meta.isMaster()) { +// CMActions.manager.executeContractOnOtherNodes(req, rc); +// return; +// } +// req.setContractID(CMActions.manager.getContractIDByName(req.getContractID())); // -// // 三个相同requestID进来的时候,会有冲突。 -// // 仅在此处有冲突么? -// // 这里是从MasterServer->MasterClient,请求的是"executeContractLocally"。 +// // 三个相同requestID进来的时候,会有冲突。 +// // 仅在此处有冲突么? +// // 这里是从MasterServer->MasterClient,请求的是"executeContractLocally"。 // -// // 如果是多点合约的请求,A1、A2、A3的序号应该一致,不能分配一个新的seq,根据requestID判断是否不需要重新分配一个序号 -// //TODO seqMap memory leak -// //TODO -// //TODO -// if (null != requestID && requestID.endsWith("_mul")) { -// synchronized (lock) { -// if (seqMap.containsKey(requestID)) { -// req.seq = seqMap.get(requestID).seq; -// } else { -// req.seq = request_index.getAndIncrement(); -// seqMap.put(requestID, new MultiReqSeq(req.seq)); -// } -// } -// } else { -// req.seq = request_index.getAndIncrement(); -// } -// req.needSeq = true; -// String id = -// System.currentTimeMillis() + "_" + (int) (Math.random() * 1000000) + "_" + req.seq; -// LOGGER.info("execute receive requestID=" + requestID + " msgID=" + id); +// // 如果是多点合约的请求,A1、A2、A3的序号应该一致,不能分配一个新的seq,根据requestID判断是否不需要重新分配一个序号 +// //TODO seqMap memory leak +// //TODO +// //TODO +// if (null != requestID && requestID.endsWith("_mul")) { +// synchronized (lock) { +// if (seqMap.containsKey(requestID)) { +// req.seq = seqMap.get(requestID).seq; +// } else { +// req.seq = request_index.getAndIncrement(); +// seqMap.put(requestID, new MultiReqSeq(req.seq)); +// } +// } +// } else { +// req.seq = request_index.getAndIncrement(); +// } +// req.needSeq = true; +// String id = +// System.currentTimeMillis() + "_" + (int) (Math.random() * 1000000) + "_" + req.seq; +// LOGGER.info("execute receive requestID=" + requestID + " msgID=" + id); // -// if (checkCurNodeNumValid()) { -// LOGGER.debug("checkCurNodeNumValid=true"); -// ResultCallback collector = -// createResultCallback(id, rc, resultCount, req.seq, req.getContractID()); -// MasterServerTCPAction.sync.sleep(id, collector); -// LOGGER.info("requestID=" + requestID + " master broadcasts request " + req.seq); -// sendRequest(id, req, collector); -// } else { -// LOGGER.debug("invalidNodeNumOnResult"); -// request_index.getAndDecrement(); -// ContractResult finalResult = -// new ContractResult( -// ContractResult.Status.Error, -// new JsonPrimitive("node number unavailable, request refused.")); -// rc.onResult(JsonUtil.toJson(finalResult)); -// } +// if (checkCurNodeNumValid()) { +// LOGGER.debug("checkCurNodeNumValid=true"); +// ResultCallback collector = +// createResultCallback(id, rc, resultCount, req.seq, req.getContractID()); +// MasterServerTCPAction.sync.sleep(id, collector); +// LOGGER.info("requestID=" + requestID + " master broadcasts request " + req.seq); +// sendRequest(id, req, collector); +// } else { +// LOGGER.debug("invalidNodeNumOnResult"); +// request_index.getAndDecrement(); +// ContractResult finalResult = +// new ContractResult( +// ContractResult.Status.Error, +// new JsonPrimitive("node number unavailable, request refused.")); +// rc.onResult(JsonUtil.toJson(finalResult)); +// } // -// // } +// // } // -// /* // 三个相同requestID进来的时候,会有冲突。 -// // 仅在此处有冲突么? -// // 这里是从MasterServer->MasterClient,请求的是"executeContractLocally"。 -// req.seq = request_index.getAndIncrement(); -// req.needSeq = true; -// ResultCallback collector = createResultCallback(id, rc, resultCount, req.getContractID()); -// MasterServerTCPAction.sync.sleep(id, collector); -// sendRequest(id, req, collector);*/ -// } +// /* // 三个相同requestID进来的时候,会有冲突。 +// // 仅在此处有冲突么? +// // 这里是从MasterServer->MasterClient,请求的是"executeContractLocally"。 +// req.seq = request_index.getAndIncrement(); +// req.needSeq = true; +// ResultCallback collector = createResultCallback(id, rc, resultCount, req.getContractID()); +// MasterServerTCPAction.sync.sleep(id, collector); +// sendRequest(id, req, collector);*/ +// } // -// // 清理缓存的多点合约请求序号 -// public void clearCache() { -// final long time = System.currentTimeMillis() - 30000L; -// seqMap.entrySet() -// .removeIf( -// entry -> { -// MultiReqSeq cache = entry.getValue(); -// if (null == cache) { -// return true; -// } -// return cache.startTime < time; -// }); -// } +// // 清理缓存的多点合约请求序号 +// public void clearCache() { +// final long time = System.currentTimeMillis() - 30000L; +// seqMap.entrySet() +// .removeIf( +// entry -> { +// MultiReqSeq cache = entry.getValue(); +// if (null == cache) { +// return true; +// } +// return cache.startTime < time; +// }); +// } // -// public static class ResultMerger extends ResultCallback { -// ComponedContractResult componedContractResult; -// AtomicInteger order; -// String contractID; -// int count; -// int request_seq; -// ResultCallback originalCallback; -// Set nodeIDs = new HashSet<>(); // 已收到返回结果的节点 +// public static class ResultMerger extends ResultCallback { +// ComponedContractResult componedContractResult; +// AtomicInteger order; +// String contractID; +// int count; +// int request_seq; +// ResultCallback originalCallback; +// Set nodeIDs = new HashSet<>(); // 已收到返回结果的节点 // -// ResultMerger( -// final ResultCallback originalCb, -// final int count, -// final int request_seq, -// final String contractID) { -// originalCallback = originalCb; -// this.count = count; -// this.request_seq = request_seq; -// this.contractID = contractID; -// componedContractResult = new ComponedContractResult(count); -// order = new AtomicInteger(0); -// } +// ResultMerger( +// final ResultCallback originalCb, +// final int count, +// final int request_seq, +// final String contractID) { +// originalCallback = originalCb; +// this.count = count; +// this.request_seq = request_seq; +// this.contractID = contractID; +// componedContractResult = new ComponedContractResult(count); +// order = new AtomicInteger(0); +// } // -// public String getContractID() { -// return contractID; -// } +// public String getContractID() { +// return contractID; +// } // -// public String getInfo() { -// return "contractID=" -// + contractID -// + " 收到第 " -// + order -// + " 个节点回复 : " -// + " order=" -// + order -// + " count=" -// + count -// + " "; -// } +// public String getInfo() { +// return "contractID=" +// + contractID +// + " 收到第 " +// + order +// + " 个节点回复 : " +// + " order=" +// + order +// + " count=" +// + count +// + " "; +// } // -// @Override -// public void onResult(String str) { -// // TODO 必须在这里聚合。 -// // str的data是个ContractResult -// // 在这儿也是返回个ContractResult -// try { -// LOGGER.debug("a result of contract" + contractID + ": " + str); -// JsonObject obj = JsonParser.parseString(str).getAsJsonObject(); -// if (obj.has("nodeID")) { -// String id = obj.get("nodeID").getAsString(); -// if (nodeIDs.contains(id)) { -// LOGGER.debug( -// "ignored result because the result of node " -// + id.substring(0, 5) -// + " has been received"); -// return; -// } -// nodeIDs.add(id); -// } +// @Override +// public void onResult(String str) { +// // TODO 必须在这里聚合。 +// // str的data是个ContractResult +// // 在这儿也是返回个ContractResult +// try { +// LOGGER.debug("a result of contract" + contractID + ": " + str); +// JsonObject obj = JsonParser.parseString(str).getAsJsonObject(); +// if (obj.has("nodeID")) { +// String id = obj.get("nodeID").getAsString(); +// if (nodeIDs.contains(id)) { +// LOGGER.debug( +// "ignored result because the result of node " +// + id.substring(0, 5) +// + " has been received"); +// return; +// } +// nodeIDs.add(id); +// } // -// LOGGER.debug( -// String.format( -// "contractID=%s received=%s order=%d count=%d", -// contractID, str, order.get(), count)); -// componedContractResult.add(obj); -// // 收集到所有结果 -// if (order.incrementAndGet() == count) { -// ContractResult finalResult = componedContractResult.figureFinalResult(); -// finalResult.needSeq = true; -// finalResult.seq = request_seq; +// LOGGER.debug( +// String.format( +// "contractID=%s received=%s order=%d count=%d", +// contractID, str, order.get(), count)); +// componedContractResult.add(obj); +// // 收集到所有结果 +// if (order.incrementAndGet() == count) { +// ContractResult finalResult = componedContractResult.figureFinalResult(); +// finalResult.needSeq = true; +// finalResult.seq = request_seq; // -// // if (null == finalResult) { -// // finalResult = -// // new ContractResult( -// // ContractResult.Status.Exception, -// // new JsonPrimitive( -// // "no nore than half of the -// // consistent result")); -// // originalCallback.onResult(new -// // Gson().toJson(finalResult)); -// // } else { -// originalCallback.onResult(JsonUtil.toJson(finalResult)); -// // } -// LOGGER.debug( -// String.format( -// "%d results are the same: %s", -// finalResult.size, finalResult.result)); +// // if (null == finalResult) { +// // finalResult = +// // new ContractResult( +// // ContractResult.Status.Exception, +// // new JsonPrimitive( +// // "no nore than half of the +// // consistent result")); +// // originalCallback.onResult(new +// // Gson().toJson(finalResult)); +// // } else { +// originalCallback.onResult(JsonUtil.toJson(finalResult)); +// // } +// LOGGER.debug( +// String.format( +// "%d results are the same: %s", +// finalResult.size, finalResult.result)); // -// // 集群中事务序号+1 -// CMActions.manager.multiContractRecorder -// .getMultiContractMeta(contractID) -// .nextSeqAtMaster(); +// // 集群中事务序号+1 +// CMActions.manager.multiContractRecorder +// .getMultiContractMeta(contractID) +// .nextSeqAtMaster(); // -// // recover,其中无状态合约CP出错无需恢复 -// Set nodesID = componedContractResult.getProblemNodes(); -// if (null == nodesID || nodesID.isEmpty()) { -// return; -// } -// for (String nodeID : nodesID) { -// LOGGER.warn("node fails! " + nodeID); -// if (MasterServerRecoverMechAction.recoverStatus.get(nodeID).get(contractID) -// == RecoverFlag.Fine) { -// MasterServerRecoverMechAction.recoverStatus -// .get(nodeID) -// .put(contractID, RecoverFlag.ToRecover); -// } -// } -// for (String nodeID : nodesID) { -// if (MasterServerRecoverMechAction.recoverStatus.get(nodeID).get(contractID) -// == RecoverFlag.ToRecover) { -// LOGGER.warn("node in recover " + nodeID); +// // recover,其中无状态合约CP出错无需恢复 +// Set nodesID = componedContractResult.getProblemNodes(); +// if (null == nodesID || nodesID.isEmpty()) { +// return; +// } +// for (String nodeID : nodesID) { +// LOGGER.warn("node fails! " + nodeID); +// if (MasterServerRecoverMechAction.recoverStatus.get(nodeID).get(contractID) +// == RecoverFlag.Fine) { +// MasterServerRecoverMechAction.recoverStatus +// .get(nodeID) +// .put(contractID, RecoverFlag.ToRecover); +// } +// } +// for (String nodeID : nodesID) { +// if (MasterServerRecoverMechAction.recoverStatus.get(nodeID).get(contractID) +// == RecoverFlag.ToRecover) { +// LOGGER.warn("node in recover " + nodeID); // -// // 因为该节点结果有误,所以即时是stableMode也认为trans记录不可信 -// // 直接通过load别的节点来恢复 -// MasterServerRecoverMechAction.restartContractFromCommonMode( -// nodeID, contractID); -// } -// } -// } -// // clearCache(); -// } catch (Exception e) { -// e.printStackTrace(); -// LOGGER.warn("result exception!"); -// } -// } -// } -//} +// // 因为该节点结果有误,所以即时是stableMode也认为trans记录不可信 +// // 直接通过load别的节点来恢复 +// MasterServerRecoverMechAction.restartContractFromCommonMode( +// nodeID, contractID); +// } +// } +// } +// // clearCache(); +// } catch (Exception e) { +// e.printStackTrace(); +// LOGGER.warn("result exception!"); +// } +// } +// } +// } diff --git a/src/main/java/org/bdware/server/executor/consistency/RequestAllExecutor.java b/src/main/java/org/bdware/server/executor/consistency/RequestAllExecutor.java index ab217c6..fde3ca3 100644 --- a/src/main/java/org/bdware/server/executor/consistency/RequestAllExecutor.java +++ b/src/main/java/org/bdware/server/executor/consistency/RequestAllExecutor.java @@ -40,11 +40,10 @@ public class RequestAllExecutor implements ContractExecutor { // key为requestID,value为其seq Map seqMap = new ConcurrentHashMap<>(); Map resultCache = new ConcurrentHashMap<>(); - // MultiPointContractInfo info; + // MultiPointContractInfo info; String contractID; - public RequestAllExecutor( - ContractExecType t, int c, String con_id) { + public RequestAllExecutor(ContractExecType t, int c, String con_id) { type = t; resultCount = c; contractID = con_id; @@ -54,16 +53,13 @@ public class RequestAllExecutor implements ContractExecutor { request_index = new AtomicInteger(seq); } - public ResultCallback createResultCallback( - final String requestID, - final ResultCallback originalCb, - final int count, - final int request_seq, + public ResultCallback createResultCallback(final String requestID, + final ResultCallback originalCb, final int count, final int request_seq, final String contractID) { ComponedContractResult componedContractResult = new ComponedContractResult(count); // TODO 加对应的超时? - return new ResultCollector( - requestID, new ResultMerger(originalCb, count, request_seq, contractID), count); + return new ResultCollector(requestID, + new ResultMerger(originalCb, count, request_seq, contractID), count); } public void sendRequest(String id, ContractRequest req, ResultCallback collector) { @@ -82,8 +78,8 @@ public class RequestAllExecutor implements ContractExecutor { LOGGER.debug(JsonUtil.toJson(req)); - String[] nodes = - CMActions.manager.multiContractRecorder.getMultiContractMeta(contractID).getMembers(); + String[] nodes = CMActions.manager.multiContractRecorder.getMultiContractMeta(contractID) + .getMembers(); LOGGER.info("cluster size=" + nodes.length + " contract " + req.getContractID()); LOGGER.debug("contract " + req.getContractID() + " cluster: " + JsonUtil.toJson(nodes)); for (String node : nodes) { @@ -91,19 +87,13 @@ public class RequestAllExecutor implements ContractExecutor { if (!NetworkManager.instance.hasAgentConnection(node)) { LOGGER.warn("cmNode " + node.substring(0, 5) + " is null"); collector.onResult( - "{\"status\":\"Error\",\"result\":\"node offline\"," - + "\"nodeID\":\"" - + node - + "\"," - + "\"action\":\"onExecuteContractTrustfully\"}"); - } else if (MasterServerRecoverMechAction.recoverStatus.get(node).get(contractID) - != RecoverFlag.Fine) { + "{\"status\":\"Error\",\"result\":\"node offline\"," + "\"nodeID\":\"" + + node + "\"," + "\"action\":\"onExecuteContractTrustfully\"}"); + } else if (MasterServerRecoverMechAction.recoverStatus.get(node) + .get(contractID) != RecoverFlag.Fine) { collector.onResult( - "{\"status\":\"Error\",\"result\":\"node recovering\"," - + "\"nodeID\":\"" - + node - + "\"," - + "\"action\":\"onExecuteContractTrustfully\"}"); + "{\"status\":\"Error\",\"result\":\"node recovering\"," + "\"nodeID\":\"" + + node + "\"," + "\"action\":\"onExecuteContractTrustfully\"}"); NetworkManager.instance.sendToAgent(node, sendStr); } else { LOGGER.info("send request to cmNode " + node.substring(0, 5)); @@ -113,16 +103,17 @@ public class RequestAllExecutor implements ContractExecutor { } public boolean checkCurNodeNumValid() { - String[] nodes = - CMActions.manager.multiContractRecorder.getMultiContractMeta(contractID).getMembers(); + String[] nodes = CMActions.manager.multiContractRecorder.getMultiContractMeta(contractID) + .getMembers(); int validNode = 0; Map mapResult = new HashMap<>(); for (String node : nodes) { - mapResult.put(node.substring(0, 5), String.format("%s %s", NetworkManager.instance.hasAgentConnection(node) + "", - MasterServerRecoverMechAction.recoverStatus.get(node).get(contractID))); + mapResult.put(node.substring(0, 5), + String.format("%s %s", NetworkManager.instance.hasAgentConnection(node) + "", + MasterServerRecoverMechAction.recoverStatus.get(node).get(contractID))); if (NetworkManager.instance.hasAgentConnection(node) - && MasterServerRecoverMechAction.recoverStatus.get(node).get(contractID) - == RecoverFlag.Fine) { + && MasterServerRecoverMechAction.recoverStatus.get(node) + .get(contractID) == RecoverFlag.Fine) { validNode++; } } @@ -136,9 +127,11 @@ public class RequestAllExecutor implements ContractExecutor { } @Override - public void execute(String requestID, ContractRequest req, ResultCallback rc, OnHashCallback hcb) { + public void execute(String requestID, ContractRequest req, ResultCallback rc, + OnHashCallback hcb) { LOGGER.debug(JsonUtil.toJson(req)); - MultiContractMeta meta = CMActions.manager.multiContractRecorder.getMultiContractMeta(req.getContractID()); + MultiContractMeta meta = + CMActions.manager.multiContractRecorder.getMultiContractMeta(req.getContractID()); if (meta == null || !meta.isMaster()) { CMActions.manager.executeContractOnOtherNodes(req, rc); return; @@ -150,9 +143,9 @@ public class RequestAllExecutor implements ContractExecutor { // 这里是从MasterServer->MasterClient,请求的是"executeContractLocally"。 // 如果是多点合约的请求,A1、A2、A3的序号应该一致,不能分配一个新的seq,根据requestID判断是否不需要重新分配一个序号 - //TODO seqMap memory leak - //TODO - //TODO + // TODO seqMap memory leak + // TODO + // TODO if (null != requestID && requestID.endsWith("_mul")) { synchronized (lock) { if (seqMap.containsKey(requestID)) { @@ -180,37 +173,32 @@ public class RequestAllExecutor implements ContractExecutor { } else { LOGGER.debug("invalidNodeNumOnResult"); request_index.getAndDecrement(); - ContractResult finalResult = - new ContractResult( - ContractResult.Status.Error, - new JsonPrimitive("node number unavailable, request refused.")); + ContractResult finalResult = new ContractResult(ContractResult.Status.Error, + new JsonPrimitive("node number unavailable, request refused.")); rc.onResult(JsonUtil.toJson(finalResult)); } // } - /* // 三个相同requestID进来的时候,会有冲突。 - // 仅在此处有冲突么? - // 这里是从MasterServer->MasterClient,请求的是"executeContractLocally"。 - req.seq = request_index.getAndIncrement(); - req.needSeq = true; - ResultCallback collector = createResultCallback(id, rc, resultCount, req.getContractID()); - MasterServerTCPAction.sync.sleep(id, collector); - sendRequest(id, req, collector);*/ + /* + * // 三个相同requestID进来的时候,会有冲突。 // 仅在此处有冲突么? // + * 这里是从MasterServer->MasterClient,请求的是"executeContractLocally"。 req.seq = + * request_index.getAndIncrement(); req.needSeq = true; ResultCallback collector = + * createResultCallback(id, rc, resultCount, req.getContractID()); + * MasterServerTCPAction.sync.sleep(id, collector); sendRequest(id, req, collector); + */ } // 清理缓存的多点合约请求序号 public void clearCache() { final long time = System.currentTimeMillis() - 30000L; - seqMap.entrySet() - .removeIf( - entry -> { - MultiReqSeq cache = entry.getValue(); - if (null == cache) { - return true; - } - return cache.startTime < time; - }); + seqMap.entrySet().removeIf(entry -> { + MultiReqSeq cache = entry.getValue(); + if (null == cache) { + return true; + } + return cache.startTime < time; + }); } public static class ResultMerger extends ResultCallback { @@ -222,10 +210,7 @@ public class RequestAllExecutor implements ContractExecutor { ResultCallback originalCallback; Set nodeIDs = new HashSet<>(); // 已收到返回结果的节点 - ResultMerger( - final ResultCallback originalCb, - final int count, - final int request_seq, + ResultMerger(final ResultCallback originalCb, final int count, final int request_seq, final String contractID) { originalCallback = originalCb; this.count = count; @@ -240,16 +225,8 @@ public class RequestAllExecutor implements ContractExecutor { } public String getInfo() { - return "contractID=" - + contractID - + " 收到第 " - + order - + " 个节点回复 : " - + " order=" - + order - + " count=" - + count - + " "; + return "contractID=" + contractID + " 收到第 " + order + " 个节点回复 : " + " order=" + order + + " count=" + count + " "; } @Override @@ -263,19 +240,15 @@ public class RequestAllExecutor implements ContractExecutor { if (obj.has("nodeID")) { String id = obj.get("nodeID").getAsString(); if (nodeIDs.contains(id)) { - LOGGER.debug( - "ignored result because the result of node " - + id.substring(0, 5) - + " has been received"); + LOGGER.debug("ignored result because the result of node " + + id.substring(0, 5) + " has been received"); return; } nodeIDs.add(id); } - LOGGER.debug( - String.format( - "contractID=%s received=%s order=%d count=%d", - contractID, str, order.get(), count)); + LOGGER.debug(String.format("contractID=%s received=%s order=%d count=%d", + contractID, str, order.get(), count)); componedContractResult.add(obj); // 收集到所有结果 if (order.incrementAndGet() == count) { @@ -283,26 +256,23 @@ public class RequestAllExecutor implements ContractExecutor { finalResult.needSeq = true; finalResult.seq = request_seq; - // if (null == finalResult) { - // finalResult = - // new ContractResult( - // ContractResult.Status.Exception, - // new JsonPrimitive( - // "no nore than half of the + // if (null == finalResult) { + // finalResult = + // new ContractResult( + // ContractResult.Status.Exception, + // new JsonPrimitive( + // "no nore than half of the // consistent result")); - // originalCallback.onResult(new + // originalCallback.onResult(new // Gson().toJson(finalResult)); - // } else { + // } else { originalCallback.onResult(JsonUtil.toJson(finalResult)); - // } - LOGGER.debug( - String.format( - "%d results are the same: %s", - finalResult.size, finalResult.result)); + // } + LOGGER.debug(String.format("%d results are the same: %s", finalResult.size, + finalResult.result)); // 集群中事务序号+1 - CMActions.manager.multiContractRecorder - .getMultiContractMeta(contractID) + CMActions.manager.multiContractRecorder.getMultiContractMeta(contractID) .nextSeqAtMaster(); // recover,其中无状态合约CP出错无需恢复 @@ -312,26 +282,25 @@ public class RequestAllExecutor implements ContractExecutor { } for (String nodeID : nodesID) { LOGGER.warn("node fails! " + nodeID); - if (MasterServerRecoverMechAction.recoverStatus.get(nodeID).get(contractID) - == RecoverFlag.Fine) { - MasterServerRecoverMechAction.recoverStatus - .get(nodeID) - .put(contractID, RecoverFlag.ToRecover); + if (MasterServerRecoverMechAction.recoverStatus.get(nodeID) + .get(contractID) == RecoverFlag.Fine) { + MasterServerRecoverMechAction.recoverStatus.get(nodeID).put(contractID, + RecoverFlag.ToRecover); } } for (String nodeID : nodesID) { - if (MasterServerRecoverMechAction.recoverStatus.get(nodeID).get(contractID) - == RecoverFlag.ToRecover) { + if (MasterServerRecoverMechAction.recoverStatus.get(nodeID) + .get(contractID) == RecoverFlag.ToRecover) { LOGGER.warn("node in recover " + nodeID); // 因为该节点结果有误,所以即时是stableMode也认为trans记录不可信 // 直接通过load别的节点来恢复 - MasterServerRecoverMechAction.restartContractFromCommonMode( - nodeID, contractID); + MasterServerRecoverMechAction.restartContractFromCommonMode(nodeID, + contractID); } } } - // clearCache(); + // clearCache(); } catch (Exception e) { e.printStackTrace(); LOGGER.warn("result exception!"); diff --git a/src/main/java/org/bdware/server/executor/unconsistency/MultiPointCooperationExecutor.java b/src/main/java/org/bdware/server/executor/unconsistency/MultiPointCooperationExecutor.java index e487116..e6810d2 100644 --- a/src/main/java/org/bdware/server/executor/unconsistency/MultiPointCooperationExecutor.java +++ b/src/main/java/org/bdware/server/executor/unconsistency/MultiPointCooperationExecutor.java @@ -1,400 +1,403 @@ -//package org.bdware.server.executor.unconsistency; +// package org.bdware.server.executor.unconsistency; // -//import com.google.gson.JsonObject; -//import com.google.gson.JsonParser; -//import com.google.gson.JsonPrimitive; -//import org.apache.logging.log4j.LogManager; -//import org.apache.logging.log4j.Logger; -//import org.bdware.sc.ComponedContractResult; -//import org.bdware.sc.ContractMeta; -//import org.bdware.sc.ContractResult; -//import org.bdware.sc.bean.*; -//import org.bdware.sc.conn.OnHashCallback; -//import org.bdware.sc.conn.ResultCallback; -//import org.bdware.sc.units.MultiContractMeta; -//import org.bdware.sc.units.RecoverFlag; -//import org.bdware.sc.units.RequestCache; -//import org.bdware.sc.units.ResultCache; -//import org.bdware.sc.util.JsonUtil; -//import org.bdware.server.action.CMActions; -//import org.bdware.server.action.p2p.MasterServerRecoverMechAction; -//import org.bdware.server.action.p2p.MasterServerTCPAction; -//import org.bdware.server.trustedmodel.ContractExecutor; -//import org.bdware.server.trustedmodel.MultiReqSeq; -//import org.bdware.server.trustedmodel.ResultCollector; -//import org.bdware.units.NetworkManager; +// import com.google.gson.JsonObject; +// import com.google.gson.JsonParser; +// import com.google.gson.JsonPrimitive; +// import org.apache.logging.log4j.LogManager; +// import org.apache.logging.log4j.Logger; +// import org.bdware.sc.ComponedContractResult; +// import org.bdware.sc.ContractMeta; +// import org.bdware.sc.ContractResult; +// import org.bdware.sc.bean.*; +// import org.bdware.sc.conn.OnHashCallback; +// import org.bdware.sc.conn.ResultCallback; +// import org.bdware.sc.units.MultiContractMeta; +// import org.bdware.sc.units.RecoverFlag; +// import org.bdware.sc.units.RequestCache; +// import org.bdware.sc.units.ResultCache; +// import org.bdware.sc.util.JsonUtil; +// import org.bdware.server.action.CMActions; +// import org.bdware.server.action.p2p.MasterServerRecoverMechAction; +// import org.bdware.server.action.p2p.MasterServerTCPAction; +// import org.bdware.server.trustedmodel.ContractExecutor; +// import org.bdware.server.trustedmodel.MultiReqSeq; +// import org.bdware.server.trustedmodel.ResultCollector; +// import org.bdware.units.NetworkManager; // -//import java.math.BigInteger; -//import java.util.HashMap; -//import java.util.HashSet; -//import java.util.Map; -//import java.util.Set; -//import java.util.concurrent.ConcurrentHashMap; -//import java.util.concurrent.atomic.AtomicInteger; +// import java.math.BigInteger; +// import java.util.HashMap; +// import java.util.HashSet; +// import java.util.Map; +// import java.util.Set; +// import java.util.concurrent.ConcurrentHashMap; +// import java.util.concurrent.atomic.AtomicInteger; // //// 改为MultiPointCooperationExecutor -//public class MultiPointCooperationExecutor implements ContractExecutor { -// private static final Logger LOGGER = LogManager.getLogger(MultiPointCooperationExecutor.class); -// final Object lock = new Object(); -// int resultCount; -// AtomicInteger request_index = new AtomicInteger(0); -// ContractExecType type; -// // key为requestID,value为其seq -// Map seqMap = new ConcurrentHashMap<>(); -// Map resultCache = new ConcurrentHashMap<>(); -// // MultiPointContractInfo info; -// MultiContractMeta multiMeta; -// String contractID; +// public class MultiPointCooperationExecutor implements ContractExecutor { +// private static final Logger LOGGER = LogManager.getLogger(MultiPointCooperationExecutor.class); +// final Object lock = new Object(); +// int resultCount; +// AtomicInteger request_index = new AtomicInteger(0); +// ContractExecType type; +// // key为requestID,value为其seq +// Map seqMap = new ConcurrentHashMap<>(); +// Map resultCache = new ConcurrentHashMap<>(); +// // MultiPointContractInfo info; +// MultiContractMeta multiMeta; +// String contractID; // -// public MultiPointCooperationExecutor(ContractExecType t, int c, String con_id) { -// LOGGER.info("-- sharding executor---"); -// type = t; -// resultCount = c; -// contractID = con_id; -// multiMeta = CMActions.manager.multiContractRecorder.getMultiContractMeta(contractID); -// } +// public MultiPointCooperationExecutor(ContractExecType t, int c, String con_id) { +// LOGGER.info("-- sharding executor---"); +// type = t; +// resultCount = c; +// contractID = con_id; +// multiMeta = CMActions.manager.multiContractRecorder.getMultiContractMeta(contractID); +// } // -// public void setSeq(int seq) { -// request_index = new AtomicInteger(seq); -// } +// public void setSeq(int seq) { +// request_index = new AtomicInteger(seq); +// } // -// public ResultCallback createResultCallback( -// final String requestID, -// final ResultCallback originalCb, -// final int count, -// final int request_seq, -// final String contractID, JoinInfo joinInfo) { -// // TODO 加对应的超时? -// return new ResultCollector( -// requestID, -// new MultiPointCooperationExecutor.ResultMerger(originalCb, count, request_seq, contractID, joinInfo), -// count); // 把count改成了1,设置成获得1个响应就行 -// } +// public ResultCallback createResultCallback( +// final String requestID, +// final ResultCallback originalCb, +// final int count, +// final int request_seq, +// final String contractID, JoinInfo joinInfo) { +// // TODO 加对应的超时? +// return new ResultCollector( +// requestID, +// new MultiPointCooperationExecutor.ResultMerger(originalCb, count, request_seq, contractID, +// joinInfo), +// count); // 把count改成了1,设置成获得1个响应就行 +// } // -// public void sendRequest(String id, ContractRequest req, String[] nodes) { -// Map reqStr = new HashMap<>(); -// reqStr.put("uniReqID", id); -// reqStr.put("data", req); -// req.needSeq = false; -// reqStr.put("action", "executeContractLocally"); -// String sendStr = JsonUtil.toJson(reqStr); -// // master负责缓存请求 -// if (!MasterServerTCPAction.requestCache.containsKey(contractID)) { -// MasterServerTCPAction.requestCache.put(contractID, new RequestCache()); -// } -// // TODO 多调多统一个seq的有多个请求,这个需要改 -// MasterServerTCPAction.requestCache.get(contractID).put(req.seq, sendStr); -// LOGGER.debug(JsonUtil.toJson(req)); -// LOGGER.info("node size = " + nodes.length); -// LOGGER.debug("nodes:" + JsonUtil.toJson(nodes)); -// for (String node : nodes) { -// LOGGER.info( -// "[sendRequests] get cmNode " -// + node.substring(0, 5) -// + " not null " -// + "RequestAllExecutor 发送请求给 " -// + node.substring(0, 5)); -// NetworkManager.instance.sendToAgent(node, sendStr); -// } -// } +// public void sendRequest(String id, ContractRequest req, String[] nodes) { +// Map reqStr = new HashMap<>(); +// reqStr.put("uniReqID", id); +// reqStr.put("data", req); +// req.needSeq = false; +// reqStr.put("action", "executeContractLocally"); +// String sendStr = JsonUtil.toJson(reqStr); +// // master负责缓存请求 +// if (!MasterServerTCPAction.requestCache.containsKey(contractID)) { +// MasterServerTCPAction.requestCache.put(contractID, new RequestCache()); +// } +// // TODO 多调多统一个seq的有多个请求,这个需要改 +// MasterServerTCPAction.requestCache.get(contractID).put(req.seq, sendStr); +// LOGGER.debug(JsonUtil.toJson(req)); +// LOGGER.info("node size = " + nodes.length); +// LOGGER.debug("nodes:" + JsonUtil.toJson(nodes)); +// for (String node : nodes) { +// LOGGER.info( +// "[sendRequests] get cmNode " +// + node.substring(0, 5) +// + " not null " +// + "RequestAllExecutor 发送请求给 " +// + node.substring(0, 5)); +// NetworkManager.instance.sendToAgent(node, sendStr); +// } +// } // -// private String[] getAccordingToRouteInfo(RouteInfo routeInfo, ContractRequest req, String[] members) { -// try { -// int val; -// switch (routeInfo.useDefault) { -// case byRequester: -// val = -// new BigInteger(req.getRequester(), 16) -// .mod(new BigInteger("" + members.length)) -// .intValue(); -// while (val < 0) { -// val = val + members.length; -// } -// return new String[]{members[val]}; -// case byArgHash: -// val = req.getArg().hashCode(); -// val = val % members.length; -// while (val < 0) { -// val += members.length; -// } -// return new String[]{members[val]}; -// case byTarget: -// JsonObject jo = req.getArg().getAsJsonObject(); -// val = -// new BigInteger(jo.get("target").getAsString(), 16) -// .mod(new BigInteger("" + members.length)) -// .intValue(); -// while (val < 0) { -// val = val + members.length; -// } -// return new String[]{members[val]}; -// default: -// return members; -// } -// } catch (Exception e) { -// return members; -// } -// } +// private String[] getAccordingToRouteInfo(RouteInfo routeInfo, ContractRequest req, String[] +// members) { +// try { +// int val; +// switch (routeInfo.useDefault) { +// case byRequester: +// val = +// new BigInteger(req.getRequester(), 16) +// .mod(new BigInteger("" + members.length)) +// .intValue(); +// while (val < 0) { +// val = val + members.length; +// } +// return new String[]{members[val]}; +// case byArgHash: +// val = req.getArg().hashCode(); +// val = val % members.length; +// while (val < 0) { +// val += members.length; +// } +// return new String[]{members[val]}; +// case byTarget: +// JsonObject jo = req.getArg().getAsJsonObject(); +// val = +// new BigInteger(jo.get("target").getAsString(), 16) +// .mod(new BigInteger("" + members.length)) +// .intValue(); +// while (val < 0) { +// val = val + members.length; +// } +// return new String[]{members[val]}; +// default: +// return members; +// } +// } catch (Exception e) { +// return members; +// } +// } // -// public boolean checkCurNodeNumValid() { -// LOGGER.info("checkCurNodeNumValid"); -// String[] nodes = multiMeta.getMembers(); -// // List nodes = info.members; -// int validNode = 0; -// for (String node : nodes) { -// if (NetworkManager.instance.hasAgentConnection(node) -// && MasterServerRecoverMechAction.recoverStatus.get(node).get(contractID) -// == RecoverFlag.Fine) { -// validNode++; -// } -// } -// int c = resultCount; -// if (type == ContractExecType.Sharding) c = (int) Math.ceil((double) c / 2); -// LOGGER.info("c=" + c + " validNode=" + validNode); -// return validNode >= c; -// } +// public boolean checkCurNodeNumValid() { +// LOGGER.info("checkCurNodeNumValid"); +// String[] nodes = multiMeta.getMembers(); +// // List nodes = info.members; +// int validNode = 0; +// for (String node : nodes) { +// if (NetworkManager.instance.hasAgentConnection(node) +// && MasterServerRecoverMechAction.recoverStatus.get(node).get(contractID) +// == RecoverFlag.Fine) { +// validNode++; +// } +// } +// int c = resultCount; +// if (type == ContractExecType.Sharding) c = (int) Math.ceil((double) c / 2); +// LOGGER.info("c=" + c + " validNode=" + validNode); +// return validNode >= c; +// } // -// @Override -// public void execute(String requestID, ContractRequest req, ResultCallback rc, OnHashCallback hcb) { -// LOGGER.info("[MultiPointCooperationExecutor] execute " + JsonUtil.toJson(req)); -// // 获得action 函数名 -// LOGGER.info("action is : " + req.getAction()); -// req.setContractID(CMActions.manager.getContractIDByName(req.getContractID())); -// if (requestID != null && requestID.endsWith("_mul")) { -// synchronized (lock) { -// if (seqMap.containsKey(requestID)) { -// req.seq = seqMap.get(requestID).seq; -// } else { -// req.seq = request_index.getAndIncrement(); -// seqMap.put(requestID, new MultiReqSeq(req.seq)); -// } -// } -// } else { -// req.seq = request_index.getAndIncrement(); -// } -// req.needSeq = true; -// String id = -// System.currentTimeMillis() + "_" + (int) (Math.random() * 1000000) + "_" + req.seq; -// LOGGER.info("execute receive requestID= " + requestID + " msgID=" + id); -// if (checkCurNodeNumValid()) { // 校验成功 current node num 合法 -// LOGGER.info("checkCurNodeNumValid true"); -// ContractMeta meta = -// CMActions.manager.statusRecorder.getContractMeta(req.getContractID()); -// FunctionDesp fun = meta.getExportedFunction(req.getAction()); -// ResultCallback collector; -// // TODO @fanbo 下面的count 1要改,应该是根据route的规则来。 -// //Count 根据join规则来。 -// //nodes 根据route规则来。 -// JoinInfo joinInfo = fun.joinInfo; -// RouteInfo routeInfo = fun.routeInfo; -// int count = getJoinCount(joinInfo, contractID); -// LOGGER.info("requestID=" + requestID + " join Count: " + count); +// @Override +// public void execute(String requestID, ContractRequest req, ResultCallback rc, OnHashCallback hcb) +// { +// LOGGER.info("[MultiPointCooperationExecutor] execute " + JsonUtil.toJson(req)); +// // 获得action 函数名 +// LOGGER.info("action is : " + req.getAction()); +// req.setContractID(CMActions.manager.getContractIDByName(req.getContractID())); +// if (requestID != null && requestID.endsWith("_mul")) { +// synchronized (lock) { +// if (seqMap.containsKey(requestID)) { +// req.seq = seqMap.get(requestID).seq; +// } else { +// req.seq = request_index.getAndIncrement(); +// seqMap.put(requestID, new MultiReqSeq(req.seq)); +// } +// } +// } else { +// req.seq = request_index.getAndIncrement(); +// } +// req.needSeq = true; +// String id = +// System.currentTimeMillis() + "_" + (int) (Math.random() * 1000000) + "_" + req.seq; +// LOGGER.info("execute receive requestID= " + requestID + " msgID=" + id); +// if (checkCurNodeNumValid()) { // 校验成功 current node num 合法 +// LOGGER.info("checkCurNodeNumValid true"); +// ContractMeta meta = +// CMActions.manager.statusRecorder.getContractMeta(req.getContractID()); +// FunctionDesp fun = meta.getExportedFunction(req.getAction()); +// ResultCallback collector; +// // TODO @fanbo 下面的count 1要改,应该是根据route的规则来。 +// //Count 根据join规则来。 +// //nodes 根据route规则来。 +// JoinInfo joinInfo = fun.joinInfo; +// RouteInfo routeInfo = fun.routeInfo; +// int count = getJoinCount(joinInfo, contractID); +// LOGGER.info("requestID=" + requestID + " join Count: " + count); // -// String[] members = multiMeta.getMembers(); -// String[] nodes = getAccordingToRouteInfo(routeInfo, req, members); -// if (nodes.length < count) { -// count = nodes.length; -// } -// collector = -// createResultCallback(id, rc, count, req.seq, req.getContractID(), joinInfo); // 初始化结果收集器 -// MasterServerTCPAction.sync.sleep(id, collector); -// LOGGER.info("requestID=" + requestID + " master broadcasts request " + req.seq); -// sendRequest(id, req, nodes); // 发送请求 -// } else { -// LOGGER.info("invalidNodeNumOnResult"); -// request_index.getAndDecrement(); -// ContractResult finalResult = -// new ContractResult( -// ContractResult.Status.Error, -// new JsonPrimitive("node number unavailbale,request refused.")); -// rc.onResult(JsonUtil.toJson(finalResult)); -// } -// } +// String[] members = multiMeta.getMembers(); +// String[] nodes = getAccordingToRouteInfo(routeInfo, req, members); +// if (nodes.length < count) { +// count = nodes.length; +// } +// collector = +// createResultCallback(id, rc, count, req.seq, req.getContractID(), joinInfo); // 初始化结果收集器 +// MasterServerTCPAction.sync.sleep(id, collector); +// LOGGER.info("requestID=" + requestID + " master broadcasts request " + req.seq); +// sendRequest(id, req, nodes); // 发送请求 +// } else { +// LOGGER.info("invalidNodeNumOnResult"); +// request_index.getAndDecrement(); +// ContractResult finalResult = +// new ContractResult( +// ContractResult.Status.Error, +// new JsonPrimitive("node number unavailbale,request refused.")); +// rc.onResult(JsonUtil.toJson(finalResult)); +// } +// } // -// private int getJoinCount(JoinInfo joinInfo, String contractID) { -// if (joinInfo == null) return resultCount; -// if (joinInfo.joinCount.isJsonPrimitive() && joinInfo.joinCount.getAsJsonPrimitive().isNumber()) { -// return joinInfo.joinCount.getAsJsonPrimitive().getAsInt(); -// } -// try { -// ContractRequest cr = new ContractRequest(); -// cr.setContractID(contractID); -// cr.setAction(joinInfo.joinCount.getAsString()); -// //TODO Arg需要好好设计一下。 -// //TODO 又好用又简单的那种设计 -// //TODO -// cr.setArg(""); -// String result = CMActions.manager.executeLocally(cr, null); -// return JsonUtil.parseString(result).getAsJsonObject().get("result").getAsInt(); -// } catch (Exception e) { -// e.printStackTrace(); -// return 1; -// } -// } +// private int getJoinCount(JoinInfo joinInfo, String contractID) { +// if (joinInfo == null) return resultCount; +// if (joinInfo.joinCount.isJsonPrimitive() && joinInfo.joinCount.getAsJsonPrimitive().isNumber()) { +// return joinInfo.joinCount.getAsJsonPrimitive().getAsInt(); +// } +// try { +// ContractRequest cr = new ContractRequest(); +// cr.setContractID(contractID); +// cr.setAction(joinInfo.joinCount.getAsString()); +// //TODO Arg需要好好设计一下。 +// //TODO 又好用又简单的那种设计 +// //TODO +// cr.setArg(""); +// String result = CMActions.manager.executeLocally(cr, null); +// return JsonUtil.parseString(result).getAsJsonObject().get("result").getAsInt(); +// } catch (Exception e) { +// e.printStackTrace(); +// return 1; +// } +// } // -// // 清理缓存的多点合约请求序号 -// public void clearCache() { -// final long time = System.currentTimeMillis() - 30000L; -// seqMap.entrySet() -// .removeIf( -// entry -> { -// MultiReqSeq cache = entry.getValue(); -// if (null == cache) { -// return true; -// } -// return cache.startTime < time; -// }); -// } +// // 清理缓存的多点合约请求序号 +// public void clearCache() { +// final long time = System.currentTimeMillis() - 30000L; +// seqMap.entrySet() +// .removeIf( +// entry -> { +// MultiReqSeq cache = entry.getValue(); +// if (null == cache) { +// return true; +// } +// return cache.startTime < time; +// }); +// } // -// public static class ResultMerger extends ResultCallback { -// ComponedContractResult componedContractResult; -// AtomicInteger order; -// String contractID; -// int count; // 记录有多少个节点 -// int request_seq; -// ResultCallback originalCallback; -// Set nodeIDs = new HashSet<>(); // 已收到返回结果的节点 -// JoinInfo joinInfo; +// public static class ResultMerger extends ResultCallback { +// ComponedContractResult componedContractResult; +// AtomicInteger order; +// String contractID; +// int count; // 记录有多少个节点 +// int request_seq; +// ResultCallback originalCallback; +// Set nodeIDs = new HashSet<>(); // 已收到返回结果的节点 +// JoinInfo joinInfo; // -// ResultMerger( -// final ResultCallback originalCb, -// final int count, -// final int request_seq, -// final String contractID, -// final JoinInfo joinInfo) { -// originalCallback = originalCb; -// this.count = count; -// this.request_seq = request_seq; -// this.contractID = contractID; -// componedContractResult = new ComponedContractResult(count); -// order = new AtomicInteger(0); -// this.joinInfo = joinInfo; -// } +// ResultMerger( +// final ResultCallback originalCb, +// final int count, +// final int request_seq, +// final String contractID, +// final JoinInfo joinInfo) { +// originalCallback = originalCb; +// this.count = count; +// this.request_seq = request_seq; +// this.contractID = contractID; +// componedContractResult = new ComponedContractResult(count); +// order = new AtomicInteger(0); +// this.joinInfo = joinInfo; +// } // -// public String getInfo() { -// return "contractID=" -// + contractID -// + " 收到第 " -// + order -// + " 个节点回复 : " -// + " order=" -// + order -// + " count=" -// + count -// + " "; -// } +// public String getInfo() { +// return "contractID=" +// + contractID +// + " 收到第 " +// + order +// + " 个节点回复 : " +// + " order=" +// + order +// + " count=" +// + count +// + " "; +// } // -// @Override -// public void onResult(String str) { -// // TODO 必须在这里聚合。 -// // str的data是个ContractResult -// // 在这儿也是返回个ContractResult -// try { -// LOGGER.info(str); -// JsonObject obj = JsonParser.parseString(str).getAsJsonObject(); -// String id = obj.get("nodeID").getAsString(); -// if (nodeIDs.contains(id)) { -// LOGGER.info("已经收到节点 " + id.substring(0, 5) + " 的结果,该结果被忽略"); -// return; -// } -// nodeIDs.add(id); -// LOGGER.info( -// "contractID=" -// + contractID -// + " 收到第 " -// + order -// + " 个节点回复 : " -// + str -// + " order=" -// + order -// + " count=" -// + count); -// componedContractResult.add(obj); -// // 收集到所有结果 -// if (order.incrementAndGet() == count) { -// ContractResult finalResult = componedContractResult.mergeFinalResult(); +// @Override +// public void onResult(String str) { +// // TODO 必须在这里聚合。 +// // str的data是个ContractResult +// // 在这儿也是返回个ContractResult +// try { +// LOGGER.info(str); +// JsonObject obj = JsonParser.parseString(str).getAsJsonObject(); +// String id = obj.get("nodeID").getAsString(); +// if (nodeIDs.contains(id)) { +// LOGGER.info("已经收到节点 " + id.substring(0, 5) + " 的结果,该结果被忽略"); +// return; +// } +// nodeIDs.add(id); +// LOGGER.info( +// "contractID=" +// + contractID +// + " 收到第 " +// + order +// + " 个节点回复 : " +// + str +// + " order=" +// + order +// + " count=" +// + count); +// componedContractResult.add(obj); +// // 收集到所有结果 +// if (order.incrementAndGet() == count) { +// ContractResult finalResult = componedContractResult.mergeFinalResult(); // -// finalResult.needSeq = true; -// finalResult.seq = request_seq; +// finalResult.needSeq = true; +// finalResult.seq = request_seq; // -// // if (null == finalResult) { -// // finalResult = -// // new ContractResult( -// // ContractResult.Status.Exception, -// // new JsonPrimitive( -// // "no nore than half of the -// // consistent result")); -// // originalCallback.onResult(new -// // Gson().toJson(finalResult)); -// // } else { -// if (joinInfo != null) { -// handleJoinInfo(finalResult, joinInfo); -// } -// originalCallback.onResult(JsonUtil.toJson(finalResult)); -// // } -// LOGGER.info( -// "本次执行最终结果为 " + finalResult.size + "个节点合并的,结果为 " + finalResult.result); +// // if (null == finalResult) { +// // finalResult = +// // new ContractResult( +// // ContractResult.Status.Exception, +// // new JsonPrimitive( +// // "no nore than half of the +// // consistent result")); +// // originalCallback.onResult(new +// // Gson().toJson(finalResult)); +// // } else { +// if (joinInfo != null) { +// handleJoinInfo(finalResult, joinInfo); +// } +// originalCallback.onResult(JsonUtil.toJson(finalResult)); +// // } +// LOGGER.info( +// "本次执行最终结果为 " + finalResult.size + "个节点合并的,结果为 " + finalResult.result); // -// // 集群中事务序号+1 -// // MasterServerTCPAction.contractID2Members.get(contractID).nextSeq(); -// CMActions.manager -// .multiContractRecorder -// .getMultiContractMeta(contractID) -// .nextSeqAtMaster(); -// // recover,其中无状态合约CP出错无需恢复 -// Set nodesID = componedContractResult.getProblemNodes(); -// if (null == nodesID || nodesID.isEmpty()) { -// return; -// } -// for (String nodeID : nodesID) { -// LOGGER.info("结果出现问题的节点有:" + nodeID); -// if (MasterServerRecoverMechAction.recoverStatus.get(nodeID).get(contractID) -// == RecoverFlag.Fine) { -// MasterServerRecoverMechAction.recoverStatus -// .get(nodeID) -// .put(contractID, RecoverFlag.ToRecover); -// } -// } -// for (String nodeID : nodesID) { -// if (MasterServerRecoverMechAction.recoverStatus.get(nodeID).get(contractID) -// == RecoverFlag.ToRecover) { -// LOGGER.info("问题节点开始恢复:" + nodeID); +// // 集群中事务序号+1 +// // MasterServerTCPAction.contractID2Members.get(contractID).nextSeq(); +// CMActions.manager +// .multiContractRecorder +// .getMultiContractMeta(contractID) +// .nextSeqAtMaster(); +// // recover,其中无状态合约CP出错无需恢复 +// Set nodesID = componedContractResult.getProblemNodes(); +// if (null == nodesID || nodesID.isEmpty()) { +// return; +// } +// for (String nodeID : nodesID) { +// LOGGER.info("结果出现问题的节点有:" + nodeID); +// if (MasterServerRecoverMechAction.recoverStatus.get(nodeID).get(contractID) +// == RecoverFlag.Fine) { +// MasterServerRecoverMechAction.recoverStatus +// .get(nodeID) +// .put(contractID, RecoverFlag.ToRecover); +// } +// } +// for (String nodeID : nodesID) { +// if (MasterServerRecoverMechAction.recoverStatus.get(nodeID).get(contractID) +// == RecoverFlag.ToRecover) { +// LOGGER.info("问题节点开始恢复:" + nodeID); // -// // 因为该节点结果有误,所以即时是stableMode也认为trans记录不可信 -// // 直接通过load别的节点来恢复 -// MasterServerRecoverMechAction.restartContractFromCommonMode( -// nodeID, contractID); -// } -// } -// } -// // clearCache(); -// } catch (Exception e) { -// e.printStackTrace(); -// LOGGER.info("本次执行最终结果为有异常"); -// } -// } +// // 因为该节点结果有误,所以即时是stableMode也认为trans记录不可信 +// // 直接通过load别的节点来恢复 +// MasterServerRecoverMechAction.restartContractFromCommonMode( +// nodeID, contractID); +// } +// } +// } +// // clearCache(); +// } catch (Exception e) { +// e.printStackTrace(); +// LOGGER.info("本次执行最终结果为有异常"); +// } +// } // -// private void handleJoinInfo(ContractResult finalResult, JoinInfo joinInfo) { -// JsonObject jo = finalResult.result.getAsJsonObject(); -// if (joinInfo != null && joinInfo.joinRule != null) { -// //TODO 不应该是double 类型 -// switch (joinInfo.joinRule) { -// case "add": -// double val = 0; -// for (String key : jo.keySet()) { -// val += jo.get(key).getAsDouble(); -// } -// finalResult.result = new JsonPrimitive(val); -// break; -// case "multiply": -// val = 1; -// for (String key : jo.keySet()) { -// val *= jo.get(key).getAsDouble(); -// } -// finalResult.result = new JsonPrimitive(val); -// break; -// } -// } -// } -// } -//} +// private void handleJoinInfo(ContractResult finalResult, JoinInfo joinInfo) { +// JsonObject jo = finalResult.result.getAsJsonObject(); +// if (joinInfo != null && joinInfo.joinRule != null) { +// //TODO 不应该是double 类型 +// switch (joinInfo.joinRule) { +// case "add": +// double val = 0; +// for (String key : jo.keySet()) { +// val += jo.get(key).getAsDouble(); +// } +// finalResult.result = new JsonPrimitive(val); +// break; +// case "multiply": +// val = 1; +// for (String key : jo.keySet()) { +// val *= jo.get(key).getAsDouble(); +// } +// finalResult.result = new JsonPrimitive(val); +// break; +// } +// } +// } +// } +// } diff --git a/src/main/java/org/bdware/server/executor/unconsistency/RequestOnceExecutor.java b/src/main/java/org/bdware/server/executor/unconsistency/RequestOnceExecutor.java index f1d3470..f37d905 100644 --- a/src/main/java/org/bdware/server/executor/unconsistency/RequestOnceExecutor.java +++ b/src/main/java/org/bdware/server/executor/unconsistency/RequestOnceExecutor.java @@ -1,68 +1,70 @@ -//package org.bdware.server.executor.unconsistency; +// package org.bdware.server.executor.unconsistency; // -//import com.google.gson.JsonObject; -//import com.google.gson.JsonParser; -//import org.apache.logging.log4j.LogManager; -//import org.apache.logging.log4j.Logger; -//import org.bdware.sc.bean.ContractRequest; -//import org.bdware.sc.conn.OnHashCallback; -//import org.bdware.sc.conn.ResultCallback; -//import org.bdware.sc.util.JsonUtil; -//import org.bdware.server.ControllerManager; -//import org.bdware.server.action.CMActions; -//import org.bdware.server.action.p2p.MasterServerTCPAction; -//import org.bdware.server.trustedmodel.ContractExecutor; -//import org.bdware.server.trustedmodel.AgentManager; -//import org.bdware.units.NetworkManager; +// import com.google.gson.JsonObject; +// import com.google.gson.JsonParser; +// import org.apache.logging.log4j.LogManager; +// import org.apache.logging.log4j.Logger; +// import org.bdware.sc.bean.ContractRequest; +// import org.bdware.sc.conn.OnHashCallback; +// import org.bdware.sc.conn.ResultCallback; +// import org.bdware.sc.util.JsonUtil; +// import org.bdware.server.ControllerManager; +// import org.bdware.server.action.CMActions; +// import org.bdware.server.action.p2p.MasterServerTCPAction; +// import org.bdware.server.trustedmodel.ContractExecutor; +// import org.bdware.server.trustedmodel.AgentManager; +// import org.bdware.units.NetworkManager; // -//import java.util.HashMap; -//import java.util.Map; -//import java.util.concurrent.atomic.AtomicInteger; +// import java.util.HashMap; +// import java.util.Map; +// import java.util.concurrent.atomic.AtomicInteger; // -//public class RequestOnceExecutor implements ContractExecutor { -// private static final Logger LOGGER = LogManager.getLogger(RequestOnceExecutor.class); -// String contractID; -// AtomicInteger order = new AtomicInteger(0); +// public class RequestOnceExecutor implements ContractExecutor { +// private static final Logger LOGGER = LogManager.getLogger(RequestOnceExecutor.class); +// String contractID; +// AtomicInteger order = new AtomicInteger(0); // -// public RequestOnceExecutor(String contractID) { -// this.contractID = contractID; -// } +// public RequestOnceExecutor(String contractID) { +// this.contractID = contractID; +// } // -// @Override -// public void execute(String requestID, ContractRequest req, ResultCallback rc, OnHashCallback hcb) { -// ResultCallback cb = -// new ResultCallback() { -// @Override -// public void onResult(String str) { -// LOGGER.debug(str); -// JsonObject jo = JsonParser.parseString(str).getAsJsonObject(); -// JsonObject result = -// JsonParser.parseString(jo.get("data").getAsString()) -// .getAsJsonObject(); -// for (String key : result.keySet()) jo.add(key, result.get(key)); -// jo.remove("action"); -// jo.addProperty("action", "onExecuteResult"); -// LOGGER.debug(jo.toString()); -// rc.onResult(jo.toString()); -// } -// }; -// MasterServerTCPAction.sync.sleep(requestID, cb); -// String[] members = CMActions.manager.multiContractRecorder.getMultiContractMeta(contractID).getMembers(); -// for (int i = 0; i < members.length; i++) { -// LOGGER.info("[members]:" + members.length); -// int size = members.length; -// String nodeID = members[order.incrementAndGet() % size]; -// //ADD Connect -// Map obj = new HashMap<>(); -// obj.put("action", "executeContractLocally"); -// obj.put("requestID",requestID); -// obj.put("data", req); -// obj.put("uniReqID", requestID); -// NetworkManager.instance.sendToAgent(nodeID,JsonUtil.toJson(obj)); -// return; -// } -// rc.onResult( -// "{\"status\":\"Error\",\"result\":\"all nodes " -// + " offline\",\"action\":\"onExecuteContract\"}"); -// } -//} +// @Override +// public void execute(String requestID, ContractRequest req, ResultCallback rc, OnHashCallback hcb) +// { +// ResultCallback cb = +// new ResultCallback() { +// @Override +// public void onResult(String str) { +// LOGGER.debug(str); +// JsonObject jo = JsonParser.parseString(str).getAsJsonObject(); +// JsonObject result = +// JsonParser.parseString(jo.get("data").getAsString()) +// .getAsJsonObject(); +// for (String key : result.keySet()) jo.add(key, result.get(key)); +// jo.remove("action"); +// jo.addProperty("action", "onExecuteResult"); +// LOGGER.debug(jo.toString()); +// rc.onResult(jo.toString()); +// } +// }; +// MasterServerTCPAction.sync.sleep(requestID, cb); +// String[] members = +// CMActions.manager.multiContractRecorder.getMultiContractMeta(contractID).getMembers(); +// for (int i = 0; i < members.length; i++) { +// LOGGER.info("[members]:" + members.length); +// int size = members.length; +// String nodeID = members[order.incrementAndGet() % size]; +// //ADD Connect +// Map obj = new HashMap<>(); +// obj.put("action", "executeContractLocally"); +// obj.put("requestID",requestID); +// obj.put("data", req); +// obj.put("uniReqID", requestID); +// NetworkManager.instance.sendToAgent(nodeID,JsonUtil.toJson(obj)); +// return; +// } +// rc.onResult( +// "{\"status\":\"Error\",\"result\":\"all nodes " +// + " offline\",\"action\":\"onExecuteContract\"}"); +// } +// } diff --git a/src/main/java/org/bdware/server/executor/unconsistency/ResponseOnceExecutor.java b/src/main/java/org/bdware/server/executor/unconsistency/ResponseOnceExecutor.java index 6921560..1cae412 100644 --- a/src/main/java/org/bdware/server/executor/unconsistency/ResponseOnceExecutor.java +++ b/src/main/java/org/bdware/server/executor/unconsistency/ResponseOnceExecutor.java @@ -1,83 +1,86 @@ -//package org.bdware.server.executor.unconsistency; +// package org.bdware.server.executor.unconsistency; // -//import com.google.gson.JsonObject; -//import com.google.gson.JsonParser; -//import org.apache.logging.log4j.LogManager; -//import org.apache.logging.log4j.Logger; -//import org.bdware.sc.ContractResult; -//import org.bdware.sc.bean.ContractRequest; -//import org.bdware.sc.conn.OnHashCallback; -//import org.bdware.sc.conn.ResultCallback; -//import org.bdware.sc.util.JsonUtil; -//import org.bdware.server.action.CMActions; -//import org.bdware.server.action.p2p.MasterServerTCPAction; -//import org.bdware.server.trustedmodel.ContractExecutor; -//import org.bdware.units.NetworkManager; +// import com.google.gson.JsonObject; +// import com.google.gson.JsonParser; +// import org.apache.logging.log4j.LogManager; +// import org.apache.logging.log4j.Logger; +// import org.bdware.sc.ContractResult; +// import org.bdware.sc.bean.ContractRequest; +// import org.bdware.sc.conn.OnHashCallback; +// import org.bdware.sc.conn.ResultCallback; +// import org.bdware.sc.util.JsonUtil; +// import org.bdware.server.action.CMActions; +// import org.bdware.server.action.p2p.MasterServerTCPAction; +// import org.bdware.server.trustedmodel.ContractExecutor; +// import org.bdware.units.NetworkManager; // -//import java.util.HashMap; -//import java.util.Map; -//import java.util.concurrent.atomic.AtomicInteger; +// import java.util.HashMap; +// import java.util.Map; +// import java.util.concurrent.atomic.AtomicInteger; // -//public class ResponseOnceExecutor implements ContractExecutor { -// private static final Logger LOGGER = LogManager.getLogger(ResponseOnceExecutor.class); -// private final String contractID; -// AtomicInteger order = new AtomicInteger(0); +// public class ResponseOnceExecutor implements ContractExecutor { +// private static final Logger LOGGER = LogManager.getLogger(ResponseOnceExecutor.class); +// private final String contractID; +// AtomicInteger order = new AtomicInteger(0); // -// public ResponseOnceExecutor(String contractID) { -// this.contractID = contractID; -// } +// public ResponseOnceExecutor(String contractID) { +// this.contractID = contractID; +// } // -// @Override -// public void execute(String requestID, ContractRequest req, ResultCallback rc, OnHashCallback hcb) { -// executeInternal(requestID, rc, req, 2); -// } +// @Override +// public void execute(String requestID, ContractRequest req, ResultCallback rc, OnHashCallback hcb) +// { +// executeInternal(requestID, rc, req, 2); +// } // -// private void executeInternal( -// String requestID, ResultCallback rc, ContractRequest req, int count) { -// // String contractID = req.getContractID(); -// // TODO 标注失效节点,是否选择重新迁移?? -// ResultCallback cb = -// new ResultCallback() { -// @Override -// public void onResult(String str) { -// LOGGER.debug(str); -// JsonObject jo = JsonParser.parseString(str).getAsJsonObject(); -// jo.remove("action"); -// jo.addProperty("action", "onExecuteResult"); -// LOGGER.debug(jo.toString()); -// if (jo.has("data")) { -// String data = jo.get("data").getAsString(); -// ContractResult cr = JsonUtil.fromJson(data, ContractResult.class); -// if (cr.status != ContractResult.Status.Success && count > 0) { -// executeInternal(requestID, rc, req, count - 1); -// } else rc.onResult(jo.toString()); -// } else { -// JsonObject jo2 = new JsonObject(); -// jo2.addProperty("action", "onExecuteResult"); -// jo.remove("action"); -// jo2.addProperty("data", jo.toString()); -// rc.onResult(jo2.toString()); -// } -// } -// }; -// MasterServerTCPAction.sync.sleepWithTimeout(requestID, cb, 5); -// if (!sendOnce(requestID, req)) -// rc.onResult( -// "{\"status\":\"Error\",\"data\":\"{\\\"status\\\":\\\"Error\\\",\\\"result\\\":\\\"all nodes offline\\\"}\",\"action\":\"onExecuteContract\"}"); -// } +// private void executeInternal( +// String requestID, ResultCallback rc, ContractRequest req, int count) { +// // String contractID = req.getContractID(); +// // TODO 标注失效节点,是否选择重新迁移?? +// ResultCallback cb = +// new ResultCallback() { +// @Override +// public void onResult(String str) { +// LOGGER.debug(str); +// JsonObject jo = JsonParser.parseString(str).getAsJsonObject(); +// jo.remove("action"); +// jo.addProperty("action", "onExecuteResult"); +// LOGGER.debug(jo.toString()); +// if (jo.has("data")) { +// String data = jo.get("data").getAsString(); +// ContractResult cr = JsonUtil.fromJson(data, ContractResult.class); +// if (cr.status != ContractResult.Status.Success && count > 0) { +// executeInternal(requestID, rc, req, count - 1); +// } else rc.onResult(jo.toString()); +// } else { +// JsonObject jo2 = new JsonObject(); +// jo2.addProperty("action", "onExecuteResult"); +// jo.remove("action"); +// jo2.addProperty("data", jo.toString()); +// rc.onResult(jo2.toString()); +// } +// } +// }; +// MasterServerTCPAction.sync.sleepWithTimeout(requestID, cb, 5); +// if (!sendOnce(requestID, req)) +// rc.onResult( +// "{\"status\":\"Error\",\"data\":\"{\\\"status\\\":\\\"Error\\\",\\\"result\\\":\\\"all nodes +// offline\\\"}\",\"action\":\"onExecuteContract\"}"); +// } // -// private boolean sendOnce(String requestID, ContractRequest req) { -// String[] members = CMActions.manager.multiContractRecorder.getMultiContractMeta(contractID).getMembers(); -// for (int i = 0; i < members.length; i++) { -// int size = members.length; -// String nodeID = members[order.incrementAndGet() % size]; -// Map obj = new HashMap<>(); -// obj.put("action", "executeContractLocally"); -// obj.put("data", req); -// obj.put("uniReqID", requestID); -// NetworkManager.instance.sendToAgent(nodeID, JsonUtil.toJson(obj)); -// return true; -// } -// return false; -// } -//} +// private boolean sendOnce(String requestID, ContractRequest req) { +// String[] members = +// CMActions.manager.multiContractRecorder.getMultiContractMeta(contractID).getMembers(); +// for (int i = 0; i < members.length; i++) { +// int size = members.length; +// String nodeID = members[order.incrementAndGet() % size]; +// Map obj = new HashMap<>(); +// obj.put("action", "executeContractLocally"); +// obj.put("data", req); +// obj.put("uniReqID", requestID); +// NetworkManager.instance.sendToAgent(nodeID, JsonUtil.toJson(obj)); +// return true; +// } +// return false; +// } +// } diff --git a/src/main/java/org/bdware/server/executor/unconsistency/_UNUSED_RouteEnabledExecutor.java b/src/main/java/org/bdware/server/executor/unconsistency/_UNUSED_RouteEnabledExecutor.java index e962aa6..15974de 100644 --- a/src/main/java/org/bdware/server/executor/unconsistency/_UNUSED_RouteEnabledExecutor.java +++ b/src/main/java/org/bdware/server/executor/unconsistency/_UNUSED_RouteEnabledExecutor.java @@ -33,30 +33,30 @@ public class _UNUSED_RouteEnabledExecutor implements ContractExecutor { } @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); } - private void executeInternal( - String requestID, ResultCallback rc, ContractRequest req, int count) { - // String contractID = req.getContractID(); + private void executeInternal(String requestID, ResultCallback rc, ContractRequest req, + int count) { + // String contractID = req.getContractID(); // TODO 标注失效节点,是否选择重新迁移?? - ResultCallback cb = - new ResultCallback() { - @Override - public void onResult(String str) { - LOGGER.debug(str); - JsonObject jo = JsonParser.parseString(str).getAsJsonObject(); - JsonObject result = - JsonParser.parseString(jo.get("data").getAsString()) - .getAsJsonObject(); - for (String key : result.keySet()) jo.add(key, result.get(key)); - jo.remove("action"); - jo.addProperty("action", "onExecuteResult"); - LOGGER.debug(jo.toString()); - rc.onResult(jo.toString()); - } - }; + ResultCallback cb = new ResultCallback() { + @Override + public void onResult(String str) { + LOGGER.debug(str); + JsonObject jo = JsonParser.parseString(str).getAsJsonObject(); + JsonObject result = + JsonParser.parseString(jo.get("data").getAsString()).getAsJsonObject(); + for (String key : result.keySet()) + jo.add(key, result.get(key)); + jo.remove("action"); + jo.addProperty("action", "onExecuteResult"); + LOGGER.debug(jo.toString()); + rc.onResult(jo.toString()); + } + }; MasterServerTCPAction.sync.sleepWithTimeout(requestID, cb, 5); if (!send(requestID, req)) rc.onResult( @@ -69,7 +69,8 @@ public class _UNUSED_RouteEnabledExecutor implements ContractExecutor { req.getArg(); req.getRequester(); req.getAction(); - MultiContractMeta mMeta = CMActions.manager.multiContractRecorder.getMultiContractMeta(meta.getID()); + MultiContractMeta mMeta = + CMActions.manager.multiContractRecorder.getMultiContractMeta(meta.getID()); FunctionDesp desp = meta.getExportedFunction(req.getAction()); RouteInfo info = desp.getRoute(); @@ -77,10 +78,8 @@ public class _UNUSED_RouteEnabledExecutor implements ContractExecutor { if (info != null && info.useDefault != null) { switch (info.useDefault) { case byRequester: - hash = - new BigInteger(req.getRequester(), 16) - .mod(BigInteger.valueOf(mMeta.getMembers().length)) - .intValue(); + hash = new BigInteger(req.getRequester(), 16) + .mod(BigInteger.valueOf(mMeta.getMembers().length)).intValue(); break; case byArgHash: hash = req.getArg().hashCode(); @@ -88,13 +87,15 @@ public class _UNUSED_RouteEnabledExecutor implements ContractExecutor { } } - String[] members = - CMActions.manager.multiContractRecorder.getMultiContractMeta(contractID).getMembers(); + String[] members = CMActions.manager.multiContractRecorder.getMultiContractMeta(contractID) + .getMembers(); String nodeID; for (int i = 0; i < members.length; i++) { int size = members.length; - if (hash != -1) nodeID = members[hash % size]; - else nodeID = members[order.incrementAndGet() % size]; + if (hash != -1) + nodeID = members[hash % size]; + else + nodeID = members[order.incrementAndGet() % size]; Map obj = new HashMap<>(); obj.put("action", "executeContractLocally"); obj.put("data", req); diff --git a/src/main/java/org/bdware/server/http/CMHttpHandler.java b/src/main/java/org/bdware/server/http/CMHttpHandler.java index 0dc346b..2f0b3e4 100644 --- a/src/main/java/org/bdware/server/http/CMHttpHandler.java +++ b/src/main/java/org/bdware/server/http/CMHttpHandler.java @@ -44,11 +44,8 @@ public class CMHttpHandler extends SimpleChannelInboundHandler { URIHandler uriHandlers; public CMHttpHandler() { - FileFilter fileFilter = - pathname -> - !pathname.getName().equals("CenterPortal.html") - && !pathname.getAbsolutePath() - .contains(".."); // TODO 路径判断,过滤下载任意文件 + FileFilter fileFilter = pathname -> !pathname.getName().equals("CenterPortal.html") + && !pathname.getAbsolutePath().contains(".."); // TODO 路径判断,过滤下载任意文件 HttpFileHandleAdapter ideFileService = new HttpFileHandleAdapter( new File("./WebContent/ide/").getAbsolutePath(), fileFilter) { @URIPath({"/"}) @@ -57,67 +54,54 @@ public class CMHttpHandler extends SimpleChannelInboundHandler { channelRead0(ctx, request); } }; - HttpFileHandleAdapter otherFileService = new HttpFileHandleAdapter( - new File("./WebContent/").getAbsolutePath(), fileFilter) { - @URIPath({"/client/", "/doc/", "/blog/"}) - private void handleFile(ChannelHandlerContext ctx, FullHttpRequest request) - throws Exception { - channelRead0(ctx, request); - } - }; - UserManagerAction userManagerAction = new UserManagerAction(null); - MasterWSAction masterWSAction = new MasterWSAction(null); - actionExecutor = - new ActionExecutor( - ContractManagerFrameHandler.executorService, - new CMActions(), - ManagerActions.instance, - new FileActions(null), - userManagerAction, masterWSAction, - GRPCPool.instance, - new HttpFileAction(), - new BDIndexerAction(), - LedgerActions.instance, - new CMLogAction(), - new TemporyTestAction()) { - @Override - public boolean checkPermission(Action a, JsonObject arg, long per) { - boolean flag = a.httpAccess(); - long val = a.userPermission(); // 使用者必须达到的permission - if (val == 0) { - return true; - } - long permission = arg.get("permission").getAsLong(); - boolean flag2 = false; // 启动http权限后应改为false - String status = "refuse"; - String action = arg.get("action").getAsString(); - - if (val == 0) { - flag2 = true; - } else if ((permission & val) == val) { - System.out.print((permission & val)); - flag2 = true; - } - - if (flag && flag2) { - status = "accept"; - } - - String pubkey = "anonymity"; - if (arg.has("pubKey")) { - pubkey = arg.get("pubKey").getAsString(); - } - TimeDBUtil.instance.put( - CMTables.LocalNodeLogDB.toString(), - String.format( - "{\"action\":\"%s\",\"pubKey\":\"%s\",\"status\":\"%s\",\"date\":%d}", - action, - pubkey, - status, - System.currentTimeMillis())); - return flag && flag2; + HttpFileHandleAdapter otherFileService = + new HttpFileHandleAdapter(new File("./WebContent/").getAbsolutePath(), fileFilter) { + @URIPath({"/client/", "/doc/", "/blog/"}) + private void handleFile(ChannelHandlerContext ctx, FullHttpRequest request) + throws Exception { + channelRead0(ctx, request); } }; + UserManagerAction userManagerAction = new UserManagerAction(null); + MasterWSAction masterWSAction = new MasterWSAction(null); + actionExecutor = new ActionExecutor( + ContractManagerFrameHandler.executorService, new CMActions(), + ManagerActions.instance, new FileActions(null), userManagerAction, masterWSAction, + GRPCPool.instance, new HttpFileAction(), new BDIndexerAction(), + LedgerActions.instance, new CMLogAction(), new TemporyTestAction()) { + @Override + public boolean checkPermission(Action a, JsonObject arg, long per) { + boolean flag = a.httpAccess(); + long val = a.userPermission(); // 使用者必须达到的permission + if (val == 0) { + return true; + } + long permission = arg.get("permission").getAsLong(); + boolean flag2 = false; // 启动http权限后应改为false + String status = "refuse"; + String action = arg.get("action").getAsString(); + + if (val == 0) { + flag2 = true; + } else if ((permission & val) == val) { + System.out.print((permission & val)); + flag2 = true; + } + + if (flag && flag2) { + status = "accept"; + } + + String pubkey = "anonymity"; + if (arg.has("pubKey")) { + pubkey = arg.get("pubKey").getAsString(); + } + TimeDBUtil.instance.put(CMTables.LocalNodeLogDB.toString(), String.format( + "{\"action\":\"%s\",\"pubKey\":\"%s\",\"status\":\"%s\",\"date\":%d}", + action, pubkey, status, System.currentTimeMillis())); + return flag && flag2; + } + }; if (wsPluginActions != null) for (String str : wsPluginActions) { Object obj = createInstanceByClzName(str); @@ -166,20 +150,15 @@ public class CMHttpHandler extends SimpleChannelInboundHandler { @URIPath(method = HttpMethod.OPTIONS) public void crossOrigin(ChannelHandlerContext ctx, FullHttpRequest request) { - DefaultFullHttpResponse fullResponse = - new DefaultFullHttpResponse( - request.protocolVersion(), - OK, - Unpooled.wrappedBuffer("success".getBytes())); + DefaultFullHttpResponse fullResponse = new DefaultFullHttpResponse( + request.protocolVersion(), OK, Unpooled.wrappedBuffer("success".getBytes())); fullResponse.headers().remove("Access-Control-Allow-Origin"); fullResponse.headers().remove("Access-Control-Allow-Headers"); fullResponse.headers().add("Access-Control-Allow-Origin", "*"); fullResponse.headers().add("Access-Control-Allow-Methods", "*"); - fullResponse - .headers() - .add("Access-Control-Allow-Headers", - "Content-Type, Cookie, Accept-Encoding, User-Agent, Host, Referer, " + - "X-Requested-With, Accept, Accept-Language, Cache-Control, Connection"); + fullResponse.headers().add("Access-Control-Allow-Headers", + "Content-Type, Cookie, Accept-Encoding, User-Agent, Host, Referer, " + + "X-Requested-With, Accept, Accept-Language, Cache-Control, Connection"); ChannelFuture f = ctx.write(fullResponse); f.addListener(ChannelFutureListener.CLOSE); LOGGER.info("[OOOOOOOOption] received!"); @@ -187,34 +166,35 @@ public class CMHttpHandler extends SimpleChannelInboundHandler { @URIPath({"/SCIDE/CMManager", "/SCIDE/SCManager", "/BDO"}) public void handleHttpGet(ChannelHandlerContext ctx, FullHttpRequest msg) throws Exception { - JsonObject transformedParam = ArgParser.parseGetAndVerify(msg, new ArgParser.VerifiedCallback() { - @Override - public void onResult(boolean verified, JsonObject transformedParam) { - LOGGER.info("verify signature: " + verified + " " + transformedParam.toString()); - if (verified) { - // 查permission - String pubkey = transformedParam.get("pubKey").getAsString(); - String ret = KeyValueDBUtil.instance.getValue(CMTables.NodeRole.toString(), pubkey); - long permission; - if (ret != null && ret.length() > 0) { - permission = 0x86000d41L | Role.compoundValue(ret.split(",")); - } else { - assert ret != null; - permission = Role.compoundValue(ret.split(",")); + JsonObject transformedParam = + ArgParser.parseGetAndVerify(msg, new ArgParser.VerifiedCallback() { + @Override + public void onResult(boolean verified, JsonObject transformedParam) { + LOGGER.info("verify signature: " + verified + " " + + transformedParam.toString()); + if (verified) { + // 查permission + String pubkey = transformedParam.get("pubKey").getAsString(); + String ret = KeyValueDBUtil.instance + .getValue(CMTables.NodeRole.toString(), pubkey); + long permission; + if (ret != null && ret.length() > 0) { + permission = 0x86000d41L | Role.compoundValue(ret.split(",")); + } else { + assert ret != null; + permission = Role.compoundValue(ret.split(",")); + } + transformedParam.addProperty("permission", permission); + LOGGER.info("user permission: " + permission); + transformedParam.addProperty("verifiedPubKey", + transformedParam.get("pubKey").getAsString()); + } } - transformedParam.addProperty("permission", permission); - LOGGER.info("user permission: " + permission); - transformedParam.addProperty( - "verifiedPubKey", transformedParam.get("pubKey").getAsString()); - } - } - }); + }); handleReq(transformedParam, ctx, msg); } - @URIPath( - method = HttpMethod.POST, - value = {"/SCIDE/CMManager", "/SCIDE/SCManager", "/BDO"}) + @URIPath(method = HttpMethod.POST, value = {"/SCIDE/CMManager", "/SCIDE/SCManager", "/BDO"}) public void handleHttpPost(ChannelHandlerContext ctx, FullHttpRequest msg) throws UnsupportedEncodingException { // http请求中规定签名必须是最后一个且公钥名必须为pubKey,否则验签失败 @@ -242,11 +222,8 @@ public class CMHttpHandler extends SimpleChannelInboundHandler { String str = "action:" + action; boolean verify = false; try { - verify = - SM2Util.plainStrVerify( - map.get("pubKey").getAsString(), - str, - map.get("sign").getAsString()); + verify = SM2Util.plainStrVerify(map.get("pubKey").getAsString(), str, + map.get("sign").getAsString()); } catch (Exception e) { LOGGER.error(e.getMessage()); LOGGER.debug(ExceptionUtil.exceptionToString(e)); @@ -279,9 +256,8 @@ public class CMHttpHandler extends SimpleChannelInboundHandler { if (!map.has("action")) { LOGGER.error("no action in map!"); ret = UNSUPPORTED_ACTION.getBytes(); - DefaultFullHttpResponse response = - new DefaultFullHttpResponse( - HttpVersion.HTTP_1_1, OK, Unpooled.wrappedBuffer(ret)); + DefaultFullHttpResponse response = new DefaultFullHttpResponse(HttpVersion.HTTP_1_1, + OK, Unpooled.wrappedBuffer(ret)); response.headers().add("Access-Control-Allow-Origin", "*"); response.headers().add("Access-Control-Allow-Methods", "*"); ChannelFuture f = ctx.write(response); @@ -323,11 +299,8 @@ public class CMHttpHandler extends SimpleChannelInboundHandler { actionExecutor.handle(action, map, cb); } } catch (IllegalArgumentException e) { - DefaultFullHttpResponse response = - new DefaultFullHttpResponse( - HttpVersion.HTTP_1_1, - OK, - Unpooled.wrappedBuffer(e.getMessage().getBytes())); + DefaultFullHttpResponse response = new DefaultFullHttpResponse(HttpVersion.HTTP_1_1, OK, + Unpooled.wrappedBuffer(e.getMessage().getBytes())); response.headers().add("Access-Control-Allow-Origin", "*"); response.headers().add("Access-Control-Allow-Methods", "*"); ChannelFuture f = ctx.write(response); @@ -335,11 +308,8 @@ public class CMHttpHandler extends SimpleChannelInboundHandler { } catch (Exception e) { Map ret = new HashMap<>(); ret.put("msg", ExceptionUtil.exceptionToString(e)); - DefaultFullHttpResponse response = - new DefaultFullHttpResponse( - HttpVersion.HTTP_1_1, - OK, - Unpooled.wrappedBuffer(JsonUtil.toJson(ret).getBytes())); + DefaultFullHttpResponse response = new DefaultFullHttpResponse(HttpVersion.HTTP_1_1, OK, + Unpooled.wrappedBuffer(JsonUtil.toJson(ret).getBytes())); response.headers().add("Access-Control-Allow-Origin", "*"); response.headers().add("Access-Control-Allow-Methods", "*"); ChannelFuture f = ctx.write(response); @@ -349,9 +319,10 @@ public class CMHttpHandler extends SimpleChannelInboundHandler { @Override 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)); - // ctx.close(); + // ctx.close(); } private String parseCtx2String(ChannelHandlerContext ctx) { diff --git a/src/main/java/org/bdware/server/http/DOIPOverHttpHandler.java b/src/main/java/org/bdware/server/http/DOIPOverHttpHandler.java index 4320c26..5e5ec7a 100644 --- a/src/main/java/org/bdware/server/http/DOIPOverHttpHandler.java +++ b/src/main/java/org/bdware/server/http/DOIPOverHttpHandler.java @@ -62,25 +62,16 @@ public class DOIPOverHttpHandler { String ops = arg.get("operation").getAsString(); Operations defaultOp = Operations.parse(ops); if (defaultOp == null) { - CMActions.executeContractInternal( - arg, - new ResultCallback() { - @Override - public void onResult(String str) { - FullHttpResponse response = - new DefaultFullHttpResponse( - HTTP_1_1, - HttpResponseStatus.OK, - Unpooled.wrappedBuffer(str.getBytes())); - response.headers() - .set( - HttpHeaderNames.CONTENT_TYPE, - "text/plain; charset=UTF-8"); - ctx.writeAndFlush(response) - .addListener(ChannelFutureListener.CLOSE); - } - }, - null); + CMActions.executeContractInternal(arg, new ResultCallback() { + @Override + public void onResult(String str) { + FullHttpResponse response = new DefaultFullHttpResponse(HTTP_1_1, + HttpResponseStatus.OK, Unpooled.wrappedBuffer(str.getBytes())); + response.headers().set(HttpHeaderNames.CONTENT_TYPE, + "text/plain; charset=UTF-8"); + ctx.writeAndFlush(response).addListener(ChannelFutureListener.CLOSE); + } + }, null); } else { switch (defaultOp) { case ListOps: @@ -105,11 +96,8 @@ public class DOIPOverHttpHandler { e.printStackTrace(); ByteArrayOutputStream bo = new ByteArrayOutputStream(); e.printStackTrace(new PrintStream(bo)); - FullHttpResponse response = - new DefaultFullHttpResponse( - HTTP_1_1, - HttpResponseStatus.OK, - Unpooled.wrappedBuffer(bo.toByteArray())); + FullHttpResponse response = new DefaultFullHttpResponse(HTTP_1_1, HttpResponseStatus.OK, + Unpooled.wrappedBuffer(bo.toByteArray())); response.headers().set(HttpHeaderNames.CONTENT_TYPE, "text/plain; charset=UTF-8"); ctx.writeAndFlush(response).addListener(ChannelFutureListener.CLOSE); } @@ -118,22 +106,18 @@ public class DOIPOverHttpHandler { private void sendListContractProcess(JsonObject arg, ChannelHandlerContext ctx) { JsonObject ret = new JsonObject(); ret.addProperty("action", "onListOps"); - ret.addProperty( - "data", CMActions.manager.listTheContracts(arg.get("contractID").getAsString())); - FullHttpResponse response = - new DefaultFullHttpResponse( - HTTP_1_1, - HttpResponseStatus.OK, - Unpooled.wrappedBuffer(JsonUtil.toJson(ret).getBytes())); + ret.addProperty("data", + CMActions.manager.listTheContracts(arg.get("contractID").getAsString())); + FullHttpResponse response = new DefaultFullHttpResponse(HTTP_1_1, HttpResponseStatus.OK, + Unpooled.wrappedBuffer(JsonUtil.toJson(ret).getBytes())); response.headers().set(HttpHeaderNames.CONTENT_TYPE, "text/plain; charset=UTF-8"); ctx.writeAndFlush(response).addListener(ChannelFutureListener.CLOSE); } private void sendYpk(JsonObject arg, ChannelHandlerContext ctx, FullHttpRequest request) throws IOException { - ContractMeta meta = - CMActions.manager.statusRecorder.getContractMeta( - arg.get("contractID").getAsString()); + ContractMeta meta = CMActions.manager.statusRecorder + .getContractMeta(arg.get("contractID").getAsString()); if (meta == null) { HttpFileHandleAdapter.sendError(ctx, HttpResponseStatus.NOT_FOUND); return; @@ -168,9 +152,8 @@ public class DOIPOverHttpHandler { } private void sendPublicFiles(JsonObject arg, ChannelHandlerContext ctx) throws Exception { - ContractMeta meta = - CMActions.manager.statusRecorder.getContractMeta( - arg.get("contractID").getAsString()); + ContractMeta meta = CMActions.manager.statusRecorder + .getContractMeta(arg.get("contractID").getAsString()); if (meta == null) { HttpFileHandleAdapter.sendError(ctx, HttpResponseStatus.NOT_FOUND); return; @@ -193,23 +176,21 @@ public class DOIPOverHttpHandler { HttpFileHandleAdapter.appendContentType(path, response.headers()); ctx.write(response); ChannelFuture future = ctx.writeAndFlush(new ChunkedStream(fin)); - future.addListener( - new GenericFutureListener>() { - @Override - public void operationComplete(Future arg0) throws Exception { - ctx.writeAndFlush(LastHttpContent.EMPTY_LAST_CONTENT); - fin.close(); - } - }); + future.addListener(new GenericFutureListener>() { + @Override + public void operationComplete(Future arg0) throws Exception { + ctx.writeAndFlush(LastHttpContent.EMPTY_LAST_CONTENT); + fin.close(); + } + }); // 写入文件尾部 future.addListener(ChannelFutureListener.CLOSE); return; } private void sendAssets(JsonObject arg, ChannelHandlerContext ctx) throws Exception { - ContractMeta meta = - CMActions.manager.statusRecorder.getContractMeta( - arg.get("contractID").getAsString()); + ContractMeta meta = CMActions.manager.statusRecorder + .getContractMeta(arg.get("contractID").getAsString()); if (meta == null) { HttpFileHandleAdapter.sendError(ctx, HttpResponseStatus.NOT_FOUND); return; @@ -226,14 +207,13 @@ public class DOIPOverHttpHandler { HttpFileHandleAdapter.appendContentType(path, response.headers()); ctx.write(response); ChannelFuture future = ctx.writeAndFlush(new ChunkedStream(in)); - future.addListener( - new GenericFutureListener>() { - @Override - public void operationComplete(Future arg0) throws Exception { - ctx.writeAndFlush(LastHttpContent.EMPTY_LAST_CONTENT); - in.close(); - } - }); + future.addListener(new GenericFutureListener>() { + @Override + public void operationComplete(Future arg0) throws Exception { + ctx.writeAndFlush(LastHttpContent.EMPTY_LAST_CONTENT); + in.close(); + } + }); // 写入文件尾部 future.addListener(ChannelFutureListener.CLOSE); return; @@ -244,16 +224,14 @@ public class DOIPOverHttpHandler { ZipFile cachedFile = zipFilePool.get(scriptStr); if (cachedFile == null) { File f = new File(scriptStr); - cachedFile = - new ZipFile(f); + cachedFile = new ZipFile(f); zipFilePool.put(scriptStr, cachedFile); lastModified.put(scriptStr, f.lastModified()); } else { File f = new File(scriptStr); if (lastModified.get(scriptStr) != f.lastModified()) { cachedFile.close(); - cachedFile = - new ZipFile(f); + cachedFile = new ZipFile(f); zipFilePool.put(scriptStr, cachedFile); lastModified.put(scriptStr, f.lastModified()); } @@ -275,22 +253,21 @@ public class DOIPOverHttpHandler { if (uri != null && transformedParam.has("pubKey")) { int index = fulluri.lastIndexOf('&'); 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); boolean verify = false; try { - verify = - SM2Util.plainStrVerify( - transformedParam.get("pubKey").getAsString(), - str, - transformedParam.get("sign").getAsString()); + verify = SM2Util.plainStrVerify(transformedParam.get("pubKey").getAsString(), str, + transformedParam.get("sign").getAsString()); } catch (Exception e) { e.printStackTrace(); } if (verify) { - transformedParam.addProperty( - "verifiedPubKey", transformedParam.get("pubKey").getAsString()); - } else transformedParam.remove("verifiedPubKey"); + transformedParam.addProperty("verifiedPubKey", + transformedParam.get("pubKey").getAsString()); + } else + transformedParam.remove("verifiedPubKey"); } transformedParam.addProperty("contractID", data[2].replaceAll("\\?.*$", "")); if (data.length > 3) { @@ -325,22 +302,19 @@ public class DOIPOverHttpHandler { JsonObject transformedParam = new JsonObject(); for (String key : parameters.keySet()) { List val = parameters.get(key); - if (val != null) transformedParam.addProperty(key, val.get(0)); + if (val != null) + transformedParam.addProperty(key, val.get(0)); } return transformedParam; } enum Operations { - Hello("0.DOIP/Op.Hello"), - ListOps("0.DOIP/Op.ListOperations"), - Retrieve("0.DOIP/Op.Retrieve"), - RetrieveYPK("86.BDWare/Op.RetrieveYPK"), - Create("0.DOIP/Op.Create"), - Update("0.DOIP/Op.Update"), - Delete("0.DOIP/Op.Delete"), - Search("0.DOIP/Op.Search"), - Extension("0.DOIP/Op.Extension"), - Unknown("0.DOIP/Op.Unknown"); + Hello("0.DOIP/Op.Hello"), ListOps("0.DOIP/Op.ListOperations"), Retrieve( + "0.DOIP/Op.Retrieve"), RetrieveYPK("86.BDWare/Op.RetrieveYPK"), Create( + "0.DOIP/Op.Create"), Update("0.DOIP/Op.Update"), Delete( + "0.DOIP/Op.Delete"), Search("0.DOIP/Op.Search"), Extension( + "0.DOIP/Op.Extension"), Unknown("0.DOIP/Op.Unknown"); + private final String val; Operations(String s) { @@ -349,7 +323,8 @@ public class DOIPOverHttpHandler { public static Operations parse(String str) { for (Operations ops : EnumSet.allOf(Operations.class)) { - if (ops.val.equals(str)) return ops; + if (ops.val.equals(str)) + return ops; } return null; } diff --git a/src/main/java/org/bdware/server/nodecenter/client/NodeCenterClientController.java b/src/main/java/org/bdware/server/nodecenter/client/NodeCenterClientController.java index 7a8471f..bda517a 100644 --- a/src/main/java/org/bdware/server/nodecenter/client/NodeCenterClientController.java +++ b/src/main/java/org/bdware/server/nodecenter/client/NodeCenterClientController.java @@ -43,7 +43,7 @@ public class NodeCenterClientController implements NodeCenterConn { private static boolean startCheck = false; private final NetNeighbors neighbors; public Map distributeReqMap = new ConcurrentHashMap<>(); - // public NodeCenterClientController cmClientController; + // public NodeCenterClientController cmClientController; String nodeID; NodeCenterClientHandler handler; // 合约contractID,master的公钥 @@ -123,11 +123,8 @@ public class NodeCenterClientController implements NodeCenterConn { setNodeID.put("id", keyPair.getPublicKeyStr()); String signature = "no signature"; try { - byte[] sig = - SM2Util.sign( - keyPair.getPrivateKeyParameter(), - (keyPair.getPublicKeyStr() + json.get("session").getAsString()) - .getBytes()); + byte[] sig = SM2Util.sign(keyPair.getPrivateKeyParameter(), + (keyPair.getPublicKeyStr() + json.get("session").getAsString()).getBytes()); signature = ByteUtils.toHexString(sig); } catch (Exception e) { e.printStackTrace(); @@ -148,8 +145,8 @@ public class NodeCenterClientController implements NodeCenterConn { @Action public void syncPong(JsonObject json, ResultCallback resultCallback) { - sync.wakeUp( - json.get("requestID").getAsString(), "{\"status\":\"Success\",\"result\":\"a\"}"); + sync.wakeUp(json.get("requestID").getAsString(), + "{\"status\":\"Success\",\"result\":\"a\"}"); } public boolean syncPing() { @@ -172,12 +169,9 @@ public class NodeCenterClientController implements NodeCenterConn { } public void listCMInfo() { - sendMsg( - "{\"action\":\"listCMInfo\",\"pubKey\":\"" - + KeyValueDBUtil.instance.getValue(CMTables.ConfigDB.toString(), "pubKey") - + "\",\"requestID\":\"" - + System.currentTimeMillis() - + "\"}"); + sendMsg("{\"action\":\"listCMInfo\",\"pubKey\":\"" + + KeyValueDBUtil.instance.getValue(CMTables.ConfigDB.toString(), "pubKey") + + "\",\"requestID\":\"" + System.currentTimeMillis() + "\"}"); } @Action @@ -229,7 +223,8 @@ public class NodeCenterClientController implements NodeCenterConn { @Action(async = true) public void publishEventFromCenter(JsonObject jo, ResultCallback rcb) { if (jo.has("event")) { - CMActions.manager.deliverEvent(JsonUtil.fromJson(jo.get("event").getAsString(), REvent.class)); + 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); ByteArrayOutputStream bo = new ByteArrayOutputStream(); 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); } resp.addProperty("readmeStr", bo.toString()); @@ -277,17 +272,18 @@ public class NodeCenterClientController implements NodeCenterConn { String requestID = jo.get("requestID").getAsString(); String requesterNodeID = jo.get("requesterNodeID").getAsString(); String crStr = jo.get("contractRequest").getAsString(); - CMActions.manager.executeLocallyAsync(JsonUtil.fromJson(crStr, ContractRequest.class), new ResultCallback() { - @Override - public void onResult(String str) { - JsonObject ret = new JsonObject(); - ret.addProperty("action", "onReceiveContractExecution"); - ret.addProperty("requestID", requestID); - ret.addProperty("requesterNodeID", requesterNodeID); - ret.addProperty("contractResult", str); - sendMsg(JsonUtil.toJson(ret)); - } - },null); + CMActions.manager.executeLocallyAsync(JsonUtil.fromJson(crStr, ContractRequest.class), + new ResultCallback() { + @Override + public void onResult(String str) { + JsonObject ret = new JsonObject(); + ret.addProperty("action", "onReceiveContractExecution"); + ret.addProperty("requestID", requestID); + ret.addProperty("requesterNodeID", requesterNodeID); + ret.addProperty("contractResult", str); + sendMsg(JsonUtil.toJson(ret)); + } + }, null); } @Action(async = true) @@ -357,15 +353,15 @@ public class NodeCenterClientController implements NodeCenterConn { String requestID = System.currentTimeMillis() + "_" + (int) (Math.random() * 100000); req.put("requestID", requestID); sendMsg(JsonUtil.toJson(req)); - //TODO use async instead? + // TODO use async instead? ContractResult cr = sync.syncSleep(requestID); LOGGER.debug("result: " + JsonUtil.toJson(cr)); LOGGER.info("node " + pubKey + " succeed!"); if (!cr.result.equals(JsonNull.INSTANCE)) { try { JsonObject jo = cr.result.getAsJsonObject(); - NetworkManager.instance.updateAgentRouter( - jo.get("pubKey").getAsString(), jo.get("masterAddress").getAsString()); + NetworkManager.instance.updateAgentRouter(jo.get("pubKey").getAsString(), + jo.get("masterAddress").getAsString()); NetworkManager.instance.connectToAgent(jo.get("pubKey").getAsString(), null); return "success"; } catch (Exception e) { @@ -389,18 +385,17 @@ public class NodeCenterClientController implements NodeCenterConn { if (!cr.result.equals(JsonNull.INSTANCE)) { try { JsonObject jo = cr.result.getAsJsonObject(); - NetworkManager.instance.updateAgentRouter( - jo.get("pubKey").getAsString(), jo.get("masterAddress").getAsString()); + NetworkManager.instance.updateAgentRouter(jo.get("pubKey").getAsString(), + jo.get("masterAddress").getAsString()); NetworkManager.instance.connectToAgent(jo.get("pubKey").getAsString(), null); - LOGGER.info( - String.format("the master of contract %s: pubKey=%s address=%s", - contractID, - jo.get("pubKey").getAsString(), - jo.get("masterAddress").getAsString())); + LOGGER.info(String.format("the master of contract %s: pubKey=%s address=%s", + contractID, jo.get("pubKey").getAsString(), + jo.get("masterAddress").getAsString())); contractID2PubKey.put(contractID, jo.get("pubKey").getAsString()); return jo.get("pubKey").getAsString(); } 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) { @@ -419,8 +414,8 @@ public class NodeCenterClientController implements NodeCenterConn { return; } startCheck = true; - for (MultiContractMeta meta : - CMActions.manager.multiContractRecorder.getStatus().values()) { + for (MultiContractMeta meta : CMActions.manager.multiContractRecorder.getStatus() + .values()) { String contractID = meta.getContractID(); LOGGER.info("check master of contract " + contractID); ContractMeta cmeta = CMActions.manager.statusRecorder.getContractMeta(meta.getID()); @@ -434,20 +429,21 @@ public class NodeCenterClientController implements NodeCenterConn { // 该合约可能在这个节点崩溃期间已经被终止,不存在了,这个节点不用恢复这个合约了,直接从数据库中删除 LOGGER.info("该合约在集群已经不存在!"); KeyValueDBUtil.instance.delete(CMTables.UnitContracts.toString(), contractID); - if (KeyValueDBUtil.instance.containsKey( - CMTables.CheckPointLastHash.toString(), contractID)) { - KeyValueDBUtil.instance.delete( - CMTables.CheckPointLastHash.toString(), contractID); + if (KeyValueDBUtil.instance.containsKey(CMTables.CheckPointLastHash.toString(), + contractID)) { + KeyValueDBUtil.instance.delete(CMTables.CheckPointLastHash.toString(), + contractID); } - if (KeyValueDBUtil.instance.containsKey( - CMTables.LastExeSeq.toString(), contractID)) { + if (KeyValueDBUtil.instance.containsKey(CMTables.LastExeSeq.toString(), + contractID)) { KeyValueDBUtil.instance.delete(CMTables.LastExeSeq.toString(), contractID); } continue; } 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(); queryUnitContractsID2(contractID, master); } @@ -488,9 +484,7 @@ public class NodeCenterClientController implements NodeCenterConn { @Action(async = true) public void requestLog(JsonObject json, ResultCallback rc) { - if (!json.has("requestID") - || !json.has("contractID") - || !json.has("offset") + if (!json.has("requestID") || !json.has("contractID") || !json.has("offset") || !json.has("count")) { LOGGER.debug( "[CMClientController] missing arguments, requestID / contractID / offset / count"); @@ -566,7 +560,7 @@ public class NodeCenterClientController implements NodeCenterConn { long total = tempZip.length(); LOGGER.debug("temp length = " + total); long count = 0; - for (int len; (len = (fin.read(buff))) > 0; ) { + for (int len; (len = (fin.read(buff))) > 0;) { LOGGER.debug("read len = " + len); req.put("data", ByteUtil.encodeBASE64(buff, len)); count += len; @@ -630,8 +624,8 @@ public class NodeCenterClientController implements NodeCenterConn { MasterElectTimeRecorder.slaveConnectFinish = System.currentTimeMillis(); // 开启master恢复 - MasterServerRecoverMechAction.newMasterRecover( - contractID, json.get("members").getAsString(), onlineMembers); + MasterServerRecoverMechAction.newMasterRecover(contractID, + json.get("members").getAsString(), onlineMembers); } private boolean waitForConnection(List nodeNames) { @@ -651,7 +645,8 @@ public class NodeCenterClientController implements NodeCenterConn { e.printStackTrace(); } } - } else return true; + } else + return true; } return false; } @@ -667,7 +662,8 @@ public class NodeCenterClientController implements NodeCenterConn { String distributeID = null; if (json.has("distributeID")) distributeID = json.get("distributeID").getAsString(); - else distributeID = json.get("responseID").getAsString(); + else + distributeID = json.get("responseID").getAsString(); ResultCallback to = distributeReqMap.get(distributeID); distributeReqMap.remove(distributeID); to.onResult(json.get("content").getAsString()); @@ -719,13 +715,11 @@ public class NodeCenterClientController implements NodeCenterConn { public void NCStartElect(JsonObject jo, ResultCallback result) { String conID = jo.get("contractID").getAsString(); 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); - LOGGER.info( - "[CMClientController] NCStartElect : contractID=" - + conID - + " client==null:" - + (null == cc)); + LOGGER.info("[CMClientController] NCStartElect : contractID=" + conID + " client==null:" + + (null == cc)); // 不是自己本地的合约 if (null == cc) { @@ -772,7 +766,7 @@ public class NodeCenterClientController implements NodeCenterConn { } public void run() { - for (; ; ) { + for (;;) { if (receiveQueue.size() > 0) { try { JsonObject jo = receiveQueue.poll(); @@ -799,11 +793,12 @@ public class NodeCenterClientController implements NodeCenterConn { boolean isAppend = args.get("isAppend").getAsBoolean(); boolean isDone = args.get("isDone").getAsBoolean(); boolean isPrivate = args.get("isPrivate").getAsBoolean(); - LOGGER.debug( - String.format("isAppend=%b isDone=%b isPrivate=%b", isAppend, isDone, isPrivate)); + LOGGER.debug(String.format("isAppend=%b isDone=%b isPrivate=%b", isAppend, isDone, + isPrivate)); String path = GlobalConf.instance.publicCompiledDir; if (isPrivate && args.has("pubKey")) { - path = GlobalConf.instance.privateCompiledDir + "/" + args.get("pubKey").getAsString(); + path = GlobalConf.instance.privateCompiledDir + "/" + + args.get("pubKey").getAsString(); } File dir = new File(path); if (!dir.exists()) { diff --git a/src/main/java/org/bdware/server/nodecenter/client/NodeCenterClientHandler.java b/src/main/java/org/bdware/server/nodecenter/client/NodeCenterClientHandler.java index 29973ce..943327b 100644 --- a/src/main/java/org/bdware/server/nodecenter/client/NodeCenterClientHandler.java +++ b/src/main/java/org/bdware/server/nodecenter/client/NodeCenterClientHandler.java @@ -20,7 +20,6 @@ import java.io.ByteArrayInputStream; import java.io.InputStreamReader; import java.util.HashMap; import java.util.Map; -import java.util.concurrent.ConcurrentHashMap; import static org.bdware.server.CMHttpServer.pluginLoader; @@ -31,7 +30,7 @@ public class NodeCenterClientHandler extends SimpleChannelInboundHandler public boolean hasPermission; private final NodeCenterClientController controller; Channel channel; - // UDPTrustfulExecutor udpExecutor; + // UDPTrustfulExecutor udpExecutor; // RecoverMechExecutor recoverMechExecutor; ActionExecutor ae; private boolean isConnected; @@ -82,8 +81,8 @@ public class NodeCenterClientHandler extends SimpleChannelInboundHandler } public synchronized void sendMsg(String msg) { - // logger.debug("[CMClientHandler] sendMsg, TID:" + - // Thread.currentThread().getId() + msg+" isActive:"+channel.isActive()+" + // logger.debug("[CMClientHandler] sendMsg, TID:" + + // Thread.currentThread().getId() + msg+" isActive:"+channel.isActive()+" // "+channel.isOpen()); ByteBuf buf = Unpooled.wrappedBuffer(msg.getBytes()); channel.writeAndFlush(buf); @@ -100,19 +99,16 @@ public class NodeCenterClientHandler extends SimpleChannelInboundHandler final JsonObject arg = JsonParser.parseReader(new InputStreamReader(new ByteArrayInputStream(bytes))) .getAsJsonObject(); - // logger.debug("[CMClient] receive:" + arg.toString()); + // logger.debug("[CMClient] receive:" + arg.toString()); if (arg.has("action")) { final String action = arg.get("action").getAsString(); - ae.handle( - action, - arg, - new ResultCallback() { - @Override - public void onResult(String str) { - sendMsg(str); - } - }); + ae.handle(action, arg, new ResultCallback() { + @Override + public void onResult(String str) { + sendMsg(str); + } + }); } } catch (java.lang.IllegalArgumentException e) { @@ -136,7 +132,8 @@ public class NodeCenterClientHandler extends SimpleChannelInboundHandler public void close() { try { isConnected = false; - if (channel != null) channel.close(); + if (channel != null) + channel.close(); } catch (Exception e) { e.printStackTrace(); } finally { diff --git a/src/main/java/org/bdware/server/tcp/PubkeyResultCallback.java b/src/main/java/org/bdware/server/tcp/PubkeyResultCallback.java index b360d75..2670c06 100644 --- a/src/main/java/org/bdware/server/tcp/PubkeyResultCallback.java +++ b/src/main/java/org/bdware/server/tcp/PubkeyResultCallback.java @@ -19,4 +19,4 @@ public class PubkeyResultCallback extends ResultCallback { public void onResult(String str) { rc.onResult(str); } -} \ No newline at end of file +} diff --git a/src/main/java/org/bdware/server/tcp/TCPClientFrameHandler.java b/src/main/java/org/bdware/server/tcp/TCPClientFrameHandler.java index c37a62b..9bf1f73 100644 --- a/src/main/java/org/bdware/server/tcp/TCPClientFrameHandler.java +++ b/src/main/java/org/bdware/server/tcp/TCPClientFrameHandler.java @@ -40,16 +40,10 @@ public class TCPClientFrameHandler extends SimpleChannelInboundHandler { public TCPClientFrameHandler(String masterPubkey) { master = masterPubkey; aliveCheckClientAction = new AliveCheckClientAction(masterPubkey); - ae = new ActionExecutor<>( - executorService, - aliveCheckClientAction, - new MasterClientTCPAction(), - new MasterClientRecoverMechAction(), - MasterClientTransferAction.instance, - new MasterServerRecoverMechAction(), - new MasterServerTransferAction(), - new MasterServerTCPAction(), - new EventActions()); + ae = new ActionExecutor<>(executorService, aliveCheckClientAction, + new MasterClientTCPAction(), new MasterClientRecoverMechAction(), + MasterClientTransferAction.instance, new MasterServerRecoverMechAction(), + new MasterServerTransferAction(), new MasterServerTCPAction(), new EventActions()); for (String str : clientToAgentPlugins) { Object obj = createInstanceByClzName(str); ae.appendHandler(obj); @@ -66,21 +60,22 @@ public class TCPClientFrameHandler extends SimpleChannelInboundHandler { } -// public void updateContractID2Client(String contract) { -// // 如果该合约正在和旧的master保持连接 -// if (MasterClientTCPAction.contractID2MasterInfo.containsKey(contract)) { -// MasterClientTCPAction former = -// MasterClientTCPAction.contractID2MasterInfo.get(contract); -// former.closeMaster(); -// } -// -// MasterClientTCPAction.contractID2MasterInfo.put(contract, actions); -// } + // public void updateContractID2Client(String contract) { + // // 如果该合约正在和旧的master保持连接 + // if (MasterClientTCPAction.contractID2MasterInfo.containsKey(contract)) { + // MasterClientTCPAction former = + // MasterClientTCPAction.contractID2MasterInfo.get(contract); + // former.closeMaster(); + // } + // + // MasterClientTCPAction.contractID2MasterInfo.put(contract, actions); + // } public void close() { try { aliveCheckClientAction.closeMaster(); - if (channel != null) channel.close(); + if (channel != null) + channel.close(); } catch (Exception e) { e.printStackTrace(); } finally { @@ -108,7 +103,8 @@ public class TCPClientFrameHandler extends SimpleChannelInboundHandler { ByteBuf bb = (ByteBuf) frame; JsonObject arg; try { - arg = JsonUtil.parseReaderAsJsonObject(new InputStreamReader(new ByteBufInputStream(bb))); + arg = JsonUtil + .parseReaderAsJsonObject(new InputStreamReader(new ByteBufInputStream(bb))); } catch (Exception e) { e.printStackTrace(); Response response = new Response(); @@ -126,10 +122,7 @@ public class TCPClientFrameHandler extends SimpleChannelInboundHandler { sendMsg(ret); } }); - ae.handle( - action, - arg, pc - ); + ae.handle(action, arg, pc); } catch (IllegalArgumentException e) { response = new Response(); response.action = "onException"; @@ -145,12 +138,9 @@ public class TCPClientFrameHandler extends SimpleChannelInboundHandler { StringBuilder ret = new StringBuilder(); int count = 0; for (String s : strs) { - if (s.contains("sun.reflect") - || s.contains("java.lang.reflect") - || s.contains("org.apache") - || s.contains("java.util") - || s.contains("java.lang") - || s.contains("io.netty")) { + if (s.contains("sun.reflect") || s.contains("java.lang.reflect") + || s.contains("org.apache") || s.contains("java.util") + || s.contains("java.lang") || s.contains("io.netty")) { continue; } ret.append(s); diff --git a/src/main/java/org/bdware/server/tcp/TCPServerFrameHandler.java b/src/main/java/org/bdware/server/tcp/TCPServerFrameHandler.java index ffcaa13..370f2b2 100644 --- a/src/main/java/org/bdware/server/tcp/TCPServerFrameHandler.java +++ b/src/main/java/org/bdware/server/tcp/TCPServerFrameHandler.java @@ -31,52 +31,44 @@ public class TCPServerFrameHandler extends SimpleChannelInboundHandler { public TCPServerFrameHandler() { checkAction = new AliveCheckServerAction(this); - ae = - new ActionExecutor( - executorService, - checkAction, - new MasterClientTCPAction(), - new MasterClientRecoverMechAction(), - MasterClientTransferAction.instance, - new MasterServerRecoverMechAction(), - new MasterServerTransferAction(), - new MasterServerTCPAction(), - new EventActions()) { - @Override - public boolean checkPermission( - Action a, final JsonObject args, long permission) { - return true; - // long val = a.userPermission(); - // - // boolean flag; - // String status = "refuse"; - // String action = args.get("action"); - // - // if (val == 0) { - // flag = true; - // status = "accept"; - // } else if ((permission & val) == val) { - // flag = true; - // status = "accept"; - // } else { - // flag = false; - // } - // - // TimeDBUtil.instance.put( - // NCTables.CMLog.toString(), - // "{\"action\":\"" - // + action - // + "\",\"pubKey\":\"" - // + pubKey - // + "\",\"status\":\"" - // + status - // + "\",\"date\":" - // + System.currentTimeMillis() - // + "}"); - // - // return flag; - } - }; + ae = new ActionExecutor(executorService, checkAction, + new MasterClientTCPAction(), new MasterClientRecoverMechAction(), + MasterClientTransferAction.instance, new MasterServerRecoverMechAction(), + new MasterServerTransferAction(), new MasterServerTCPAction(), new EventActions()) { + @Override + public boolean checkPermission(Action a, final JsonObject args, long permission) { + return true; + // long val = a.userPermission(); + // + // boolean flag; + // String status = "refuse"; + // String action = args.get("action"); + // + // if (val == 0) { + // flag = true; + // status = "accept"; + // } else if ((permission & val) == val) { + // flag = true; + // status = "accept"; + // } else { + // flag = false; + // } + // + // TimeDBUtil.instance.put( + // NCTables.CMLog.toString(), + // "{\"action\":\"" + // + action + // + "\",\"pubKey\":\"" + // + pubKey + // + "\",\"status\":\"" + // + status + // + "\",\"date\":" + // + System.currentTimeMillis() + // + "}"); + // + // return flag; + } + }; } @@ -98,8 +90,9 @@ public class TCPServerFrameHandler extends SimpleChannelInboundHandler { ByteBuf bb = (ByteBuf) frame; JsonObject arg; try { - arg = JsonUtil.parseReaderAsJsonObject(new InputStreamReader(new ByteBufInputStream(bb))); - // logger.info("[MasterServer] receive:" + arg.toString()); + arg = JsonUtil + .parseReaderAsJsonObject(new InputStreamReader(new ByteBufInputStream(bb))); + // logger.info("[MasterServer] receive:" + arg.toString()); } catch (Exception e) { e.printStackTrace(); @@ -114,16 +107,14 @@ public class TCPServerFrameHandler extends SimpleChannelInboundHandler { final String action = arg.get("action").getAsString(); - PubkeyResultCallback pubkeyResultCallback = new PubkeyResultCallback(checkAction.pubKey, new ResultCallback() { - @Override - public void onResult(String ret) { - sendMsg(ret); - } - }); - ae.handle( - action, - arg, pubkeyResultCallback - ); + PubkeyResultCallback pubkeyResultCallback = + new PubkeyResultCallback(checkAction.pubKey, new ResultCallback() { + @Override + public void onResult(String ret) { + sendMsg(ret); + } + }); + ae.handle(action, arg, pubkeyResultCallback); } catch (IllegalArgumentException e) { response = new Response(); @@ -141,12 +132,9 @@ public class TCPServerFrameHandler extends SimpleChannelInboundHandler { StringBuilder ret = new StringBuilder(); int count = 0; for (String s : strs) { - if (s.contains("sun.reflect") - || s.contains("java.lang.reflect") - || s.contains("org.apache") - || s.contains("java.util") - || s.contains("java.lang") - || s.contains("io.netty")) { + if (s.contains("sun.reflect") || s.contains("java.lang.reflect") + || s.contains("org.apache") || s.contains("java.util") + || s.contains("java.lang") || s.contains("io.netty")) { continue; } ret.append(s); diff --git a/src/main/java/org/bdware/server/trustedmodel/AgentManager.java b/src/main/java/org/bdware/server/trustedmodel/AgentManager.java index 99d1ce3..7f9f2c9 100644 --- a/src/main/java/org/bdware/server/trustedmodel/AgentManager.java +++ b/src/main/java/org/bdware/server/trustedmodel/AgentManager.java @@ -38,23 +38,19 @@ public class AgentManager implements AgentPeerManagerIntf { if (maxMasterProxyLoad > CongestionControl.maxMasterProxyLoad) CongestionControl.maxMasterProxyLoad = maxMasterProxyLoad; if (CongestionControl.slaveControl()) { - ContractResult cr = - new ContractResult( - ContractResult.Status.Error, - new JsonPrimitive("canceled because of queue too long")); + ContractResult cr = new ContractResult(ContractResult.Status.Error, + new JsonPrimitive("canceled because of queue too long")); cb.onResult(JsonUtil.parseObjectAsJsonObject(cr)); CongestionControl.masterProxyLoad.decrementAndGet(); return; } - MasterServerTCPAction.sync.sleep( - c.getRequestID(), - new ResultCallback() { - @Override - public void onResult(String str) { - cb.onResult(JsonUtil.parseStringAsJsonObject(str)); - CongestionControl.masterProxyLoad.decrementAndGet(); - } - }); + MasterServerTCPAction.sync.sleep(c.getRequestID(), new ResultCallback() { + @Override + public void onResult(String str) { + cb.onResult(JsonUtil.parseStringAsJsonObject(str)); + CongestionControl.masterProxyLoad.decrementAndGet(); + } + }); Map req = new HashMap<>(); req.put("action", "requestContractExecutionServer"); req.put("requestID", c.getRequestID()); @@ -93,8 +89,8 @@ public class AgentManager implements AgentPeerManagerIntf { @Override public void transferToOtherNode(String pubKey, String contractID) { - // TODO 问题1,合约的ypk或者script怎么获取?ypk如果是包含私有路径的可以在Contract中设置一个字段,启动的时候写入吗 目前认为这个从前端传入 - // TODO 问题2 转移过程中进度返回给哪个前端显示?需要显示吗? + // TODO 问题1,合约的ypk或者script怎么获取?ypk如果是包含私有路径的可以在Contract中设置一个字段,启动的时候写入吗 目前认为这个从前端传入 + // TODO 问题2 转移过程中进度返回给哪个前端显示?需要显示吗? LOGGER.info("transferToOtherNode : pubKey=" + pubKey + " contractID=" + contractID); ContractMeta meta = CMActions.manager.statusRecorder.getContractMeta(contractID); MasterClientTransferAction.instance.transferInstance(pubKey, meta.getID()); diff --git a/src/main/java/org/bdware/server/trustedmodel/KillUnitContractResultCollector.java b/src/main/java/org/bdware/server/trustedmodel/KillUnitContractResultCollector.java index 37ed20f..3400f99 100644 --- a/src/main/java/org/bdware/server/trustedmodel/KillUnitContractResultCollector.java +++ b/src/main/java/org/bdware/server/trustedmodel/KillUnitContractResultCollector.java @@ -9,7 +9,7 @@ import java.util.Map; import java.util.concurrent.atomic.AtomicInteger; public class KillUnitContractResultCollector extends ResultCallback { - // private static final Logger LOGGER = LogManager.getLogger(ResultCallback.class); + // private static final Logger LOGGER = LogManager.getLogger(ResultCallback.class); int total; String requestID; AtomicInteger count = new AtomicInteger(0); @@ -24,9 +24,9 @@ public class KillUnitContractResultCollector extends ResultCallback { @Override public void onResult(String str) { - //解析str,判断该节点是否kill成功 - Map map = JsonUtil.fromJson(str, new TypeToken>() { - }.getType()); + // 解析str,判断该节点是否kill成功 + Map map = + JsonUtil.fromJson(str, new TypeToken>() {}.getType()); String data = map.get("data"); if (data != null && data.equals("success")) { // diff --git a/src/main/java/org/bdware/server/trustedmodel/MultiPointContractInfo.java b/src/main/java/org/bdware/server/trustedmodel/MultiPointContractInfo.java index 81bb9f3..2ec275b 100644 --- a/src/main/java/org/bdware/server/trustedmodel/MultiPointContractInfo.java +++ b/src/main/java/org/bdware/server/trustedmodel/MultiPointContractInfo.java @@ -5,9 +5,9 @@ import org.bdware.sc.bean.ContractExecType; import java.util.List; import java.util.concurrent.atomic.AtomicInteger; -//在master上 +// 在master上 public class MultiPointContractInfo { - public List members; //pubKey + public List members; // pubKey public String masterNode; public ContractExecType type; public ContractUnitStatus unitStatus = ContractUnitStatus.CommonMode; diff --git a/src/main/java/org/bdware/server/trustedmodel/MultiPointCooperateContractInfo.java b/src/main/java/org/bdware/server/trustedmodel/MultiPointCooperateContractInfo.java index 997124e..273b5a5 100644 --- a/src/main/java/org/bdware/server/trustedmodel/MultiPointCooperateContractInfo.java +++ b/src/main/java/org/bdware/server/trustedmodel/MultiPointCooperateContractInfo.java @@ -5,10 +5,10 @@ import org.bdware.sc.bean.ContractExecType; import java.util.List; import java.util.concurrent.atomic.AtomicInteger; -//改名 MultiPointCooperateContractInfo +// 改名 MultiPointCooperateContractInfo public class MultiPointCooperateContractInfo extends MultiPointContractInfo { - public List members; //pubKey - public List shardingId; //sharding id 初始化时被分配 + public List members; // pubKey + public List shardingId; // sharding id 初始化时被分配 public String masterNode; public ContractExecType type; public ContractUnitStatus unitStatus = ContractUnitStatus.CommonMode; diff --git a/src/main/java/org/bdware/server/trustedmodel/ResultCollector.java b/src/main/java/org/bdware/server/trustedmodel/ResultCollector.java index f90d4c2..871cd95 100644 --- a/src/main/java/org/bdware/server/trustedmodel/ResultCollector.java +++ b/src/main/java/org/bdware/server/trustedmodel/ResultCollector.java @@ -6,7 +6,7 @@ import org.bdware.server.action.p2p.MasterServerTCPAction; import java.util.concurrent.atomic.AtomicInteger; public class ResultCollector extends ResultCallback { - // private static final Logger LOGGER = LogManager.getLogger(ResultCallback.class); + // private static final Logger LOGGER = LogManager.getLogger(ResultCallback.class); int total; String requestID; AtomicInteger count = new AtomicInteger(0); diff --git a/src/main/java/org/bdware/server/ws/ContractManagerFrameHandler.java b/src/main/java/org/bdware/server/ws/ContractManagerFrameHandler.java index f914faa..bb26195 100644 --- a/src/main/java/org/bdware/server/ws/ContractManagerFrameHandler.java +++ b/src/main/java/org/bdware/server/ws/ContractManagerFrameHandler.java @@ -29,7 +29,7 @@ public class ContractManagerFrameHandler extends SimpleChannelInboundHandler too much method? @@ -45,60 +45,41 @@ public class ContractManagerFrameHandler extends SimpleChannelInboundHandler( - executorService, - cmAction, - //temAction, - fileAction, - ManagerActions.instance, - userManagerAction, - new MasterWSAction(this), // 多节点执行 - new CMLogAction(), - new ProcessAction(), - GRPCPool.instance, - new EventWSActions()) { - @Override - public boolean checkPermission(Action a, JsonObject arg, long permission) { - long val = a.userPermission(); + ae = new ActionExecutor(executorService, cmAction, + // temAction, + fileAction, ManagerActions.instance, userManagerAction, new MasterWSAction(this), // 多节点执行 + new CMLogAction(), new ProcessAction(), GRPCPool.instance, new EventWSActions()) { + @Override + public boolean checkPermission(Action a, JsonObject arg, long permission) { + long val = a.userPermission(); - boolean flag; - String status = "refuse"; - String action = arg.get("action").getAsString(); - if (val == 0) { - flag = true; - status = "accept"; - } else if ((permission & val) == val) { - flag = true; - status = "accept"; - } else { - flag = false; - } - LOGGER.debug( - String.format( - "%s val:%d permission:%d status:%s", - action, - val, - permission, - status)); + boolean flag; + String status = "refuse"; + String action = arg.get("action").getAsString(); + if (val == 0) { + flag = true; + status = "accept"; + } else if ((permission & val) == val) { + flag = true; + status = "accept"; + } else { + flag = false; + } + LOGGER.debug(String.format("%s val:%d permission:%d status:%s", action, val, + permission, status)); - CMHttpServer.nodeLogDB.put( - action, - String.format( - "{\"action\":\"%s\",\"pubKey\":\"%s\",\"status\":\"%s\",\"date\":%d}", - action, - userManagerAction.getPubKey(), - status, - System.currentTimeMillis())); - // TimeDBUtil.instance.put(CMTables.LocalNodeLogDB.toString(), - // sb.toString()); - return flag; - } - }; + CMHttpServer.nodeLogDB.put(action, String.format( + "{\"action\":\"%s\",\"pubKey\":\"%s\",\"status\":\"%s\",\"date\":%d}", + action, userManagerAction.getPubKey(), status, System.currentTimeMillis())); + // TimeDBUtil.instance.put(CMTables.LocalNodeLogDB.toString(), + // sb.toString()); + return flag; + } + }; for (String str : CMHttpHandler.wsPluginActions) { Object obj = createInstanceByClzName(str); ae.appendHandler(obj); @@ -156,8 +137,7 @@ public class ContractManagerFrameHandler extends SimpleChannelInboundHandler 0) { @@ -170,41 +150,39 @@ public class ContractManagerFrameHandler extends SimpleChannelInboundHandler 0) { map.addProperty("verifiedPubKey", userManagerAction.getPubKey()); } final JsonObject jmap = map; - ae.handle( - action, - map, - new ResultCallback(ctx.channel()) { - @Override - public void onResult(Map jo) { - if (jmap.has("requestID")) { - jo.put("responseID", jmap.get("requestID").getAsString()); - } - onResult(JsonUtil.toJson(jo)); - } + ae.handle(action, map, new ResultCallback(ctx.channel()) { + @Override + public void onResult(Map jo) { + if (jmap.has("requestID")) { + jo.put("responseID", jmap.get("requestID").getAsString()); + } + onResult(JsonUtil.toJson(jo)); + } - @Override - public void onResult(JsonObject jo) { - if (jmap.has("requestID")) { - jo.add("responseID", jmap.get("requestID")); - } - onResult(jo.toString()); - } + @Override + public void onResult(JsonObject jo) { + if (jmap.has("requestID")) { + jo.add("responseID", jmap.get("requestID")); + } + onResult(jo.toString()); + } - @Override - public void onResult(String ret) { - if (ret != null) { - ctx.channel().writeAndFlush(new TextWebSocketFrame(ret)); - } - } - }); + @Override + public void onResult(String ret) { + if (ret != null) { + ctx.channel().writeAndFlush(new TextWebSocketFrame(ret)); + } + } + }); } catch (IllegalArgumentException e) { response = new Response(); response.action = "onException"; @@ -239,7 +217,8 @@ public class ContractManagerFrameHandler extends SimpleChannelInboundHandler 5) break; + if (count++ > 5) + break; } response.data = ret.toString(); ctx.channel().writeAndFlush(new TextWebSocketFrame(JsonUtil.toJson(response))); diff --git a/src/main/java/org/bdware/server/ws/WebSocketServer.java b/src/main/java/org/bdware/server/ws/WebSocketServer.java index 0d0a676..9645f1b 100644 --- a/src/main/java/org/bdware/server/ws/WebSocketServer.java +++ b/src/main/java/org/bdware/server/ws/WebSocketServer.java @@ -16,26 +16,30 @@ import org.apache.logging.log4j.Logger; /** * An HTTP server which serves Web Socket requests at: * - *

http://localhost:8080/websocket + *

+ * http://localhost:8080/websocket * - *

Open your browser at http://localhost:8080/, then the - * demo page will be loaded and a Web Socket connection will be made automatically. + *

+ * Open your browser at http://localhost:8080/, then the demo + * page will be loaded and a Web Socket connection will be made automatically. * - *

This server illustrates support for the different web socket specification versions and will - * work with: + *

+ * This server illustrates support for the different web socket specification versions and will work + * with: * *

    - *
  • Safari 5+ (draft-ietf-hybi-thewebsocketprotocol-00) - *
  • Chrome 6-13 (draft-ietf-hybi-thewebsocketprotocol-00) - *
  • Chrome 14+ (draft-ietf-hybi-thewebsocketprotocol-10) - *
  • Chrome 16+ (RFC 6455 aka draft-ietf-hybi-thewebsocketprotocol-17) - *
  • Firefox 7+ (draft-ietf-hybi-thewebsocketprotocol-10) - *
  • Firefox 11+ (RFC 6455 aka draft-ietf-hybi-thewebsocketprotocol-17) + *
  • Safari 5+ (draft-ietf-hybi-thewebsocketprotocol-00) + *
  • Chrome 6-13 (draft-ietf-hybi-thewebsocketprotocol-00) + *
  • Chrome 14+ (draft-ietf-hybi-thewebsocketprotocol-10) + *
  • Chrome 16+ (RFC 6455 aka draft-ietf-hybi-thewebsocketprotocol-17) + *
  • Firefox 7+ (draft-ietf-hybi-thewebsocketprotocol-10) + *
  • Firefox 11+ (RFC 6455 aka draft-ietf-hybi-thewebsocketprotocol-17) *
*/ public final class WebSocketServer { 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); public static void main(String[] args) throws Exception { @@ -52,19 +56,14 @@ public final class WebSocketServer { EventLoopGroup workerGroup = new NioEventLoopGroup(); try { ServerBootstrap b = new ServerBootstrap(); - b.group(bossGroup, workerGroup) - .channel(NioServerSocketChannel.class) + b.group(bossGroup, workerGroup).channel(NioServerSocketChannel.class) .handler(new LoggingHandler(LogLevel.INFO)) .childHandler(new WebSocketServerInitializer(sslCtx)); Channel ch = b.bind(PORT).sync().channel(); - LOGGER.info( - "Open your web browser and navigate to " - + (SSL ? "https" : "http") - + "://127.0.0.1:" - + PORT - + '/'); + LOGGER.info("Open your web browser and navigate to " + (SSL ? "https" : "http") + + "://127.0.0.1:" + PORT + '/'); ch.closeFuture().sync(); } finally { diff --git a/src/main/java/org/bdware/server/ws/WebSocketServerInitializer.java b/src/main/java/org/bdware/server/ws/WebSocketServerInitializer.java index 1a59345..95bbf10 100644 --- a/src/main/java/org/bdware/server/ws/WebSocketServerInitializer.java +++ b/src/main/java/org/bdware/server/ws/WebSocketServerInitializer.java @@ -13,25 +13,25 @@ import io.netty.handler.ssl.SslContext; */ public class WebSocketServerInitializer extends ChannelInitializer { - private static final String WEBSOCKET_PATH = "/websocket"; + private static final String WEBSOCKET_PATH = "/websocket"; - private final SslContext sslCtx; + private final SslContext sslCtx; - public WebSocketServerInitializer(SslContext sslCtx) { - this.sslCtx = sslCtx; - } + public WebSocketServerInitializer(SslContext sslCtx) { + this.sslCtx = sslCtx; + } - @Override - public void initChannel(SocketChannel ch) throws Exception { - ChannelPipeline pipeline = ch.pipeline(); - if (sslCtx != null) { - pipeline.addLast(sslCtx.newHandler(ch.alloc())); - } - pipeline.addLast(new HttpServerCodec()); - pipeline.addLast(new HttpObjectAggregator(65536)); - pipeline.addLast(new WebSocketServerCompressionHandler()); - pipeline.addLast(new WebSocketServerProtocolHandler(WEBSOCKET_PATH, null, true)); - pipeline.addLast(new WebSocketIndexPageHandler(WEBSOCKET_PATH)); - pipeline.addLast(new ContractManagerFrameHandler()); - } -} \ No newline at end of file + @Override + public void initChannel(SocketChannel ch) throws Exception { + ChannelPipeline pipeline = ch.pipeline(); + if (sslCtx != null) { + pipeline.addLast(sslCtx.newHandler(ch.alloc())); + } + pipeline.addLast(new HttpServerCodec()); + pipeline.addLast(new HttpObjectAggregator(65536)); + pipeline.addLast(new WebSocketServerCompressionHandler()); + pipeline.addLast(new WebSocketServerProtocolHandler(WEBSOCKET_PATH, null, true)); + pipeline.addLast(new WebSocketIndexPageHandler(WEBSOCKET_PATH)); + pipeline.addLast(new ContractManagerFrameHandler()); + } +} diff --git a/src/main/java/org/bdware/units/NetworkManager.java b/src/main/java/org/bdware/units/NetworkManager.java index a55c478..266d48a 100644 --- a/src/main/java/org/bdware/units/NetworkManager.java +++ b/src/main/java/org/bdware/units/NetworkManager.java @@ -41,10 +41,11 @@ import java.util.concurrent.TimeUnit; * @author OliveDS (Shuang Deng) */ public class NetworkManager { - //Manage server->client connection; + // Manage server->client connection; public static final Map CONNECTORS = new ConcurrentHashMap<>(); - //Manage client->server connection; - public static final Map SERVER_CONNECTORS = new ConcurrentHashMap<>(); + // Manage client->server connection; + public static final Map SERVER_CONNECTORS = + new ConcurrentHashMap<>(); public static final String NODE_CENTER_CLIENT = "NODE_CENTER_CLIENT"; public static final String P2P_GRPC_CLIENT = "P2P_GRPC_CLIENT"; private static final Map slaverRouter = new HashMap<>(); @@ -59,18 +60,13 @@ public class NetworkManager { } public static void reconnectAgent(String master) { - LOGGER.debug( - String.format("master=%s\t%s", - master, - JsonUtil.toJson(slaverRouter))); + LOGGER.debug(String.format("master=%s\t%s", master, JsonUtil.toJson(slaverRouter))); try { NetworkManager.AgentConnector conn; synchronized (conn = NetworkManager.CONNECTORS.get(master)) { if (!conn.handler.isOpen()) { String[] ipAndPort = slaverRouter.get(master).split(":"); - conn.bootstrap - .connect(ipAndPort[0], Integer.parseInt(ipAndPort[1])) - .sync() + conn.bootstrap.connect(ipAndPort[0], Integer.parseInt(ipAndPort[1])).sync() .channel(); } } @@ -94,46 +90,36 @@ public class NetworkManager { nodeCenterClientHandler = ControllerManager.createNodeCenterClientHandler(); EventLoopGroup group = new NioEventLoopGroup(); b.group(group); - b.channel(NioSocketChannel.class) - .handler( - new ChannelInitializer() { - @Override - protected void initChannel(SocketChannel ch) { - ChannelPipeline p = ch.pipeline(); - p.addLast(new DelimiterCodec()).addLast(nodeCenterClientHandler); - } - }); - ContractManager.scheduledThreadPool.scheduleWithFixedDelay( - () -> { - try { - // manager.clearCache(); - String URL = GlobalConf.getNodeCenterUrl(); -// LOGGER.debug("GlobalConf.getNodeCenterUrl() -> URL=" + URL); - URI uri = null; - try { - uri = new URI(URL); - } catch (URISyntaxException e) { - LOGGER.error("creating uri failed! " + e.getMessage()); - } - if (!nodeCenterClientHandler.isConnected() - || !ControllerManager.getNodeCenterController().syncPing()) { - nodeCenterClientHandler.close(); - assert null != uri; - b.connect(uri.getHost(), uri.getPort()).sync().channel(); - LOGGER.info( - "connect to node center: " - + uri.getHost() - + ":" - + uri.getPort()); - } - } catch (Exception e) { -// e.printStackTrace(); - LOGGER.warn("connecting to node center failed! " + e.getMessage()); - } - }, - 0, - 30 + (int) (20 * Math.random()), - TimeUnit.SECONDS); + b.channel(NioSocketChannel.class).handler(new ChannelInitializer() { + @Override + protected void initChannel(SocketChannel ch) { + ChannelPipeline p = ch.pipeline(); + p.addLast(new DelimiterCodec()).addLast(nodeCenterClientHandler); + } + }); + ContractManager.scheduledThreadPool.scheduleWithFixedDelay(() -> { + try { + // manager.clearCache(); + String URL = GlobalConf.getNodeCenterUrl(); + // LOGGER.debug("GlobalConf.getNodeCenterUrl() -> URL=" + URL); + URI uri = null; + try { + uri = new URI(URL); + } catch (URISyntaxException e) { + LOGGER.error("creating uri failed! " + e.getMessage()); + } + if (!nodeCenterClientHandler.isConnected() + || !ControllerManager.getNodeCenterController().syncPing()) { + nodeCenterClientHandler.close(); + assert null != uri; + b.connect(uri.getHost(), uri.getPort()).sync().channel(); + LOGGER.info("connect to node center: " + uri.getHost() + ":" + uri.getPort()); + } + } catch (Exception e) { + // e.printStackTrace(); + LOGGER.warn("connecting to node center failed! " + e.getMessage()); + } + }, 0, 30 + (int) (20 * Math.random()), TimeUnit.SECONDS); } @@ -142,20 +128,16 @@ public class NetworkManager { ServerBootstrap b = new ServerBootstrap(); EventLoopGroup bossGroup = new NioEventLoopGroup(1); b.option(ChannelOption.ALLOCATOR, PooledByteBufAllocator.DEFAULT); - b.group(bossGroup, workerGroup) - .channel(NioServerSocketChannel.class) - .option(ChannelOption.SO_BACKLOG, 100) - .localAddress(port) + b.group(bossGroup, workerGroup).channel(NioServerSocketChannel.class) + .option(ChannelOption.SO_BACKLOG, 100).localAddress(port) .childOption(ChannelOption.SO_KEEPALIVE, true) - .childHandler( - new ChannelInitializer() { - @Override - protected void initChannel(SocketChannel arg0) { - arg0.pipeline() - .addLast(new DelimiterCodec()) - .addLast(new TCPServerFrameHandler()); - } - }); + .childHandler(new ChannelInitializer() { + @Override + protected void initChannel(SocketChannel arg0) { + arg0.pipeline().addLast(new DelimiterCodec()) + .addLast(new TCPServerFrameHandler()); + } + }); b.bind(port).sync().channel(); } catch (InterruptedException e) { @@ -164,7 +146,7 @@ public class NetworkManager { } - //TODO Remove in future + // TODO Remove in future public void sendToNodeCenter(String msg) { nodeCenterClientHandler.sendMsg(msg); } @@ -174,9 +156,8 @@ public class NetworkManager { } public void waitForNodeCenterConnected() { - for (int i = 0; - i < 10 && null != nodeCenterClientHandler && !nodeCenterClientHandler.isConnected(); - i++) { + for (int i = 0; i < 10 && null != nodeCenterClientHandler + && !nodeCenterClientHandler.isConnected(); i++) { try { Thread.sleep(200); } catch (InterruptedException e) { @@ -191,7 +172,7 @@ public class NetworkManager { } } - //----------AgentNetworkManagement + // ----------AgentNetworkManagement public void updateAgentRouter(String nodeID, String address) { @@ -233,15 +214,13 @@ public class NetworkManager { connector.handler = handler; b.option(ChannelOption.CONNECT_TIMEOUT_MILLIS, 5000); b.group(CMHttpServer.workerGroup); - b.channel(NioSocketChannel.class) - .handler( - new ChannelInitializer() { - @Override - protected void initChannel(SocketChannel ch) { - ChannelPipeline p = ch.pipeline(); - p.addLast(new DelimiterCodec()).addLast(handler); - } - }); + b.channel(NioSocketChannel.class).handler(new ChannelInitializer() { + @Override + protected void initChannel(SocketChannel ch) { + ChannelPipeline p = ch.pipeline(); + p.addLast(new DelimiterCodec()).addLast(handler); + } + }); } reconnectAgent(master); } @@ -292,8 +271,8 @@ public class NetworkManager { return CONNECTORS.containsKey(pubKey); } - //-------UNUSED TOMerge------------ - //UNUSED + // -------UNUSED TOMerge------------ + // UNUSED public TCPClientFrameHandler createTCPClient(String peer, String ipPort) throws InterruptedException { if (peer.equals(GlobalConf.instance.peerID)) { @@ -306,30 +285,28 @@ public class NetworkManager { NioEventLoopGroup group = new NioEventLoopGroup(); Bootstrap b = new Bootstrap(); final TCPClientFrameHandler handler = new TCPClientFrameHandler(peer); - //tcpClientMap.put(peer, handler); - b.group(group) - .channel(NioSocketChannel.class) + // tcpClientMap.put(peer, handler); + b.group(group).channel(NioSocketChannel.class) .remoteAddress(new InetSocketAddress(host, port)) .option(ChannelOption.TCP_NODELAY, true) - .handler( - new ChannelInitializer() { - @Override - public void initChannel(SocketChannel ch) throws Exception { - ch.pipeline() - // .addLast(new - // IdleStateHandler(0, 4, 0, TimeUnit.SECONDS)) - .addLast(new DelimiterCodec()) - .addLast(new IdleStateHandler(0, 5, 0)) - // .addLast(new - // HeartBeatEncode()) - .addLast(handler); - } - }); + .handler(new ChannelInitializer() { + @Override + public void initChannel(SocketChannel ch) throws Exception { + ch.pipeline() + // .addLast(new + // IdleStateHandler(0, 4, 0, TimeUnit.SECONDS)) + .addLast(new DelimiterCodec()) + .addLast(new IdleStateHandler(0, 5, 0)) + // .addLast(new + // HeartBeatEncode()) + .addLast(handler); + } + }); ChannelFuture f = b.connect().sync(); if (f.isSuccess()) { LOGGER.info("TCP Client " + peer + " started"); } - // channel = (SocketChannel) future.channel(); + // channel = (SocketChannel) future.channel(); return handler; } @@ -352,14 +329,14 @@ public class NetworkManager { } /** - * UNUSED send to TCP nodes, if fail send by p2p + * UNUSED send to TCP nodes, if fail send by p2p * * @param msg unit message */ public void send(UnitMessage msg) { Iterator iterator = msg.getReceiverList().iterator(); String peer; - // boolean sendByP2P = false; + // boolean sendByP2P = false; TCPClientFrameHandler tcpClientFrameHandler; while (iterator.hasNext()) { peer = iterator.next(); @@ -368,17 +345,16 @@ public class NetworkManager { LOGGER.info("send msg to itself " + msg); continue; } - // tcpClientFrameHandler = NetworkManager.instance.tcpClientMap.getOrDefault(peer, null); + // tcpClientFrameHandler = NetworkManager.instance.tcpClientMap.getOrDefault(peer, + // null); if (peerID2TCPAddress.containsKey(peer)) { - //recreateTCPClient(peer); - // instance.tcpClientMap.put(peer, tcpClientFrameHandler); - UnitMessage unitMessage = - msg.toBuilder().clearReceiver().addReceiver(peer).build(); + // recreateTCPClient(peer); + // instance.tcpClientMap.put(peer, tcpClientFrameHandler); + UnitMessage unitMessage = msg.toBuilder().clearReceiver().addReceiver(peer).build(); LOGGER.info("send msg by p2p to " + peer); JavaContractServiceGrpcServer.sendMsg(unitMessage); } else { - UnitMessage unitMessage = - msg.toBuilder().clearReceiver().addReceiver(peer).build(); + UnitMessage unitMessage = msg.toBuilder().clearReceiver().addReceiver(peer).build(); LOGGER.info("send msg by p2p to " + peer); JavaContractServiceGrpcServer.sendMsg(unitMessage); } diff --git a/src/main/java/org/bdware/units/beans/MultiPointContractInfo.java b/src/main/java/org/bdware/units/beans/MultiPointContractInfo.java index 359dffa..5aab773 100644 --- a/src/main/java/org/bdware/units/beans/MultiPointContractInfo.java +++ b/src/main/java/org/bdware/units/beans/MultiPointContractInfo.java @@ -1,6 +1,5 @@ package org.bdware.units.beans; -import org.bdware.sc.bean.ContractExecType; import org.bdware.units.enums.ConsensusType; import org.bdware.units.enums.NetworkType; import org.bdware.units.enums.ResponseType; @@ -11,29 +10,33 @@ public class MultiPointContractInfo { public Set members; public Map member2PubKey; public String master; -// public ContractType contractType; + // public ContractType contractType; public String contractId; public ConsensusType consensusType; public ResponseType responseType; public NetworkType networkType; - public MultiPointContractInfo(){ -// member2PubKey = new HashMap<>(10); -// members = new HashSet<>(10); + public MultiPointContractInfo() { + // member2PubKey = new HashMap<>(10); + // members = new HashSet<>(10); } public Set getMembers() { return members; } + public String getContractId() { return contractId; } + public String getMaster() { return master; } + public boolean hasPeer(String peerID) { return members.contains(peerID); } + public String getPubKey(String peerID) { return member2PubKey.get(peerID); diff --git a/src/main/java/org/bdware/units/beans/UnitContractMessage.java b/src/main/java/org/bdware/units/beans/UnitContractMessage.java index be9d777..a8665e6 100644 --- a/src/main/java/org/bdware/units/beans/UnitContractMessage.java +++ b/src/main/java/org/bdware/units/beans/UnitContractMessage.java @@ -4,6 +4,7 @@ import java.io.Serializable; /** * ExecutionManager内部消息,封装在UnitMessage中作为content + * * @author oliveds */ public class UnitContractMessage implements Serializable { diff --git a/src/main/java/org/bdware/units/consensus/ConsensusAlgorithm.java b/src/main/java/org/bdware/units/consensus/ConsensusAlgorithm.java index 2f10c57..d36e0e1 100644 --- a/src/main/java/org/bdware/units/consensus/ConsensusAlgorithm.java +++ b/src/main/java/org/bdware/units/consensus/ConsensusAlgorithm.java @@ -12,4 +12,4 @@ public interface ConsensusAlgorithm { void setCommitter(Committer c); void setConnection(TrustfulExecutorConnection c); -} \ No newline at end of file +} diff --git a/src/main/java/org/bdware/units/consensus/ConsensusCenter.java b/src/main/java/org/bdware/units/consensus/ConsensusCenter.java index dbf65ea..add98af 100644 --- a/src/main/java/org/bdware/units/consensus/ConsensusCenter.java +++ b/src/main/java/org/bdware/units/consensus/ConsensusCenter.java @@ -8,7 +8,7 @@ public interface ConsensusCenter { void handle(UnitSequencingMessage unitSequencingMessage); -// void updateMaster(String master); + // void updateMaster(String master); -// UnitSequencingMessage formConsensusRequest(UnitContractMessage msg); + // UnitSequencingMessage formConsensusRequest(UnitContractMessage msg); } diff --git a/src/main/java/org/bdware/units/consensus/PBFTCenter.java b/src/main/java/org/bdware/units/consensus/PBFTCenter.java index 9e355c7..7c19367 100644 --- a/src/main/java/org/bdware/units/consensus/PBFTCenter.java +++ b/src/main/java/org/bdware/units/consensus/PBFTCenter.java @@ -23,8 +23,8 @@ public class PBFTCenter implements ConsensusCenter { MultiPointContractInfo contractInfo; Map infos; Map committedMsg; - // Map original; -// String master; + // Map original; + // String master; boolean isMaster; private String contractID; private NetworkType networkType; @@ -36,12 +36,12 @@ public class PBFTCenter implements ConsensusCenter { networkType = NetworkType.getType(msg.network); infos = new HashMap<>(); committedMsg = new HashMap<>(); -// original = new HashMap<>(); + // original = new HashMap<>(); // receive init, then insert -// members = ContractUnitManager.instance.getContractInfo(contractID); -// if (members.master.equals(GlobalConf.instance.peerID)) { -// isMaster = true; -// } + // members = ContractUnitManager.instance.getContractInfo(contractID); + // if (members.master.equals(GlobalConf.instance.peerID)) { + // isMaster = true; + // } } @Override @@ -59,32 +59,33 @@ public class PBFTCenter implements ConsensusCenter { PBFTInfo temp; switch (ConsensusStage.fromByte(unitSequencingMessage.stageType)) { case Init: - MultiPointContractInfo contractInfo = - JsonUtil.fromJson(unitSequencingMessage.content, MultiPointContractInfo.class); + MultiPointContractInfo contractInfo = JsonUtil + .fromJson(unitSequencingMessage.content, MultiPointContractInfo.class); updateUnitInfo(contractInfo); break; case AddMember: -// PBFTMember member = PBFTMember.parse(pbftMessage.content); -// if (member != null) -// members.put(sender, member); -// case DeleteMember: + // PBFTMember member = PBFTMember.parse(pbftMessage.content); + // if (member != null) + // members.put(sender, member); + // case DeleteMember: break; case Request: // master form preprepare, full content -// int hash = unitSequencingMessage.content.hashCode(); -// original.put(hash, new Pair(sender, pbftMessage)); + // int hash = unitSequencingMessage.content.hashCode(); + // original.put(hash, new Pair(sender, pbftMessage)); if (isMaster) { temp = new PBFTInfo(); temp.order = allocatedID.incrementAndGet(); temp.request = unitSequencingMessage.content; infos.put(temp.order, temp); -// original.put(unitSequencingMessage.requestID, temp); + // original.put(unitSequencingMessage.requestID, temp); unitSequencingMessage.stageType = PBFTType.PrePrepare.toInt(); unitSequencingMessage.order = temp.order; -// unitSequencingMessage.content = unitSequencingMessage.content.hashCode() + ""; + // unitSequencingMessage.content = unitSequencingMessage.content.hashCode() + + // ""; broadcast(unitSequencingMessage); } else { -// sendToMaster(unitSequencingMessage); + // sendToMaster(unitSequencingMessage); } break; case PrePrepare: @@ -111,7 +112,7 @@ public class PBFTCenter implements ConsensusCenter { } if (temp.updatePrepare(unitSequencingMessage, this)) { UnitSequencingMessage commitMsg = temp.formCommit(unitSequencingMessage); -// temp.updateCommit(commitMsg, this); + // temp.updateCommit(commitMsg, this); broadcast(commitMsg); } break; @@ -138,7 +139,7 @@ public class PBFTCenter implements ConsensusCenter { unitSequencingMessage.stageType = ConsensusStage.PrePrepare.toInt(); unitSequencingMessage.sender = GlobalConf.instance.peerID; String content = JsonUtil.toJson(unitSequencingMessage); - SequencingManager.instance.send(content, new String[]{peer}); + SequencingManager.instance.send(content, new String[] {peer}); } break; default: @@ -152,7 +153,8 @@ public class PBFTCenter implements ConsensusCenter { } 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 { @@ -175,7 +177,8 @@ public class PBFTCenter implements ConsensusCenter { isPrePrepareReceived = false; } - public synchronized boolean updatePrepare(UnitSequencingMessage message, PBFTCenter center) { + public synchronized boolean updatePrepare(UnitSequencingMessage message, + PBFTCenter center) { if (isSendCommit) { return false; } @@ -209,18 +212,15 @@ public class PBFTCenter implements ConsensusCenter { } public String getDisplayStr() { - return String.format( - "pSize=%d cSize=%d isSendCommit=%b isSendReply=%b buffSize=%d", - null == prepare ? -1 : prepare.size(), - null == commit ? -1 : commit.size(), - isSendCommit, - isSendReply, - buff.size()); + return String.format("pSize=%d cSize=%d isSendCommit=%b isSendReply=%b buffSize=%d", + null == prepare ? -1 : prepare.size(), null == commit ? -1 : commit.size(), + isSendCommit, isSendReply, buff.size()); } public UnitSequencingMessage formPrepare(UnitSequencingMessage unitSequencingMessage) { -// UnitSequencingMessage prepareMsg = new UnitSequencingMessage(ConsensusStage.Prepare.toInt()); -// prepareMsg.order = this.order; + // UnitSequencingMessage prepareMsg = new + // UnitSequencingMessage(ConsensusStage.Prepare.toInt()); + // prepareMsg.order = this.order; unitSequencingMessage.content = String.valueOf(this.request.hashCode()); unitSequencingMessage.sender = GlobalConf.instance.peerID; unitSequencingMessage.stageType = ConsensusStage.Prepare.toInt(); @@ -228,17 +228,19 @@ public class PBFTCenter implements ConsensusCenter { } public void requestPrePrepareFromMaster() { - UnitSequencingMessage requestMsg = new UnitSequencingMessage(ConsensusStage.ReSend.toInt()); + UnitSequencingMessage requestMsg = + new UnitSequencingMessage(ConsensusStage.ReSend.toInt()); requestMsg.order = this.order; requestMsg.sender = GlobalConf.instance.peerID; -// return requestMsg; + // return 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) { -// UnitSequencingMessage commitMsg = new UnitSequencingMessage(ConsensusStage.Commit.toInt()); -// unitSequencingMessage.order = this.order; + // UnitSequencingMessage commitMsg = new + // UnitSequencingMessage(ConsensusStage.Commit.toInt()); + // unitSequencingMessage.order = this.order; unitSequencingMessage.content = String.valueOf(this.request.hashCode()); unitSequencingMessage.sender = GlobalConf.instance.peerID; unitSequencingMessage.stageType = ConsensusStage.Commit.toInt(); @@ -246,7 +248,8 @@ public class PBFTCenter implements ConsensusCenter { } public void onCommit() { - UnitContractMessage unitContractMessage = JsonUtil.fromJson(request, UnitContractMessage.class); + UnitContractMessage unitContractMessage = + JsonUtil.fromJson(request, UnitContractMessage.class); if (this.order == (committedID.get() + 1L)) { execute(unitContractMessage, this.order); } else { diff --git a/src/main/java/org/bdware/units/consensus/RAFTCenter.java b/src/main/java/org/bdware/units/consensus/RAFTCenter.java index 6c34a3d..f234b26 100644 --- a/src/main/java/org/bdware/units/consensus/RAFTCenter.java +++ b/src/main/java/org/bdware/units/consensus/RAFTCenter.java @@ -10,8 +10,7 @@ public class RAFTCenter implements ConsensusCenter { private static ConsensusType PBFT; private String contractID; - public RAFTCenter(UnitContractMessage msg) { - } + public RAFTCenter(UnitContractMessage msg) {} @Override public void updateUnitInfo(MultiPointContractInfo contractInfo) { diff --git a/src/main/java/org/bdware/units/consensus/SingleCenter.java b/src/main/java/org/bdware/units/consensus/SingleCenter.java index f1b288e..3fcc6d5 100644 --- a/src/main/java/org/bdware/units/consensus/SingleCenter.java +++ b/src/main/java/org/bdware/units/consensus/SingleCenter.java @@ -35,12 +35,12 @@ public class SingleCenter implements ConsensusCenter { networkType = NetworkType.getType(msg.network); infos = new HashMap<>(); committedMsg = new HashMap<>(); -// original = new HashMap<>(); + // original = new HashMap<>(); // receive init, then insert -// members = ContractUnitManager.instance.getContractInfo(contractID); -// if (members.master.equals(GlobalConf.instance.peerID)) { -// isMaster = true; -// } + // members = ContractUnitManager.instance.getContractInfo(contractID); + // if (members.master.equals(GlobalConf.instance.peerID)) { + // isMaster = true; + // } } @Override @@ -58,8 +58,8 @@ public class SingleCenter implements ConsensusCenter { SingleInfo temp; switch (ConsensusStage.fromByte(unitSequencingMessage.stageType)) { case Init: - MultiPointContractInfo contractInfo = - JsonUtil.fromJson(unitSequencingMessage.content, MultiPointContractInfo.class); + MultiPointContractInfo contractInfo = JsonUtil + .fromJson(unitSequencingMessage.content, MultiPointContractInfo.class); updateUnitInfo(contractInfo); break; case Request: @@ -72,7 +72,7 @@ public class SingleCenter implements ConsensusCenter { unitSequencingMessage.order = temp.order; broadcast(unitSequencingMessage); } else { -// sendToMaster(unitSequencingMessage); + // sendToMaster(unitSequencingMessage); } break; case Commit: @@ -93,7 +93,7 @@ public class SingleCenter implements ConsensusCenter { unitSequencingMessage.stageType = ConsensusStage.PrePrepare.toInt(); unitSequencingMessage.sender = GlobalConf.instance.peerID; String content = JsonUtil.toJson(unitSequencingMessage); - SequencingManager.instance.send(content, new String[]{peer}); + SequencingManager.instance.send(content, new String[] {peer}); } break; default: @@ -102,8 +102,7 @@ public class SingleCenter implements ConsensusCenter { } private void broadcast(UnitSequencingMessage msg) { - SequencingManager.instance.send( - JsonUtil.toJson(msg), + SequencingManager.instance.send(JsonUtil.toJson(msg), contractInfo.getMembers().toArray(new String[contractInfo.members.size()])); } @@ -116,7 +115,8 @@ public class SingleCenter implements ConsensusCenter { isSendReply = false; } - public synchronized boolean updateCommit(UnitSequencingMessage message, SingleCenter center) { + public synchronized boolean updateCommit(UnitSequencingMessage message, + SingleCenter center) { if (isSendReply) { return false; } @@ -126,7 +126,8 @@ public class SingleCenter implements ConsensusCenter { } public void onCommit() { - UnitContractMessage unitContractMessage = JsonUtil.fromJson(request, UnitContractMessage.class); + UnitContractMessage unitContractMessage = + JsonUtil.fromJson(request, UnitContractMessage.class); if (this.order == (committedID.get() + 1L)) { execute(unitContractMessage, this.order); } else { diff --git a/src/main/java/org/bdware/units/enums/ConsensusStage.java b/src/main/java/org/bdware/units/enums/ConsensusStage.java index df12360..a761e68 100644 --- a/src/main/java/org/bdware/units/enums/ConsensusStage.java +++ b/src/main/java/org/bdware/units/enums/ConsensusStage.java @@ -1,7 +1,8 @@ package org.bdware.units.enums; 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; diff --git a/src/main/java/org/bdware/units/enums/UnitContractMessageType.java b/src/main/java/org/bdware/units/enums/UnitContractMessageType.java index 3e934d3..abc3765 100644 --- a/src/main/java/org/bdware/units/enums/UnitContractMessageType.java +++ b/src/main/java/org/bdware/units/enums/UnitContractMessageType.java @@ -1,12 +1,8 @@ package org.bdware.units.enums; public enum UnitContractMessageType { - ContractUnitRequest(0), - ContractUnitResponse (1), - GetMyPeerID(2), - MyPeerIDResponse(3), - ContractStatusRequest(4), - ContractStatusResponse (5); + ContractUnitRequest(0), ContractUnitResponse(1), GetMyPeerID(2), MyPeerIDResponse( + 3), ContractStatusRequest(4), ContractStatusResponse(5); private final int value; diff --git a/src/main/java/org/bdware/units/enums/UnitContractNetworkType.java b/src/main/java/org/bdware/units/enums/UnitContractNetworkType.java index 0e8d431..c6461ad 100644 --- a/src/main/java/org/bdware/units/enums/UnitContractNetworkType.java +++ b/src/main/java/org/bdware/units/enums/UnitContractNetworkType.java @@ -1,8 +1,7 @@ package org.bdware.units.enums; public enum UnitContractNetworkType { - TCP(0), - P2P (1); + TCP(0), P2P(1); private final int value; diff --git a/src/main/java/org/bdware/units/enums/UnitContractRequestType.java b/src/main/java/org/bdware/units/enums/UnitContractRequestType.java index f174519..7327449 100644 --- a/src/main/java/org/bdware/units/enums/UnitContractRequestType.java +++ b/src/main/java/org/bdware/units/enums/UnitContractRequestType.java @@ -1,11 +1,7 @@ package org.bdware.units.enums; public enum UnitContractRequestType { - START(0), - STOP (1), - EXECUTE(2), - REPLY(3), - REQUEST(4); + START(0), STOP(1), EXECUTE(2), REPLY(3), REQUEST(4); private final int value; diff --git a/src/main/java/org/bdware/units/function/BaseFunctionManager.java b/src/main/java/org/bdware/units/function/BaseFunctionManager.java index 5258844..ad3d01b 100644 --- a/src/main/java/org/bdware/units/function/BaseFunctionManager.java +++ b/src/main/java/org/bdware/units/function/BaseFunctionManager.java @@ -26,7 +26,8 @@ public class BaseFunctionManager { public void send(String msg, String[] peers) { String requestId = getRequestId(); - BDLedgerContract.UnitMessage unitMessage = this.addRequestIdAndGetMessage(requestId, msg, peers); + BDLedgerContract.UnitMessage unitMessage = + this.addRequestIdAndGetMessage(requestId, msg, peers); NetworkManager.instance.send(unitMessage); } @@ -39,7 +40,8 @@ public class BaseFunctionManager { public void send(String msg, String[] peers, ResultCallback resultCallback) { String requestId = getRequestId(); - BDLedgerContract.UnitMessage unitMessage = this.addRequestIdAndGetMessage(requestId, msg, peers); + BDLedgerContract.UnitMessage unitMessage = + this.addRequestIdAndGetMessage(requestId, msg, peers); NetworkManager.instance.send(unitMessage); requestCallbacks.put(requestId, resultCallback); } @@ -58,10 +60,8 @@ public class BaseFunctionManager { System.out.println("[BaseFunctionManager] handleResponse null"); return; } - if (responseCenter.updateReply( - arg.get("content").getAsString(), - arg.get("sender").getAsString(), - arg.get("pubkey").getAsString())) { + if (responseCenter.updateReply(arg.get("content").getAsString(), + arg.get("sender").getAsString(), arg.get("pubkey").getAsString())) { responseCenter.formReply(); } } @@ -74,12 +74,12 @@ public class BaseFunctionManager { 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.addProperty(REQUEST_ID, requestId); BDLedgerContract.UnitMessage.Builder builder = BDLedgerContract.UnitMessage.newBuilder() - .setMsgType(getMessageType()) - .setSender(GlobalConf.instance.peerID) + .setMsgType(getMessageType()).setSender(GlobalConf.instance.peerID) .setContent(ByteString.copyFromUtf8(jsonObject.toString())); for (String peer : peers) { builder.addReceiver(peer); @@ -87,16 +87,12 @@ public class BaseFunctionManager { return builder.build(); } - private BDLedgerContract.UnitMessage addRequestIdAndGetMessage( - String requestId, - String msg, - String[] peers, - BDLedgerContract.UnitMessageType unitMessageType) { + private BDLedgerContract.UnitMessage addRequestIdAndGetMessage(String requestId, String msg, + String[] peers, BDLedgerContract.UnitMessageType unitMessageType) { JsonObject jsonObject = (JsonObject) JsonParser.parseString(msg); jsonObject.addProperty(REQUEST_ID, requestId); BDLedgerContract.UnitMessage.Builder builder = BDLedgerContract.UnitMessage.newBuilder() - .setMsgType(unitMessageType) - .setSender(GlobalConf.instance.peerID) + .setMsgType(unitMessageType).setSender(GlobalConf.instance.peerID) .setContent(ByteString.copyFromUtf8(jsonObject.toString())); for (String peer : peers) { builder.addReceiver(peer); @@ -109,4 +105,4 @@ public class BaseFunctionManager { String action; Object data; } -} \ No newline at end of file +} diff --git a/src/main/java/org/bdware/units/function/CommunicationManager.java b/src/main/java/org/bdware/units/function/CommunicationManager.java index 9e73fda..3e2f362 100644 --- a/src/main/java/org/bdware/units/function/CommunicationManager.java +++ b/src/main/java/org/bdware/units/function/CommunicationManager.java @@ -34,9 +34,10 @@ public class CommunicationManager extends BaseFunctionManager { private static final String MANAGER_SYMBOL = "COMM"; private static final Logger LOGGER = LogManager.getLogger(CommunicationManager.class); 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; - //new ThreadPoolExecutor(10,30,1L, TimeUnit.HOURS, new LinkedBlockingDeque(100)); + // new ThreadPoolExecutor(10,30,1L, TimeUnit.HOURS, new LinkedBlockingDeque(100)); private ActionExecutor ae; private NodeCenterClientController nodeCenterClientController; private String[] p2pPeers; @@ -49,11 +50,8 @@ public class CommunicationManager extends BaseFunctionManager { instance = new CommunicationManager(); instance.nodeCenterClientController = ControllerManager.getNodeCenterController(); instance.communicationAction = new CommunicationAction(); - instance.ae = new ActionExecutor( - executorService, - instance.nodeCenterClientController, - instance.communicationAction - ) { + instance.ae = new ActionExecutor(executorService, + instance.nodeCenterClientController, instance.communicationAction) { @Override public boolean checkPermission(Action a, final JsonObject args, long permission) { return true; @@ -67,11 +65,9 @@ public class CommunicationManager extends BaseFunctionManager { } public static void send(String msg, String symbol) { - UnitMessage unitMessage = UnitMessage.newBuilder() - .setSender(GlobalConf.instance.peerID) + UnitMessage unitMessage = UnitMessage.newBuilder().setSender(GlobalConf.instance.peerID) .setMsgType(BDLedgerContract.UnitMessageType.UnitCommunicateMessage) - .setContent(ByteString.copyFromUtf8(msg)) - .build(); + .setContent(ByteString.copyFromUtf8(msg)).build(); NetworkManager.instance.sendTo(unitMessage, symbol); } @@ -81,39 +77,38 @@ public class CommunicationManager extends BaseFunctionManager { } public void handle(String str, String sender) { -// JsonObject jsonObject = (JsonObject) JsonParser.parseStringAsJsonObject(str); -// if(jsonObject.has("action")) { -// String action = jsonObject.get("action").getAsString(); -// switch (action) { -// case "myPeerId": -// GlobalConf.setPeerID(jsonObject.get("peerId").getAsString()); -// break; -// default: -// logger.debug("[CommunicationManager] not handled " + jsonObject.toString()); -// } -// } + // JsonObject jsonObject = (JsonObject) JsonParser.parseStringAsJsonObject(str); + // if(jsonObject.has("action")) { + // String action = jsonObject.get("action").getAsString(); + // switch (action) { + // case "myPeerId": + // GlobalConf.setPeerID(jsonObject.get("peerId").getAsString()); + // break; + // default: + // logger.debug("[CommunicationManager] not handled " + jsonObject.toString()); + // } + // } JsonObject arg = (JsonObject) JsonParser.parseString(str); Response response; try { final String action = arg.get("action").getAsString(); -// if (isResponse(action)) { -// handleResponse(arg); -// return; -// } -// logger.info("[CommunicationManager] handle:" + arg.toString()); - ae.handle(action, arg, - new ResultCallback() { - @Override - public void onResult(String arg) { - System.out.println("[CommunicationManager] onResult"); -// CommunicationManager.instance.send(arg, new String[]{sender}); - } - }); + // if (isResponse(action)) { + // handleResponse(arg); + // return; + // } + // logger.info("[CommunicationManager] handle:" + arg.toString()); + ae.handle(action, arg, new ResultCallback() { + @Override + public void onResult(String arg) { + System.out.println("[CommunicationManager] onResult"); + // CommunicationManager.instance.send(arg, new String[]{sender}); + } + }); } catch (IllegalArgumentException e) { response = new Response(); response.action = "onException"; 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) { e.printStackTrace(); ByteArrayOutputStream bo = new ByteArrayOutputStream(); @@ -124,12 +119,9 @@ public class CommunicationManager extends BaseFunctionManager { StringBuilder ret = new StringBuilder(); int count = 0; for (String s : strs) { - if (s.contains("sun.reflect") - || s.contains("java.lang.reflect") - || s.contains("org.apache") - || s.contains("java.util") - || s.contains("java.lang") - || s.contains("io.netty")) { + if (s.contains("sun.reflect") || s.contains("java.lang.reflect") + || s.contains("org.apache") || s.contains("java.util") + || s.contains("java.lang") || s.contains("io.netty")) { continue; } ret.append(s); @@ -149,11 +141,9 @@ public class CommunicationManager extends BaseFunctionManager { JsonObject jsonObject = new JsonObject(); jsonObject.addProperty(ACTION, "getP2PNodes"); jsonObject.addProperty(REQUEST_ID, requestID); - UnitMessage unitMessage = UnitMessage.newBuilder() - .setSender(GlobalConf.instance.peerID) + UnitMessage unitMessage = UnitMessage.newBuilder().setSender(GlobalConf.instance.peerID) .setMsgType(BDLedgerContract.UnitMessageType.UnitCommunicateMessage) - .setContent(ByteString.copyFromUtf8(jsonObject.toString())) - .build(); + .setContent(ByteString.copyFromUtf8(jsonObject.toString())).build(); NetworkManager.instance.send(unitMessage, NetworkType.P2P); } @@ -186,11 +176,9 @@ public class CommunicationManager extends BaseFunctionManager { public void askForNextContractID() { JsonObject jsonObject = new JsonObject(); jsonObject.addProperty(ACTION, "askForNextContractID"); - UnitMessage unitMessage = UnitMessage.newBuilder() - .setSender(GlobalConf.instance.peerID) + UnitMessage unitMessage = UnitMessage.newBuilder().setSender(GlobalConf.instance.peerID) .setMsgType(BDLedgerContract.UnitMessageType.UnitCommunicateMessage) - .setContent(ByteString.copyFromUtf8(jsonObject.toString())) - .build(); + .setContent(ByteString.copyFromUtf8(jsonObject.toString())).build(); NetworkManager.instance.send(unitMessage, NetworkType.P2P); } @@ -206,5 +194,4 @@ public class CommunicationManager extends BaseFunctionManager { - } diff --git a/src/main/java/org/bdware/units/function/ContractUnitManager.java b/src/main/java/org/bdware/units/function/ContractUnitManager.java index dea16eb..afb37c0 100644 --- a/src/main/java/org/bdware/units/function/ContractUnitManager.java +++ b/src/main/java/org/bdware/units/function/ContractUnitManager.java @@ -26,15 +26,17 @@ public class ContractUnitManager extends BaseFunctionManager { private static final String MANAGER_SYMBOL = "UNIT"; private static final Logger LOGGER = LogManager.getLogger(ExecutionManager.class); 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(); - private final Map contractID2Members = new ConcurrentHashMap<>(); + private final Map contractID2Members = + new ConcurrentHashMap<>(); protected ActionExecutor actionExecutor; protected UnitsInfoAction unitsInfoActions; private Map requestCache = new ConcurrentHashMap<>(); private Map nodeinfos; - public ContractUnitManager() { - } + + public ContractUnitManager() {} public static ContractUnitManager init() { if (instance != null) { @@ -42,7 +44,8 @@ public class ContractUnitManager extends BaseFunctionManager { } instance = new ContractUnitManager(); instance.unitsInfoActions = new UnitsInfoAction(); - instance.actionExecutor = new ActionExecutor(executorService, instance.unitsInfoActions) { + instance.actionExecutor = new ActionExecutor(executorService, + instance.unitsInfoActions) { @Override public boolean checkPermission(Action a, final JsonObject args, long permission) { return true; @@ -62,18 +65,17 @@ public class ContractUnitManager extends BaseFunctionManager { return; } LOGGER.info("[ContractUnitManager] handle:" + arg); - actionExecutor.handle(action, arg, - new ResultCallback() { - @Override - public void onResult(String arg) { - ContractUnitManager.instance.send(arg, new String[]{sender}); - } - }); + actionExecutor.handle(action, arg, new ResultCallback() { + @Override + public void onResult(String arg) { + ContractUnitManager.instance.send(arg, new String[] {sender}); + } + }); } catch (IllegalArgumentException e) { response = new Response(); response.action = "onException"; 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) { e.printStackTrace(); ByteArrayOutputStream bo = new ByteArrayOutputStream(); @@ -84,12 +86,9 @@ public class ContractUnitManager extends BaseFunctionManager { StringBuilder ret = new StringBuilder(); int count = 0; for (String s : strs) { - if (s.contains("sun.reflect") - || s.contains("java.lang.reflect") - || s.contains("org.apache") - || s.contains("java.util") - || s.contains("java.lang") - || s.contains("io.netty")) { + if (s.contains("sun.reflect") || s.contains("java.lang.reflect") + || s.contains("org.apache") || s.contains("java.util") + || s.contains("java.lang") || s.contains("io.netty")) { continue; } ret.append(s); diff --git a/src/main/java/org/bdware/units/function/ExecutionManager.java b/src/main/java/org/bdware/units/function/ExecutionManager.java index 69671d4..fdaf3fb 100644 --- a/src/main/java/org/bdware/units/function/ExecutionManager.java +++ b/src/main/java/org/bdware/units/function/ExecutionManager.java @@ -46,34 +46,31 @@ public class ExecutionManager extends BaseFunctionManager { private final BDLedgerContract.UnitMessageType UNIT_MESSAGE_TYPE = BDLedgerContract.UnitMessageType.UnitContractMessage; public Map contractID2Sequencing = new HashMap<>(); - // protected MasterServerTCPAction masterActions; - // protected MasterClientTCPAction clientActions; + // protected MasterServerTCPAction masterActions; + // protected MasterClientTCPAction clientActions; protected ActionExecutor actionExecutor; private Map contractID2PubKey = new HashMap<>(); private Map requestCaches = new ConcurrentHashMap<>(); private String nextContractID; public static ExecutionManager instance = init(); - public ExecutionManager() { - } + public ExecutionManager() {} public static ExecutionManager init() { if (instance != null) { return instance; } instance = new ExecutionManager(); - // instance.masterActions = new MasterServerTCPAction(); - // instance.clientActions = new MasterClientTCPAction(); - instance.actionExecutor = - new ActionExecutor( - executorService) { // , instance.masterActions, - // instance.clientActions) { - @Override - public boolean checkPermission( - Action a, final JsonObject args, long permission) { - return true; - } - }; + // instance.masterActions = new MasterServerTCPAction(); + // instance.clientActions = new MasterClientTCPAction(); + instance.actionExecutor = new ActionExecutor(executorService) { // , + // instance.masterActions, + // instance.clientActions) { + @Override + public boolean checkPermission(Action a, final JsonObject args, long permission) { + return true; + } + }; return instance; } @@ -82,33 +79,29 @@ public class ExecutionManager extends BaseFunctionManager { arg.addProperty("sender", sender); Response response; try { - // if (arg.get("msgType").getAsInt() == 1) { - // handleResponse(arg); - // return; - // } + // if (arg.get("msgType").getAsInt() == 1) { + // handleResponse(arg); + // return; + // } final String action = arg.get("action").getAsString(); LOGGER.info("[ExecutionManager] handle:" + arg.toString()); - // requestID2Sender.put(arg.get("requestID").getAsString(), sender); - actionExecutor.handle( - action, - arg, - new ResultCallback() { - @Override - public void onResult(String msg) { - try { - UnitMessage unitMessage = - UnitMessage.parseFrom(ByteUtil.decodeBASE64(msg)); - NetworkManager.instance.send(unitMessage); - } catch (InvalidProtocolBufferException e) { - e.printStackTrace(); - } - } - }); + // requestID2Sender.put(arg.get("requestID").getAsString(), sender); + actionExecutor.handle(action, arg, new ResultCallback() { + @Override + public void onResult(String msg) { + try { + UnitMessage unitMessage = UnitMessage.parseFrom(ByteUtil.decodeBASE64(msg)); + NetworkManager.instance.send(unitMessage); + } catch (InvalidProtocolBufferException e) { + e.printStackTrace(); + } + } + }); } catch (IllegalArgumentException e) { response = new Response(); response.action = "onException"; 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) { e.printStackTrace(); ByteArrayOutputStream bo = new ByteArrayOutputStream(); @@ -119,12 +112,9 @@ public class ExecutionManager extends BaseFunctionManager { StringBuilder ret = new StringBuilder(); int count = 0; for (String s : strs) { - if (s.contains("sun.reflect") - || s.contains("java.lang.reflect") - || s.contains("org.apache") - || s.contains("java.util") - || s.contains("java.lang") - || s.contains("io.netty")) { + if (s.contains("sun.reflect") || s.contains("java.lang.reflect") + || s.contains("org.apache") || s.contains("java.util") + || s.contains("java.lang") || s.contains("io.netty")) { continue; } ret.append(s); @@ -143,11 +133,11 @@ public class ExecutionManager extends BaseFunctionManager { */ public void updateLocalContractToNodeCenter() { ControllerManager.getNodeCenterController().updateContract(); - // List info = CMActions.manager.getContractDespList(); - // JsonObject jo = new JsonObject(); - // jo.addProperty("action", "updateContract"); - // jo.addProperty("contracts", JsonUtil.toJson(info)); - // send(jo.toString(), new String[]{GlobalConf.getNodeCenterAddress()}); + // List info = CMActions.manager.getContractDespList(); + // JsonObject jo = new JsonObject(); + // jo.addProperty("action", "updateContract"); + // jo.addProperty("contracts", JsonUtil.toJson(info)); + // send(jo.toString(), new String[]{GlobalConf.getNodeCenterAddress()}); } public void killContractRequest(String contract, ResultCallback rc) { @@ -164,21 +154,15 @@ public class ExecutionManager extends BaseFunctionManager { if (info.consensusType == ConsensusType.None) { peers = info.getMembers().toArray(new String[info.members.size()]); } else { - peers = new String[]{info.master}; + peers = new String[] {info.master}; } - ResponseCenter responseCenter = - new ResponseCenter( - requestId, - rc, - peers.length, - UnitContractRequestType.STOP, - ResponseType.ALL.getValue()); + ResponseCenter responseCenter = new ResponseCenter(requestId, rc, peers.length, + UnitContractRequestType.STOP, ResponseType.ALL.getValue()); responseCenter.setInfos(contract); this.responseCenters.put(requestId, responseCenter); - // respCaches.put(requestId, new RespCache(num)); + // respCaches.put(requestId, new RespCache(num)); UnitContractMessage unitContractMessage = - new UnitContractMessage( - UnitContractMessageType.ContractUnitRequest.getValue(), + new UnitContractMessage(UnitContractMessageType.ContractUnitRequest.getValue(), UnitContractRequestType.STOP.getValue()); unitContractMessage.action = "stopContractAtSlave"; unitContractMessage.requestID = requestId; @@ -190,49 +174,38 @@ public class ExecutionManager extends BaseFunctionManager { unitContractMessage.collector = GlobalConf.instance.peerID; // Sequencing if (consensusType != ConsensusType.None) { - SequencingManager.instance.sequencingRequest( - unitContractMessage.contractID, unitContractMessage, peers, rc); + SequencingManager.instance.sequencingRequest(unitContractMessage.contractID, + unitContractMessage, peers, rc); } else { String msgContent = JsonUtil.toJson(unitContractMessage); UnitMessage unitMessage; - unitMessage = - UnitMessage.newBuilder() - .setMsgType(BDLedgerContract.UnitMessageType.UnitContractMessage) - .setContent(ByteString.copyFromUtf8(msgContent)) - .setSender(GlobalConf.instance.peerID) - .addAllReceiver(Arrays.asList(peers)) - .build(); + unitMessage = UnitMessage.newBuilder() + .setMsgType(BDLedgerContract.UnitMessageType.UnitContractMessage) + .setContent(ByteString.copyFromUtf8(msgContent)) + .setSender(GlobalConf.instance.peerID).addAllReceiver(Arrays.asList(peers)) + .build(); NetworkManager.instance.send(unitMessage, networkType); } } - public void startContractRequest( - boolean tcpType, - String contract, - int num, - String[] peers, - String content, - int sequencing, - int response, - ResultCallback resultCallback) { + public void startContractRequest(boolean tcpType, String contract, int num, String[] peers, + String content, int sequencing, int response, ResultCallback resultCallback) { LOGGER.info("[startContractRequest] " + contract + " " + num); String requestId = getRequestId(); - // this.requestCallbacks.put(requestId, resultCallback); - ResponseCenter responseCenter = - new ResponseCenter( - requestId, resultCallback, num, UnitContractRequestType.START, response); + // this.requestCallbacks.put(requestId, resultCallback); + ResponseCenter responseCenter = new ResponseCenter(requestId, resultCallback, num, + UnitContractRequestType.START, response); responseCenter.setType(ResponseType.ALL); this.responseCenters.put(requestId, responseCenter); - // respCaches.put(requestId, new RespCache(num)); + // respCaches.put(requestId, new RespCache(num)); UnitContractMessage unitContractMessage = - new UnitContractMessage( - UnitContractMessageType.ContractUnitRequest.getValue(), + new UnitContractMessage(UnitContractMessageType.ContractUnitRequest.getValue(), UnitContractRequestType.START.getValue()); unitContractMessage.action = "startContractAtSlave"; unitContractMessage.requestID = requestId; unitContractMessage.contractID = getNextContractID(); ExecutionManager.instance.askForNextContractID(); - // logger.info("hashcode " + nextContractID.hashCode()); + // logger.info("hashcode " + nextContractID.hashCode()); unitContractMessage.content = content; unitContractMessage.sequencing = sequencing; unitContractMessage.rcheck = response; @@ -242,22 +215,18 @@ public class ExecutionManager extends BaseFunctionManager { UnitMessage unitMessage; if (null != peers && peers.length > 0) { responseCenter.updatePeers(peers); - unitMessage = - UnitMessage.newBuilder() - .setMsgType(BDLedgerContract.UnitMessageType.UnitContractMessage) - .setContent(ByteString.copyFromUtf8(msgContent)) - .addAllReceiver(Arrays.asList(peers)) - .setSender(GlobalConf.instance.peerID) - .build(); + unitMessage = UnitMessage.newBuilder() + .setMsgType(BDLedgerContract.UnitMessageType.UnitContractMessage) + .setContent(ByteString.copyFromUtf8(msgContent)) + .addAllReceiver(Arrays.asList(peers)).setSender(GlobalConf.instance.peerID) + .build(); } 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 - unitMessage = - UnitMessage.newBuilder() - .setMsgType(BDLedgerContract.UnitMessageType.UnitContractMessage) - .setContent(ByteString.copyFromUtf8(msgContent)) - .setSender(GlobalConf.instance.peerID) - .build(); + unitMessage = UnitMessage.newBuilder() + .setMsgType(BDLedgerContract.UnitMessageType.UnitContractMessage) + .setContent(ByteString.copyFromUtf8(msgContent)) + .setSender(GlobalConf.instance.peerID).build(); } NetworkManager.instance.send(unitMessage, tcpType ? NetworkType.TCP : NetworkType.P2P); } @@ -272,32 +241,24 @@ public class ExecutionManager extends BaseFunctionManager { nextContractID = content; } - public void executeContractRequest( - String contract, - String operation, - String arg, - int network, - int sequencing, - int responseType, - ResultCallback rc) { + public void executeContractRequest(String contract, String operation, String arg, int network, + int sequencing, int responseType, ResultCallback rc) { String requestId = getRequestId(); - // this.requestCallbacks.put(requestId, resultCallback); + // this.requestCallbacks.put(requestId, resultCallback); String[] peers; MultiPointContractInfo info = ContractUnitManager.instance.getContractInfo(contract); if (info.consensusType == ConsensusType.None) { peers = info.getMembers().toArray(new String[info.members.size()]); } else { - peers = new String[]{info.master}; + peers = new String[] {info.master}; } - ResponseCenter responseCenter = - new ResponseCenter( - requestId, rc, peers.length, UnitContractRequestType.EXECUTE, responseType); + ResponseCenter responseCenter = new ResponseCenter(requestId, rc, peers.length, + UnitContractRequestType.EXECUTE, responseType); responseCenter.setInfos(contract); this.responseCenters.put(requestId, responseCenter); - // respCaches.put(requestId, new RespCache(num)); + // respCaches.put(requestId, new RespCache(num)); UnitContractMessage unitContractMessage = - new UnitContractMessage( - UnitContractMessageType.ContractUnitRequest.getValue(), + new UnitContractMessage(UnitContractMessageType.ContractUnitRequest.getValue(), UnitContractRequestType.EXECUTE.getValue()); unitContractMessage.action = "executeContractAtSlave"; unitContractMessage.requestID = requestId; @@ -310,61 +271,54 @@ public class ExecutionManager extends BaseFunctionManager { // Sequencing ConsensusType consensusType = ConsensusType.getType(sequencing); if (consensusType != ConsensusType.None) { - SequencingManager.instance.sequencingRequest( - unitContractMessage.contractID, unitContractMessage, peers, rc); + SequencingManager.instance.sequencingRequest(unitContractMessage.contractID, + unitContractMessage, peers, rc); } else { String msgContent = JsonUtil.toJson(unitContractMessage); UnitMessage unitMessage; - unitMessage = - UnitMessage.newBuilder() - .setMsgType(BDLedgerContract.UnitMessageType.UnitContractMessage) - .setContent(ByteString.copyFromUtf8(msgContent)) - .setSender(GlobalConf.instance.peerID) - .addAllReceiver(Arrays.asList(peers)) - .build(); + unitMessage = UnitMessage.newBuilder() + .setMsgType(BDLedgerContract.UnitMessageType.UnitContractMessage) + .setContent(ByteString.copyFromUtf8(msgContent)) + .setSender(GlobalConf.instance.peerID).addAllReceiver(Arrays.asList(peers)) + .build(); NetworkManager.instance.send(unitMessage, NetworkType.getType(network)); } } - public void stopContractRequest( - String contract, - String operation, - String arg, - int network, - int sequencing, - ResultCallback rc) { - // String requestId = getRequestId(); - //// this.requestCallbacks.put(requestId, resultCallback); - // MultiPointContractInfo info = + public void stopContractRequest(String contract, String operation, String arg, int network, + int sequencing, ResultCallback rc) { + // String requestId = getRequestId(); + //// this.requestCallbacks.put(requestId, resultCallback); + // MultiPointContractInfo info = // ContractUnitManager.instance.getContractInfo(contract); - // String[] peers; - // if (info.consensusType == ConsensusType.None) { - // peers = info.getMembers().toArray(new String[info.members.size()]); - // } else { - // peers = new String[]{info.master}; - // } - // this.responseCenters.put(requestId, new ResponseCenter(requestId, rc, + // String[] peers; + // if (info.consensusType == ConsensusType.None) { + // peers = info.getMembers().toArray(new String[info.members.size()]); + // } else { + // peers = new String[]{info.master}; + // } + // this.responseCenters.put(requestId, new ResponseCenter(requestId, rc, // peers.length, UnitContractRequestType.EXECUTE, sequencing)); - //// respCaches.put(requestId, new RespCache(num)); - // UnitContractMessage unitContractMessage = new UnitContractMessage( - // UnitContractMessageType.ContractUnitRequest.getValue(), - // UnitContractRequestType.EXECUTE.getValue()); - // unitContractMessage.action = "executeContractAtSlave"; - // unitContractMessage.requestID = requestId; - // unitContractMessage.contractID = contract; - // unitContractMessage.operation = operation; - // unitContractMessage.arg = arg; - // unitContractMessage.sequencing = sequencing; - // unitContractMessage.network = network; - // String msgContent = gson.toJson(unitContractMessage); - // UnitMessage unitMessage; - // unitMessage = UnitMessage.newBuilder() - // .setMsgType(BDLedgerContract.UnitMessageType.UnitContractMessage) - // .setContent(ByteString.copyFromUtf8(msgContent)) - // .setSender(GlobalConf.instance.peerID) - // .addAllReceiver(Arrays.asList(peers)) - // .build(); - // NetworkManager.instance.send(unitMessage, NetworkType.getType(network)); + //// respCaches.put(requestId, new RespCache(num)); + // UnitContractMessage unitContractMessage = new UnitContractMessage( + // UnitContractMessageType.ContractUnitRequest.getValue(), + // UnitContractRequestType.EXECUTE.getValue()); + // unitContractMessage.action = "executeContractAtSlave"; + // unitContractMessage.requestID = requestId; + // unitContractMessage.contractID = contract; + // unitContractMessage.operation = operation; + // unitContractMessage.arg = arg; + // unitContractMessage.sequencing = sequencing; + // unitContractMessage.network = network; + // String msgContent = gson.toJson(unitContractMessage); + // UnitMessage unitMessage; + // unitMessage = UnitMessage.newBuilder() + // .setMsgType(BDLedgerContract.UnitMessageType.UnitContractMessage) + // .setContent(ByteString.copyFromUtf8(msgContent)) + // .setSender(GlobalConf.instance.peerID) + // .addAllReceiver(Arrays.asList(peers)) + // .build(); + // NetworkManager.instance.send(unitMessage, NetworkType.getType(network)); } public void askForNextContractID() { @@ -389,5 +343,4 @@ public class ExecutionManager extends BaseFunctionManager { - } diff --git a/src/main/java/org/bdware/units/function/RecoveryManager.java b/src/main/java/org/bdware/units/function/RecoveryManager.java index c8530c7..a240d09 100644 --- a/src/main/java/org/bdware/units/function/RecoveryManager.java +++ b/src/main/java/org/bdware/units/function/RecoveryManager.java @@ -9,7 +9,7 @@ public class RecoveryManager extends BaseFunctionManager { JsonObject jo = new JsonObject(); jo.addProperty("action", "NCStartElect"); jo.addProperty("contractID", contractID); - //NetworkManager.instance.cmClientHandler.sendMsg(JsonUtil.toJson(jo)); + // NetworkManager.instance.cmClientHandler.sendMsg(JsonUtil.toJson(jo)); } diff --git a/src/main/java/org/bdware/units/function/SequencingManager.java b/src/main/java/org/bdware/units/function/SequencingManager.java index 29d796b..93db906 100644 --- a/src/main/java/org/bdware/units/function/SequencingManager.java +++ b/src/main/java/org/bdware/units/function/SequencingManager.java @@ -23,16 +23,15 @@ import java.util.Map; public class SequencingManager extends BaseFunctionManager { private static final String MANAGER_SYMBOL = "SEQUENCING"; private static final Logger LOGGER = LogManager.getLogger(SequencingManager.class); - // protected SequencingActions sequencingActions; -// protected ActionExecutor actionExecutor; + // protected SequencingActions sequencingActions; + // protected ActionExecutor actionExecutor; private final BDLedgerContract.UnitMessageType UNIT_MESSAGE_TYPE = BDLedgerContract.UnitMessageType.UnitSequencingMessage; - // protected static ExecutorService executorService = Executors.newFixedThreadPool(10); + // protected static ExecutorService executorService = Executors.newFixedThreadPool(10); private final Map consensusCenters = new HashMap<>(); public static SequencingManager instance = init(); - public SequencingManager() { - } + public SequencingManager() {} public static SequencingManager init() { if (null != instance) { @@ -51,8 +50,8 @@ public class SequencingManager extends BaseFunctionManager { String contractID = unitSequencingMessage.contractID; ConsensusCenter consensusCenter = consensusCenters.get(contractID); if (null == consensusCenter) { -// consensusCenter = createConsensusCenter(unitSequencingMessage); -// this.consensusCenters.put(contractID, consensusCenter); + // consensusCenter = createConsensusCenter(unitSequencingMessage); + // this.consensusCenters.put(contractID, consensusCenter); } // create null, then no dingxu if (null == consensusCenter) { @@ -60,125 +59,124 @@ public class SequencingManager extends BaseFunctionManager { return; } consensusCenter.handle(unitSequencingMessage); -// try { -//// if (arg.get("msgType").getAsInt() == 1) { -//// handleResponse(arg); -//// return; -//// } -// final String action = arg.get("action").getAsString(); -// logger.info("[SequencingManager] handle:" + arg.toString()); -// actionExecutor.handle(action, arg, -// new ResultCallback() { -// @Override -// public void onResult(String msg) { -// try { -// BDLedgerContract.UnitMessage unitMessage = -// BDLedgerContract.UnitMessage.parseFrom(Base64.decode(msg)); -// NetworkManager.instance.send(unitMessage); -// } catch (InvalidProtocolBufferException e) { -// e.printStackTrace(); -// } -// } -// }); -// } catch (IllegalArgumentException e) { -// response = new SequencingManager.Response(); -// response.action = "onException"; -// response.data = e.getMessage(); -// ExecutionManager.instance.send(JsonUtil.toJson(response), new String[]{sender}); -// } catch (Exception e) { -// e.printStackTrace(); -// ByteArrayOutputStream bo = new ByteArrayOutputStream(); -// e.printStackTrace(new PrintStream(bo)); -// response = new SequencingManager.Response(); -// response.action = "onException"; -// String[] strs = bo.toString().split("\n"); -// StringBuilder ret = new StringBuilder(); -// int count = 0; -// for (String s : strs) { -// if (s.contains("sun.reflect") -// || s.contains("java.lang.reflect") -// || s.contains("org.apache") -// || s.contains("java.util") -// || s.contains("java.lang") -// || s.contains("io.netty")) { -// continue; -// } -// ret.append(s); -// ret.append("\n"); -// if (count++ > 10) { -// break; -// } -// } -// response.data = ret.toString(); -// logger.debug(JsonUtil.toJson(response)); -// } + // try { + //// if (arg.get("msgType").getAsInt() == 1) { + //// handleResponse(arg); + //// return; + //// } + // final String action = arg.get("action").getAsString(); + // logger.info("[SequencingManager] handle:" + arg.toString()); + // actionExecutor.handle(action, arg, + // new ResultCallback() { + // @Override + // public void onResult(String msg) { + // try { + // BDLedgerContract.UnitMessage unitMessage = + // BDLedgerContract.UnitMessage.parseFrom(Base64.decode(msg)); + // NetworkManager.instance.send(unitMessage); + // } catch (InvalidProtocolBufferException e) { + // e.printStackTrace(); + // } + // } + // }); + // } catch (IllegalArgumentException e) { + // response = new SequencingManager.Response(); + // response.action = "onException"; + // response.data = e.getMessage(); + // ExecutionManager.instance.send(JsonUtil.toJson(response), new String[]{sender}); + // } catch (Exception e) { + // e.printStackTrace(); + // ByteArrayOutputStream bo = new ByteArrayOutputStream(); + // e.printStackTrace(new PrintStream(bo)); + // response = new SequencingManager.Response(); + // response.action = "onException"; + // String[] strs = bo.toString().split("\n"); + // StringBuilder ret = new StringBuilder(); + // int count = 0; + // for (String s : strs) { + // if (s.contains("sun.reflect") + // || s.contains("java.lang.reflect") + // || s.contains("org.apache") + // || s.contains("java.util") + // || s.contains("java.lang") + // || s.contains("io.netty")) { + // continue; + // } + // ret.append(s); + // ret.append("\n"); + // if (count++ > 10) { + // break; + // } + // } + // response.data = ret.toString(); + // logger.debug(JsonUtil.toJson(response)); + // } } public void createConsensusCenterToStore(UnitContractMessage msg) { - //create local center + // create local center String contractID = msg.contractID; ConsensusCenter consensusCenter = createConsensusCenter(msg); consensusCenters.put(contractID, consensusCenter); } - public void sequencingRequest( - String contractID, - UnitContractMessage msg, - String[] peers, + public void sequencingRequest(String contractID, UnitContractMessage msg, String[] peers, ResultCallback resultCallback) { // content is UnitContractMessage -// ConsensusCenter consensusCenter = consensusCenters.get(contractID); -// if (null == consensusCenter) { -// consensusCenter = createConsensusCenter(msg); -// this.consensusCenters.put(contractID, consensusCenter); -// } -// // create null, then no dingxu -// if (consensusCenter == null) { -// ExecutionManager.instance.send(gson.toJson(msg), peers); -// return; -// } + // ConsensusCenter consensusCenter = consensusCenters.get(contractID); + // if (null == consensusCenter) { + // consensusCenter = createConsensusCenter(msg); + // this.consensusCenters.put(contractID, consensusCenter); + // } + // // create null, then no dingxu + // if (consensusCenter == null) { + // ExecutionManager.instance.send(gson.toJson(msg), peers); + // return; + // } String requestID = msg.requestID; requestCallbacks.put(requestID, resultCallback); - UnitSequencingMessage sequencingMessage = new UnitSequencingMessage(ConsensusStage.Request.toInt()); + UnitSequencingMessage sequencingMessage = + new UnitSequencingMessage(ConsensusStage.Request.toInt()); sequencingMessage.sequencing = msg.sequencing; sequencingMessage.network = msg.network; sequencingMessage.contractID = contractID; sequencingMessage.requestID = requestID; sequencingMessage.content = JsonUtil.toJson(msg); 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, -// new ResponseCenter(requestId, resultCallback, num, UnitContractRequestType.START, sequencing)); -//// respCaches.put(requestId, new RespCache(num)); -// UnitContractMessage unitContractMessage = new UnitContractMessage( -// UnitContractMessageType.ContractUnitRequest.getValue(), -// UnitContractRequestType.START.getValue()); -// unitContractMessage.action = "startContractAtSlave"; -// unitContractMessage.requestID = requestId; -//// unitContractMessage.contractID = contract; -// unitContractMessage.content = content; -// unitContractMessage.sequencing = sequencing; -// unitContractMessage.num = num; -// unitContractMessage.network = tcpType?0:1; -// String msgContent = gson.toJson(unitContractMessage); -// BDLedgerContract.UnitMessage unitMessage; -// if (null != peers && peers.length > 0) { -// unitMessage = BDLedgerContract.UnitMessage.newBuilder() -// .setMsgType(BDLedgerContract.UnitMessageType.UnitContractMessage) -// .setContent(ByteString.copyFromUtf8(msgContent)) -// .addAllReceiver(Arrays.asList(peers)) -// .setSender(GlobalConf.instance.peerID) -// .build(); -// } else { -// // No specified receiver, send to p2p nodes randomly -// unitMessage = BDLedgerContract.UnitMessage.newBuilder() -// .setMsgType(BDLedgerContract.UnitMessageType.UnitContractMessage) -// .setContent(ByteString.copyFromUtf8(msgContent)) -// .setSender(GlobalConf.instance.peerID) -// .build(); -// } -// NetworkManager.instance.send(unitMessage, tcpType?null:NetworkManager.P2P_GRPC_CLIENT); + // this.responseCenters.put(requestId, + // new ResponseCenter(requestId, resultCallback, num, UnitContractRequestType.START, + // sequencing)); + //// respCaches.put(requestId, new RespCache(num)); + // UnitContractMessage unitContractMessage = new UnitContractMessage( + // UnitContractMessageType.ContractUnitRequest.getValue(), + // UnitContractRequestType.START.getValue()); + // unitContractMessage.action = "startContractAtSlave"; + // unitContractMessage.requestID = requestId; + //// unitContractMessage.contractID = contract; + // unitContractMessage.content = content; + // unitContractMessage.sequencing = sequencing; + // unitContractMessage.num = num; + // unitContractMessage.network = tcpType?0:1; + // String msgContent = gson.toJson(unitContractMessage); + // BDLedgerContract.UnitMessage unitMessage; + // if (null != peers && peers.length > 0) { + // unitMessage = BDLedgerContract.UnitMessage.newBuilder() + // .setMsgType(BDLedgerContract.UnitMessageType.UnitContractMessage) + // .setContent(ByteString.copyFromUtf8(msgContent)) + // .addAllReceiver(Arrays.asList(peers)) + // .setSender(GlobalConf.instance.peerID) + // .build(); + // } else { + // // No specified receiver, send to p2p nodes randomly + // unitMessage = BDLedgerContract.UnitMessage.newBuilder() + // .setMsgType(BDLedgerContract.UnitMessageType.UnitContractMessage) + // .setContent(ByteString.copyFromUtf8(msgContent)) + // .setSender(GlobalConf.instance.peerID) + // .build(); + // } + // NetworkManager.instance.send(unitMessage, tcpType?null:NetworkManager.P2P_GRPC_CLIENT); } private ConsensusCenter createConsensusCenter(UnitContractMessage msg) { @@ -195,19 +193,21 @@ public class SequencingManager extends BaseFunctionManager { } public void updateContractInfo2Unit(int network, String contractID, String firstSuccessPeer) { - MultiPointContractInfo contractInfo = ContractUnitManager.instance.getContractInfo(contractID); + MultiPointContractInfo contractInfo = + ContractUnitManager.instance.getContractInfo(contractID); contractInfo.master = firstSuccessPeer; UnitContractMessage unitContractMessage = new UnitContractMessage(0); unitContractMessage.content = JsonUtil.toJson(contractInfo); unitContractMessage.contractID = contractID; -// unitContractMessage.network = network; + // unitContractMessage.network = network; unitContractMessage.action = "updateContractStartInfo"; - send(JsonUtil.toJson(unitContractMessage), - contractInfo.getMembers().toArray(new String[0]), BDLedgerContract.UnitMessageType.UnitUnitMessage); + send(JsonUtil.toJson(unitContractMessage), contractInfo.getMembers().toArray(new String[0]), + BDLedgerContract.UnitMessageType.UnitUnitMessage); } 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); while (null == consensusCenter) { try { @@ -232,5 +232,4 @@ public class SequencingManager extends BaseFunctionManager { - } diff --git a/src/main/java/org/bdware/units/grpc/BDLedgerContract.java b/src/main/java/org/bdware/units/grpc/BDLedgerContract.java index a6020c2..0fe6886 100644 --- a/src/main/java/org/bdware/units/grpc/BDLedgerContract.java +++ b/src/main/java/org/bdware/units/grpc/BDLedgerContract.java @@ -1,1159 +1,1209 @@ package org.bdware.units.grpc; -// Generated by the protocol buffer compiler. DO NOT EDIT! +// Generated by the protocol buffer compiler. DO NOT EDIT! // source: BDLedgerContract.proto public final class BDLedgerContract { - private BDLedgerContract() {} - public static void registerAllExtensions( - com.google.protobuf.ExtensionRegistryLite registry) { - } + private BDLedgerContract() {} - public static void registerAllExtensions( - com.google.protobuf.ExtensionRegistry registry) { - registerAllExtensions( - (com.google.protobuf.ExtensionRegistryLite) registry); - } - /** - * Protobuf enum {@code UnitMessageType} - */ - public enum UnitMessageType - implements com.google.protobuf.ProtocolMessageEnum { - /** - * UnitContractMessage = 0; - */ - UnitContractMessage(0), - /** - * UnitCommunicateMessage = 1; - */ - UnitCommunicateMessage(1), - /** - * UnitUnitMessage = 2; - */ - UnitUnitMessage(2), - /** - * UnitSequencingMessage = 3; - */ - UnitSequencingMessage(3), - /** - * UnitRecoverMessage = 4; - */ - UnitRecoverMessage(4), - UNRECOGNIZED(-1), - ; + public static void registerAllExtensions(com.google.protobuf.ExtensionRegistryLite registry) {} - /** - * UnitContractMessage = 0; - */ - public static final int UnitContractMessage_VALUE = 0; - /** - * UnitCommunicateMessage = 1; - */ - public static final int UnitCommunicateMessage_VALUE = 1; - /** - * UnitUnitMessage = 2; - */ - public static final int UnitUnitMessage_VALUE = 2; - /** - * UnitSequencingMessage = 3; - */ - public static final int UnitSequencingMessage_VALUE = 3; - /** - * UnitRecoverMessage = 4; - */ - public static final int UnitRecoverMessage_VALUE = 4; - - - public final int getNumber() { - if (this == UNRECOGNIZED) { - throw new IllegalArgumentException( - "Can't get the number of an unknown enum value."); - } - return value; + public static void registerAllExtensions(com.google.protobuf.ExtensionRegistry registry) { + registerAllExtensions((com.google.protobuf.ExtensionRegistryLite) registry); } /** - * @param value The numeric wire value of the corresponding enum entry. - * @return The enum associated with the given numeric wire value. - * @deprecated Use {@link #forNumber(int)} instead. + * Protobuf enum {@code UnitMessageType} */ - @Deprecated - public static UnitMessageType valueOf(int value) { - return forNumber(value); - } + public enum UnitMessageType implements com.google.protobuf.ProtocolMessageEnum { + /** + * UnitContractMessage = 0; + */ + UnitContractMessage(0), + /** + * UnitCommunicateMessage = 1; + */ + UnitCommunicateMessage(1), + /** + * UnitUnitMessage = 2; + */ + UnitUnitMessage(2), + /** + * UnitSequencingMessage = 3; + */ + UnitSequencingMessage(3), + /** + * UnitRecoverMessage = 4; + */ + UnitRecoverMessage(4), UNRECOGNIZED(-1),; - /** - * @param value The numeric wire value of the corresponding enum entry. - * @return The enum associated with the given numeric wire value. - */ - public static UnitMessageType forNumber(int value) { - switch (value) { - case 0: return UnitContractMessage; - case 1: return UnitCommunicateMessage; - case 2: return UnitUnitMessage; - case 3: return UnitSequencingMessage; - case 4: return UnitRecoverMessage; - default: return null; - } - } + /** + * UnitContractMessage = 0; + */ + public static final int UnitContractMessage_VALUE = 0; + /** + * UnitCommunicateMessage = 1; + */ + public static final int UnitCommunicateMessage_VALUE = 1; + /** + * UnitUnitMessage = 2; + */ + public static final int UnitUnitMessage_VALUE = 2; + /** + * UnitSequencingMessage = 3; + */ + public static final int UnitSequencingMessage_VALUE = 3; + /** + * UnitRecoverMessage = 4; + */ + public static final int UnitRecoverMessage_VALUE = 4; - public static com.google.protobuf.Internal.EnumLiteMap - internalGetValueMap() { - return internalValueMap; - } - private static final com.google.protobuf.Internal.EnumLiteMap< - UnitMessageType> internalValueMap = - new com.google.protobuf.Internal.EnumLiteMap() { - public UnitMessageType findValueByNumber(int number) { - return UnitMessageType.forNumber(number); + + public final int getNumber() { + if (this == UNRECOGNIZED) { + throw new IllegalArgumentException( + "Can't get the number of an unknown enum value."); } - }; - - public final com.google.protobuf.Descriptors.EnumValueDescriptor - getValueDescriptor() { - if (this == UNRECOGNIZED) { - throw new IllegalStateException( - "Can't get the descriptor of an unrecognized enum value."); - } - return getDescriptor().getValues().get(ordinal()); - } - public final com.google.protobuf.Descriptors.EnumDescriptor - getDescriptorForType() { - return getDescriptor(); - } - public static final com.google.protobuf.Descriptors.EnumDescriptor - getDescriptor() { - return BDLedgerContract.getDescriptor().getEnumTypes().get(0); - } - - private static final UnitMessageType[] VALUES = values(); - - public static UnitMessageType valueOf( - com.google.protobuf.Descriptors.EnumValueDescriptor desc) { - if (desc.getType() != getDescriptor()) { - throw new IllegalArgumentException( - "EnumValueDescriptor is not for this type."); - } - if (desc.getIndex() == -1) { - return UNRECOGNIZED; - } - return VALUES[desc.getIndex()]; - } - - private final int value; - - private UnitMessageType(int value) { - this.value = value; - } - - // @@protoc_insertion_point(enum_scope:UnitMessageType) - } - - public interface UnitMessageOrBuilder extends - // @@protoc_insertion_point(interface_extends:UnitMessage) - com.google.protobuf.MessageOrBuilder { - - /** - * .UnitMessageType msgType = 1; - * @return The enum numeric value on the wire for msgType. - */ - int getMsgTypeValue(); - /** - * .UnitMessageType msgType = 1; - * @return The msgType. - */ - UnitMessageType getMsgType(); - - /** - * string sender = 2; - * @return The sender. - */ - String getSender(); - /** - * string sender = 2; - * @return The bytes for sender. - */ - com.google.protobuf.ByteString - getSenderBytes(); - - /** - * bytes content = 3; - * @return The content. - */ - com.google.protobuf.ByteString getContent(); - - /** - * repeated string receiver = 4; - * @return A list containing the receiver. - */ - java.util.List - getReceiverList(); - /** - * repeated string receiver = 4; - * @return The count of receiver. - */ - int getReceiverCount(); - /** - * repeated string receiver = 4; - * @param index The index of the element to return. - * @return The receiver at the given index. - */ - String getReceiver(int index); - /** - * repeated string receiver = 4; - * @param index The index of the value to return. - * @return The bytes of the receiver at the given index. - */ - com.google.protobuf.ByteString - getReceiverBytes(int index); - } - /** - * Protobuf type {@code UnitMessage} - */ - public static final class UnitMessage extends - com.google.protobuf.GeneratedMessageV3 implements - // @@protoc_insertion_point(message_implements:UnitMessage) - UnitMessageOrBuilder { - private static final long serialVersionUID = 0L; - // Use UnitMessage.newBuilder() to construct. - private UnitMessage(com.google.protobuf.GeneratedMessageV3.Builder builder) { - super(builder); - } - private UnitMessage() { - msgType_ = 0; - sender_ = ""; - content_ = com.google.protobuf.ByteString.EMPTY; - receiver_ = com.google.protobuf.LazyStringArrayList.EMPTY; - } - - @Override - @SuppressWarnings({"unused"}) - protected Object newInstance( - UnusedPrivateParameter unused) { - return new UnitMessage(); - } - - @Override - public final com.google.protobuf.UnknownFieldSet - getUnknownFields() { - return this.unknownFields; - } - private UnitMessage( - com.google.protobuf.CodedInputStream input, - com.google.protobuf.ExtensionRegistryLite extensionRegistry) - throws com.google.protobuf.InvalidProtocolBufferException { - this(); - if (extensionRegistry == null) { - throw new NullPointerException(); - } - int mutable_bitField0_ = 0; - com.google.protobuf.UnknownFieldSet.Builder unknownFields = - com.google.protobuf.UnknownFieldSet.newBuilder(); - try { - boolean done = false; - while (!done) { - int tag = input.readTag(); - switch (tag) { - case 0: - done = true; - break; - case 8: { - int rawValue = input.readEnum(); - - msgType_ = rawValue; - break; - } - case 18: { - String s = input.readStringRequireUtf8(); - - sender_ = s; - break; - } - case 26: { - - content_ = input.readBytes(); - break; - } - case 34: { - String s = input.readStringRequireUtf8(); - if (!((mutable_bitField0_ & 0x00000001) != 0)) { - receiver_ = new com.google.protobuf.LazyStringArrayList(); - mutable_bitField0_ |= 0x00000001; - } - receiver_.add(s); - break; - } - default: { - if (!parseUnknownField( - input, unknownFields, extensionRegistry, tag)) { - done = true; - } - break; - } - } + return value; } - } catch (com.google.protobuf.InvalidProtocolBufferException e) { - throw e.setUnfinishedMessage(this); - } catch (java.io.IOException e) { - throw new com.google.protobuf.InvalidProtocolBufferException( - e).setUnfinishedMessage(this); - } finally { - if (((mutable_bitField0_ & 0x00000001) != 0)) { - receiver_ = receiver_.getUnmodifiableView(); + + /** + * @param value The numeric wire value of the corresponding enum entry. + * @return The enum associated with the given numeric wire value. + * @deprecated Use {@link #forNumber(int)} instead. + */ + @Deprecated + public static UnitMessageType valueOf(int value) { + return forNumber(value); } - this.unknownFields = unknownFields.build(); - makeExtensionsImmutable(); - } - } - public static final com.google.protobuf.Descriptors.Descriptor - getDescriptor() { - return BDLedgerContract.internal_static_UnitMessage_descriptor; - } - @Override - protected FieldAccessorTable - internalGetFieldAccessorTable() { - return BDLedgerContract.internal_static_UnitMessage_fieldAccessorTable - .ensureFieldAccessorsInitialized( - UnitMessage.class, Builder.class); - } - - public static final int MSGTYPE_FIELD_NUMBER = 1; - private int msgType_; - /** - * .UnitMessageType msgType = 1; - * @return The enum numeric value on the wire for msgType. - */ - @Override public int getMsgTypeValue() { - return msgType_; - } - /** - * .UnitMessageType msgType = 1; - * @return The msgType. - */ - @Override public UnitMessageType getMsgType() { - @SuppressWarnings("deprecation") - UnitMessageType result = UnitMessageType.valueOf(msgType_); - return result == null ? UnitMessageType.UNRECOGNIZED : result; - } - - public static final int SENDER_FIELD_NUMBER = 2; - private volatile Object sender_; - /** - * string sender = 2; - * @return The sender. - */ - @Override - public String getSender() { - Object ref = sender_; - if (ref instanceof String) { - return (String) ref; - } else { - com.google.protobuf.ByteString bs = - (com.google.protobuf.ByteString) ref; - String s = bs.toStringUtf8(); - sender_ = s; - return s; - } - } - /** - * string sender = 2; - * @return The bytes for sender. - */ - @Override - public com.google.protobuf.ByteString - getSenderBytes() { - Object ref = sender_; - if (ref instanceof String) { - com.google.protobuf.ByteString b = - com.google.protobuf.ByteString.copyFromUtf8( - (String) ref); - sender_ = b; - return b; - } else { - return (com.google.protobuf.ByteString) ref; - } - } - - public static final int CONTENT_FIELD_NUMBER = 3; - private com.google.protobuf.ByteString content_; - /** - * bytes content = 3; - * @return The content. - */ - @Override - public com.google.protobuf.ByteString getContent() { - return content_; - } - - public static final int RECEIVER_FIELD_NUMBER = 4; - private com.google.protobuf.LazyStringList receiver_; - /** - * repeated string receiver = 4; - * @return A list containing the receiver. - */ - public com.google.protobuf.ProtocolStringList - getReceiverList() { - return receiver_; - } - /** - * repeated string receiver = 4; - * @return The count of receiver. - */ - public int getReceiverCount() { - return receiver_.size(); - } - /** - * repeated string receiver = 4; - * @param index The index of the element to return. - * @return The receiver at the given index. - */ - public String getReceiver(int index) { - return receiver_.get(index); - } - /** - * repeated string receiver = 4; - * @param index The index of the value to return. - * @return The bytes of the receiver at the given index. - */ - public com.google.protobuf.ByteString - getReceiverBytes(int index) { - return receiver_.getByteString(index); - } - - private byte memoizedIsInitialized = -1; - @Override - public final boolean isInitialized() { - byte isInitialized = memoizedIsInitialized; - if (isInitialized == 1) return true; - if (isInitialized == 0) return false; - - memoizedIsInitialized = 1; - return true; - } - - @Override - public void writeTo(com.google.protobuf.CodedOutputStream output) - throws java.io.IOException { - if (msgType_ != UnitMessageType.UnitContractMessage.getNumber()) { - output.writeEnum(1, msgType_); - } - if (!getSenderBytes().isEmpty()) { - com.google.protobuf.GeneratedMessageV3.writeString(output, 2, sender_); - } - if (!content_.isEmpty()) { - output.writeBytes(3, content_); - } - for (int i = 0; i < receiver_.size(); i++) { - com.google.protobuf.GeneratedMessageV3.writeString(output, 4, receiver_.getRaw(i)); - } - unknownFields.writeTo(output); - } - - @Override - public int getSerializedSize() { - int size = memoizedSize; - if (size != -1) return size; - - size = 0; - if (msgType_ != UnitMessageType.UnitContractMessage.getNumber()) { - size += com.google.protobuf.CodedOutputStream - .computeEnumSize(1, msgType_); - } - if (!getSenderBytes().isEmpty()) { - size += com.google.protobuf.GeneratedMessageV3.computeStringSize(2, sender_); - } - if (!content_.isEmpty()) { - size += com.google.protobuf.CodedOutputStream - .computeBytesSize(3, content_); - } - { - int dataSize = 0; - for (int i = 0; i < receiver_.size(); i++) { - dataSize += computeStringSizeNoTag(receiver_.getRaw(i)); + /** + * @param value The numeric wire value of the corresponding enum entry. + * @return The enum associated with the given numeric wire value. + */ + public static UnitMessageType forNumber(int value) { + switch (value) { + case 0: + return UnitContractMessage; + case 1: + return UnitCommunicateMessage; + case 2: + return UnitUnitMessage; + case 3: + return UnitSequencingMessage; + case 4: + return UnitRecoverMessage; + default: + return null; + } } - size += dataSize; - size += 1 * getReceiverList().size(); - } - size += unknownFields.getSerializedSize(); - memoizedSize = size; - return size; + + public static com.google.protobuf.Internal.EnumLiteMap internalGetValueMap() { + return internalValueMap; + } + + private static final com.google.protobuf.Internal.EnumLiteMap internalValueMap = + new com.google.protobuf.Internal.EnumLiteMap() { + public UnitMessageType findValueByNumber(int number) { + return UnitMessageType.forNumber(number); + } + }; + + public final com.google.protobuf.Descriptors.EnumValueDescriptor getValueDescriptor() { + if (this == UNRECOGNIZED) { + throw new IllegalStateException( + "Can't get the descriptor of an unrecognized enum value."); + } + return getDescriptor().getValues().get(ordinal()); + } + + public final com.google.protobuf.Descriptors.EnumDescriptor getDescriptorForType() { + return getDescriptor(); + } + + public static final com.google.protobuf.Descriptors.EnumDescriptor getDescriptor() { + return BDLedgerContract.getDescriptor().getEnumTypes().get(0); + } + + private static final UnitMessageType[] VALUES = values(); + + public static UnitMessageType valueOf( + com.google.protobuf.Descriptors.EnumValueDescriptor desc) { + if (desc.getType() != getDescriptor()) { + throw new IllegalArgumentException("EnumValueDescriptor is not for this type."); + } + if (desc.getIndex() == -1) { + return UNRECOGNIZED; + } + return VALUES[desc.getIndex()]; + } + + private final int value; + + private UnitMessageType(int value) { + this.value = value; + } + + // @@protoc_insertion_point(enum_scope:UnitMessageType) } - @Override - public boolean equals(final Object obj) { - if (obj == this) { - return true; - } - if (!(obj instanceof UnitMessage)) { - return super.equals(obj); - } - UnitMessage other = (UnitMessage) obj; + public interface UnitMessageOrBuilder extends + // @@protoc_insertion_point(interface_extends:UnitMessage) + com.google.protobuf.MessageOrBuilder { - if (msgType_ != other.msgType_) return false; - if (!getSender() - .equals(other.getSender())) return false; - if (!getContent() - .equals(other.getContent())) return false; - if (!getReceiverList() - .equals(other.getReceiverList())) return false; - if (!unknownFields.equals(other.unknownFields)) return false; - return true; - } + /** + * .UnitMessageType msgType = 1; + * + * @return The enum numeric value on the wire for msgType. + */ + int getMsgTypeValue(); - @Override - public int hashCode() { - if (memoizedHashCode != 0) { - return memoizedHashCode; - } - int hash = 41; - hash = (19 * hash) + getDescriptor().hashCode(); - hash = (37 * hash) + MSGTYPE_FIELD_NUMBER; - hash = (53 * hash) + msgType_; - hash = (37 * hash) + SENDER_FIELD_NUMBER; - hash = (53 * hash) + getSender().hashCode(); - hash = (37 * hash) + CONTENT_FIELD_NUMBER; - hash = (53 * hash) + getContent().hashCode(); - if (getReceiverCount() > 0) { - hash = (37 * hash) + RECEIVER_FIELD_NUMBER; - hash = (53 * hash) + getReceiverList().hashCode(); - } - hash = (29 * hash) + unknownFields.hashCode(); - memoizedHashCode = hash; - return hash; - } + /** + * .UnitMessageType msgType = 1; + * + * @return The msgType. + */ + UnitMessageType getMsgType(); - public static UnitMessage parseFrom( - java.nio.ByteBuffer data) - throws com.google.protobuf.InvalidProtocolBufferException { - return PARSER.parseFrom(data); - } - public static UnitMessage parseFrom( - java.nio.ByteBuffer data, - com.google.protobuf.ExtensionRegistryLite extensionRegistry) - throws com.google.protobuf.InvalidProtocolBufferException { - return PARSER.parseFrom(data, extensionRegistry); - } - public static UnitMessage parseFrom( - com.google.protobuf.ByteString data) - throws com.google.protobuf.InvalidProtocolBufferException { - return PARSER.parseFrom(data); - } - public static UnitMessage parseFrom( - com.google.protobuf.ByteString data, - com.google.protobuf.ExtensionRegistryLite extensionRegistry) - throws com.google.protobuf.InvalidProtocolBufferException { - return PARSER.parseFrom(data, extensionRegistry); - } - public static UnitMessage parseFrom(byte[] data) - throws com.google.protobuf.InvalidProtocolBufferException { - return PARSER.parseFrom(data); - } - public static UnitMessage parseFrom( - byte[] data, - com.google.protobuf.ExtensionRegistryLite extensionRegistry) - throws com.google.protobuf.InvalidProtocolBufferException { - return PARSER.parseFrom(data, extensionRegistry); - } - public static UnitMessage parseFrom(java.io.InputStream input) - throws java.io.IOException { - return com.google.protobuf.GeneratedMessageV3 - .parseWithIOException(PARSER, input); - } - public static UnitMessage parseFrom( - java.io.InputStream input, - com.google.protobuf.ExtensionRegistryLite extensionRegistry) - throws java.io.IOException { - return com.google.protobuf.GeneratedMessageV3 - .parseWithIOException(PARSER, input, extensionRegistry); - } - public static UnitMessage parseDelimitedFrom(java.io.InputStream input) - throws java.io.IOException { - return com.google.protobuf.GeneratedMessageV3 - .parseDelimitedWithIOException(PARSER, input); - } - public static UnitMessage parseDelimitedFrom( - java.io.InputStream input, - com.google.protobuf.ExtensionRegistryLite extensionRegistry) - throws java.io.IOException { - return com.google.protobuf.GeneratedMessageV3 - .parseDelimitedWithIOException(PARSER, input, extensionRegistry); - } - public static UnitMessage parseFrom( - com.google.protobuf.CodedInputStream input) - throws java.io.IOException { - return com.google.protobuf.GeneratedMessageV3 - .parseWithIOException(PARSER, input); - } - public static UnitMessage parseFrom( - com.google.protobuf.CodedInputStream input, - com.google.protobuf.ExtensionRegistryLite extensionRegistry) - throws java.io.IOException { - return com.google.protobuf.GeneratedMessageV3 - .parseWithIOException(PARSER, input, extensionRegistry); - } + /** + * string sender = 2; + * + * @return The sender. + */ + String getSender(); - @Override - public Builder newBuilderForType() { return newBuilder(); } - public static Builder newBuilder() { - return DEFAULT_INSTANCE.toBuilder(); - } - public static Builder newBuilder(UnitMessage prototype) { - return DEFAULT_INSTANCE.toBuilder().mergeFrom(prototype); - } - @Override - public Builder toBuilder() { - return this == DEFAULT_INSTANCE - ? new Builder() : new Builder().mergeFrom(this); - } + /** + * string sender = 2; + * + * @return The bytes for sender. + */ + com.google.protobuf.ByteString getSenderBytes(); - @Override - protected Builder newBuilderForType( - BuilderParent parent) { - Builder builder = new Builder(parent); - return builder; + /** + * bytes content = 3; + * + * @return The content. + */ + com.google.protobuf.ByteString getContent(); + + /** + * repeated string receiver = 4; + * + * @return A list containing the receiver. + */ + java.util.List getReceiverList(); + + /** + * repeated string receiver = 4; + * + * @return The count of receiver. + */ + int getReceiverCount(); + + /** + * repeated string receiver = 4; + * + * @param index The index of the element to return. + * @return The receiver at the given index. + */ + String getReceiver(int index); + + /** + * repeated string receiver = 4; + * + * @param index The index of the value to return. + * @return The bytes of the receiver at the given index. + */ + com.google.protobuf.ByteString getReceiverBytes(int index); } /** * Protobuf type {@code UnitMessage} */ - public static final class Builder extends - com.google.protobuf.GeneratedMessageV3.Builder implements - // @@protoc_insertion_point(builder_implements:UnitMessage) - UnitMessageOrBuilder { - public static final com.google.protobuf.Descriptors.Descriptor - getDescriptor() { - return BDLedgerContract.internal_static_UnitMessage_descriptor; - } + public static final class UnitMessage extends com.google.protobuf.GeneratedMessageV3 implements + // @@protoc_insertion_point(message_implements:UnitMessage) + UnitMessageOrBuilder { + private static final long serialVersionUID = 0L; - @Override - protected FieldAccessorTable - internalGetFieldAccessorTable() { - return BDLedgerContract.internal_static_UnitMessage_fieldAccessorTable - .ensureFieldAccessorsInitialized( - UnitMessage.class, Builder.class); - } - - // Construct using BDLedgerContract.UnitMessage.newBuilder() - private Builder() { - maybeForceBuilderInitialization(); - } - - private Builder( - BuilderParent parent) { - super(parent); - maybeForceBuilderInitialization(); - } - private void maybeForceBuilderInitialization() { - if (com.google.protobuf.GeneratedMessageV3 - .alwaysUseFieldBuilders) { + // Use UnitMessage.newBuilder() to construct. + private UnitMessage(com.google.protobuf.GeneratedMessageV3.Builder builder) { + super(builder); } - } - @Override - public Builder clear() { - super.clear(); - msgType_ = 0; - sender_ = ""; - - content_ = com.google.protobuf.ByteString.EMPTY; - - receiver_ = com.google.protobuf.LazyStringArrayList.EMPTY; - bitField0_ = (bitField0_ & ~0x00000001); - return this; - } - - @Override - public com.google.protobuf.Descriptors.Descriptor - getDescriptorForType() { - return BDLedgerContract.internal_static_UnitMessage_descriptor; - } - - @Override - public UnitMessage getDefaultInstanceForType() { - return UnitMessage.getDefaultInstance(); - } - - @Override - public UnitMessage build() { - UnitMessage result = buildPartial(); - if (!result.isInitialized()) { - throw newUninitializedMessageException(result); + private UnitMessage() { + msgType_ = 0; + sender_ = ""; + content_ = com.google.protobuf.ByteString.EMPTY; + receiver_ = com.google.protobuf.LazyStringArrayList.EMPTY; } - return result; - } - @Override - public UnitMessage buildPartial() { - UnitMessage result = new UnitMessage(this); - int from_bitField0_ = bitField0_; - result.msgType_ = msgType_; - result.sender_ = sender_; - result.content_ = content_; - if (((bitField0_ & 0x00000001) != 0)) { - receiver_ = receiver_.getUnmodifiableView(); - bitField0_ = (bitField0_ & ~0x00000001); + @Override + @SuppressWarnings({"unused"}) + protected Object newInstance(UnusedPrivateParameter unused) { + return new UnitMessage(); } - result.receiver_ = receiver_; - onBuilt(); - return result; - } - @Override - public Builder clone() { - return super.clone(); - } - @Override - public Builder setField( - com.google.protobuf.Descriptors.FieldDescriptor field, - Object value) { - return super.setField(field, value); - } - @Override - public Builder clearField( - com.google.protobuf.Descriptors.FieldDescriptor field) { - return super.clearField(field); - } - @Override - public Builder clearOneof( - com.google.protobuf.Descriptors.OneofDescriptor oneof) { - return super.clearOneof(oneof); - } - @Override - public Builder setRepeatedField( - com.google.protobuf.Descriptors.FieldDescriptor field, - int index, Object value) { - return super.setRepeatedField(field, index, value); - } - @Override - public Builder addRepeatedField( - com.google.protobuf.Descriptors.FieldDescriptor field, - Object value) { - return super.addRepeatedField(field, value); - } - @Override - public Builder mergeFrom(com.google.protobuf.Message other) { - if (other instanceof UnitMessage) { - return mergeFrom((UnitMessage)other); - } else { - super.mergeFrom(other); - return this; + @Override + public final com.google.protobuf.UnknownFieldSet getUnknownFields() { + return this.unknownFields; } - } - public Builder mergeFrom(UnitMessage other) { - if (other == UnitMessage.getDefaultInstance()) return this; - if (other.msgType_ != 0) { - setMsgTypeValue(other.getMsgTypeValue()); + private UnitMessage(com.google.protobuf.CodedInputStream input, + com.google.protobuf.ExtensionRegistryLite extensionRegistry) + throws com.google.protobuf.InvalidProtocolBufferException { + this(); + if (extensionRegistry == null) { + throw new NullPointerException(); + } + int mutable_bitField0_ = 0; + com.google.protobuf.UnknownFieldSet.Builder unknownFields = + com.google.protobuf.UnknownFieldSet.newBuilder(); + try { + boolean done = false; + while (!done) { + int tag = input.readTag(); + switch (tag) { + case 0: + done = true; + break; + case 8: { + int rawValue = input.readEnum(); + + msgType_ = rawValue; + break; + } + case 18: { + String s = input.readStringRequireUtf8(); + + sender_ = s; + break; + } + case 26: { + + content_ = input.readBytes(); + break; + } + case 34: { + String s = input.readStringRequireUtf8(); + if (!((mutable_bitField0_ & 0x00000001) != 0)) { + receiver_ = new com.google.protobuf.LazyStringArrayList(); + mutable_bitField0_ |= 0x00000001; + } + receiver_.add(s); + break; + } + default: { + if (!parseUnknownField(input, unknownFields, extensionRegistry, tag)) { + done = true; + } + break; + } + } + } + } catch (com.google.protobuf.InvalidProtocolBufferException e) { + throw e.setUnfinishedMessage(this); + } catch (java.io.IOException e) { + throw new com.google.protobuf.InvalidProtocolBufferException(e) + .setUnfinishedMessage(this); + } finally { + if (((mutable_bitField0_ & 0x00000001) != 0)) { + receiver_ = receiver_.getUnmodifiableView(); + } + this.unknownFields = unknownFields.build(); + makeExtensionsImmutable(); + } } - if (!other.getSender().isEmpty()) { - sender_ = other.sender_; - onChanged(); + + public static final com.google.protobuf.Descriptors.Descriptor getDescriptor() { + return BDLedgerContract.internal_static_UnitMessage_descriptor; } - if (other.getContent() != com.google.protobuf.ByteString.EMPTY) { - setContent(other.getContent()); + + @Override + protected FieldAccessorTable internalGetFieldAccessorTable() { + return BDLedgerContract.internal_static_UnitMessage_fieldAccessorTable + .ensureFieldAccessorsInitialized(UnitMessage.class, Builder.class); } - if (!other.receiver_.isEmpty()) { - if (receiver_.isEmpty()) { - receiver_ = other.receiver_; - bitField0_ = (bitField0_ & ~0x00000001); - } else { - ensureReceiverIsMutable(); - receiver_.addAll(other.receiver_); - } - onChanged(); + + public static final int MSGTYPE_FIELD_NUMBER = 1; + private int msgType_; + + /** + * .UnitMessageType msgType = 1; + * + * @return The enum numeric value on the wire for msgType. + */ + @Override + public int getMsgTypeValue() { + return msgType_; } - this.mergeUnknownFields(other.unknownFields); - onChanged(); - return this; - } - @Override - public final boolean isInitialized() { - return true; - } - - @Override - public Builder mergeFrom( - com.google.protobuf.CodedInputStream input, - com.google.protobuf.ExtensionRegistryLite extensionRegistry) - throws java.io.IOException { - UnitMessage parsedMessage = null; - try { - parsedMessage = PARSER.parsePartialFrom(input, extensionRegistry); - } catch (com.google.protobuf.InvalidProtocolBufferException e) { - parsedMessage = (UnitMessage) e.getUnfinishedMessage(); - throw e.unwrapIOException(); - } finally { - if (parsedMessage != null) { - mergeFrom(parsedMessage); - } + /** + * .UnitMessageType msgType = 1; + * + * @return The msgType. + */ + @Override + public UnitMessageType getMsgType() { + @SuppressWarnings("deprecation") + UnitMessageType result = UnitMessageType.valueOf(msgType_); + return result == null ? UnitMessageType.UNRECOGNIZED : result; } - return this; - } - private int bitField0_; - private int msgType_ = 0; - /** - * .UnitMessageType msgType = 1; - * @return The enum numeric value on the wire for msgType. - */ - @Override public int getMsgTypeValue() { - return msgType_; - } - /** - * .UnitMessageType msgType = 1; - * @param value The enum numeric value on the wire for msgType to set. - * @return This builder for chaining. - */ - public Builder setMsgTypeValue(int value) { - - msgType_ = value; - onChanged(); - return this; - } - /** - * .UnitMessageType msgType = 1; - * @return The msgType. - */ - @Override - public UnitMessageType getMsgType() { - @SuppressWarnings("deprecation") - UnitMessageType result = UnitMessageType.valueOf(msgType_); - return result == null ? UnitMessageType.UNRECOGNIZED : result; - } - /** - * .UnitMessageType msgType = 1; - * @param value The msgType to set. - * @return This builder for chaining. - */ - public Builder setMsgType(UnitMessageType value) { - if (value == null) { - throw new NullPointerException(); + public static final int SENDER_FIELD_NUMBER = 2; + private volatile Object sender_; + + /** + * string sender = 2; + * + * @return The sender. + */ + @Override + public String getSender() { + Object ref = sender_; + if (ref instanceof String) { + return (String) ref; + } else { + com.google.protobuf.ByteString bs = (com.google.protobuf.ByteString) ref; + String s = bs.toStringUtf8(); + sender_ = s; + return s; + } } - - msgType_ = value.getNumber(); - onChanged(); - return this; - } - /** - * .UnitMessageType msgType = 1; - * @return This builder for chaining. - */ - public Builder clearMsgType() { - - msgType_ = 0; - onChanged(); - return this; - } - private Object sender_ = ""; - /** - * string sender = 2; - * @return The sender. - */ - public String getSender() { - Object ref = sender_; - if (!(ref instanceof String)) { - com.google.protobuf.ByteString bs = - (com.google.protobuf.ByteString) ref; - String s = bs.toStringUtf8(); - sender_ = s; - return s; - } else { - return (String) ref; + /** + * string sender = 2; + * + * @return The bytes for sender. + */ + @Override + public com.google.protobuf.ByteString getSenderBytes() { + Object ref = sender_; + if (ref instanceof String) { + com.google.protobuf.ByteString b = + com.google.protobuf.ByteString.copyFromUtf8((String) ref); + sender_ = b; + return b; + } else { + return (com.google.protobuf.ByteString) ref; + } } - } - /** - * string sender = 2; - * @return The bytes for sender. - */ - public com.google.protobuf.ByteString - getSenderBytes() { - Object ref = sender_; - if (ref instanceof String) { - com.google.protobuf.ByteString b = - com.google.protobuf.ByteString.copyFromUtf8( - (String) ref); - sender_ = b; - return b; - } else { - return (com.google.protobuf.ByteString) ref; + + public static final int CONTENT_FIELD_NUMBER = 3; + private com.google.protobuf.ByteString content_; + + /** + * bytes content = 3; + * + * @return The content. + */ + @Override + public com.google.protobuf.ByteString getContent() { + return content_; } - } - /** - * string sender = 2; - * @param value The sender to set. - * @return This builder for chaining. - */ - public Builder setSender( - String value) { - if (value == null) { - throw new NullPointerException(); - } - - sender_ = value; - onChanged(); - return this; - } - /** - * string sender = 2; - * @return This builder for chaining. - */ - public Builder clearSender() { - - sender_ = getDefaultInstance().getSender(); - onChanged(); - return this; - } - /** - * string sender = 2; - * @param value The bytes for sender to set. - * @return This builder for chaining. - */ - public Builder setSenderBytes( - com.google.protobuf.ByteString value) { - if (value == null) { - throw new NullPointerException(); - } - checkByteStringIsUtf8(value); - - sender_ = value; - onChanged(); - return this; - } - private com.google.protobuf.ByteString content_ = com.google.protobuf.ByteString.EMPTY; - /** - * bytes content = 3; - * @return The content. - */ - @Override - public com.google.protobuf.ByteString getContent() { - return content_; - } - /** - * bytes content = 3; - * @param value The content to set. - * @return This builder for chaining. - */ - public Builder setContent(com.google.protobuf.ByteString value) { - if (value == null) { - throw new NullPointerException(); - } - - content_ = value; - onChanged(); - return this; - } - /** - * bytes content = 3; - * @return This builder for chaining. - */ - public Builder clearContent() { - - content_ = getDefaultInstance().getContent(); - onChanged(); - return this; - } + public static final int RECEIVER_FIELD_NUMBER = 4; + private com.google.protobuf.LazyStringList receiver_; - private com.google.protobuf.LazyStringList receiver_ = com.google.protobuf.LazyStringArrayList.EMPTY; - private void ensureReceiverIsMutable() { - if (!((bitField0_ & 0x00000001) != 0)) { - receiver_ = new com.google.protobuf.LazyStringArrayList(receiver_); - bitField0_ |= 0x00000001; - } - } - /** - * repeated string receiver = 4; - * @return A list containing the receiver. - */ - public com.google.protobuf.ProtocolStringList - getReceiverList() { - return receiver_.getUnmodifiableView(); - } - /** - * repeated string receiver = 4; - * @return The count of receiver. - */ - public int getReceiverCount() { - return receiver_.size(); - } - /** - * repeated string receiver = 4; - * @param index The index of the element to return. - * @return The receiver at the given index. - */ - public String getReceiver(int index) { - return receiver_.get(index); - } - /** - * repeated string receiver = 4; - * @param index The index of the value to return. - * @return The bytes of the receiver at the given index. - */ - public com.google.protobuf.ByteString - getReceiverBytes(int index) { - return receiver_.getByteString(index); - } - /** - * repeated string receiver = 4; - * @param index The index to set the value at. - * @param value The receiver to set. - * @return This builder for chaining. - */ - public Builder setReceiver( - int index, String value) { - if (value == null) { - throw new NullPointerException(); - } - ensureReceiverIsMutable(); - receiver_.set(index, value); - onChanged(); - return this; - } - /** - * repeated string receiver = 4; - * @param value The receiver to add. - * @return This builder for chaining. - */ - public Builder addReceiver( - String value) { - if (value == null) { - throw new NullPointerException(); - } - ensureReceiverIsMutable(); - receiver_.add(value); - onChanged(); - return this; - } - /** - * repeated string receiver = 4; - * @param values The receiver to add. - * @return This builder for chaining. - */ - public Builder addAllReceiver( - Iterable values) { - ensureReceiverIsMutable(); - com.google.protobuf.AbstractMessageLite.Builder.addAll( - values, receiver_); - onChanged(); - return this; - } - /** - * repeated string receiver = 4; - * @return This builder for chaining. - */ - public Builder clearReceiver() { - receiver_ = com.google.protobuf.LazyStringArrayList.EMPTY; - bitField0_ = (bitField0_ & ~0x00000001); - onChanged(); - return this; - } - /** - * repeated string receiver = 4; - * @param value The bytes of the receiver to add. - * @return This builder for chaining. - */ - public Builder addReceiverBytes( - com.google.protobuf.ByteString value) { - if (value == null) { - throw new NullPointerException(); - } - checkByteStringIsUtf8(value); - ensureReceiverIsMutable(); - receiver_.add(value); - onChanged(); - return this; - } - @Override - public final Builder setUnknownFields( - final com.google.protobuf.UnknownFieldSet unknownFields) { - return super.setUnknownFields(unknownFields); - } + /** + * repeated string receiver = 4; + * + * @return A list containing the receiver. + */ + public com.google.protobuf.ProtocolStringList getReceiverList() { + return receiver_; + } - @Override - public final Builder mergeUnknownFields( - final com.google.protobuf.UnknownFieldSet unknownFields) { - return super.mergeUnknownFields(unknownFields); - } + /** + * repeated string receiver = 4; + * + * @return The count of receiver. + */ + public int getReceiverCount() { + return receiver_.size(); + } + + /** + * repeated string receiver = 4; + * + * @param index The index of the element to return. + * @return The receiver at the given index. + */ + public String getReceiver(int index) { + return receiver_.get(index); + } + + /** + * repeated string receiver = 4; + * + * @param index The index of the value to return. + * @return The bytes of the receiver at the given index. + */ + public com.google.protobuf.ByteString getReceiverBytes(int index) { + return receiver_.getByteString(index); + } + + private byte memoizedIsInitialized = -1; + + @Override + public final boolean isInitialized() { + byte isInitialized = memoizedIsInitialized; + if (isInitialized == 1) + return true; + if (isInitialized == 0) + return false; + + memoizedIsInitialized = 1; + return true; + } + + @Override + public void writeTo(com.google.protobuf.CodedOutputStream output) + throws java.io.IOException { + if (msgType_ != UnitMessageType.UnitContractMessage.getNumber()) { + output.writeEnum(1, msgType_); + } + if (!getSenderBytes().isEmpty()) { + com.google.protobuf.GeneratedMessageV3.writeString(output, 2, sender_); + } + if (!content_.isEmpty()) { + output.writeBytes(3, content_); + } + for (int i = 0; i < receiver_.size(); i++) { + com.google.protobuf.GeneratedMessageV3.writeString(output, 4, receiver_.getRaw(i)); + } + unknownFields.writeTo(output); + } + + @Override + public int getSerializedSize() { + int size = memoizedSize; + if (size != -1) + return size; + + size = 0; + if (msgType_ != UnitMessageType.UnitContractMessage.getNumber()) { + size += com.google.protobuf.CodedOutputStream.computeEnumSize(1, msgType_); + } + if (!getSenderBytes().isEmpty()) { + size += com.google.protobuf.GeneratedMessageV3.computeStringSize(2, sender_); + } + if (!content_.isEmpty()) { + size += com.google.protobuf.CodedOutputStream.computeBytesSize(3, content_); + } + { + int dataSize = 0; + for (int i = 0; i < receiver_.size(); i++) { + dataSize += computeStringSizeNoTag(receiver_.getRaw(i)); + } + size += dataSize; + size += 1 * getReceiverList().size(); + } + size += unknownFields.getSerializedSize(); + memoizedSize = size; + return size; + } + + @Override + public boolean equals(final Object obj) { + if (obj == this) { + return true; + } + if (!(obj instanceof UnitMessage)) { + return super.equals(obj); + } + UnitMessage other = (UnitMessage) obj; + + if (msgType_ != other.msgType_) + return false; + if (!getSender().equals(other.getSender())) + return false; + if (!getContent().equals(other.getContent())) + return false; + if (!getReceiverList().equals(other.getReceiverList())) + return false; + if (!unknownFields.equals(other.unknownFields)) + return false; + return true; + } + + @Override + public int hashCode() { + if (memoizedHashCode != 0) { + return memoizedHashCode; + } + int hash = 41; + hash = (19 * hash) + getDescriptor().hashCode(); + hash = (37 * hash) + MSGTYPE_FIELD_NUMBER; + hash = (53 * hash) + msgType_; + hash = (37 * hash) + SENDER_FIELD_NUMBER; + hash = (53 * hash) + getSender().hashCode(); + hash = (37 * hash) + CONTENT_FIELD_NUMBER; + hash = (53 * hash) + getContent().hashCode(); + if (getReceiverCount() > 0) { + hash = (37 * hash) + RECEIVER_FIELD_NUMBER; + hash = (53 * hash) + getReceiverList().hashCode(); + } + hash = (29 * hash) + unknownFields.hashCode(); + memoizedHashCode = hash; + return hash; + } + + public static UnitMessage parseFrom(java.nio.ByteBuffer data) + throws com.google.protobuf.InvalidProtocolBufferException { + return PARSER.parseFrom(data); + } + + public static UnitMessage parseFrom(java.nio.ByteBuffer data, + com.google.protobuf.ExtensionRegistryLite extensionRegistry) + throws com.google.protobuf.InvalidProtocolBufferException { + return PARSER.parseFrom(data, extensionRegistry); + } + + public static UnitMessage parseFrom(com.google.protobuf.ByteString data) + throws com.google.protobuf.InvalidProtocolBufferException { + return PARSER.parseFrom(data); + } + + public static UnitMessage parseFrom(com.google.protobuf.ByteString data, + com.google.protobuf.ExtensionRegistryLite extensionRegistry) + throws com.google.protobuf.InvalidProtocolBufferException { + return PARSER.parseFrom(data, extensionRegistry); + } + + public static UnitMessage parseFrom(byte[] data) + throws com.google.protobuf.InvalidProtocolBufferException { + return PARSER.parseFrom(data); + } + + public static UnitMessage parseFrom(byte[] data, + com.google.protobuf.ExtensionRegistryLite extensionRegistry) + throws com.google.protobuf.InvalidProtocolBufferException { + return PARSER.parseFrom(data, extensionRegistry); + } + + public static UnitMessage parseFrom(java.io.InputStream input) throws java.io.IOException { + return com.google.protobuf.GeneratedMessageV3.parseWithIOException(PARSER, input); + } + + public static UnitMessage parseFrom(java.io.InputStream input, + com.google.protobuf.ExtensionRegistryLite extensionRegistry) + throws java.io.IOException { + return com.google.protobuf.GeneratedMessageV3.parseWithIOException(PARSER, input, + extensionRegistry); + } + + public static UnitMessage parseDelimitedFrom(java.io.InputStream input) + throws java.io.IOException { + return com.google.protobuf.GeneratedMessageV3.parseDelimitedWithIOException(PARSER, + input); + } + + public static UnitMessage parseDelimitedFrom(java.io.InputStream input, + com.google.protobuf.ExtensionRegistryLite extensionRegistry) + throws java.io.IOException { + return com.google.protobuf.GeneratedMessageV3.parseDelimitedWithIOException(PARSER, + input, extensionRegistry); + } + + public static UnitMessage parseFrom(com.google.protobuf.CodedInputStream input) + throws java.io.IOException { + return com.google.protobuf.GeneratedMessageV3.parseWithIOException(PARSER, input); + } + + public static UnitMessage parseFrom(com.google.protobuf.CodedInputStream input, + com.google.protobuf.ExtensionRegistryLite extensionRegistry) + throws java.io.IOException { + return com.google.protobuf.GeneratedMessageV3.parseWithIOException(PARSER, input, + extensionRegistry); + } + + @Override + public Builder newBuilderForType() { + return newBuilder(); + } + + public static Builder newBuilder() { + return DEFAULT_INSTANCE.toBuilder(); + } + + public static Builder newBuilder(UnitMessage prototype) { + return DEFAULT_INSTANCE.toBuilder().mergeFrom(prototype); + } + + @Override + public Builder toBuilder() { + return this == DEFAULT_INSTANCE ? new Builder() : new Builder().mergeFrom(this); + } + + @Override + protected Builder newBuilderForType(BuilderParent parent) { + Builder builder = new Builder(parent); + return builder; + } + + /** + * Protobuf type {@code UnitMessage} + */ + public static final class Builder + extends com.google.protobuf.GeneratedMessageV3.Builder implements + // @@protoc_insertion_point(builder_implements:UnitMessage) + UnitMessageOrBuilder { + public static final com.google.protobuf.Descriptors.Descriptor getDescriptor() { + return BDLedgerContract.internal_static_UnitMessage_descriptor; + } + + @Override + protected FieldAccessorTable internalGetFieldAccessorTable() { + return BDLedgerContract.internal_static_UnitMessage_fieldAccessorTable + .ensureFieldAccessorsInitialized(UnitMessage.class, Builder.class); + } + + // Construct using BDLedgerContract.UnitMessage.newBuilder() + private Builder() { + maybeForceBuilderInitialization(); + } + + private Builder(BuilderParent parent) { + super(parent); + maybeForceBuilderInitialization(); + } + + private void maybeForceBuilderInitialization() { + if (com.google.protobuf.GeneratedMessageV3.alwaysUseFieldBuilders) { + } + } + + @Override + public Builder clear() { + super.clear(); + msgType_ = 0; + + sender_ = ""; + + content_ = com.google.protobuf.ByteString.EMPTY; + + receiver_ = com.google.protobuf.LazyStringArrayList.EMPTY; + bitField0_ = (bitField0_ & ~0x00000001); + return this; + } + + @Override + public com.google.protobuf.Descriptors.Descriptor getDescriptorForType() { + return BDLedgerContract.internal_static_UnitMessage_descriptor; + } + + @Override + public UnitMessage getDefaultInstanceForType() { + return UnitMessage.getDefaultInstance(); + } + + @Override + public UnitMessage build() { + UnitMessage result = buildPartial(); + if (!result.isInitialized()) { + throw newUninitializedMessageException(result); + } + return result; + } + + @Override + public UnitMessage buildPartial() { + UnitMessage result = new UnitMessage(this); + int from_bitField0_ = bitField0_; + result.msgType_ = msgType_; + result.sender_ = sender_; + result.content_ = content_; + if (((bitField0_ & 0x00000001) != 0)) { + receiver_ = receiver_.getUnmodifiableView(); + bitField0_ = (bitField0_ & ~0x00000001); + } + result.receiver_ = receiver_; + onBuilt(); + return result; + } + + @Override + public Builder clone() { + return super.clone(); + } + + @Override + public Builder setField(com.google.protobuf.Descriptors.FieldDescriptor field, + Object value) { + return super.setField(field, value); + } + + @Override + public Builder clearField(com.google.protobuf.Descriptors.FieldDescriptor field) { + return super.clearField(field); + } + + @Override + public Builder clearOneof(com.google.protobuf.Descriptors.OneofDescriptor oneof) { + return super.clearOneof(oneof); + } + + @Override + public Builder setRepeatedField(com.google.protobuf.Descriptors.FieldDescriptor field, + int index, Object value) { + return super.setRepeatedField(field, index, value); + } + + @Override + public Builder addRepeatedField(com.google.protobuf.Descriptors.FieldDescriptor field, + Object value) { + return super.addRepeatedField(field, value); + } + + @Override + public Builder mergeFrom(com.google.protobuf.Message other) { + if (other instanceof UnitMessage) { + return mergeFrom((UnitMessage) other); + } else { + super.mergeFrom(other); + return this; + } + } + + public Builder mergeFrom(UnitMessage other) { + if (other == UnitMessage.getDefaultInstance()) + return this; + if (other.msgType_ != 0) { + setMsgTypeValue(other.getMsgTypeValue()); + } + if (!other.getSender().isEmpty()) { + sender_ = other.sender_; + onChanged(); + } + if (other.getContent() != com.google.protobuf.ByteString.EMPTY) { + setContent(other.getContent()); + } + if (!other.receiver_.isEmpty()) { + if (receiver_.isEmpty()) { + receiver_ = other.receiver_; + bitField0_ = (bitField0_ & ~0x00000001); + } else { + ensureReceiverIsMutable(); + receiver_.addAll(other.receiver_); + } + onChanged(); + } + this.mergeUnknownFields(other.unknownFields); + onChanged(); + return this; + } + + @Override + public final boolean isInitialized() { + return true; + } + + @Override + public Builder mergeFrom(com.google.protobuf.CodedInputStream input, + com.google.protobuf.ExtensionRegistryLite extensionRegistry) + throws java.io.IOException { + UnitMessage parsedMessage = null; + try { + parsedMessage = PARSER.parsePartialFrom(input, extensionRegistry); + } catch (com.google.protobuf.InvalidProtocolBufferException e) { + parsedMessage = (UnitMessage) e.getUnfinishedMessage(); + throw e.unwrapIOException(); + } finally { + if (parsedMessage != null) { + mergeFrom(parsedMessage); + } + } + return this; + } + + private int bitField0_; + + private int msgType_ = 0; + + /** + * .UnitMessageType msgType = 1; + * + * @return The enum numeric value on the wire for msgType. + */ + @Override + public int getMsgTypeValue() { + return msgType_; + } + + /** + * .UnitMessageType msgType = 1; + * + * @param value The enum numeric value on the wire for msgType to set. + * @return This builder for chaining. + */ + public Builder setMsgTypeValue(int value) { + + msgType_ = value; + onChanged(); + return this; + } + + /** + * .UnitMessageType msgType = 1; + * + * @return The msgType. + */ + @Override + public UnitMessageType getMsgType() { + @SuppressWarnings("deprecation") + UnitMessageType result = UnitMessageType.valueOf(msgType_); + return result == null ? UnitMessageType.UNRECOGNIZED : result; + } + + /** + * .UnitMessageType msgType = 1; + * + * @param value The msgType to set. + * @return This builder for chaining. + */ + public Builder setMsgType(UnitMessageType value) { + if (value == null) { + throw new NullPointerException(); + } + + msgType_ = value.getNumber(); + onChanged(); + return this; + } + + /** + * .UnitMessageType msgType = 1; + * + * @return This builder for chaining. + */ + public Builder clearMsgType() { + + msgType_ = 0; + onChanged(); + return this; + } + + private Object sender_ = ""; + + /** + * string sender = 2; + * + * @return The sender. + */ + public String getSender() { + Object ref = sender_; + if (!(ref instanceof String)) { + com.google.protobuf.ByteString bs = (com.google.protobuf.ByteString) ref; + String s = bs.toStringUtf8(); + sender_ = s; + return s; + } else { + return (String) ref; + } + } + + /** + * string sender = 2; + * + * @return The bytes for sender. + */ + public com.google.protobuf.ByteString getSenderBytes() { + Object ref = sender_; + if (ref instanceof String) { + com.google.protobuf.ByteString b = + com.google.protobuf.ByteString.copyFromUtf8((String) ref); + sender_ = b; + return b; + } else { + return (com.google.protobuf.ByteString) ref; + } + } + + /** + * string sender = 2; + * + * @param value The sender to set. + * @return This builder for chaining. + */ + public Builder setSender(String value) { + if (value == null) { + throw new NullPointerException(); + } + + sender_ = value; + onChanged(); + return this; + } + + /** + * string sender = 2; + * + * @return This builder for chaining. + */ + public Builder clearSender() { + + sender_ = getDefaultInstance().getSender(); + onChanged(); + return this; + } + + /** + * string sender = 2; + * + * @param value The bytes for sender to set. + * @return This builder for chaining. + */ + public Builder setSenderBytes(com.google.protobuf.ByteString value) { + if (value == null) { + throw new NullPointerException(); + } + checkByteStringIsUtf8(value); + + sender_ = value; + onChanged(); + return this; + } + + private com.google.protobuf.ByteString content_ = com.google.protobuf.ByteString.EMPTY; + + /** + * bytes content = 3; + * + * @return The content. + */ + @Override + public com.google.protobuf.ByteString getContent() { + return content_; + } + + /** + * bytes content = 3; + * + * @param value The content to set. + * @return This builder for chaining. + */ + public Builder setContent(com.google.protobuf.ByteString value) { + if (value == null) { + throw new NullPointerException(); + } + + content_ = value; + onChanged(); + return this; + } + + /** + * bytes content = 3; + * + * @return This builder for chaining. + */ + public Builder clearContent() { + + content_ = getDefaultInstance().getContent(); + onChanged(); + return this; + } + + private com.google.protobuf.LazyStringList receiver_ = + com.google.protobuf.LazyStringArrayList.EMPTY; + + private void ensureReceiverIsMutable() { + if (!((bitField0_ & 0x00000001) != 0)) { + receiver_ = new com.google.protobuf.LazyStringArrayList(receiver_); + bitField0_ |= 0x00000001; + } + } + + /** + * repeated string receiver = 4; + * + * @return A list containing the receiver. + */ + public com.google.protobuf.ProtocolStringList getReceiverList() { + return receiver_.getUnmodifiableView(); + } + + /** + * repeated string receiver = 4; + * + * @return The count of receiver. + */ + public int getReceiverCount() { + return receiver_.size(); + } + + /** + * repeated string receiver = 4; + * + * @param index The index of the element to return. + * @return The receiver at the given index. + */ + public String getReceiver(int index) { + return receiver_.get(index); + } + + /** + * repeated string receiver = 4; + * + * @param index The index of the value to return. + * @return The bytes of the receiver at the given index. + */ + public com.google.protobuf.ByteString getReceiverBytes(int index) { + return receiver_.getByteString(index); + } + + /** + * repeated string receiver = 4; + * + * @param index The index to set the value at. + * @param value The receiver to set. + * @return This builder for chaining. + */ + public Builder setReceiver(int index, String value) { + if (value == null) { + throw new NullPointerException(); + } + ensureReceiverIsMutable(); + receiver_.set(index, value); + onChanged(); + return this; + } + + /** + * repeated string receiver = 4; + * + * @param value The receiver to add. + * @return This builder for chaining. + */ + public Builder addReceiver(String value) { + if (value == null) { + throw new NullPointerException(); + } + ensureReceiverIsMutable(); + receiver_.add(value); + onChanged(); + return this; + } + + /** + * repeated string receiver = 4; + * + * @param values The receiver to add. + * @return This builder for chaining. + */ + public Builder addAllReceiver(Iterable values) { + ensureReceiverIsMutable(); + com.google.protobuf.AbstractMessageLite.Builder.addAll(values, receiver_); + onChanged(); + return this; + } + + /** + * repeated string receiver = 4; + * + * @return This builder for chaining. + */ + public Builder clearReceiver() { + receiver_ = com.google.protobuf.LazyStringArrayList.EMPTY; + bitField0_ = (bitField0_ & ~0x00000001); + onChanged(); + return this; + } + + /** + * repeated string receiver = 4; + * + * @param value The bytes of the receiver to add. + * @return This builder for chaining. + */ + public Builder addReceiverBytes(com.google.protobuf.ByteString value) { + if (value == null) { + throw new NullPointerException(); + } + checkByteStringIsUtf8(value); + ensureReceiverIsMutable(); + receiver_.add(value); + onChanged(); + return this; + } + + @Override + public final Builder setUnknownFields( + final com.google.protobuf.UnknownFieldSet unknownFields) { + return super.setUnknownFields(unknownFields); + } + + @Override + public final Builder mergeUnknownFields( + final com.google.protobuf.UnknownFieldSet unknownFields) { + return super.mergeUnknownFields(unknownFields); + } - // @@protoc_insertion_point(builder_scope:UnitMessage) + // @@protoc_insertion_point(builder_scope:UnitMessage) + } + + // @@protoc_insertion_point(class_scope:UnitMessage) + private static final UnitMessage DEFAULT_INSTANCE; + static { + DEFAULT_INSTANCE = new UnitMessage(); + } + + public static UnitMessage getDefaultInstance() { + return DEFAULT_INSTANCE; + } + + private static final com.google.protobuf.Parser PARSER = + new com.google.protobuf.AbstractParser() { + @Override + public UnitMessage parsePartialFrom(com.google.protobuf.CodedInputStream input, + com.google.protobuf.ExtensionRegistryLite extensionRegistry) + throws com.google.protobuf.InvalidProtocolBufferException { + return new UnitMessage(input, extensionRegistry); + } + }; + + public static com.google.protobuf.Parser parser() { + return PARSER; + } + + @Override + public com.google.protobuf.Parser getParserForType() { + return PARSER; + } + + @Override + public UnitMessage getDefaultInstanceForType() { + return DEFAULT_INSTANCE; + } + } - // @@protoc_insertion_point(class_scope:UnitMessage) - private static final UnitMessage DEFAULT_INSTANCE; + private static final com.google.protobuf.Descriptors.Descriptor internal_static_UnitMessage_descriptor; + private static final com.google.protobuf.GeneratedMessageV3.FieldAccessorTable internal_static_UnitMessage_fieldAccessorTable; + + public static com.google.protobuf.Descriptors.FileDescriptor getDescriptor() { + return descriptor; + } + + private static com.google.protobuf.Descriptors.FileDescriptor descriptor; static { - DEFAULT_INSTANCE = new UnitMessage(); + String[] descriptorData = {"\n\026BDLedgerContract.proto\"c\n\013UnitMessage\022" + + "!\n\007msgType\030\001 \001(\0162\020.UnitMessageType\022\016\n\006se" + + "nder\030\002 \001(\t\022\017\n\007content\030\003 \001(\014\022\020\n\010receiver\030" + + "\004 \003(\t*\216\001\n\017UnitMessageType\022\027\n\023UnitContrac" + + "tMessage\020\000\022\032\n\026UnitCommunicateMessage\020\001\022\023" + + "\n\017UnitUnitMessage\020\002\022\031\n\025UnitSequencingMes" + + "sage\020\003\022\026\n\022UnitRecoverMessage\020\0042U\n\027BDLedg" + + "erContractService\022:\n\026BDLedgerContractStr" + + "eam\022\014.UnitMessage\032\014.UnitMessage\"\000(\0010\001B%Z" + + "#bdware.org/bdledger/pkg/contract/pbb\006pr" + "oto3"}; + descriptor = com.google.protobuf.Descriptors.FileDescriptor.internalBuildGeneratedFileFrom( + descriptorData, new com.google.protobuf.Descriptors.FileDescriptor[] {}); + internal_static_UnitMessage_descriptor = getDescriptor().getMessageTypes().get(0); + internal_static_UnitMessage_fieldAccessorTable = + new com.google.protobuf.GeneratedMessageV3.FieldAccessorTable( + internal_static_UnitMessage_descriptor, + new String[] {"MsgType", "Sender", "Content", "Receiver",}); } - public static UnitMessage getDefaultInstance() { - return DEFAULT_INSTANCE; - } - - private static final com.google.protobuf.Parser - PARSER = new com.google.protobuf.AbstractParser() { - @Override - public UnitMessage parsePartialFrom( - com.google.protobuf.CodedInputStream input, - com.google.protobuf.ExtensionRegistryLite extensionRegistry) - throws com.google.protobuf.InvalidProtocolBufferException { - return new UnitMessage(input, extensionRegistry); - } - }; - - public static com.google.protobuf.Parser parser() { - return PARSER; - } - - @Override - public com.google.protobuf.Parser getParserForType() { - return PARSER; - } - - @Override - public UnitMessage getDefaultInstanceForType() { - return DEFAULT_INSTANCE; - } - - } - - private static final com.google.protobuf.Descriptors.Descriptor - internal_static_UnitMessage_descriptor; - private static final - com.google.protobuf.GeneratedMessageV3.FieldAccessorTable - internal_static_UnitMessage_fieldAccessorTable; - - public static com.google.protobuf.Descriptors.FileDescriptor - getDescriptor() { - return descriptor; - } - private static com.google.protobuf.Descriptors.FileDescriptor - descriptor; - static { - String[] descriptorData = { - "\n\026BDLedgerContract.proto\"c\n\013UnitMessage\022" + - "!\n\007msgType\030\001 \001(\0162\020.UnitMessageType\022\016\n\006se" + - "nder\030\002 \001(\t\022\017\n\007content\030\003 \001(\014\022\020\n\010receiver\030" + - "\004 \003(\t*\216\001\n\017UnitMessageType\022\027\n\023UnitContrac" + - "tMessage\020\000\022\032\n\026UnitCommunicateMessage\020\001\022\023" + - "\n\017UnitUnitMessage\020\002\022\031\n\025UnitSequencingMes" + - "sage\020\003\022\026\n\022UnitRecoverMessage\020\0042U\n\027BDLedg" + - "erContractService\022:\n\026BDLedgerContractStr" + - "eam\022\014.UnitMessage\032\014.UnitMessage\"\000(\0010\001B%Z" + - "#bdware.org/bdledger/pkg/contract/pbb\006pr" + - "oto3" - }; - descriptor = com.google.protobuf.Descriptors.FileDescriptor - .internalBuildGeneratedFileFrom(descriptorData, - new com.google.protobuf.Descriptors.FileDescriptor[] { - }); - internal_static_UnitMessage_descriptor = - getDescriptor().getMessageTypes().get(0); - internal_static_UnitMessage_fieldAccessorTable = new - com.google.protobuf.GeneratedMessageV3.FieldAccessorTable( - internal_static_UnitMessage_descriptor, - new String[] { "MsgType", "Sender", "Content", "Receiver", }); - } - - // @@protoc_insertion_point(outer_class_scope) + // @@protoc_insertion_point(outer_class_scope) } diff --git a/src/main/java/org/bdware/units/grpc/BDLedgerContractServiceGrpc.java b/src/main/java/org/bdware/units/grpc/BDLedgerContractServiceGrpc.java index 6819b40..24cb688 100644 --- a/src/main/java/org/bdware/units/grpc/BDLedgerContractServiceGrpc.java +++ b/src/main/java/org/bdware/units/grpc/BDLedgerContractServiceGrpc.java @@ -1,216 +1,207 @@ 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.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.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.asyncUnimplementedUnaryCall; import static io.grpc.stub.ServerCalls.asyncUnimplementedStreamingCall; /** */ -@javax.annotation.Generated( - value = "by gRPC proto compiler (version 1.4.1-SNAPSHOT)", - comments = "Source: BDLedgerContract.proto") +@javax.annotation.Generated(value = "by gRPC proto compiler (version 1.4.1-SNAPSHOT)", + comments = "Source: BDLedgerContract.proto") public final class BDLedgerContractServiceGrpc { - private BDLedgerContractServiceGrpc() {} + private BDLedgerContractServiceGrpc() {} - public static final String SERVICE_NAME = "BDLedgerContractService"; + public static final String SERVICE_NAME = "BDLedgerContractService"; - // Static method descriptors that strictly reflect the proto. - @io.grpc.ExperimentalApi("https://github.com/grpc/grpc-java/issues/1901") - public static final io.grpc.MethodDescriptor METHOD_BDLEDGER_CONTRACT_STREAM = - io.grpc.MethodDescriptor.newBuilder() - .setType(io.grpc.MethodDescriptor.MethodType.BIDI_STREAMING) - .setFullMethodName(generateFullMethodName( - "BDLedgerContractService", "BDLedgerContractStream")) - .setRequestMarshaller(io.grpc.protobuf.ProtoUtils.marshaller( - BDLedgerContract.UnitMessage.getDefaultInstance())) - .setResponseMarshaller(io.grpc.protobuf.ProtoUtils.marshaller( - BDLedgerContract.UnitMessage.getDefaultInstance())) - .build(); - - /** - * Creates a new async stub that supports all call types for the service - */ - public static BDLedgerContractServiceStub newStub(io.grpc.Channel channel) { - return new BDLedgerContractServiceStub(channel); - } - - /** - * Creates a new blocking-style stub that supports unary and streaming output calls on the service - */ - public static BDLedgerContractServiceBlockingStub newBlockingStub( - io.grpc.Channel channel) { - return new BDLedgerContractServiceBlockingStub(channel); - } - - /** - * Creates a new ListenableFuture-style stub that supports unary calls on the service - */ - public static BDLedgerContractServiceFutureStub newFutureStub( - io.grpc.Channel channel) { - return new BDLedgerContractServiceFutureStub(channel); - } - - /** - */ - public static abstract class BDLedgerContractServiceImplBase implements io.grpc.BindableService { + // Static method descriptors that strictly reflect the proto. + @io.grpc.ExperimentalApi("https://github.com/grpc/grpc-java/issues/1901") + public static final io.grpc.MethodDescriptor METHOD_BDLEDGER_CONTRACT_STREAM = + io.grpc.MethodDescriptor.newBuilder() + .setType(io.grpc.MethodDescriptor.MethodType.BIDI_STREAMING) + .setFullMethodName(generateFullMethodName("BDLedgerContractService", + "BDLedgerContractStream")) + .setRequestMarshaller(io.grpc.protobuf.ProtoUtils + .marshaller(BDLedgerContract.UnitMessage.getDefaultInstance())) + .setResponseMarshaller(io.grpc.protobuf.ProtoUtils + .marshaller(BDLedgerContract.UnitMessage.getDefaultInstance())) + .build(); /** + * Creates a new async stub that supports all call types for the service */ - public io.grpc.stub.StreamObserver bDLedgerContractStream( - io.grpc.stub.StreamObserver responseObserver) { - return asyncUnimplementedStreamingCall(METHOD_BDLEDGER_CONTRACT_STREAM, responseObserver); + public static BDLedgerContractServiceStub newStub(io.grpc.Channel channel) { + return new BDLedgerContractServiceStub(channel); } - @Override public final io.grpc.ServerServiceDefinition bindService() { - return io.grpc.ServerServiceDefinition.builder(getServiceDescriptor()) - .addMethod( - METHOD_BDLEDGER_CONTRACT_STREAM, - asyncBidiStreamingCall( - new MethodHandlers< - BDLedgerContract.UnitMessage, - BDLedgerContract.UnitMessage>( - this, METHODID_BDLEDGER_CONTRACT_STREAM))) - .build(); - } - } - - /** - */ - public static final class BDLedgerContractServiceStub extends io.grpc.stub.AbstractStub { - private BDLedgerContractServiceStub(io.grpc.Channel channel) { - super(channel); + /** + * Creates a new blocking-style stub that supports unary and streaming output calls on the + * service + */ + public static BDLedgerContractServiceBlockingStub newBlockingStub(io.grpc.Channel channel) { + return new BDLedgerContractServiceBlockingStub(channel); } - private BDLedgerContractServiceStub(io.grpc.Channel channel, - io.grpc.CallOptions callOptions) { - super(channel, callOptions); - } - - @Override - protected BDLedgerContractServiceStub build(io.grpc.Channel channel, - io.grpc.CallOptions callOptions) { - return new BDLedgerContractServiceStub(channel, callOptions); + /** + * Creates a new ListenableFuture-style stub that supports unary calls on the service + */ + public static BDLedgerContractServiceFutureStub newFutureStub(io.grpc.Channel channel) { + return new BDLedgerContractServiceFutureStub(channel); } /** */ - public io.grpc.stub.StreamObserver bDLedgerContractStream( - io.grpc.stub.StreamObserver responseObserver) { - return asyncBidiStreamingCall( - getChannel().newCall(METHOD_BDLEDGER_CONTRACT_STREAM, getCallOptions()), responseObserver); - } - } + public static abstract class BDLedgerContractServiceImplBase + implements io.grpc.BindableService { - /** - */ - public static final class BDLedgerContractServiceBlockingStub extends io.grpc.stub.AbstractStub { - private BDLedgerContractServiceBlockingStub(io.grpc.Channel channel) { - super(channel); - } - - private BDLedgerContractServiceBlockingStub(io.grpc.Channel channel, - io.grpc.CallOptions callOptions) { - super(channel, callOptions); - } - - @Override - protected BDLedgerContractServiceBlockingStub build(io.grpc.Channel channel, - io.grpc.CallOptions callOptions) { - return new BDLedgerContractServiceBlockingStub(channel, callOptions); - } - } - - /** - */ - public static final class BDLedgerContractServiceFutureStub extends io.grpc.stub.AbstractStub { - private BDLedgerContractServiceFutureStub(io.grpc.Channel channel) { - super(channel); - } - - private BDLedgerContractServiceFutureStub(io.grpc.Channel channel, - io.grpc.CallOptions callOptions) { - super(channel, callOptions); - } - - @Override - protected BDLedgerContractServiceFutureStub build(io.grpc.Channel channel, - io.grpc.CallOptions callOptions) { - return new BDLedgerContractServiceFutureStub(channel, callOptions); - } - } - - private static final int METHODID_BDLEDGER_CONTRACT_STREAM = 0; - - private static final class MethodHandlers implements - io.grpc.stub.ServerCalls.UnaryMethod, - io.grpc.stub.ServerCalls.ServerStreamingMethod, - io.grpc.stub.ServerCalls.ClientStreamingMethod, - io.grpc.stub.ServerCalls.BidiStreamingMethod { - private final BDLedgerContractServiceImplBase serviceImpl; - private final int methodId; - - MethodHandlers(BDLedgerContractServiceImplBase serviceImpl, int methodId) { - this.serviceImpl = serviceImpl; - this.methodId = methodId; - } - - @Override - @SuppressWarnings("unchecked") - public void invoke(Req request, io.grpc.stub.StreamObserver responseObserver) { - switch (methodId) { - default: - throw new AssertionError(); - } - } - - @Override - @SuppressWarnings("unchecked") - public io.grpc.stub.StreamObserver invoke( - io.grpc.stub.StreamObserver responseObserver) { - switch (methodId) { - case METHODID_BDLEDGER_CONTRACT_STREAM: - return (io.grpc.stub.StreamObserver) serviceImpl.bDLedgerContractStream( - (io.grpc.stub.StreamObserver) responseObserver); - default: - throw new AssertionError(); - } - } - } - - private static final class BDLedgerContractServiceDescriptorSupplier implements io.grpc.protobuf.ProtoFileDescriptorSupplier { - @Override - public com.google.protobuf.Descriptors.FileDescriptor getFileDescriptor() { - return BDLedgerContract.getDescriptor(); - } - } - - private static volatile io.grpc.ServiceDescriptor serviceDescriptor; - - public static io.grpc.ServiceDescriptor getServiceDescriptor() { - io.grpc.ServiceDescriptor result = serviceDescriptor; - if (result == null) { - synchronized (BDLedgerContractServiceGrpc.class) { - result = serviceDescriptor; - if (result == null) { - serviceDescriptor = result = io.grpc.ServiceDescriptor.newBuilder(SERVICE_NAME) - .setSchemaDescriptor(new BDLedgerContractServiceDescriptorSupplier()) - .addMethod(METHOD_BDLEDGER_CONTRACT_STREAM) - .build(); + /** + */ + public io.grpc.stub.StreamObserver bDLedgerContractStream( + io.grpc.stub.StreamObserver responseObserver) { + return asyncUnimplementedStreamingCall(METHOD_BDLEDGER_CONTRACT_STREAM, + responseObserver); + } + + @Override + public final io.grpc.ServerServiceDefinition bindService() { + return io.grpc.ServerServiceDefinition.builder(getServiceDescriptor()) + .addMethod(METHOD_BDLEDGER_CONTRACT_STREAM, asyncBidiStreamingCall( + new MethodHandlers( + this, METHODID_BDLEDGER_CONTRACT_STREAM))) + .build(); } - } } - return result; - } + + /** + */ + public static final class BDLedgerContractServiceStub + extends io.grpc.stub.AbstractStub { + private BDLedgerContractServiceStub(io.grpc.Channel channel) { + super(channel); + } + + private BDLedgerContractServiceStub(io.grpc.Channel channel, + io.grpc.CallOptions callOptions) { + super(channel, callOptions); + } + + @Override + protected BDLedgerContractServiceStub build(io.grpc.Channel channel, + io.grpc.CallOptions callOptions) { + return new BDLedgerContractServiceStub(channel, callOptions); + } + + /** + */ + public io.grpc.stub.StreamObserver bDLedgerContractStream( + io.grpc.stub.StreamObserver responseObserver) { + return asyncBidiStreamingCall( + getChannel().newCall(METHOD_BDLEDGER_CONTRACT_STREAM, getCallOptions()), + responseObserver); + } + } + + /** + */ + public static final class BDLedgerContractServiceBlockingStub + extends io.grpc.stub.AbstractStub { + private BDLedgerContractServiceBlockingStub(io.grpc.Channel channel) { + super(channel); + } + + private BDLedgerContractServiceBlockingStub(io.grpc.Channel channel, + io.grpc.CallOptions callOptions) { + super(channel, callOptions); + } + + @Override + protected BDLedgerContractServiceBlockingStub build(io.grpc.Channel channel, + io.grpc.CallOptions callOptions) { + return new BDLedgerContractServiceBlockingStub(channel, callOptions); + } + } + + /** + */ + public static final class BDLedgerContractServiceFutureStub + extends io.grpc.stub.AbstractStub { + private BDLedgerContractServiceFutureStub(io.grpc.Channel channel) { + super(channel); + } + + private BDLedgerContractServiceFutureStub(io.grpc.Channel channel, + io.grpc.CallOptions callOptions) { + super(channel, callOptions); + } + + @Override + protected BDLedgerContractServiceFutureStub build(io.grpc.Channel channel, + io.grpc.CallOptions callOptions) { + return new BDLedgerContractServiceFutureStub(channel, callOptions); + } + } + + private static final int METHODID_BDLEDGER_CONTRACT_STREAM = 0; + + private static final class MethodHandlers + implements io.grpc.stub.ServerCalls.UnaryMethod, + io.grpc.stub.ServerCalls.ServerStreamingMethod, + io.grpc.stub.ServerCalls.ClientStreamingMethod, + io.grpc.stub.ServerCalls.BidiStreamingMethod { + private final BDLedgerContractServiceImplBase serviceImpl; + private final int methodId; + + MethodHandlers(BDLedgerContractServiceImplBase serviceImpl, int methodId) { + this.serviceImpl = serviceImpl; + this.methodId = methodId; + } + + @Override + @SuppressWarnings("unchecked") + public void invoke(Req request, io.grpc.stub.StreamObserver responseObserver) { + switch (methodId) { + default: + throw new AssertionError(); + } + } + + @Override + @SuppressWarnings("unchecked") + public io.grpc.stub.StreamObserver invoke( + io.grpc.stub.StreamObserver responseObserver) { + switch (methodId) { + case METHODID_BDLEDGER_CONTRACT_STREAM: + return (io.grpc.stub.StreamObserver) serviceImpl.bDLedgerContractStream( + (io.grpc.stub.StreamObserver) responseObserver); + default: + throw new AssertionError(); + } + } + } + + private static final class BDLedgerContractServiceDescriptorSupplier + implements io.grpc.protobuf.ProtoFileDescriptorSupplier { + @Override + public com.google.protobuf.Descriptors.FileDescriptor getFileDescriptor() { + return BDLedgerContract.getDescriptor(); + } + } + + private static volatile io.grpc.ServiceDescriptor serviceDescriptor; + + public static io.grpc.ServiceDescriptor getServiceDescriptor() { + io.grpc.ServiceDescriptor result = serviceDescriptor; + if (result == null) { + synchronized (BDLedgerContractServiceGrpc.class) { + result = serviceDescriptor; + if (result == null) { + serviceDescriptor = result = io.grpc.ServiceDescriptor.newBuilder(SERVICE_NAME) + .setSchemaDescriptor(new BDLedgerContractServiceDescriptorSupplier()) + .addMethod(METHOD_BDLEDGER_CONTRACT_STREAM).build(); + } + } + } + return result; + } } diff --git a/src/main/java/org/bdware/units/grpc/JavaContractServiceGrpcServer.java b/src/main/java/org/bdware/units/grpc/JavaContractServiceGrpcServer.java index 359006a..4aca3af 100644 --- a/src/main/java/org/bdware/units/grpc/JavaContractServiceGrpcServer.java +++ b/src/main/java/org/bdware/units/grpc/JavaContractServiceGrpcServer.java @@ -76,15 +76,13 @@ public class JavaContractServiceGrpcServer { public void start() throws IOException { server.start(); logger.info("[JavaContractServiceGrpcServer] Server started, listening on " + port); - Runtime.getRuntime() - .addShutdownHook( - new Thread(() -> { - // Use stderr here since the logger may has been reset by its JVM - // shutdown hook. - System.err.println("*** shutting down gRPC server since JVM is shutting down"); - JavaContractServiceGrpcServer.this.stop(); - System.err.println("*** server shut down"); - })); + Runtime.getRuntime().addShutdownHook(new Thread(() -> { + // Use stderr here since the logger may has been reset by its JVM + // shutdown hook. + System.err.println("*** shutting down gRPC server since JVM is shutting down"); + JavaContractServiceGrpcServer.this.stop(); + System.err.println("*** server shut down"); + })); } /** @@ -94,9 +92,9 @@ public class JavaContractServiceGrpcServer { if (server != null) { server.shutdown(); } - // if (sendTask != null) { - // sendTask.shutdown(); - // } + // if (sendTask != null) { + // sendTask.shutdown(); + // } } /** @@ -111,7 +109,8 @@ public class JavaContractServiceGrpcServer { /** * Our implementation of RouteGuide service. * - *

See route_guide.proto for details of the methods. + *

+ * See route_guide.proto for details of the methods. */ private static class JavaContractService extends BDLedgerContractServiceGrpc.BDLedgerContractServiceImplBase { @@ -134,7 +133,7 @@ public class JavaContractServiceGrpcServer { javaServer = new StreamObserver() { @Override public void onNext(BDLedgerContract.UnitMessage msg) { -// System.out.println("P2P receive "+ msg.toString()); + // System.out.println("P2P receive "+ msg.toString()); UnitMessageHandler.instance.handle(msg); } diff --git a/src/main/java/org/bdware/units/msghandler/ResponseCenter.java b/src/main/java/org/bdware/units/msghandler/ResponseCenter.java index d494f38..aa23164 100644 --- a/src/main/java/org/bdware/units/msghandler/ResponseCenter.java +++ b/src/main/java/org/bdware/units/msghandler/ResponseCenter.java @@ -15,7 +15,7 @@ public class ResponseCenter { String requestID; Map successes; Map fails; - // Map peers; + // Map peers; Set peers; Map peers2PubKey; ResultCallback callback; @@ -23,16 +23,12 @@ public class ResponseCenter { UnitContractRequestType cuType; int size; boolean isSendReply; - // int type; + // int type; long start; private ResponseType responseType; - public ResponseCenter( - String requestID, - ResultCallback rc, - int num, - UnitContractRequestType cuType, - int type) { + public ResponseCenter(String requestID, ResultCallback rc, int num, + UnitContractRequestType cuType, int type) { this.requestID = requestID; this.callback = rc; this.isSendReply = false; @@ -45,16 +41,16 @@ public class ResponseCenter { this.successes = new HashMap<>(this.size); this.fails = new HashMap<>(this.size); this.peers = new HashSet<>(this.size); - // for(String peer : peers) { - // this.peers.add(peer); - // } + // for(String peer : peers) { + // this.peers.add(peer); + // } } public boolean updateReply(String content, String sender, String str) { - // if (!peers.contains(sender)) { - // return false; - // }\ - // TODO 读取pubkey校验结果 + // if (!peers.contains(sender)) { + // return false; + // }\ + // TODO 读取pubkey校验结果 switch (cuType) { case START: peers2PubKey.put(sender, str); @@ -72,8 +68,8 @@ public class ResponseCenter { fails.put(sender, result.result.toString()); } int num = count.addAndGet(1); - System.out.println( - "---: updateReply, size:" + num + "/" + size + " --sender:" + sender); + System.out + .println("---: updateReply, size:" + num + "/" + size + " --sender:" + sender); } switch (this.responseType) { case ALL: @@ -130,7 +126,8 @@ public class ResponseCenter { Map data = new HashMap<>(); if (successes.size() > 0) { 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 { // 结果不一致 data.put("status", "Exception"); } @@ -138,7 +135,7 @@ public class ResponseCenter { result.append(s).append(" / "); } data.put("result", result.toString()); - // ret.put("result", result); + // ret.put("result", result); ret.put("data", JsonUtil.toJson(data)); ret.put("responseID", this.requestID); ret.put("executeTime", System.currentTimeMillis() - start); diff --git a/src/main/java/org/bdware/units/msghandler/UnitMessageHandler.java b/src/main/java/org/bdware/units/msghandler/UnitMessageHandler.java index 4b47136..1994656 100644 --- a/src/main/java/org/bdware/units/msghandler/UnitMessageHandler.java +++ b/src/main/java/org/bdware/units/msghandler/UnitMessageHandler.java @@ -11,32 +11,34 @@ import org.bdware.units.grpc.BDLedgerContract.UnitMessage; /** * 接收UnitMessage, 执行相应处理,如合约启动,执行,定序等 + * * @author oliveds */ public class UnitMessageHandler { private static final Logger LOGGER = LogManager.getLogger(UnitMessageHandler.class); public static UnitMessageHandler instance = init(); - public UnitMessageHandler(){} + public UnitMessageHandler() {} public static UnitMessageHandler init() { - if(instance == null) { + if (instance == null) { instance = new UnitMessageHandler(); } return instance; } + public void handle(UnitMessage msg) { String content = msg.getContent().toStringUtf8(); String sender = msg.getSender(); -// LOGGER.debug("[UnitMessageHandler] receive " + msg.toString()); - handleInner(msg.getMsgType(),content,sender); + // LOGGER.debug("[UnitMessageHandler] receive " + msg.toString()); + handleInner(msg.getMsgType(), content, sender); } public void handleWithSender(UnitMessage msg, String sender) { String content = msg.getContent().toStringUtf8(); - sender = sender.replace("/",""); + sender = sender.replace("/", ""); 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) { @@ -51,13 +53,13 @@ public class UnitMessageHandler { ContractUnitManager.instance.handle(content, sender); break; case UnitRecoverMessage: -// RecoveryManager.instance.handle(content,sender); + // RecoveryManager.instance.handle(content,sender); break; case UnitSequencingMessage: - SequencingManager.instance.handle(content,sender); + SequencingManager.instance.handle(content, sender); break; default: -// CommunicationManager.instance.handle(content, sender); + // CommunicationManager.instance.handle(content, sender); } } } diff --git a/src/main/java/org/bdware/units/tcp/TCPClientFrameHandler.java b/src/main/java/org/bdware/units/tcp/TCPClientFrameHandler.java index 1fae25f..61d2a8b 100644 --- a/src/main/java/org/bdware/units/tcp/TCPClientFrameHandler.java +++ b/src/main/java/org/bdware/units/tcp/TCPClientFrameHandler.java @@ -25,11 +25,11 @@ public class TCPClientFrameHandler extends SimpleChannelInboundHandler ChannelHandlerContext ctx; private Channel channel; private String peer; -// HeartBeatProtocol heartBeat; + // HeartBeatProtocol heartBeat; public TCPClientFrameHandler(String peerId) { peer = peerId; -// heartBeat = new HeartBeatProtocol(peer); + // heartBeat = new HeartBeatProtocol(peer); for (String str : tcpPlugins) { Object obj = createInstanceByClzName(str); ae.appendHandler(obj); @@ -50,11 +50,10 @@ public class TCPClientFrameHandler extends SimpleChannelInboundHandler if (evt instanceof IdleStateEvent) { IdleStateEvent idleStateEvent = (IdleStateEvent) evt; if (idleStateEvent.state() == IdleState.WRITER_IDLE) { -// logger.info("[TCPClientFrameHandler] 5s msg"); - //向服务端发送消息 + // logger.info("[TCPClientFrameHandler] 5s msg"); + // 向服务端发送消息 UnitMessage unitMessage = UnitMessage.newBuilder() - .setMsgType(BDLedgerContract.UnitMessageType.UnitRecoverMessage) - .build(); + .setMsgType(BDLedgerContract.UnitMessageType.UnitRecoverMessage).build(); ByteBuf byteBuf = Unpooled.wrappedBuffer(unitMessage.toByteArray()); ctx.writeAndFlush(byteBuf).addListener(ChannelFutureListener.CLOSE_ON_FAILURE); } @@ -83,7 +82,7 @@ public class TCPClientFrameHandler extends SimpleChannelInboundHandler @Override protected void channelRead0(ChannelHandlerContext ctx, ByteBuf bb) { -// ByteBuf bb = (ByteBuf) frame; + // ByteBuf bb = (ByteBuf) frame; UnitMessage unitMessage; try { byte[] bytes = new byte[bb.readableBytes()]; @@ -101,14 +100,14 @@ public class TCPClientFrameHandler extends SimpleChannelInboundHandler ByteBuf byteBuf = Unpooled.wrappedBuffer(unitMessage.toByteArray()); ctx.writeAndFlush(byteBuf).addListener(ChannelFutureListener.CLOSE_ON_FAILURE); -// if (isOpen()) { -// // ByteArrayOutputStream bos = new ByteArrayOutputStream(); -//// unitMessage.writeTo(bos); -//// ctx.channel().writeAndFlush(bos); -//// bos.close(); -// ByteBuf buf = Unpooled.wrappedBuffer(unitMessage.toByteArray()); -// ctx.channel().writeAndFlush(buf); -// } + // if (isOpen()) { + // // ByteArrayOutputStream bos = new ByteArrayOutputStream(); + //// unitMessage.writeTo(bos); + //// ctx.channel().writeAndFlush(bos); + //// bos.close(); + // ByteBuf buf = Unpooled.wrappedBuffer(unitMessage.toByteArray()); + // ctx.channel().writeAndFlush(buf); + // } } public boolean isOpen() { diff --git a/src/main/java/org/bdware/units/tcp/TCPServerFrameHandler.java b/src/main/java/org/bdware/units/tcp/TCPServerFrameHandler.java index da7f937..87ec466 100644 --- a/src/main/java/org/bdware/units/tcp/TCPServerFrameHandler.java +++ b/src/main/java/org/bdware/units/tcp/TCPServerFrameHandler.java @@ -8,21 +8,18 @@ import org.bdware.units.grpc.BDLedgerContract.UnitMessage; import org.bdware.units.msghandler.UnitMessageHandler; /** - * 节点间TCP建立通信传输 - * 1. 复杂情况组网 - * 2. 自动选择网络方式 + * 节点间TCP建立通信传输 1. 复杂情况组网 2. 自动选择网络方式 */ public class TCPServerFrameHandler extends SimpleChannelInboundHandler { - // private static final Logger LOGGER = LogManager.getLogger(TCPServerFrameHandler.class); + // private static final Logger LOGGER = LogManager.getLogger(TCPServerFrameHandler.class); public ChannelHandlerContext ctx; - public TCPServerFrameHandler() { - } + public TCPServerFrameHandler() {} @Override protected void channelRead0(ChannelHandlerContext ctx, ByteBuf bb) { this.ctx = ctx; -// ByteBuf bb = (ByteBuf) frame; + // ByteBuf bb = (ByteBuf) frame; UnitMessage msg; try { byte[] bytes = new byte[bb.readableBytes()]; @@ -32,20 +29,20 @@ public class TCPServerFrameHandler extends SimpleChannelInboundHandler e.printStackTrace(); return; } -// ByteBuf bb = (ByteBuf) frame; -// byte[] bytes = new byte[bb.readableBytes()]; -// logger.info("TCP server receive:" +bytes.toString()); -// bb.readBytes(bytes); -// UnitMessage msg; -// try { -// msg = UnitMessage.parseFrom(bytes); -// logger.info("TCP receive:" + msg.toString()); -// -// } catch (IOException e) { -// logger.info("[TCPServerFrameHandler] bytes:" + new String(bytes)); -// e.printStackTrace(); -// return; -// } + // ByteBuf bb = (ByteBuf) frame; + // byte[] bytes = new byte[bb.readableBytes()]; + // logger.info("TCP server receive:" +bytes.toString()); + // bb.readBytes(bytes); + // UnitMessage msg; + // try { + // msg = UnitMessage.parseFrom(bytes); + // logger.info("TCP receive:" + msg.toString()); + // + // } catch (IOException e) { + // logger.info("[TCPServerFrameHandler] bytes:" + new String(bytes)); + // e.printStackTrace(); + // return; + // } try { UnitMessageHandler.instance.handleWithSender(msg, msg.getSender()); } catch (Exception e) { @@ -57,16 +54,16 @@ public class TCPServerFrameHandler extends SimpleChannelInboundHandler return ctx.channel().isOpen(); } -// public void sendMsg(UnitMessage unitMsg) { -// if (ctx != null) { -// try { -// ByteArrayOutputStream bos = new ByteArrayOutputStream(); -// unitMsg.writeTo(bos); -// ctx.channel().writeAndFlush(bos); -// bos.close(); -// } catch (IOException e) { -// e.printStackTrace(); -// } -// } -// } + // public void sendMsg(UnitMessage unitMsg) { + // if (ctx != null) { + // try { + // ByteArrayOutputStream bos = new ByteArrayOutputStream(); + // unitMsg.writeTo(bos); + // ctx.channel().writeAndFlush(bos); + // bos.close(); + // } catch (IOException e) { + // e.printStackTrace(); + // } + // } + // } } diff --git a/src/main/java/org/bdware/units/tcp/TCPUtils.java b/src/main/java/org/bdware/units/tcp/TCPUtils.java index a87aa56..e168558 100644 --- a/src/main/java/org/bdware/units/tcp/TCPUtils.java +++ b/src/main/java/org/bdware/units/tcp/TCPUtils.java @@ -1,14 +1,15 @@ package org.bdware.units.tcp; -import jdk.nashorn.internal.runtime.regexp.joni.Regex; import java.util.regex.Matcher; import java.util.regex.Pattern; 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); + public static boolean isTCPAddress(String address) { Matcher m = tcpAddressPattern.matcher(address); return m.find(); diff --git a/src/main/java/org/bdware/utils/FuncInvokeInfo.java b/src/main/java/org/bdware/utils/FuncInvokeInfo.java index d06f98d..edbd256 100644 --- a/src/main/java/org/bdware/utils/FuncInvokeInfo.java +++ b/src/main/java/org/bdware/utils/FuncInvokeInfo.java @@ -31,13 +31,15 @@ public class FuncInvokeInfo { // invokeInfo.clear(); invokeInfoList.clear(); } + // 以数组形式返回 public ArrayList getOneFunction(String ContractName, String FunctionName) { String Key = ContractName + "|" + FunctionName; // HashMapRet=invokeInfo.get(Key); LinkedList Ret = invokeInfoList.getValues(Key); - if (Ret == null) return null; + if (Ret == null) + return null; ArrayList ret = new ArrayList(); for (int i = 0; i < Ret.size(); i++) { ret.add(Ret.get(i)); @@ -51,30 +53,26 @@ public class FuncInvokeInfo { ; } - public void putOneInvoke( - String ContractName, String FunctionName, String ResponseID, JsonElement args, String res) { + public void putOneInvoke(String ContractName, String FunctionName, String ResponseID, + JsonElement args, String res) { String Key1 = ContractName + "|" + FunctionName; String Key2 = ResponseID; - JsonObject Record =new JsonObject(); - Record.add("args",args); - Record.addProperty("res",res); + JsonObject Record = new JsonObject(); + Record.add("args", args); + Record.addProperty("res", res); invokeInfoList.add(Key1, Record); // HashMapOldRecordInfo=new HashMap(); - /*OldRecordInfo=invokeInfo.get(Key1);//查看是否有这个合约的调用,有就追加,没有就新建 - if(OldRecordInfo==null){ - HashMaptemp=new HashMap(); - temp.put(Key2,Record); - invokeInfo.put(Key1,temp); - System.out.println(temp.size()); - } - else{ - OldRecordInfo.put(Key2,Record); - //System.out.println("aaa"+OldRecordInfo); - - - }*/ + /* + * OldRecordInfo=invokeInfo.get(Key1);//查看是否有这个合约的调用,有就追加,没有就新建 if(OldRecordInfo==null){ + * HashMaptemp=new HashMap(); temp.put(Key2,Record); + * invokeInfo.put(Key1,temp); System.out.println(temp.size()); } else{ + * OldRecordInfo.put(Key2,Record); //System.out.println("aaa"+OldRecordInfo); + * + * + * } + */ } } diff --git a/src/test/java/org/bdware/server/ByteTest.java b/src/test/java/org/bdware/server/ByteTest.java index e516a3d..5bd5e2c 100644 --- a/src/test/java/org/bdware/server/ByteTest.java +++ b/src/test/java/org/bdware/server/ByteTest.java @@ -10,7 +10,7 @@ public class ByteTest { @Test public void run() { String hexStr = "af28b0815f865cc04cd9828a9eff0d394da08fed"; - hexStr = "badf98195fb23838651ad581885489c3d750db6c"; + hexStr = "badf98195fb23838651ad581885489c3d750db6c"; String b64 = ByteUtil.encodeBASE64(ByteUtils.fromHexString(hexStr)); System.out.println(URLEncoder.encode(b64)); } diff --git a/src/test/java/org/bdware/server/ContractInfoDBTest.java b/src/test/java/org/bdware/server/ContractInfoDBTest.java index 1f68d03..98b9181 100644 --- a/src/test/java/org/bdware/server/ContractInfoDBTest.java +++ b/src/test/java/org/bdware/server/ContractInfoDBTest.java @@ -11,8 +11,7 @@ public class ContractInfoDBTest { String pre = "CONTRACT_INFO_META_"; KeyValueDBUtil.setupCM(); - KeyValueDBUtil.instance.visitDB( - CMTables.ContractInfo.toString(), + KeyValueDBUtil.instance.visitDB(CMTables.ContractInfo.toString(), new Jedion.JedionVisitor() { @Override public void visit(String key, String value) { diff --git a/src/test/java/org/bdware/server/DBTest.java b/src/test/java/org/bdware/server/DBTest.java index 4cd1d70..95542d6 100644 --- a/src/test/java/org/bdware/server/DBTest.java +++ b/src/test/java/org/bdware/server/DBTest.java @@ -10,9 +10,7 @@ public class DBTest { public static void main(String[] arg) { KeyValueDBUtil.setupCM(); System.out.println(new File("./BDWareProjectDir/").getAbsolutePath()); - KeyValueDBUtil.instance.setValue( - CMTables.ConfigDB.toString(), - "projectDir", + KeyValueDBUtil.instance.setValue(CMTables.ConfigDB.toString(), "projectDir", new File("./BDWareProjectDir/").getAbsolutePath()); } } diff --git a/src/test/java/org/bdware/server/DOIPOverHttpTest.java b/src/test/java/org/bdware/server/DOIPOverHttpTest.java index 2898677..d1247ab 100644 --- a/src/test/java/org/bdware/server/DOIPOverHttpTest.java +++ b/src/test/java/org/bdware/server/DOIPOverHttpTest.java @@ -17,9 +17,8 @@ public class DOIPOverHttpTest { @Test public void retrieveYPK() throws CryptoException { - SM2KeyPair key = - SM2KeyPair.fromJson( - "{\"privateKey\":\"c1c6ff60964c3e9d3ca5dd241d1af98a2f72013aee00d1f7330bd56afdf9c086\",\"publicKey\":\"04fce45a4e5aafed640c77d940a99bc2e5c8649280a975cd1302783d3e74bb219482d706aa08ec3777a2bc1a0d279daecf7256cd50f968423deaa524b6877ffbbf\"}"); + SM2KeyPair key = SM2KeyPair.fromJson( + "{\"privateKey\":\"c1c6ff60964c3e9d3ca5dd241d1af98a2f72013aee00d1f7330bd56afdf9c086\",\"publicKey\":\"04fce45a4e5aafed640c77d940a99bc2e5c8649280a975cd1302783d3e74bb219482d706aa08ec3777a2bc1a0d279daecf7256cd50f968423deaa524b6877ffbbf\"}"); String path = "/DOIP/TrustedStorage/ypk?pubKey=" + key.getPublicKeyStr(); String sign = ByteUtils.toHexString(SM2Util.sign(key.getPrivateKeyParameter(), path.getBytes())); @@ -31,21 +30,18 @@ public class DOIPOverHttpTest { @Test public void selfDefinedDOOp() throws CryptoException { - SM2KeyPair key = - SM2KeyPair.fromJson( - "{\"privateKey\":\"589d94ee5688358a1c5c18430dd9c75097ddddebf769f139da36a807911d20f8\",\"publicKey\":\"04d1924329f72ced148f6f333fb985ccbaa31b1e3aacf10be5f43d4a4ff5ad88899a005e79e37fc06993e1d66ada8cf8b711cb36f59538bb7d3e39e70fa9360ddd\"}"); + SM2KeyPair key = SM2KeyPair.fromJson( + "{\"privateKey\":\"589d94ee5688358a1c5c18430dd9c75097ddddebf769f139da36a807911d20f8\",\"publicKey\":\"04d1924329f72ced148f6f333fb985ccbaa31b1e3aacf10be5f43d4a4ff5ad88899a005e79e37fc06993e1d66ada8cf8b711cb36f59538bb7d3e39e70fa9360ddd\"}"); String contractID = "AnnotationExample"; String operation = "getDocument"; String arg = ""; String toSign = String.format("%s|%s|%s|%s", contractID, operation, arg, key.getPublicKeyStr()); - String sign = - ByteUtils.toHexString( - SM2Util.sign(key.getPrivateKeyParameter(), toSign.getBytes())); - String url = - String.format( - "http://127.0.0.1:18000/DOIP/%s?operation=%s&arg=%s&pubkey=%s&signature=%s", - contractID, operation, arg, key.getPublicKeyStr(), sign); + String sign = ByteUtils + .toHexString(SM2Util.sign(key.getPrivateKeyParameter(), toSign.getBytes())); + String url = String.format( + "http://127.0.0.1:18000/DOIP/%s?operation=%s&arg=%s&pubkey=%s&signature=%s", + contractID, operation, arg, key.getPublicKeyStr(), sign); System.out.println(new Gson().toJson(HttpUtil.httpGet(url))); // http://127.0.0.1:18000/DOIP/AnnotationExample?operation=getDoccument&arg=&pubkey=04d1924329f72ced148f6f333fb985ccbaa31b1e3aacf10be5f43d4a4ff5ad88899a005e79e37fc06993e1d66ada8cf8b711cb36f59538bb7d3e39e70fa9360ddd&signature=3046022100a460bf43fc61c9e01f99ba55364e066e65be3dfbe9d7bb181cb65b6eee51a696022100ec4f509097053069deebc8525d1c7f8c297c278291291688a3ebfba94e715de7 // 签名规则一样contractID|operation|arg|pubkey diff --git a/src/test/java/org/bdware/server/DoipClientTest.java b/src/test/java/org/bdware/server/DoipClientTest.java index 16dc4df..69225b1 100644 --- a/src/test/java/org/bdware/server/DoipClientTest.java +++ b/src/test/java/org/bdware/server/DoipClientTest.java @@ -31,7 +31,8 @@ public class DoipClientTest { LOGGER.info(msg); } }); - for (; i.get() == 0; ) Thread.yield(); + for (; i.get() == 0;) + Thread.yield(); } } diff --git a/src/test/java/org/bdware/server/GRPCPoolTest.java b/src/test/java/org/bdware/server/GRPCPoolTest.java index 6eb3b74..3fcffac 100644 --- a/src/test/java/org/bdware/server/GRPCPoolTest.java +++ b/src/test/java/org/bdware/server/GRPCPoolTest.java @@ -10,11 +10,11 @@ public class GRPCPoolTest { @Test public void createLedger() throws InterruptedException { - // 091:119.23.207.45:18091 47.107.94.135:18091 120.79.215.187:18091 - // 092: - // 093: -// String from = "0xadfadfadfa"; -// String to = "0x3dafdsaf"; + // 091:119.23.207.45:18091 47.107.94.135:18091 120.79.215.187:18091 + // 092: + // 093: + // String from = "0xadfadfadfa"; + // String to = "0x3dafdsaf"; GRPCPool.loadConf("119.23.207.45:18091"); Client client = GRPCPool.grpcClients.get(0); @@ -28,13 +28,10 @@ public class GRPCPoolTest { QueryProto.GetTransactionByHashResponse trans = client.getTransactionByHashSync("test", "4eb1827bf18c96fd60d6fc787103639e14497885"); System.out.println(trans.getTransaction().getData().toStringUtf8()); - GRPCPool.instance.writeToChain( - (reqID, hashStr) -> { - System.out.println("[OnHashCallback] " + hashStr); - flag.notify(); - }, - GRPCPool.mockedFrom, - GRPCPool.mockedTo, + GRPCPool.instance.writeToChain((reqID, hashStr) -> { + System.out.println("[OnHashCallback] " + hashStr); + flag.notify(); + }, GRPCPool.mockedFrom, GRPCPool.mockedTo, "HeiHei dfadsfdfadf" + System.currentTimeMillis(), System.currentTimeMillis() + "__T", "test"); synchronized (flag) { diff --git a/src/test/java/org/bdware/server/MonitorTest.java b/src/test/java/org/bdware/server/MonitorTest.java index c267f65..19a16d6 100644 --- a/src/test/java/org/bdware/server/MonitorTest.java +++ b/src/test/java/org/bdware/server/MonitorTest.java @@ -73,7 +73,8 @@ public class MonitorTest { sc2.close(); 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 tmp = new HashMap<>(); tmp.put("pid", pid); @@ -101,7 +102,7 @@ public class MonitorTest { } } catch (IOException e) { e.printStackTrace(); - } // 表示只执行一次就自动退出, + } // 表示只执行一次就自动退出, } @Test @@ -116,7 +117,7 @@ public class MonitorTest { LineNumberReader input = new LineNumberReader(ir); String line; while ((line = input.readLine()) != null) { - //System.out.println(line); + // System.out.println(line); if (line.contains("%Cpu(s):")) { Scanner sc2 = new Scanner(new ByteArrayInputStream(line.getBytes())); if (sc2.hasNext()) { @@ -140,7 +141,8 @@ public class MonitorTest { if (sc2.hasNext()) { sc2.next(); } - if (sc2.hasNextFloat()) freeCPU = sc2.nextFloat() + "%"; + if (sc2.hasNextFloat()) + freeCPU = sc2.nextFloat() + "%"; sc2.close(); } else if (line.contains("MiB Mem :")) { Scanner sc2 = new Scanner(new ByteArrayInputStream(line.getBytes())); @@ -180,4 +182,4 @@ public class MonitorTest { e.printStackTrace(); } } -} \ No newline at end of file +} diff --git a/src/test/java/org/bdware/server/NCTCPConnectTest.java b/src/test/java/org/bdware/server/NCTCPConnectTest.java index 25c18bb..3ae32e8 100644 --- a/src/test/java/org/bdware/server/NCTCPConnectTest.java +++ b/src/test/java/org/bdware/server/NCTCPConnectTest.java @@ -19,37 +19,35 @@ public class NCTCPConnectTest { b.option(ChannelOption.CONNECT_TIMEOUT_MILLIS, 5000); EventLoopGroup group = new NioEventLoopGroup(); b.group(group); - b.channel(NioSocketChannel.class) - .handler( - new ChannelInitializer() { - @Override - protected void initChannel(SocketChannel ch) { - ChannelPipeline p = ch.pipeline(); - p.addLast(new DelimiterCodec()).addLast(new SimpleChannelInboundHandler() { - @Override - protected void channelRead0(ChannelHandlerContext ctx, ByteBuf msg) { + b.channel(NioSocketChannel.class).handler(new ChannelInitializer() { + @Override + protected void initChannel(SocketChannel ch) { + ChannelPipeline p = ch.pipeline(); + p.addLast(new DelimiterCodec()).addLast(new SimpleChannelInboundHandler() { + @Override + protected void channelRead0(ChannelHandlerContext ctx, ByteBuf msg) { - System.out.println(msg.toString()); - } + System.out.println(msg.toString()); + } - @Override - public void channelActive(ChannelHandlerContext ctx) { + @Override + public void channelActive(ChannelHandlerContext ctx) { - Map getSession = new HashMap<>(); - getSession.put("action", "getSessionID"); - // setNodeID.put("cimanager", keyPair.getPublicKeyStr()); - // setNodeID.put("nodeManager", value); - System.out.println("Send getSessionID"); + Map getSession = new HashMap<>(); + getSession.put("action", "getSessionID"); + // setNodeID.put("cimanager", keyPair.getPublicKeyStr()); + // setNodeID.put("nodeManager", value); + System.out.println("Send getSessionID"); - ctx.channel().writeAndFlush("1123123123121231".getBytes()).addListener( - future -> { - System.out.println(future.isSuccess()); - future.cause().printStackTrace(); - }); - } + ctx.channel().writeAndFlush("1123123123121231".getBytes()) + .addListener(future -> { + System.out.println(future.isSuccess()); + future.cause().printStackTrace(); }); - } - }); + } + }); + } + }); try { b.connect("127.0.0.1", 13344).sync().channel(); } catch (InterruptedException e) { diff --git a/src/test/java/org/bdware/server/PermissionHelper.java b/src/test/java/org/bdware/server/PermissionHelper.java index be65173..9298498 100644 --- a/src/test/java/org/bdware/server/PermissionHelper.java +++ b/src/test/java/org/bdware/server/PermissionHelper.java @@ -19,8 +19,7 @@ import java.util.*; public class PermissionHelper { @Before - public void init() { - } + public void init() {} @Test public void compareClientAndServer() { @@ -41,8 +40,7 @@ public class PermissionHelper { } - private List parseWithClzName( - Map> handlers) { + private List parseWithClzName(Map> handlers) { List lines = new ArrayList<>(); for (String str : handlers.keySet()) { Method m = handlers.get(str).first(); @@ -96,8 +94,8 @@ public class PermissionHelper { parse(handler.ae.getHandlers(), false); } - private void parse( - Map> handlers, boolean checkHttpAccess) { + private void parse(Map> handlers, + boolean checkHttpAccess) { List lines = new ArrayList<>(); EnumSet set = EnumSet.allOf(Role.class); set.remove(Role.CenterManager); @@ -107,7 +105,8 @@ public class PermissionHelper { Action a = m.getAnnotation(Action.class); if (checkHttpAccess) { - if (!a.httpAccess()) continue; + if (!a.httpAccess()) + continue; } Line l = new Line(); lines.add(l); @@ -121,7 +120,8 @@ public class PermissionHelper { } l.roles = ""; 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( "NodeManager;ContractProvider;ContractInstanceManager;ContractUser;Anonymous;")) l.roles = "任意角色"; diff --git a/src/test/java/org/bdware/server/RequestIDTest.java b/src/test/java/org/bdware/server/RequestIDTest.java index 0c7f533..a848677 100644 --- a/src/test/java/org/bdware/server/RequestIDTest.java +++ b/src/test/java/org/bdware/server/RequestIDTest.java @@ -9,4 +9,4 @@ public class RequestIDTest { reqID = reqID.replaceFirst("[^_]*_", "").replaceAll("_.*$", ""); System.out.println(reqID); } -} \ No newline at end of file +} diff --git a/src/test/java/org/bdware/server/SocketGetTest.java b/src/test/java/org/bdware/server/SocketGetTest.java index 008475b..19ed1f6 100644 --- a/src/test/java/org/bdware/server/SocketGetTest.java +++ b/src/test/java/org/bdware/server/SocketGetTest.java @@ -25,17 +25,15 @@ public class SocketGetTest { @Before public void init() { get = new SocketGet("127.0.0.1", 1615); - // get = new SocketGet("127.0.0.1", 1618); - // get = new SocketGet("39.106.6.6", 1616); + // get = new SocketGet("127.0.0.1", 1618); + // get = new SocketGet("39.106.6.6", 1616); } @Test public void setLogStage() { try { - URL url = - new URL( - "http://127.0.0.1:18000/SCIDE/SCManager?action=setLogStage&logStage=" - + logStage); + URL url = new URL("http://127.0.0.1:18000/SCIDE/SCManager?action=setLogStage&logStage=" + + logStage); HttpURLConnection connection = (HttpURLConnection) url.openConnection(); InputStream input = connection.getInputStream(); Scanner sc = new Scanner(input); @@ -58,7 +56,8 @@ public class SocketGetTest { cr.setContractID("ContractExecutor"); cr.setAction("executeWithoutSig"); 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) { Thread.yield(); } @@ -74,7 +73,8 @@ public class SocketGetTest { cr.setContractID("Hello"); cr.setAction("hello"); 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) { Thread.yield(); } @@ -104,10 +104,10 @@ public class SocketGetTest { @Override public void onResult(String str) { count.incrementAndGet(); - // if (count.get() < 10) - // System.out.println(str); + // if (count.get() < 10) + // System.out.println(str); // if (count.get() > reqCount * 0.999) - // logger.info((">900 " + (System.currentTimeMillis() - start))); + // logger.info((">900 " + (System.currentTimeMillis() - start))); } } } diff --git a/src/test/java/org/bdware/server/doip/BCOManagerTest.java b/src/test/java/org/bdware/server/doip/BCOManagerTest.java index 44c284b..8a51c35 100644 --- a/src/test/java/org/bdware/server/doip/BCOManagerTest.java +++ b/src/test/java/org/bdware/server/doip/BCOManagerTest.java @@ -22,10 +22,11 @@ public class BCOManagerTest { AuditIrpClient client = new AuditIrpClient(config); SM2KeyPair key = SM2Util.generateSM2KeyPair(); - // config.privateKey = key.getPrivateKeyStr(); + // config.privateKey = key.getPrivateKeyStr(); // 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 diff --git a/src/test/java/org/bdware/server/setMaskTest.java b/src/test/java/org/bdware/server/setMaskTest.java index 54749ad..61acf73 100644 --- a/src/test/java/org/bdware/server/setMaskTest.java +++ b/src/test/java/org/bdware/server/setMaskTest.java @@ -5,85 +5,68 @@ import com.google.gson.JsonParser; import org.bdware.sc.http.HttpUtil; 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.util.ArrayList; -import java.util.HashMap; -import java.util.List; -import java.util.Map; + public class setMaskTest { @Test - public void test1(){ - /*String baseUrl = "http://127.0.0.1:21030/SCIDE/CMManager?"; - StringBuilder url = new StringBuilder(baseUrl + "action=setMask"); - HashMap param = new HashMap<>(); - HashMap pa=new HashMap(); - String contractName = "Hello"; - - param.put("contractName", "Hello"); - param.put("defaultAccept", "true"); - param.put("clientSecret", "abcdefg"); - 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)); - } - */ - String url="http://127.0.0.1:21030/SCIDE/CMManager?action=setMask"; - String contractID="AAA12BMySQL"; - JsonElement maskInfo= JsonParser.parseString("{\n" + - " \"name\": \"dx_md5\",\n" + - " \"parameter\":\n" + - " {\n" + - " \"columnIndex\":1,\n" + - " \"paras\":[\"\"]\n" + - " }\n" + - " }"); - String pubkey="04c111cde30c257eb9d891653e2a25eb15df5239dd9882389e8daeffd4b16f65f30b30688b58d3e2eaf25ce5a529a601e4924581b55cedf78d94d17864b73c51a7"; + public void test1() { + /* + * String baseUrl = "http://127.0.0.1:21030/SCIDE/CMManager?"; StringBuilder url = new + * StringBuilder(baseUrl + "action=setMask"); HashMap param = new + * HashMap<>(); HashMap pa=new HashMap(); String contractName + * = "Hello"; + * + * param.put("contractName", "Hello"); param.put("defaultAccept", "true"); + * param.put("clientSecret", "abcdefg"); 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)); } + */ + String url = "http://127.0.0.1:21030/SCIDE/CMManager?action=setMask"; + String contractID = "AAA12BMySQL"; + JsonElement maskInfo = + JsonParser.parseString("{\n" + " \"name\": \"dx_md5\",\n" + + " \"parameter\":\n" + " {\n" + + " \"columnIndex\":1,\n" + + " \"paras\":[\"\"]\n" + " }\n" + + " }"); + String pubkey = + "04c111cde30c257eb9d891653e2a25eb15df5239dd9882389e8daeffd4b16f65f30b30688b58d3e2eaf25ce5a529a601e4924581b55cedf78d94d17864b73c51a7"; System.out.println(url); - String sign="30440220138c8ae1956f6af19ddb24b9a0fe5cf9cc4f8ecd25537a8b5c4dcd5f30a4f985022026475279687ccdfb112cbcc307e573333d80f45386281def4df54b8b7532ed79"; - url+="&contractID="+contractID+"&maskInfo="+maskInfo+"&pubkey="+pubkey+"&signature="+sign; + String 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=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&&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=setMask" + "&contractID=" + contractID + + "&maskInfo=" + maskInfo; System.out.println(url); String resp = HttpUtil.httpGet(url.toString()).get("response").toString(); System.out.println(resp); } + @Test - public void testgetMask(){ - /*String baseUrl = "http://127.0.0.1:21030/SCIDE/CMManager?"; - StringBuilder url = new StringBuilder(baseUrl + "action=setMask"); - HashMap param = new HashMap<>(); - HashMap pa=new HashMap(); - String contractName = "Hello"; - - param.put("contractName", "Hello"); - param.put("defaultAccept", "true"); - param.put("clientSecret", "abcdefg"); - 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)); - } - */ - String contractID="AAA12BMySQL"; - String url="http://127.0.0.1:21030/SCIDE/CMManager?action=getMask"+"&contractID="+contractID+"&requestID=1"; + public void testgetMask() { + /* + * String baseUrl = "http://127.0.0.1:21030/SCIDE/CMManager?"; StringBuilder url = new + * StringBuilder(baseUrl + "action=setMask"); HashMap param = new + * HashMap<>(); HashMap pa=new HashMap(); String contractName + * = "Hello"; + * + * param.put("contractName", "Hello"); param.put("defaultAccept", "true"); + * param.put("clientSecret", "abcdefg"); 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)); } + */ + String contractID = "AAA12BMySQL"; + String url = "http://127.0.0.1:21030/SCIDE/CMManager?action=getMask" + "&contractID=" + + contractID + "&requestID=1"; System.out.println(url); String resp = HttpUtil.httpGet(url.toString()).get("response").toString(); diff --git a/src/test/java/org/bdware/server/template/MySQLTemplateTest.java b/src/test/java/org/bdware/server/template/MySQLTemplateTest.java index 17d3e58..1265396 100644 --- a/src/test/java/org/bdware/server/template/MySQLTemplateTest.java +++ b/src/test/java/org/bdware/server/template/MySQLTemplateTest.java @@ -15,8 +15,8 @@ public class MySQLTemplateTest { @Test public void testManifest() { VelocityEngine engine = new VelocityEngine(); - engine.setProperty( - "file.resource.loader.path", new File("./ContractTemplate/").getAbsolutePath()); + engine.setProperty("file.resource.loader.path", + new File("./ContractTemplate/").getAbsolutePath()); VelocityContext ctx = new VelocityContext(); ctx.put("ContractName", "ABCC"); Template script = engine.getTemplate("MySQLTemplate/manifest.vm"); @@ -28,8 +28,7 @@ public class MySQLTemplateTest { @Test public void testMySQLConf() { Map str = new HashMap<>(); - str.put( - "MySQLUrl", + str.put("MySQLUrl", "jdbc:mysql://127.0.0.1:3306/EcoData?useUnicode=yes&characterEncoding=UTF-8"); str.put("MySQLName", "root"); str.put("MySQLPWD", "12qwas"); @@ -39,8 +38,8 @@ public class MySQLTemplateTest { @Test public void testOneTableAllField() { VelocityEngine engine = new VelocityEngine(); - engine.setProperty( - "file.resource.loader.path", new File("./ContractTemplate/").getAbsolutePath()); + engine.setProperty("file.resource.loader.path", + new File("./ContractTemplate/").getAbsolutePath()); VelocityContext ctx = new VelocityContext(); ctx.put("ContractName", "ABCC");