Compare commits

..

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

44 changed files with 2904 additions and 2050 deletions

View File

@ -3,8 +3,6 @@ plugins {
id 'application' id 'application'
} }
apply from: '../spotless.gradle'
mainClassName = 'org.bdware.server.NodeCenterServer' mainClassName = 'org.bdware.server.NodeCenterServer'
application { application {
@ -60,7 +58,6 @@ task copyScript(type: Copy) {
include 'ncstop.sh' include 'ncstop.sh'
include 'ncconfig.json.template' include 'ncconfig.json.template'
include 'updateCluster.sh' include 'updateCluster.sh'
include 'log4j2.properties'
} }
into "./build/output" into "./build/output"
println("copyScript done !") println("copyScript done !")
@ -104,7 +101,7 @@ task copyWebContent(type: Copy) {
task buildBDServerClusterZip(type: Zip, dependsOn: ["copyWebContent", "copyScript", "copyJar"]) { task buildBDServerClusterZip(type: Zip, dependsOn: ["copyWebContent", "copyScript", "copyJar"]) {
from './build/output/' from './build/output/'
duplicatesStrategy = DuplicatesStrategy.INCLUDE duplicatesStrategy = DuplicatesStrategy.INCLUDE
archiveFileName = 'bdcluster-all.zip' archiveFileName = 'bdserver-cluster.zip'
destinationDirectory = file('build/') destinationDirectory = file('build/')
} }

View File

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

View File

@ -20,7 +20,7 @@ fi
# ps -ef | grep java | grep bdcluster | grep NodeCenterServer | awk '{print $2}' |xargs kill -9 # ps -ef | grep java | grep bdcluster | grep NodeCenterServer | awk '{print $2}' |xargs kill -9
#-Dlog4j.configuration=file: #-Dlog4j.configuration=file:
java -Dfile.encoding=UTF-8 -Dlog4j.configurationFile=./log4j2.properties -cp "./libs/*:bdcluster.jar" org.bdware.server.NodeCenterServer 1 >./log/nc.log 2>./log/nc.err & java -Dfile.encoding=UTF-8 -Dlog4j.configuration=file:./log4j.properties -cp "./libs/*:bdcluster.jar" org.bdware.server.NodeCenterServer 1 >./log/nc.log 2>./log/nc.err &
#以下可启用https/wss其中./ssl/xxx.pfx为ssl证书的路径:后面的123456是密码。 #以下可启用https/wss其中./ssl/xxx.pfx为ssl证书的路径:后面的123456是密码。
#java -Dfile.encoding=UTF-8 -cp "./libs/*:bdcluster.jar" org.bdware.server.NodeCenterServer -service-port=18002 -enable-ssl=./ssl/xxx.pfx:123456 -do-repo-ip=127.0.0.1 -do-repo-port=18098 1 > ./log/cm.log 2> ./log/cm.err & #java -Dfile.encoding=UTF-8 -cp "./libs/*:bdcluster.jar" org.bdware.server.NodeCenterServer -service-port=18002 -enable-ssl=./ssl/xxx.pfx:123456 -do-repo-ip=127.0.0.1 -do-repo-port=18098 1 > ./log/cm.log 2> ./log/cm.err &

View File

@ -2,84 +2,85 @@ package org.bdware.sc.udp;
import java.io.ByteArrayInputStream; import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream; import java.io.ByteArrayOutputStream;
import java.io.ObjectInputStream; import java.io.ObjectInputStream;
import java.io.ObjectOutputStream; import java.io.ObjectOutputStream;
import java.io.Serializable; import java.io.Serializable;
import java.util.ArrayList; import java.util.ArrayList;
import java.util.List; import java.util.List;
public class UDPMessage implements Serializable { public class UDPMessage implements Serializable {
private static final long serialVersionUID = -8103830946473687985L; private static final long serialVersionUID = -8103830946473687985L;
int isPart = 0; int isPart = 0;
public UDPMessageType type; public UDPMessageType type;
public int id; // 要标记sender public int id; // 要标记sender
int order; int order;
int requestID; int requestID;
byte[] content; byte[] content;
public UDPMessage() {} public UDPMessage() {
}
public void setIsPart(boolean isPart) { public void setIsPart(boolean isPart) {
this.isPart = isPart ? 1 : 0; this.isPart = isPart ? 1 : 0;
} }
public void setContent(byte[] content) { public void setContent(byte[] content) {
this.content = content; this.content = content;
} }
public byte[] getContent() { public byte[] getContent() {
return content; return content;
} }
static int Len = 6000;// 1000 static int Len = 6000;// 1000
public List<UDPMessage> split() { public List<UDPMessage> split() {
List<UDPMessage> splited = new ArrayList<>(); List<UDPMessage> splited = new ArrayList<>();
// System.out.println("[UDPMessage split] content.length" + content.length); // System.out.println("[UDPMessage split] content.length" + content.length);
if (content.length < Len) { if (content.length < Len) {
splited.add(this); splited.add(this);
return splited; return splited;
} }
for (int i = 0; i < content.length; i += Len) { for (int i = 0; i < content.length; i += Len) {
UDPMessage msg = new UDPMessage(); UDPMessage msg = new UDPMessage();
msg.isPart = 1; msg.isPart = 1;
msg.id = this.id; msg.id = this.id;
msg.order = i / Len; msg.order = i / Len;
if (i + Len > content.length) { if (i + Len > content.length) {
msg.content = new byte[content.length - i]; msg.content = new byte[content.length - i];
System.arraycopy(content, i, msg.content, 0, content.length - i); System.arraycopy(content, i, msg.content, 0, content.length - i);
} else { } else {
msg.content = new byte[Len]; msg.content = new byte[Len];
System.arraycopy(content, i, msg.content, 0, Len); System.arraycopy(content, i, msg.content, 0, Len);
} }
splited.add(msg); splited.add(msg);
} }
return splited; return splited;
} }
public byte[] toByteArray() { public byte[] toByteArray() {
try { try {
ByteArrayOutputStream bo = new ByteArrayOutputStream(); ByteArrayOutputStream bo = new ByteArrayOutputStream();
ObjectOutputStream output; ObjectOutputStream output;
output = new ObjectOutputStream(bo); output = new ObjectOutputStream(bo);
output.writeObject(this); output.writeObject(this);
return bo.toByteArray(); return bo.toByteArray();
} catch (Exception e) { } catch (Exception e) {
e.printStackTrace(); e.printStackTrace();
} }
return null; return null;
} }
public static UDPMessage parse(byte[] data, int len) { public static UDPMessage parse(byte[] data, int len) {
try { try {
ByteArrayInputStream bi = new ByteArrayInputStream(data); ByteArrayInputStream bi = new ByteArrayInputStream(data);
ObjectInputStream input = new ObjectInputStream(bi); ObjectInputStream input = new ObjectInputStream(bi);
return (UDPMessage) input.readObject(); return (UDPMessage) input.readObject();
} catch (Exception e) { } catch (Exception e) {
e.printStackTrace(); e.printStackTrace();
} }
return null; return null;
} }
} }

View File

@ -3,5 +3,5 @@ package org.bdware.sc.udp;
import java.io.Serializable; import java.io.Serializable;
public enum UDPMessageType implements Serializable { public enum UDPMessageType implements Serializable {
shakeHand, request, reply shakeHand, request, reply
} }

View File

@ -5,16 +5,16 @@ import java.net.SocketAddress;
import org.bdware.sc.conn.Node; import org.bdware.sc.conn.Node;
public class UDPNode extends Node { public class UDPNode extends Node {
public UDPNode(SocketAddress addr) { public UDPNode(SocketAddress addr) {
this.addr = addr; this.addr = addr;
} }
public int id; public int id;
public long lastUpdatedTime; public long lastUpdatedTime;
public SocketAddress addr; public SocketAddress addr;
public String getAddr() { public String getAddr() {
InetSocketAddress inet4 = (InetSocketAddress) addr; InetSocketAddress inet4 = (InetSocketAddress) addr;
return inet4.getHostString() + ":" + inet4.getPort(); return inet4.getHostString() + ":" + inet4.getPort();
} }
} }

View File

@ -21,21 +21,18 @@ import org.apache.logging.log4j.Level;
import org.apache.logging.log4j.LogManager; import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger; import org.apache.logging.log4j.Logger;
import org.apache.logging.log4j.core.config.Configurator; import org.apache.logging.log4j.core.config.Configurator;
import org.bdware.sc.DoConfig;
import org.bdware.sc.db.KeyValueDBUtil; import org.bdware.sc.db.KeyValueDBUtil;
import org.bdware.sc.db.MultiIndexTimeRocksDBUtil; import org.bdware.sc.db.MultiIndexTimeRocksDBUtil;
import org.bdware.sc.db.TimeDBUtil; import org.bdware.sc.db.TimeDBUtil;
import org.bdware.server.irp.LocalLHSProxy;
import org.bdware.server.nodecenter.*; import org.bdware.server.nodecenter.*;
import org.bdware.server.permission.Role;
import org.bdware.server.ws.DelimiterCodec; import org.bdware.server.ws.DelimiterCodec;
import java.io.BufferedReader;
import java.io.File; import java.io.File;
import java.io.FileReader;
import java.io.IOException;
import java.net.MalformedURLException; import java.net.MalformedURLException;
import java.net.URL; import java.net.URL;
import java.net.URLClassLoader; import java.net.URLClassLoader;
import java.util.Date;
import java.util.concurrent.ExecutorService; import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors; import java.util.concurrent.Executors;
import java.util.concurrent.ScheduledExecutorService; import java.util.concurrent.ScheduledExecutorService;
@ -53,19 +50,29 @@ public class NodeCenterServer {
Executors.newScheduledThreadPool(8); Executors.newScheduledThreadPool(8);
static SslContext sslContext = null; static SslContext sslContext = null;
public static URLClassLoader pluginLoader; public static URLClassLoader pluginLoader;
// static byte[] delimiter = "wonbifoodie".getBytes(); // static byte[] delimiter = "wonbifoodie".getBytes();
static { static {
KeyValueDBUtil.setupNC(); KeyValueDBUtil.setupNC();
// TimeDBUtil.setupNC(); // TimeDBUtil.setupNC();
TimeDBUtil.setupNC(); TimeDBUtil.setupNC();
Configurator.setLevel("io.netty.handler.codec.http.websocketx.WebSocket08FrameDecoder", Configurator.setLevel(
"io.netty.handler.codec.http.websocketx.WebSocket08FrameDecoder",
Level.OFF); Level.OFF);
Configurator.setLevel("io.netty.handler.codec.http.websocketx.WebSocket08FrameEncoder", Configurator.setLevel(
"io.netty.handler.codec.http.websocketx.WebSocket08FrameEncoder",
Level.OFF); Level.OFF);
} }
public static void configServer(CMDConf cmdConf) { public static void configServer(CMDConf cmdConf) {
LocalLHSProxy.port = cmdConf.doipPort;
LocalLHSProxy.enabled = true;
if (cmdConf.disableDoRepo) {
DoConfig.callContractUsingDOI = false;
}
if (cmdConf.disableLocalLhs) {
LocalLHSProxy.enabled = false;
}
if (!cmdConf.enableSsl.isEmpty()) { if (!cmdConf.enableSsl.isEmpty()) {
try { try {
String[] filePaths = cmdConf.enableSsl.split(":"); String[] filePaths = cmdConf.enableSsl.split(":");
@ -100,7 +107,7 @@ public class NodeCenterServer {
private static String[] parseStrAsList(String str) { private static String[] parseStrAsList(String str) {
if (str == null) { if (str == null) {
return new String[] {}; return new String[]{};
} }
return str.split(","); return str.split(",");
} }
@ -118,35 +125,23 @@ public class NodeCenterServer {
CMDConf cmf = CMDConf.parseFile(CONFIG_PATH).parseArgs(args); CMDConf cmf = CMDConf.parseFile(CONFIG_PATH).parseArgs(args);
configServer(cmf); configServer(cmf);
File keyFile = new File("manager.key");
if (keyFile.exists()) {
try {
BufferedReader br = new BufferedReader(new FileReader(keyFile));
String pubKey = br.readLine();
String nowManager = KeyValueDBUtil.instance.getValue(NCTables.ConfigDB.toString(),
NCManagerAction.centerManger);
// manager.key is used when node manager isn' set
if (null == nowManager || nowManager.isEmpty()) {
KeyValueDBUtil.instance.setValue(NCTables.ConfigDB.toString(),
NCManagerAction.centerManger, pubKey);
KeyValueDBUtil.instance.setValue(NCTables.ConfigDB.toString(),
NCManagerAction.clusterName, "clusterName_" + pubKey.substring(0, 5));
KeyValueDBUtil.instance.setValue(NCTables.NodeUser.toString(), pubKey,
Role.CenterManager.toString());
KeyValueDBUtil.instance.setValue(NCTables.NodeTime.toString(), pubKey,
Long.toString(new Date().getTime()));
LOGGER.info("set node manager from manager.key");
}
} catch (IOException ignored) {
}
}
if (LocalLHSProxy.enabled) {
threadPool = Executors.newSingleThreadExecutor();
threadPool.execute(() -> {
try {
LocalLHSProxy.start();
} catch (Exception e) {
LOGGER.error("local LHS proxy failed: " + e.getMessage());
}
});
}
listenSocket(cmf.servicePort + 1); listenSocket(cmf.servicePort + 1);
OtherNCProxy.instance.init(); OtherNCProxy.instance.init();
startHttp(cmf.servicePort); startHttp(cmf.servicePort);
// System.out.println("PORT"+cmf.servicePort); //System.out.println("PORT"+cmf.servicePort);
} }
public static void listenSocket(int port) throws Exception { public static void listenSocket(int port) throws Exception {
@ -155,21 +150,25 @@ public class NodeCenterServer {
EventLoopGroup workerGroup = new NioEventLoopGroup(); EventLoopGroup workerGroup = new NioEventLoopGroup();
ServerBootstrap b = new ServerBootstrap(); ServerBootstrap b = new ServerBootstrap();
b.option(ChannelOption.ALLOCATOR, PooledByteBufAllocator.DEFAULT); b.option(ChannelOption.ALLOCATOR, PooledByteBufAllocator.DEFAULT);
b.group(bossGroup, workerGroup).channel(NioServerSocketChannel.class) b.group(bossGroup, workerGroup)
.option(ChannelOption.SO_BACKLOG, 100).localAddress(port) .channel(NioServerSocketChannel.class)
.childHandler(new ChannelInitializer<SocketChannel>() { .option(ChannelOption.SO_BACKLOG, 100)
@Override .localAddress(port)
protected void initChannel(SocketChannel arg0) { .childHandler(
arg0.pipeline().addLast(new DelimiterCodec()) new ChannelInitializer<SocketChannel>() {
.addLast(new NodeCenterFrameHandler()); @Override
} protected void initChannel(SocketChannel arg0) {
}); arg0.pipeline()
.addLast(new DelimiterCodec())
.addLast(new NodeCenterFrameHandler());
}
});
b.bind(port).sync().channel(); b.bind(port).sync().channel();
} }
public static void startHttp(int port) { public static void startHttp(int port) {
File[] pluginJar = File[] pluginJar = new File("./pluginLib/")
new File("./pluginLib/").listFiles(pathname -> pathname.getName().endsWith(".jar")); .listFiles(pathname -> pathname.getName().endsWith(".jar"));
URL[] urls; URL[] urls;
if (pluginJar != null && pluginJar.length > 0) { if (pluginJar != null && pluginJar.length > 0) {
urls = new URL[pluginJar.length]; urls = new URL[pluginJar.length];
@ -182,7 +181,7 @@ public class NodeCenterServer {
} }
} }
} else { } else {
urls = new URL[] {}; urls = new URL[]{};
} }
pluginLoader = new URLClassLoader(urls, NodeCenterServer.class.getClassLoader()); pluginLoader = new URLClassLoader(urls, NodeCenterServer.class.getClassLoader());
LOGGER.info("start at: " + port); LOGGER.info("start at: " + port);
@ -193,7 +192,9 @@ public class NodeCenterServer {
ServerBootstrap b = new ServerBootstrap(); ServerBootstrap b = new ServerBootstrap();
ControlledChannelInitializer initializer = new ControlledChannelInitializer(); ControlledChannelInitializer initializer = new ControlledChannelInitializer();
b.option(ChannelOption.ALLOCATOR, PooledByteBufAllocator.DEFAULT); b.option(ChannelOption.ALLOCATOR, PooledByteBufAllocator.DEFAULT);
b.group(bossGroup, workerGroup).channel(NioServerSocketChannel.class).localAddress(port) b.group(bossGroup, workerGroup)
.channel(NioServerSocketChannel.class)
.localAddress(port)
.childHandler(initializer); .childHandler(initializer);
final Channel ch = b.bind(port).sync().channel(); final Channel ch = b.bind(port).sync().channel();
ch.closeFuture().sync(); ch.closeFuture().sync();
@ -225,9 +226,12 @@ public class NodeCenterServer {
} else { } else {
LOGGER.warn("disable ssl"); LOGGER.warn("disable ssl");
} }
arg0.pipeline().addLast(new HttpServerCodec()).addLast(new HttpObjectAggregator(65536)) arg0.pipeline()
.addLast(new HttpServerCodec())
.addLast(new HttpObjectAggregator(65536))
.addLast(new WebSocketServerProtocolHandler(PATH, null, true)) .addLast(new WebSocketServerProtocolHandler(PATH, null, true))
.addLast(new ChunkedWriteHandler()).addLast(handler) .addLast(new ChunkedWriteHandler())
.addLast(handler)
.addLast(new NodeCenterWSFrameHandler()); .addLast(new NodeCenterWSFrameHandler());
} }
} }

View File

@ -16,16 +16,15 @@ public class DistributeCallback extends ResultCallback {
private static final Logger LOGGER = LogManager.getLogger(DistributeCallback.class); private static final Logger LOGGER = LogManager.getLogger(DistributeCallback.class);
String sponsorPubkey;// 发起节点的 String sponsorPubkey;// 发起节点的
Map<String, String> nodes; Map<String, String> nodes;
String pubKey; // 发起节点的用户公钥 String pubKey; //发起节点的用户公钥
String signature; // 发起节点的 String signature; // 发起节点的
int count; // 集群中几个节点已成功启动 int count; // 集群中几个节点已成功启动
ResultCallback res; // 返回给Node ResultCallback res; // 返回给Node
String fileName; // ypk的文件名 String fileName; // ypk的文件名
int index; int index;
String distributeID; // 发起节点的分发id String distributeID; //发起节点的分发id
public DistributeCallback(String ss, String sponID, Map<String, String> n, ResultCallback re, public DistributeCallback(String ss, String sponID, Map<String, String> n, ResultCallback re, String p, String s) {
String p, String s) {
distributeID = ss; distributeID = ss;
count = 0; count = 0;
index = 1; index = 1;
@ -68,15 +67,18 @@ public class DistributeCallback extends ResultCallback {
public void onDistribute(String progress, String nodeIP) { public void onDistribute(String progress, String nodeIP) {
Map<String, String> ret2 = new HashMap<>(); Map<String, String> ret2 = new HashMap<>();
ret2.put("action", "onDistributeContract"); ret2.put("action", "onDistributeContract");
ret2.put("progress", "NC is sending ypk to NO." + index + " node in the units,progress is " ret2.put(
+ progress + "%."); "progress",
if (progress.equals("100.00")) "NC is sending ypk to NO."
index++; + index
+ " node in the units,progress is "
+ progress
+ "%.");
if (progress.equals("100.00")) index++;
Map<String, String> map = new HashMap<>(); Map<String, String> map = new HashMap<>();
map.put("action", "onDistribute"); map.put("action", "onDistributeYPK");
map.put("responseID", distributeID); map.put("responseID", distributeID);
map.put("distributeID", distributeID);
map.put("content", JsonUtil.toJson(ret2)); map.put("content", JsonUtil.toJson(ret2));
map.put("nodeIP", nodeIP); map.put("nodeIP", nodeIP);
map.put("progress", progress); map.put("progress", progress);
@ -84,7 +86,7 @@ public class DistributeCallback extends ResultCallback {
} }
public void onReceive(Map<String, String> map) { public void onReceive(Map<String, String> map) {
LOGGER.info("[DistributeCallback] onReceive : position----9"); LOGGER.debug("[DistributeCallback] onReceive : position----9");
String progress = map.get("progress"); String progress = map.get("progress");
String nodeIP = map.get("ipPort"); String nodeIP = map.get("ipPort");
if (progress.equals("100")) { if (progress.equals("100")) {
@ -93,22 +95,20 @@ public class DistributeCallback extends ResultCallback {
args.put("pubKey", pubKey); args.put("pubKey", pubKey);
args.put("signature", signature); args.put("signature", signature);
count++; count++;
LOGGER.info(count + "个节点已收完成" + " 总共有" + nodes.size() + " 个节点"); LOGGER.debug(count + "个节点已收完成" + " 总共有" + nodes.size() + " 个节点");
if (count >= nodes.size() - 1) { if (count == nodes.size()) {
// res返回给前端合约分发完成 // res返回给前端合约分发完成
LOGGER.info("个节点已收完成" + "send on finish!!!!!");
Map<String, String> ret2 = new HashMap<>(); Map<String, String> ret2 = new HashMap<>();
ret2.put("action", "onDistributeFinish"); ret2.put("action", "onDistributeFinish");
ret2.put("progress", "100%"); ret2.put("progress", "100%");
Map<String, String> map_send = new HashMap<>(); Map<String, String> map_send = new HashMap<>();
map_send.put("action", "onDistribute"); map_send.put("action", "onDistribute");
map_send.put("responseID", distributeID); map_send.put("responseID", distributeID);
map_send.put("distributeID", distributeID);
map_send.put("over", "true"); map_send.put("over", "true");
map_send.put("nodeIP", nodeIP); map_send.put("nodeIP", nodeIP);
map_send.put("content", JsonUtil.toJson(ret2)); map_send.put("content", JsonUtil.toJson(ret2));
res.onResult(JsonUtil.toJson(map_send)); res.onResult(JsonUtil.toJson(map_send));
// NC delete file //NC delete file
File file = new File("./temp/stateFiles/" + fileName); File file = new File("./temp/stateFiles/" + fileName);
if (file.exists() && file.isFile()) if (file.exists() && file.isFile())
file.delete(); file.delete();
@ -118,29 +118,25 @@ public class DistributeCallback extends ResultCallback {
@Override @Override
public void onResult(String str) { public void onResult(String str) {
LOGGER.info("[DistributeCallback] str=" + str); LOGGER.debug("[DistributeCallback] str=" + str);
Map<String, String> map = Map<String, String> map = JsonUtil.fromJson(str, new TypeToken<Map<String, String>>() {
JsonUtil.fromJson(str, new TypeToken<Map<String, String>>() {}.getType()); }.getType());
NodeCenterActions.sync.sleepWithTimeout(map.get("requestID"), this, 60); NodeCenterActions.sync.sleepWithTimeout(map.get("requestID"), this, 60);
String operation = map.get("operation"); String operation = map.get("operation");
switch (operation) { switch (operation) {
// 上传到nodecenter
case "NCreceive": case "NCreceive":
NCreceive(map.get("progress")); NCreceive(map.get("progress"));
break; break;
// 开始分发给各个节点
case "distribute": case "distribute":
distributeContractProject(map.get("receiveFileName"), map.get("isPrivate")); distributeContractProject(map.get("receiveFileName"), map.get("isPrivate"));
break; break;
// 分发给各个节点
case "onDistribute": case "onDistribute":
onDistribute(map.get("progress"), map.get("nodeIP")); onDistribute(map.get("progress"), map.get("nodeIP"));
break; break;
// 各个节点返回收到
case "onReceive": case "onReceive":
onReceive(map); onReceive(map);
break; break;

View File

@ -25,26 +25,27 @@ public class RequestAllExecutor implements ContractExecutor {
resultCount = count; resultCount = count;
} }
public ResultCallback createResultCallback(final String requestID, public ResultCallback createResultCallback(
final ResultCallback originalCb, int count, String contractID) { final String requestID, final ResultCallback originalCb, int count, String contractID) {
return new Collector(requestID, originalCb, count, contractID); return new Collector(requestID, originalCb, count, contractID);
} }
// only for test ADSP //only for test ADSP
// public ResultCallback createResultCallback( // public ResultCallback createResultCallback(
// final String requestID, final ResultCallback originalCb, int count,String contractID,String // final String requestID, final ResultCallback originalCb, int count,String contractID,String seq) {
// seq) { // ResultCallback collector = new Collector(requestID, originalCb, count,contractID,seq);
// ResultCallback collector = new Collector(requestID, originalCb, count,contractID,seq); // return collector;
// return collector; // }
// }
public void sendRequest(String req, ResultCallback collector) { public void sendRequest(String req, ResultCallback collector) {
List<String> nodes = info.members; List<String> nodes = info.members;
for (String node : nodes) { for (String node : nodes) {
CMNode cmNode = NodeCenterActions.nodeInfos.get(node); CMNode cmNode = NodeCenterActions.nodeInfos.get(node);
if (cmNode == null) { if (cmNode == null) {
collector.onResult("{\"status\":\"Error\",\"result\":\"node " + node collector.onResult(
+ " offline\",\"action\":\"onExecuteContractTrustfully\"}"); "{\"status\":\"Error\",\"result\":\"node "
+ node
+ " offline\",\"action\":\"onExecuteContractTrustfully\"}");
} else { } else {
cmNode.connection.controller.sendMsg(req); cmNode.connection.controller.sendMsg(req);
} }
@ -56,13 +57,12 @@ public class RequestAllExecutor implements ContractExecutor {
JsonObject jo2 = JsonParser.parseString(req).getAsJsonObject(); JsonObject jo2 = JsonParser.parseString(req).getAsJsonObject();
String id = jo2.get("contractID").getAsString(); String id = jo2.get("contractID").getAsString();
// only for test ADSP //only for test ADSP
// ResultCallback collector = createResultCallback(requestID, rc, // ResultCallback collector = createResultCallback(requestID, rc, resultCount,id,jo2.get("seq").getAsString());
// resultCount,id,jo2.get("seq").getAsString());
ResultCallback collector = createResultCallback(requestID, rc, resultCount, id); ResultCallback collector = createResultCallback(requestID, rc, resultCount, id);
// TODO NC.sync?有问题 //TODO NC.sync?有问题
NodeCenterActions.sync.sleep(requestID, collector); NodeCenterActions.sync.sleep(requestID, collector);
sendRequest(req, collector); sendRequest(req, collector);
} }
@ -74,20 +74,20 @@ public class RequestAllExecutor implements ContractExecutor {
AtomicInteger count = new AtomicInteger(0); AtomicInteger count = new AtomicInteger(0);
// only for testADSP //only for testADSP
// boolean flag = true; //true表示还没在文件中记录这次调用结果 // boolean flag = true; //true表示还没在文件中记录这次调用结果
// String seq; // String seq;
// Map<String,Integer> res = new ConcurrentHashMap<String,Integer>(); // Map<String,Integer> res = new ConcurrentHashMap<String,Integer>();
// only for test ADSP //only for test ADSP
// public Collector(String reqID, ResultCallback callback, int c,String id,String seq2) { // public Collector(String reqID, ResultCallback callback, int c,String id,String seq2) {
// total = c; // total = c;
// requestID = reqID; // requestID = reqID;
// commiter = callback; // commiter = callback;
// contractID = id; // contractID = id;
// seq = seq2; // seq = seq2;
// } // }
ResultCallback committer; ResultCallback committer;
public Collector(String reqID, ResultCallback callback, int c, String id) { public Collector(String reqID, ResultCallback callback, int c, String id) {
@ -105,7 +105,7 @@ public class RequestAllExecutor implements ContractExecutor {
obj.addProperty("seqNum", count.getAndIncrement()); obj.addProperty("seqNum", count.getAndIncrement());
obj.addProperty("total", total); obj.addProperty("total", total);
// NodeCenterActions.recoverMap.get(nodePubKey).get(contractID).lastExeSeq++; //NodeCenterActions.recoverMap.get(nodePubKey).get(contractID).lastExeSeq++;
if (committer != null) if (committer != null)
committer.onResult(obj.toString()); committer.onResult(obj.toString());
@ -125,45 +125,47 @@ public class RequestAllExecutor implements ContractExecutor {
String data = obj.get("data").getAsString(); String data = obj.get("data").getAsString();
ContractResult cr = JsonUtil.fromJson(data, ContractResult.class); ContractResult cr = JsonUtil.fromJson(data, ContractResult.class);
// only for testADSP //only for testADSP
// if(TestADSP.getFlag()){ // if(TestADSP.getFlag()){
// String r = cr.result; // String r = cr.result;
// if(!res.containsKey(r)){ // if(!res.containsKey(r)){
// res.put(r,0); // res.put(r,0);
// } // }
// int former = res.get(r); // int former = res.get(r);
// res.put(r,++former); // res.put(r,++former);
// for(String s : res.keySet()){ // for(String s : res.keySet()){
// if(res.get(s) > total / 2 && flag){ // if(res.get(s) > total / 2 && flag){
// //写入文件 // //写入文件
// File file = new File(TestADSP.resultPath); // File file = new File(TestADSP.resultPath);
// synchronized (file){ // synchronized (file){
// try { // try {
// FileWriter fw = new FileWriter(file, true); // FileWriter fw = new FileWriter(file, true);
// PrintWriter pw = new PrintWriter(fw); // PrintWriter pw = new PrintWriter(fw);
// pw.println(seq + " " + r); // pw.println(seq + " " + r);
// pw.flush(); // pw.flush();
// fw.flush(); // fw.flush();
// pw.close(); // pw.close();
// fw.close(); // fw.close();
// } catch (IOException e) { // } catch (IOException e) {
// e.printStackTrace(); // e.printStackTrace();
// } // }
// } // }
// flag = false; // flag = false;
// } // }
// } // }
// } // }
/* /* if (cr.status == ContractResult.Status.Error) { //TODO 规范Status的使用 改成 ==Statuc.Error才恢复
* if (cr.status == ContractResult.Status.Error) { //TODO 规范Status的使用 改成 String nodePubKey = obj.get("nodeID").getAsString();
* ==Statuc.Error才恢复 String nodePubKey = obj.get("nodeID").getAsString(); if(NodeCenterActions.recoverMap.containsKey(nodePubKey)){
* if(NodeCenterActions.recoverMap.containsKey(nodePubKey)){ ContractRecord record = ContractRecord record = NodeCenterActions.recoverMap.get(nodePubKey).get(contractID);
* NodeCenterActions.recoverMap.get(nodePubKey).get(contractID); if(record.recoverFlag == RecoverFlag.Fine){
* if(record.recoverFlag == RecoverFlag.Fine){ record.recoverFlag = record.recoverFlag = RecoverFlag.ToRecover;
* RecoverFlag.ToRecover; MasterActions.restartContracts(nodePubKey); } } } MasterActions.restartContracts(nodePubKey);
*/ }
}
}*/
} }
} }
} }

View File

@ -26,17 +26,18 @@ public class RequestOnceExecutor implements ContractExecutor {
JsonObject jo2 = (new JsonParser()).parse(req).getAsJsonObject(); JsonObject jo2 = (new JsonParser()).parse(req).getAsJsonObject();
String contractID = jo2.get("contractID").getAsString(); String contractID = jo2.get("contractID").getAsString();
ResultCallback cb = new ResultCallback() { ResultCallback cb =
@Override new ResultCallback() {
public void onResult(String str) { @Override
LOGGER.debug(str); public void onResult(String str) {
JsonObject jo = (new JsonParser()).parse(str).getAsJsonObject(); LOGGER.debug(str);
jo.remove("action"); JsonObject jo = (new JsonParser()).parse(str).getAsJsonObject();
jo.addProperty("action", "onExecuteResult"); jo.remove("action");
LOGGER.debug(jo.toString()); jo.addProperty("action", "onExecuteResult");
rc.onResult(jo.toString()); LOGGER.debug(jo.toString());
} rc.onResult(jo.toString());
}; }
};
NodeCenterActions.sync.sleep(requestID, cb); NodeCenterActions.sync.sleep(requestID, cb);
for (int i = 0; i < info.members.size(); i++) { for (int i = 0; i < info.members.size(); i++) {
int size = info.members.size(); int size = info.members.size();
@ -48,7 +49,8 @@ public class RequestOnceExecutor implements ContractExecutor {
return; return;
} }
} }
rc.onResult("{\"status\":\"Error\",\"result\":\"all nodes " rc.onResult(
+ " offline\",\"action\":\"onExecuteContract\"}"); "{\"status\":\"Error\",\"result\":\"all nodes "
+ " offline\",\"action\":\"onExecuteContract\"}");
} }
} }

View File

@ -32,30 +32,31 @@ public class ResponseOnceExecutor implements ContractExecutor {
JsonObject jo2 = (new JsonParser()).parse(req).getAsJsonObject(); JsonObject jo2 = (new JsonParser()).parse(req).getAsJsonObject();
String contractID = jo2.get("contractID").getAsString(); String contractID = jo2.get("contractID").getAsString();
// TODO 标注失效节点是否选择重新迁移 // TODO 标注失效节点是否选择重新迁移
ResultCallback cb = new ResultCallback() { ResultCallback cb =
@Override new ResultCallback() {
public void onResult(String str) { @Override
LOGGER.debug(str); public void onResult(String str) {
JsonObject jo = (new JsonParser()).parse(str).getAsJsonObject(); LOGGER.debug(str);
jo.remove("action"); JsonObject jo = (new JsonParser()).parse(str).getAsJsonObject();
jo.addProperty("action", "onExecuteResult"); jo.remove("action");
LOGGER.debug(jo.toString()); jo.addProperty("action", "onExecuteResult");
if (jo.has("data")) { LOGGER.debug(jo.toString());
String data = jo.get("data").getAsString(); if (jo.has("data")) {
ContractResult cr = JsonUtil.fromJson(data, ContractResult.class); String data = jo.get("data").getAsString();
if (cr.status != ContractResult.Status.Success && count > 0) { ContractResult cr = JsonUtil.fromJson(data, ContractResult.class);
executeInternal(requestID, rc, req, count - 1); if (cr.status != ContractResult.Status.Success && count > 0) {
} else executeInternal(requestID, rc, req, count - 1);
rc.onResult(jo.toString()); } else
} else { rc.onResult(jo.toString());
JsonObject jo2 = new JsonObject(); } else {
jo2.addProperty("action", "onExecuteResult"); JsonObject jo2 = new JsonObject();
jo.remove("action"); jo2.addProperty("action", "onExecuteResult");
jo2.addProperty("data", jo.toString()); jo.remove("action");
rc.onResult(jo2.toString()); jo2.addProperty("data", jo.toString());
} rc.onResult(jo2.toString());
} }
}; }
};
NodeCenterActions.sync.sleepWithTimeout(requestID, cb, 5); NodeCenterActions.sync.sleepWithTimeout(requestID, cb, 5);
if (!sendOnce(req)) if (!sendOnce(req))
rc.onResult( rc.onResult(

View File

@ -0,0 +1,123 @@
package org.bdware.server.irp;
import com.sun.net.httpserver.HttpExchange;
import com.sun.net.httpserver.HttpHandler;
import com.sun.net.httpserver.HttpServer;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import org.bdware.sc.util.JsonUtil;
import org.rocksdb.Options;
import org.rocksdb.RocksDB;
import org.rocksdb.RocksDBException;
import java.io.File;
import java.io.IOException;
import java.io.OutputStream;
import java.io.UnsupportedEncodingException;
import java.net.InetSocketAddress;
import java.net.URLDecoder;
import java.util.Arrays;
import java.util.HashMap;
import java.util.Map;
public class LocalLHSProxy {
private static final Logger LOGGER = LogManager.getLogger(LocalLHSProxy.class);
public static String PREFIX = "86.5000.470/";
public static int port = 18007;
public static boolean enabled = false;
public static RocksDB db;
static RegisterHandler registerHandler;
static {
RocksDB.loadLibrary();
}
public static void main(String[] args) throws Exception {
start();
}
public static void start() throws IOException, RocksDBException {
String dbPath = "./handleRecords/";
Options rockopts = new Options().setCreateIfMissing(true);
rockopts.useFixedLengthPrefixExtractor(15);
LOGGER.info("actual rocksdb path: " + new File(dbPath).getAbsolutePath());
File lock = new File(dbPath, "LOCK");
if (lock.exists()) {
LOGGER.trace("remove file " + lock.getAbsolutePath() + ": " + lock.delete());
}
db = RocksDB.open(rockopts, dbPath);
registerHandler = new RegisterHandler(db);
LOGGER.info("listen to " + port);
HttpServer server = HttpServer.create(new InetSocketAddress(port), 0);
server.createContext("/test", new TestHandler());
server.createContext("/resolve", new ResolveHandler());
server.createContext("/local/", registerHandler);
server.createContext("/view", new ViewHandler(db));
server.start();
}
private static Map<String, String> formData2Dic(String formData) {
Map<String, String> result = new HashMap<>();
if (formData == null || formData.trim().length() == 0) {
return result;
}
final String[] items = formData.split("&");
Arrays.stream(items)
.forEach(
item -> {
final String[] keyAndVal = item.split("=");
if (keyAndVal.length == 2) {
try {
final String key = URLDecoder.decode(keyAndVal[0], "utf8");
final String val = URLDecoder.decode(keyAndVal[1], "utf8");
result.put(key, val);
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
}
}
});
return result;
}
static class TestHandler implements HttpHandler {
@Override
public void handle(HttpExchange exchange) {
String response = "hello world";
try {
exchange.sendResponseHeaders(200, 0);
OutputStream os = exchange.getResponseBody();
os.write(response.getBytes());
os.close();
} catch (Exception e) {
e.printStackTrace();
}
}
}
static class ResolveHandler implements HttpHandler {
@Override
public void handle(HttpExchange exchange) {
try {
// 获得查询字符串(get)
String queryString = exchange.getRequestURI().getQuery();
Map<String, String> queryStringInfo = formData2Dic(queryString);
String id = queryStringInfo.get("identifier");
Map<String, String> respMap;
respMap = registerHandler.handleResolve(queryStringInfo);
respMap.forEach((k, v) -> {
LOGGER.debug(k + "->" + v);
});
exchange.getResponseHeaders().add("Access-Control-Allow-Origin", "*");
exchange.sendResponseHeaders(200, 0);
OutputStream os = exchange.getResponseBody();
os.write(JsonUtil.toJson(respMap).getBytes());
os.close();
} catch (Exception e) {
e.printStackTrace();
}
}
}
}

View File

@ -0,0 +1,246 @@
package org.bdware.server.irp;
import com.sun.net.httpserver.HttpExchange;
import com.sun.net.httpserver.HttpHandler;
import org.apache.commons.io.IOUtils;
import org.bdware.sc.util.JsonUtil;
import org.rocksdb.RocksDB;
import java.io.IOException;
import java.io.OutputStream;
import java.io.UnsupportedEncodingException;
import java.net.URLDecoder;
import java.util.Arrays;
import java.util.HashMap;
import java.util.Map;
import java.util.Random;
public class RegisterHandler implements HttpHandler {
RocksDB db;
String dbPath = "./handleRecords/";
public RegisterHandler(RocksDB rocksDB) {
db = rocksDB;
}
public Map<String, String> HandleRequest(Map<String, String> postInfo) {
Map<String, String> respMap = new HashMap<>();
String action = postInfo.get("action");
switch (action) {
case "resolve":
respMap = handleResolve(postInfo);
break;
case "register":
case "forceRegister":
respMap = handleRegister(postInfo);
break;
case "unregister":
case "forceDelete":
respMap = handleUnRegister(postInfo);
break;
case "reregister":
respMap = handleReregister(postInfo);
break;
default:
System.out.println("error response");
}
return respMap;
}
public Map<String, String> handleRegister(Map<String, String> reqMap) {
Map<String, String> respMap = new HashMap<>();
String type;
switch (reqMap.get("hrType")) {
case "do":
type = "do.";
ViewHandler.handleRecordCount.doCount++;
break;
case "dou":
type = "dou.";
ViewHandler.handleRecordCount.userCount++;
break;
case "doip":
type = "doip.";
ViewHandler.handleRecordCount.repoCount++;
break;
default:
type = "ukw.";
break;
}
String identifier = LocalLHSProxy.PREFIX + type + geneRandomID() + "_bdw";
reqMap.remove("action");
reqMap.remove("hrType");
reqMap.put("identifier", identifier);
String handleRecord = JsonUtil.toJson(reqMap);
try {
db.put(identifier.getBytes(), handleRecord.getBytes());
System.out.println("successful update do, identifier: " + identifier);
respMap.put("identifier", identifier);
respMap.put("status", "1");
respMap.put("response", "register DO success, identifier: " + identifier);
ViewHandler.addRegister();
} catch (Exception e) {
e.printStackTrace();
respMap.put("status", "0");
respMap.put("response", "respond failed from LHS");
}
return respMap;
}
public Map<String, String> handleReregister(Map<String, String> reqMap) {
Map<String, String> respMap = new HashMap<>();
String identifier;
if (reqMap.get("identifier") != null) identifier = reqMap.get("identifier");
else {
respMap.put("status", "0");
respMap.put("response", "identifier not found");
return respMap;
}
try {
reqMap.remove("action");
reqMap.remove("hrType");
String handleRecord = JsonUtil.toJson(reqMap);
if (db.get(identifier.getBytes()) == null) {
String idType;
if ((identifier.split("/")).length > 2)
idType = identifier.split("/")[1].split("\\.")[0];
else
idType = identifier.split("\\.")[0];
switch (idType) {
case "do":
ViewHandler.handleRecordCount.doCount++;
break;
case "dou":
ViewHandler.handleRecordCount.userCount++;
break;
case "doip":
ViewHandler.handleRecordCount.repoCount++;
break;
default:
break;
}
} else {
db.delete(identifier.getBytes());
}
db.put(identifier.getBytes(), handleRecord.getBytes());
System.out.println("successful update do, identifier: " + identifier);
respMap.put("identifier", identifier);
respMap.put("status", "1");
respMap.put("response", "reRegister DO success, identifier: " + identifier);
} catch (Exception e) {
e.printStackTrace();
respMap.put("status", "0");
respMap.put("response", "unregister failed: " + e.getMessage());
}
return respMap;
}
public Map<String, String> handleUnRegister(Map<String, String> reqMap) {
Map<String, String> respMap = new HashMap<>();
String identifier;
if (reqMap.get("identifier") != null) identifier = reqMap.get("identifier");
else {
respMap.put("status", "0");
respMap.put("response", "identifier not found");
return respMap;
}
try {
switch (identifier.split("\\.")[2]) {
case "470/do":
ViewHandler.handleRecordCount.doCount--;
break;
case "470/doip":
ViewHandler.handleRecordCount.repoCount--;
break;
case "470/dou":
ViewHandler.handleRecordCount.userCount--;
break;
}
db.delete(identifier.getBytes());
respMap.put("status", "1");
respMap.put("response", "success delete: " + identifier);
ViewHandler.addDelete();
} catch (Exception e) {
e.printStackTrace();
respMap.put("status", "0");
respMap.put("response", "unregister failed: " + e.getMessage());
}
return respMap;
}
public Map<String, String> handleResolve(Map<String, String> reqMap) {
Map<String, String> respMap = new HashMap<>();
String identifier;
if (reqMap.get("identifier") != null) identifier = reqMap.get("identifier");
else {
respMap.put("status", "0");
respMap.put("response", "identifier not found");
return respMap;
}
try {
if (db.get(identifier.getBytes()) == null) {
respMap.put("status", "0");
respMap.put("response", "not exist");
return respMap;
}
String result = new String(db.get(identifier.getBytes()));
respMap = JsonUtil.fromJson(result, HashMap.class);
ViewHandler.addResolve();
} catch (Exception e) {
e.printStackTrace();
respMap.put("status", "0");
respMap.put("response", "resolve failed: " + e.getMessage());
}
return respMap;
}
public String geneRandomID() {
String str = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789";
Random random = new Random();
StringBuilder sb = new StringBuilder();
for (int i = 0; i < 10; i++) {
int number = random.nextInt(62);
sb.append(str.charAt(number));
}
return sb.toString();
}
@Override
public void handle(HttpExchange exchange) throws IOException {
Map<String, String> respMap;
try {
//获得表单提交数据(post)
String postString = IOUtils.toString(exchange.getRequestBody());
Map<String, String> postInfo = formData2Dic(postString);
respMap = HandleRequest(postInfo);
exchange.sendResponseHeaders(200, 0);
OutputStream os = exchange.getResponseBody();
os.write(JsonUtil.toJson(respMap).getBytes());
os.close();
} catch (Exception e) {
e.printStackTrace();
}
}
public Map<String, String> formData2Dic(String formData) {
Map<String, String> result = new HashMap<>();
if (formData == null || formData.trim().length() == 0) {
return result;
}
final String[] items = formData.split("&");
Arrays.stream(items).forEach(item -> {
final String[] keyAndVal = item.split("=");
if (keyAndVal.length == 2) {
try {
final String key = URLDecoder.decode(keyAndVal[0], "utf8");
final String val = URLDecoder.decode(keyAndVal[1], "utf8");
result.put(key, val);
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
}
}
});
return result;
}
}

View File

@ -0,0 +1,11 @@
package org.bdware.server.irp;
public class StatisticsByDay {
int resolveStatics;
int deleteStatics;
int registerStatics;
public StatisticsByDay(){
registerStatics = resolveStatics = deleteStatics = 0;
}
}

View File

@ -0,0 +1,257 @@
package org.bdware.server.irp;
import com.google.gson.reflect.TypeToken;
import com.sun.net.httpserver.HttpExchange;
import com.sun.net.httpserver.HttpHandler;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import org.bdware.sc.util.JsonUtil;
import org.bdware.server.NodeCenterServer;
import org.rocksdb.ReadOptions;
import org.rocksdb.RocksDB;
import org.rocksdb.RocksDBException;
import org.rocksdb.RocksIterator;
import java.io.IOException;
import java.io.OutputStream;
import java.io.UnsupportedEncodingException;
import java.net.URLDecoder;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.*;
import java.util.concurrent.TimeUnit;
public class ViewHandler implements HttpHandler {
public static final String STATISTICS_KEY = "STATISTICS";
public static final String COUNT_KEY = "COUNT";
private static final Logger LOGGER = LogManager.getLogger(ViewHandler.class);
public static HashMap<String, StatisticsByDay> lhsStatics = new HashMap<>();
public static HandleRecordCount handleRecordCount;
RocksDB db;
public ViewHandler(RocksDB rocksDB) throws RocksDBException {
db = rocksDB;
loadFromDB();
NodeCenterServer.scheduledThreadPool.scheduleWithFixedDelay(
() -> {
try {
saveToDB();
} catch (RocksDBException e) {
LOGGER.error("saving to DB failed! " + e.getMessage());
}
},
0,
1,
TimeUnit.SECONDS);
}
public static String getToday() {
SimpleDateFormat formatter = new SimpleDateFormat("yyyyMMdd");
Date date = new Date(System.currentTimeMillis());
return formatter.format(date);
}
public static void addResolve() {
String todayDate = ViewHandler.getToday();
if (lhsStatics.get(todayDate) == null) {
StatisticsByDay statisticsByDay = new StatisticsByDay();
statisticsByDay.resolveStatics++;
lhsStatics.put(todayDate, statisticsByDay);
} else {
lhsStatics.get(todayDate).resolveStatics++;
}
}
public static void addRegister() {
String todayDate = ViewHandler.getToday();
if (lhsStatics.get(todayDate) == null) {
StatisticsByDay statisticsByDay = new StatisticsByDay();
statisticsByDay.registerStatics++;
lhsStatics.put(todayDate, statisticsByDay);
} else {
lhsStatics.get(todayDate).registerStatics++;
}
}
public static void addDelete() {
String todayDate = ViewHandler.getToday();
if (lhsStatics.get(todayDate) == null) {
StatisticsByDay statisticsByDay = new StatisticsByDay();
statisticsByDay.deleteStatics++;
lhsStatics.put(todayDate, statisticsByDay);
} else {
lhsStatics.get(todayDate).deleteStatics++;
}
}
@Override
public void handle(HttpExchange httpExchange) throws IOException {
Map<String, Object> respMap;
try {
//获得表单提交数据(post)
String postString = httpExchange.getRequestURI().getQuery();
Map<String, String> params = formData2Dic(postString);
respMap = HandleRequest(params);
httpExchange.getResponseHeaders().add("Access-Control-Allow-Origin", "*");
httpExchange.sendResponseHeaders(200, 0);
OutputStream os = httpExchange.getResponseBody();
os.write(JsonUtil.toJson(respMap).getBytes());
os.close();
} catch (Exception e) {
e.printStackTrace();
}
}
private Map<String, Object> HandleRequest(Map<String, String> postInfo) {
Map<String, Object> respMap = new HashMap<>();
String action = postInfo.get("action");
switch (action) {
case "count":
respMap = getLHSCount();
break;
case "statistics":
respMap = getLHSStatics(postInfo);
break;
default:
System.out.println("error response");
}
return respMap;
}
private void loadFromDB() throws RocksDBException {
byte[] statisticBytes = db.get(STATISTICS_KEY.getBytes());
if (statisticBytes == null) {
lhsStatics = new HashMap<>();
} else {
lhsStatics = JsonUtil.fromJson(new String(statisticBytes), new TypeToken<HashMap<String, StatisticsByDay>>() {
}.getType());
}
byte[] countBytes = db.get(COUNT_KEY.getBytes());
if (countBytes == null) {
handleRecordCount = new HandleRecordCount();
handleRecordCount.doCount = handleRecordCount.repoCount = handleRecordCount.userCount = 0;
} else {
handleRecordCount = JsonUtil.fromJson(new String(countBytes), HandleRecordCount.class);
}
}
private void saveToDB() throws RocksDBException {
String statisticStr = JsonUtil.toJson(lhsStatics);
db.put(STATISTICS_KEY.getBytes(), statisticStr.getBytes());
String countStr = JsonUtil.toJson(handleRecordCount);
db.put(COUNT_KEY.getBytes(), countStr.getBytes());
}
public Map<String, Object> getLHSStatics(Map<String, String> postInfo) {
if (postInfo.containsKey("day")) {
return getLHSStaticsWithTime(postInfo);
}
HashMap<String, Object> respMap = new HashMap<>();
for (String key : lhsStatics.keySet()) {
respMap.put(key + "", JsonUtil.toJson(lhsStatics.get(key)));
}
return respMap;
}
public Map<String, Object> getLHSStaticsWithTime(Map<String, String> postInfo) {
long day = Long.parseLong(postInfo.get("day"));
LOGGER.info(day);
List<Integer> resolve = new ArrayList<>();
List<Integer> delete = new ArrayList<>();
List<Integer> register = new ArrayList<>();
for (int i = 0; i < day; i++) {
resolve.add(0);
delete.add(0);
register.add(0);
}
long interval = 24 * 60 * 60 * 1000; //一天
long cur = System.currentTimeMillis();
long startTime = cur - day * interval;
// logger.info(JsonUtil.toJson(lhsStatics));
try {
for (String k : lhsStatics.keySet()) {
long time = new SimpleDateFormat("yyyyMMdd").parse(k).getTime();
if (time < startTime || time > cur) {
continue;
}
int index = (int) ((time - startTime) / interval);
//logger.info(index);
resolve.set(index, resolve.get(index) + lhsStatics.get(k).resolveStatics);
delete.set(index, delete.get(index) + lhsStatics.get(k).deleteStatics);
register.set(index, register.get(index) + lhsStatics.get(k).registerStatics);
}
} catch (ParseException e) {
e.printStackTrace();
}
HashMap<String, Object> respMap = new HashMap<>();
respMap.put("resolve", resolve);
respMap.put("delete", delete);
respMap.put("register", register);
return respMap;
}
public Map<String, Object> getLHSCount() {
HashMap<String, Object> respMap = new HashMap<>();
respMap.put("repoCount", String.valueOf(handleRecordCount.repoCount));
respMap.put("doCount", String.valueOf(handleRecordCount.doCount));
ReadOptions readOptions = new ReadOptions().setPrefixSameAsStart(true);
RocksIterator it1 = db.newIterator(readOptions);
ArrayList<String> doIDList = new ArrayList<>();
it1.seek("86.5000.470/do.".getBytes());
int total = 0;
while (it1.isValid() && total < 10) {
doIDList.add(new String(it1.key()));
total++;
it1.next();
}
it1.close();
RocksIterator it2 = db.newIterator(readOptions);
ArrayList<String> repoIDList = new ArrayList<>();
it2.seek("86.5000.470/doip.".getBytes());
total = 0;
while (it2.isValid() && total < 10) {
repoIDList.add(new String(it2.key()));
total++;
it2.next();
}
respMap.put("repoIDList", repoIDList);
respMap.put("doIDList", doIDList);
return respMap;
}
public Map<String, String> formData2Dic(String formData) {
Map<String, String> result = new HashMap<>();
if (formData == null || formData.trim().length() == 0) {
return result;
}
final String[] items = formData.split("&");
Arrays.stream(items).forEach(item -> {
final String[] keyAndVal = item.split("=");
if (keyAndVal.length == 2) {
try {
final String key = URLDecoder.decode(keyAndVal[0], "utf8");
final String val = URLDecoder.decode(keyAndVal[1], "utf8");
result.put(key, val);
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
}
}
});
return result;
}
static class HandleRecordCount {
int repoCount;
int doCount;
int userCount;
}
}

View File

@ -32,8 +32,8 @@ public class CMNode {
contracts = cons; contracts = cons;
contractVersion = version; contractVersion = version;
for (ContractDesp desp : cons) { for (ContractDesp desp : cons) {
KeyValueDBUtil.instance.setValue(NCTables.ContractMeta.toString(), desp.contractID, KeyValueDBUtil.instance.setValue(
desp.contractName); NCTables.ContractMeta.toString(), desp.contractID, desp.contractName);
} }
} }
@ -53,8 +53,7 @@ public class CMNode {
if (null != contracts) { if (null != contracts) {
for (ContractDesp desp : contracts) { for (ContractDesp desp : contracts) {
if (desp.contractID.equals(contractIDOrName) if (desp.contractID.equals(contractIDOrName)
|| desp.contractName.equals(contractIDOrName)) || desp.contractName.equals(contractIDOrName)) return true;
return true;
} }
} }
return false; return false;
@ -80,15 +79,14 @@ public class CMNode {
} }
try { try {
if (!connection.controller.isOpen()) { if (!connection.controller.isOpen()) {
LOGGER.info( LOGGER.info("node " + nodeName + "(" + pubKey.substring(0, 5) + ") may be offline!");
"node " + nodeName + "(" + pubKey.substring(0, 5) + ") may be offline!"); // System.out.println(
// System.out.println( // new SimpleDateFormat("yyyy-MM-dd HH:mm:ss")
// new SimpleDateFormat("yyyy-MM-dd HH:mm:ss") // .format(new Date(System.currentTimeMillis()))
// .format(new Date(System.currentTimeMillis())) // + "[ADSP][CMNode] isAlive : "
// + "[ADSP][CMNode] isAlive : " // + nodeName
// + nodeName // + " not open!"
// + " not open!" // + "\n");
// + "\n");
return doubleCheckAlive(); return doubleCheckAlive();
} else { } else {
return true; return true;
@ -118,8 +116,10 @@ public class CMNode {
LOGGER.debug("removeCIManager" + string); LOGGER.debug("removeCIManager" + string);
int start = this.cimanager.indexOf(string); int start = this.cimanager.indexOf(string);
if (start > 0) { if (start > 0) {
this.cimanager = this.cimanager.substring(0, start) this.cimanager =
.concat(this.cimanager.substring(start + 130)); this.cimanager
.substring(0, start)
.concat(this.cimanager.substring(start + 130));
} }
} }

View File

@ -1,50 +0,0 @@
package org.bdware.server.nodecenter;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import org.bdware.sc.bean.ContractDesp;
import java.util.HashSet;
import java.util.Set;
import java.util.TimerTask;
public class CheckAgentAliveTimer extends TimerTask {
private final String pubkey;
static Logger LOGGER = LogManager.getLogger(CheckAgentAliveTimer.class);
public CheckAgentAliveTimer(String pubKey) {
this.pubkey = pubKey;
}
@Override
public void run() {
try {
checkAlive();
} catch (Exception e) {
e.printStackTrace();
}
}
private void checkAlive() {
Set<String> toRemove = new HashSet<>();
CMNode info;
info = NodeCenterActions.nodeInfos.get(pubkey);
if (!info.checkAlive()) {
synchronized (info) {
if (null != info.contracts && !info.contracts.isEmpty()) {
for (ContractDesp cd : info.contracts) {
cd.setIsMaster(false);
// 注意 选举不通过NC的机制触发
LOGGER.info("checkAlive---- 设置节点 " + info.pubKey.substring(0, 5) + " 的合约 "
+ cd.contractID + " isMaster=" + false);
}
}
}
}
NodeCenterActions.nodeInfos.remove(pubkey);
try {
info.connection.controller.ctx.close();
} catch (Exception ignored) {
}
}
}

View File

@ -1,6 +1,6 @@
package org.bdware.server.nodecenter; package org.bdware.server.nodecenter;
import org.bdware.sc.conn.ResultCallback; import org.bdware.sc.conn.ResultCallback;
public interface ContractExecutor { public interface ContractExecutor {
public void execute(String requestID, ResultCallback rc, String req); public void execute(String requestID, ResultCallback rc, String req);

View File

@ -4,12 +4,12 @@ import java.util.HashMap;
import java.util.Map; import java.util.Map;
// NC //NC
public class ElectMasterTimeRecorder { public class ElectMasterTimeRecorder {
public static Long startElect; // NC开始选举 public static Long startElect; //NC开始选举
public static Long findNewMaster; // NC选出新master public static Long findNewMaster; //NC选出新master
public static String newMaster; public static String newMaster;
public static Long changeMasterFinish; // 新master在NC上更新路由信息 public static Long changeMasterFinish; //新master在NC上更新路由信息
public static Map nodeFindMasterCrash = new HashMap<String, Long>(); // nodeID,electMaster调用时间 public static Map nodeFindMasterCrash = new HashMap<String,Long>(); //nodeID,electMaster调用时间
} }

View File

@ -49,10 +49,13 @@ public class FileActions {
return ret != null && ret.equals("locked"); return ret != null && ret.equals("locked");
} }
@URIPath(method = org.bdware.server.http.HttpMethod.POST, value = {"/upload"}) @URIPath(
method = org.bdware.server.http.HttpMethod.POST,
value = {"/upload"})
public static void handleUploadRequest(ChannelHandlerContext ctx, FullHttpRequest request) { public static void handleUploadRequest(ChannelHandlerContext ctx, FullHttpRequest request) {
LOGGER.info("[FileActions] handleUploadRequest : "); // logger.info("[CMHttpHandler] handleUploadRequest : ");
// Upload method is POST // Upload method is POST
QueryStringDecoder decoderQuery = new QueryStringDecoder(request.uri()); QueryStringDecoder decoderQuery = new QueryStringDecoder(request.uri());
Map<String, List<String>> params = decoderQuery.parameters(); Map<String, List<String>> params = decoderQuery.parameters();
Map<String, String> transformedParam = new HashMap<>(); Map<String, String> transformedParam = new HashMap<>();
@ -63,12 +66,18 @@ public class FileActions {
} }
} }
if (!transformedParam.containsKey("fileName") || !transformedParam.containsKey("order") if (!transformedParam.containsKey("fileName")
|| !transformedParam.containsKey("count") || !transformedParam.containsKey("pubKey") || !transformedParam.containsKey("order")
|| !transformedParam.containsKey("count")
|| !transformedParam.containsKey("pubKey")
|| !transformedParam.containsKey("sign")) { || !transformedParam.containsKey("sign")) {
DefaultFullHttpResponse fullResponse = new DefaultFullHttpResponse( DefaultFullHttpResponse fullResponse =
request.protocolVersion(), OK, Unpooled.wrappedBuffer( new DefaultFullHttpResponse(
"{\"status\":\"false\",\"data\":\"Missing argument!\"}".getBytes())); request.protocolVersion(),
OK,
Unpooled.wrappedBuffer(
"{\"status\":\"false\",\"data\":\"Missing argument!\"}"
.getBytes()));
ChannelFuture f = ctx.write(fullResponse); ChannelFuture f = ctx.write(fullResponse);
f.addListener(ChannelFutureListener.CLOSE); f.addListener(ChannelFutureListener.CLOSE);
@ -76,8 +85,10 @@ public class FileActions {
} }
// 验签 // 验签
// HttpMethod method = request.method(); // HttpMethod method = request.method();
String uri = URLDecoder.decode(request.uri()).split("\\?")[1]; // http请求中规定签名必须是最后一个且公钥名必须为pubKey否则验签失败 String uri =
URLDecoder.decode(request.uri())
.split("\\?")[1]; // http请求中规定签名必须是最后一个且公钥名必须为pubKey否则验签失败
int index = uri.lastIndexOf('&'); int index = uri.lastIndexOf('&');
String str = uri.substring(0, index); String str = uri.substring(0, index);
@ -86,11 +97,12 @@ public class FileActions {
String sign = transformedParam.get("sign"); String sign = transformedParam.get("sign");
boolean verify = SM2Util.plainStrVerify(pubkey, str, sign); boolean verify = SM2Util.plainStrVerify(pubkey, str, sign);
LOGGER.info("[FileAction] upload http请求验签结果 : " + verify); LOGGER.info("[CMHttpHandler] upload http请求验签结果 : " + verify);
if (verify) { if (verify) {
// 查permission // 查permission
String ret = KeyValueDBUtil.instance.getValue(NCTables.NodeUser.toString(), pubkey); String ret = KeyValueDBUtil.instance.getValue(NCTables.NodeUser.toString(), pubkey);
if (ret != null && ret.length() > 0) { if (ret != null && ret.length() > 0) {
permission = 0x86000d41L | Role.compoundValue(ret.split(",")); permission = 0x86000d41L | Role.compoundValue(ret.split(","));
} else { } else {
@ -105,8 +117,9 @@ public class FileActions {
Method mm; Method mm;
Action a = null; Action a = null;
try { try {
mm = FileActions.class.getDeclaredMethod("uploadFile", JsonObject.class, mm =
ResultCallback.class); FileActions.class.getDeclaredMethod(
"uploadFile", JsonObject.class, ResultCallback.class);
a = mm.getAnnotation(Action.class); a = mm.getAnnotation(Action.class);
} catch (SecurityException | NoSuchMethodException e1) { } catch (SecurityException | NoSuchMethodException e1) {
// TODO Auto-generated catch block // TODO Auto-generated catch block
@ -136,17 +149,28 @@ public class FileActions {
status = "accept"; status = "accept";
} }
TimeDBUtil.instance.put(NCTables.NodeHttpLog.toString(), TimeDBUtil.instance.put(
"{\"action\":\"" + action + "\",\"pubKey\":\"" + transformedParam.get("pubKey") NCTables.NodeHttpLog.toString(),
+ "\",\"status\":\"" + status + "\",\"date\":" + System.currentTimeMillis() "{\"action\":\""
+ action
+ "\",\"pubKey\":\""
+ transformedParam.get("pubKey")
+ "\",\"status\":\""
+ status
+ "\",\"date\":"
+ System.currentTimeMillis()
+ "}"); + "}");
// logger.info("[CMHttpHandler] flag = " + flag + " flag2 = " + flag2); // logger.info("[CMHttpHandler] flag = " + flag + " flag2 = " + flag2);
if (!flag || !flag2) { if (!flag || !flag2) {
DefaultFullHttpResponse fullResponse = new DefaultFullHttpResponse( DefaultFullHttpResponse fullResponse =
request.protocolVersion(), OK, Unpooled.wrappedBuffer( new DefaultFullHttpResponse(
"{\"status\":\"false\",\"data\":\"Permission denied!\"}".getBytes())); request.protocolVersion(),
OK,
Unpooled.wrappedBuffer(
"{\"status\":\"false\",\"data\":\"Permission denied!\"}"
.getBytes()));
ChannelFuture f = ctx.write(fullResponse); ChannelFuture f = ctx.write(fullResponse);
f.addListener(ChannelFutureListener.CLOSE); f.addListener(ChannelFutureListener.CLOSE);
@ -169,24 +193,27 @@ public class FileActions {
} }
File target = new File(dir, fileName); File target = new File(dir, fileName);
if (fileName.contains("..")) { if (fileName.contains("..")) {
DefaultFullHttpResponse fullResponse = new DefaultFullHttpResponse( DefaultFullHttpResponse fullResponse =
request.protocolVersion(), OK, Unpooled.wrappedBuffer( new DefaultFullHttpResponse(
"{\"status\":\"false\",\"data\":\"FileName illegal!\"}".getBytes())); request.protocolVersion(),
OK,
Unpooled.wrappedBuffer(
"{\"status\":\"false\",\"data\":\"FileName illegal!\"}"
.getBytes()));
ChannelFuture f = ctx.write(fullResponse); ChannelFuture f = ctx.write(fullResponse);
f.addListener(ChannelFutureListener.CLOSE); f.addListener(ChannelFutureListener.CLOSE);
return; return;
} }
// LOGGER.info(request.refCnt()); // LOGGER.info(request.refCnt());
// httpDecoder.offer(request); // httpDecoder.offer(request);
// LOGGER.info(request.refCnt()); // LOGGER.info(request.refCnt());
FileOutputStream fout; FileOutputStream fout;
if (order == 0) { if (order == 0) {
try { try {
LOGGER.debug("Path:" + target.getAbsolutePath()); LOGGER.debug("Path:" + target.getAbsolutePath());
if (!target.getParentFile().exists()) if (!target.getParentFile().exists()) target.getParentFile().mkdirs();
target.getParentFile().mkdirs();
fout = new FileOutputStream(target, false); fout = new FileOutputStream(target, false);
fileMap.put(target.getAbsolutePath(), fout); fileMap.put(target.getAbsolutePath(), fout);
} catch (FileNotFoundException e) { } catch (FileNotFoundException e) {
@ -207,21 +234,22 @@ public class FileActions {
} }
fileMap.remove(target.getAbsolutePath()); fileMap.remove(target.getAbsolutePath());
updateTime.remove(target.getAbsolutePath()); updateTime.remove(target.getAbsolutePath());
// String doi = unzipIfYpk(target, dir); // String doi = unzipIfYpk(target, dir);
String doi = null; String doi = null;
if (null != doi) { if (null != doi) {
retStr = retStr.replaceFirst("null", doi); retStr = retStr.replaceFirst("null", doi);
} }
} }
DefaultFullHttpResponse fullResponse = new DefaultFullHttpResponse( DefaultFullHttpResponse fullResponse =
request.protocolVersion(), OK, Unpooled.wrappedBuffer(retStr.getBytes())); new DefaultFullHttpResponse(
request.protocolVersion(), OK, Unpooled.wrappedBuffer(retStr.getBytes()));
fullResponse.headers().add("Access-Control-Allow-Origin", "*"); fullResponse.headers().add("Access-Control-Allow-Origin", "*");
ChannelFuture f = ctx.write(fullResponse); ChannelFuture f = ctx.write(fullResponse);
f.addListener(ChannelFutureListener.CLOSE); f.addListener(ChannelFutureListener.CLOSE);
} }
private static void writeChunk(ChannelHandlerContext ctx, HttpPostRequestDecoder httpDecoder, private static void writeChunk(
File file) { ChannelHandlerContext ctx, HttpPostRequestDecoder httpDecoder, File file) {
try { try {
if (!file.exists()) { if (!file.exists()) {
file.createNewFile(); file.createNewFile();
@ -248,14 +276,19 @@ public class FileActions {
@URIPath(method = HttpMethod.OPTIONS) @URIPath(method = HttpMethod.OPTIONS)
public static void crossOrigin(ChannelHandlerContext ctx, FullHttpRequest request) { public static void crossOrigin(ChannelHandlerContext ctx, FullHttpRequest request) {
DefaultFullHttpResponse fullResponse = new DefaultFullHttpResponse( DefaultFullHttpResponse fullResponse =
request.protocolVersion(), OK, Unpooled.wrappedBuffer("success".getBytes())); new DefaultFullHttpResponse(
request.protocolVersion(),
OK,
Unpooled.wrappedBuffer("success".getBytes()));
fullResponse.headers().remove("Access-Control-Allow-Origin"); fullResponse.headers().remove("Access-Control-Allow-Origin");
fullResponse.headers().remove("Access-Control-Allow-Headers"); fullResponse.headers().remove("Access-Control-Allow-Headers");
fullResponse.headers().add("Access-Control-Allow-Origin", "*"); fullResponse.headers().add("Access-Control-Allow-Origin", "*");
fullResponse.headers().add("Access-Control-Allow-Headers", fullResponse
"Content-Type, Cookie, Accept-Encoding, User-Agent, Host, Referer, " .headers()
+ "X-Requested-With, Accept, Accept-Language, Cache-Control, Connection"); .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); ChannelFuture f = ctx.write(fullResponse);
f.addListener(ChannelFutureListener.CLOSE); f.addListener(ChannelFutureListener.CLOSE);
LOGGER.info("[OOOOOOOOption] received!"); LOGGER.info("[OOOOOOOOption] received!");
@ -307,8 +340,10 @@ public class FileActions {
// 文本文件 // 文本文件
if (!path.contains("..") && isTextFile(path)) { if (!path.contains("..") && isTextFile(path)) {
LOGGER.debug("[FileActions] 上传文本文件类型 : "); LOGGER.debug("[FileActions] 上传文本文件类型 : ");
BufferedWriter bw = new BufferedWriter( BufferedWriter bw =
new FileWriter(target.getAbsolutePath() + "/" + fileName, isAppend)); new BufferedWriter(
new FileWriter(
target.getAbsolutePath() + "/" + fileName, isAppend));
bw.write(content); bw.write(content);
bw.close(); bw.close();
} else { // 其他类型文件 } else { // 其他类型文件
@ -393,7 +428,10 @@ public class FileActions {
File f = new File(parPath + "/" + oldFile); File f = new File(parPath + "/" + oldFile);
if (!oldFile.contains("..") && f.exists()) { if (!oldFile.contains("..") && f.exists()) {
LOGGER.info( LOGGER.info(
"[FileController] delete:" + f.getAbsolutePath() + " exists:" + f.exists()); "[FileController] delete:"
+ f.getAbsolutePath()
+ " exists:"
+ f.exists());
f.delete(); f.delete();
} }
response.data = "success"; response.data = "success";

View File

@ -7,6 +7,7 @@ import org.apache.logging.log4j.Logger;
import org.bdware.sc.conn.ResultCallback; import org.bdware.sc.conn.ResultCallback;
import org.bdware.sc.db.KeyValueDBUtil; import org.bdware.sc.db.KeyValueDBUtil;
import org.bdware.sc.db.MultiIndexTimeDBUtilIntf; import org.bdware.sc.db.MultiIndexTimeDBUtilIntf;
import org.bdware.sc.util.JsonUtil;
import org.bdware.server.NodeCenterServer; import org.bdware.server.NodeCenterServer;
import org.bdware.server.action.Action; import org.bdware.server.action.Action;
@ -32,7 +33,10 @@ public class LogActions {
resultCallback.onResult(jsonResult); resultCallback.onResult(jsonResult);
} }
private void queryInternal(String actResp, MultiIndexTimeDBUtilIntf db, JsonObject json, private void queryInternal(
String actResp,
MultiIndexTimeDBUtilIntf db,
JsonObject json,
ResultCallback resultCallback) { ResultCallback resultCallback) {
long start = System.currentTimeMillis(); long start = System.currentTimeMillis();
if (!json.has("start")) { if (!json.has("start")) {
@ -44,25 +48,26 @@ public class LogActions {
if (json.has("end")) { if (json.has("end")) {
endTime = json.get("end").getAsLong(); endTime = json.get("end").getAsLong();
} }
String[] category = new String[] {null}; String[] category = new String[]{null};
if (json.has("category")) { if (json.has("category")) {
category = json.get("category").getAsString().split(","); category = json.get("category").getAsString().split(",");
} }
Map<String, Object> data = new HashMap<>(); Map<String, Object> data = new HashMap<>();
for (String str : category) { for (String str : category) {
List<JsonObject> array = db.queryByDateAsJson(str, startTime, endTime); List<JsonObject> array = db.queryByDateAsJson(str, startTime, endTime);
if (str == null) if (str == null) data.put("primary", array);
data.put("primary", array); else data.put(str, array);
else
data.put(str, array);
} }
simpleReply(resultCallback, actResp, data); simpleReply(resultCallback, actResp, data);
long end = System.currentTimeMillis(); long end = System.currentTimeMillis();
LOGGER.debug("[queryInternal:time]" + (end - start)); LOGGER.debug("[queryInternal:time]" + (end - start));
} }
private void countLogByCategoryInternal(String actResp, MultiIndexTimeDBUtilIntf db, private void countLogByCategoryInternal(
JsonObject json, ResultCallback resultCallback) { String actResp,
MultiIndexTimeDBUtilIntf db,
JsonObject json,
ResultCallback resultCallback) {
if (!json.has("start")) { if (!json.has("start")) {
simpleReply(resultCallback, actResp, new ArrayList<>()); simpleReply(resultCallback, actResp, new ArrayList<>());
return; return;
@ -73,17 +78,15 @@ public class LogActions {
endTime = json.get("end").getAsLong(); endTime = json.get("end").getAsLong();
} }
long interval = json.get("interval").getAsLong(); long interval = json.get("interval").getAsLong();
String[] category = new String[] {null}; String[] category = new String[]{null};
if (json.has("category")) { if (json.has("category")) {
category = json.get("category").getAsString().split(","); category = json.get("category").getAsString().split(",");
} }
JsonObject data = new JsonObject(); JsonObject data = new JsonObject();
for (String str : category) { for (String str : category) {
JsonArray array = db.countInInterval(str, startTime, interval, endTime); JsonArray array = db.countInInterval(str, startTime, interval, endTime);
if (str == null) if (str == null) data.add("primary", array);
data.add("primary", array); else data.add(str, array);
else
data.add(str, array);
} }
simpleReply(resultCallback, actResp, data); simpleReply(resultCallback, actResp, data);
} }
@ -95,8 +98,8 @@ public class LogActions {
@Action(userPermission = 1 << 8, async = true) @Action(userPermission = 1 << 8, async = true)
public void countActionLogByCategory(JsonObject json, ResultCallback resultCallback) { public void countActionLogByCategory(JsonObject json, ResultCallback resultCallback) {
countLogByCategoryInternal("onCountActionLogByCategory", NodeCenterServer.nodeHttpLogDB, countLogByCategoryInternal(
json, resultCallback); "onCountActionLogByCategory", NodeCenterServer.nodeHttpLogDB, json, resultCallback);
} }
@Action(userPermission = 1 << 8, async = true) @Action(userPermission = 1 << 8, async = true)
@ -106,8 +109,8 @@ public class LogActions {
@Action(userPermission = 1 << 8, async = true) @Action(userPermission = 1 << 8, async = true)
public void countCMLogByCategory(JsonObject json, ResultCallback resultCallback) { public void countCMLogByCategory(JsonObject json, ResultCallback resultCallback) {
countLogByCategoryInternal("onCountCMLogByCategory", NodeCenterServer.nodeTcpLogDB, json, countLogByCategoryInternal(
resultCallback); "onCountCMLogByCategory", NodeCenterServer.nodeTcpLogDB, json, resultCallback);
} }
@Action(userPermission = 1 << 9) @Action(userPermission = 1 << 9)
@ -127,7 +130,7 @@ public class LogActions {
@Action(userPermission = 1 << 9, async = true) @Action(userPermission = 1 << 9, async = true)
public void listNodes(JsonObject json, ResultCallback resultCallback) { public void listNodes(JsonObject json, ResultCallback resultCallback) {
long start = System.currentTimeMillis(); long start = System.currentTimeMillis();
final String pubKey = managerAction.getPubKey(json); final String pubKey = managerAction.pubKey;
LOGGER.debug("[listNodes] managerAction.pubKey " + pubKey); LOGGER.debug("[listNodes] managerAction.pubKey " + pubKey);
Map<String, CMNode> nodeinfos = NodeCenterActions.nodeInfos; // 所有在线节点? Map<String, CMNode> nodeinfos = NodeCenterActions.nodeInfos; // 所有在线节点?
final Map<String, CMNode> cinodeinfos = new HashMap<>(); final Map<String, CMNode> cinodeinfos = new HashMap<>();
@ -135,7 +138,8 @@ public class LogActions {
List<CMNode> onlineNodes = new ArrayList<>(); List<CMNode> onlineNodes = new ArrayList<>();
Map<String, Object> ret = new HashMap<>(); Map<String, Object> ret = new HashMap<>();
if (KeyValueDBUtil.instance.getValue(NCTables.ConfigDB.toString(), "__CenterManager__") if (KeyValueDBUtil.instance
.getValue(NCTables.ConfigDB.toString(), "__CenterManager__")
.contains(pubKey)) { .contains(pubKey)) {
LOGGER.debug("is center manager"); LOGGER.debug("is center manager");
LOGGER.debug("dbnodes " + dbnodes.toString()); LOGGER.debug("dbnodes " + dbnodes.toString());

View File

@ -11,25 +11,25 @@ import java.util.concurrent.TimeUnit;
public class MasterActions { public class MasterActions {
private static final Logger LOGGER = LogManager.getLogger(MasterActions.class); private static final Logger LOGGER = LogManager.getLogger(MasterActions.class);
// TODO 定期清缓存 // TODO 定期清缓存
public static Map<String, RequestCache> requestCache = new ConcurrentHashMap<>(); // key is public static Map<String, RequestCache> requestCache =
// contractID,only new ConcurrentHashMap<>(); // key is contractID,only for requestAll type contract
// for
// requestAll
// type
// contract
static { static {
NodeCenterServer.scheduledThreadPool.scheduleWithFixedDelay(() -> { NodeCenterServer.scheduledThreadPool.scheduleWithFixedDelay(
boolean flag = clearCache(); () -> {
if (flag) { boolean flag = clearCache();
try { if (flag) {
Thread.sleep(10000L); try {
} catch (InterruptedException e) { Thread.sleep(10000L);
LOGGER.error("sleeping is interrupted! " + e.getMessage()); } catch (InterruptedException e) {
} LOGGER.error("sleeping is interrupted! " + e.getMessage());
} }
}, 0, 0, TimeUnit.SECONDS); }
},
0,
0,
TimeUnit.SECONDS);
} }
public NodeCenterFrameHandler controller; public NodeCenterFrameHandler controller;
@ -39,184 +39,213 @@ public class MasterActions {
} }
// judge the just online node whwther need to restart contracts,send the contracts'info // judge the just online node whwther need to restart contracts,send the contracts'info
/* /* public static void restartContracts(String nodePubKey){
* public static void restartContracts(String nodePubKey){ if(!NodeCenterActions.recoverMap.containsKey(nodePubKey)){
* if(!NodeCenterActions.recoverMap.containsKey(nodePubKey)){ return; } return;
* }
* System.out.println("开始恢复节点" + NodeCenterActions.nodeinfos.get(nodePubKey).nodeName);
*
*
* // 恢复该节点的每一个集群运行的合约 for (ContractRecord record :
* NodeCenterActions.recoverMap.get(nodePubKey).values()) { String contractID =
* record.contractID; if (record.recoverFlag != RecoverFlag.ToRecover) continue;
*
* Map<String, String> req = new HashMap<String, String>(); req.put("action",
* "queryUnitStatus"); req.put("contractID", contractID); CMNode cmNode =
* NodeCenterActions.nodeinfos.get(nodePubKey);
* cmNode.connection.controller.sendMsg(gson.toJson(req)); } }
*/
/* System.out.println("开始恢复节点" + NodeCenterActions.nodeinfos.get(nodePubKey).nodeName);
* @Action(async = true) public void onQueryUnitStatus(Map<String, String> args, final
* ResultCallback rc) { String mode = args.get("mode"); String nodeID = args.get("nodeID");
* String contractID = args.get("contractID"); ContractRecord record = // 恢复该节点的每一个集群运行的合约
* NodeCenterActions.recoverMap.get(nodeID).get(contractID); logger.debug("节点" + for (ContractRecord record : NodeCenterActions.recoverMap.get(nodePubKey).values()) {
* NodeCenterActions.nodeinfos.get(args.get("nodeID")).nodeName + "崩溃前模式为" + mode); String contractID = record.contractID;
* if(mode.equals(ContractUnitStatus.CommonMode.toString())){ if (record.recoverFlag != RecoverFlag.ToRecover)
* restartFromCommonMode(nodeID,record); }else continue;
* if(mode.equals(ContractUnitStatus.StableMode.toString())){
* restartFromStableMode(nodeID,record); } } Map<String, String> req = new HashMap<String, String>();
*/ req.put("action", "queryUnitStatus");
req.put("contractID", contractID);
CMNode cmNode = NodeCenterActions.nodeinfos.get(nodePubKey);
cmNode.connection.controller.sendMsg(gson.toJson(req));
}
}*/
/* @Action(async = true)
public void onQueryUnitStatus(Map<String, String> args, final ResultCallback rc) {
String mode = args.get("mode");
String nodeID = args.get("nodeID");
String contractID = args.get("contractID");
ContractRecord record = NodeCenterActions.recoverMap.get(nodeID).get(contractID);
logger.debug("节点" + NodeCenterActions.nodeinfos.get(args.get("nodeID")).nodeName + "崩溃前模式为" + mode);
if(mode.equals(ContractUnitStatus.CommonMode.toString())){
restartFromCommonMode(nodeID,record);
}else if(mode.equals(ContractUnitStatus.StableMode.toString())){
restartFromStableMode(nodeID,record);
}
}*/
// 当StableMode的节点的lastExeSeq和集群相差超过10时通过CommonNode的恢复方式恢复 // 当StableMode的节点的lastExeSeq和集群相差超过10时通过CommonNode的恢复方式恢复
/* /* @Action(async = true)
* @Action(async = true) public void restartByCommonNode(Map<String, String> args, final public void restartByCommonNode(Map<String, String> args, final ResultCallback rc){
* ResultCallback rc){ String nodeID = args.get("nodeID"); String contractID = String nodeID = args.get("nodeID");
* args.get("contractID"); ContractRecord record = String contractID = args.get("contractID");
* NodeCenterActions.recoverMap.get(nodeID).get(contractID); ContractRecord record = NodeCenterActions.recoverMap.get(nodeID).get(contractID);
* restartFromCommonMode(nodeID,record); } restartFromCommonMode(nodeID,record);
*/ }*/
/* /*
* public static void restartFromCommonMode(String nodePubKey,ContractRecord record){ public static void restartFromCommonMode(String nodePubKey,ContractRecord record){
* logger.debug("从CommonMode中恢复:"); logger.debug("从CommonMode中恢复:");
*
* String contractID = record.contractID; String contractID = record.contractID;
*
* record.recoverFlag = RecoverFlag.Recovering; //先发消息让恢复节点的该合约收到消息后只加入队列不dealRequests record.recoverFlag = RecoverFlag.Recovering;
* Map<String, String> request = new HashMap<>(); request.put("action", "setRecovering"); //先发消息让恢复节点的该合约收到消息后只加入队列不dealRequests
* request.put("contractID",contractID); CMNode node = Map<String, String> request = new HashMap<>();
* NodeCenterActions.nodeinfos.get(nodePubKey); request.put("action", "setRecovering");
* node.connection.controller.sendMsg(gson.toJson(request)); request.put("contractID",contractID);
* CMNode node = NodeCenterActions.nodeinfos.get(nodePubKey);
* //System.out.println("第一步 : [NodeCeterActions] restartContracts 开始处理合约 contractID=" + node.connection.controller.sendMsg(gson.toJson(request));
* contractID);
* //System.out.println("第一步 : [NodeCeterActions] restartContracts 开始处理合约 contractID=" + contractID);
* if (NodeCenterActions.contractID2Members.containsKey(contractID)) {
* if (NodeCenterActions.contractID2Members.containsKey(contractID)) {
* // 在nodeinfos中找节点该节点的pubKey在pubKeys中 MultiPointContractInfo info =
* NodeCenterActions.contractID2Members.get(contractID); CMNode cmNode = null; for (int i = 0; i // 在nodeinfos中找节点该节点的pubKey在pubKeys中
* < info.members.size(); i++) { int size = info.members.size(); String tempNodeID = MultiPointContractInfo info = NodeCenterActions.contractID2Members.get(contractID);
* info.members.get(record.order.incrementAndGet() % size); CMNode cmNode = null;
* for (int i = 0; i < info.members.size(); i++) {
* if(NodeCenterActions.nodeinfos.containsKey(tempNodeID)) cmNode = int size = info.members.size();
* NodeCenterActions.nodeinfos.get(tempNodeID); else continue; String tempNodeID = info.members.get(record.order.incrementAndGet() % size);
*
* //System.out.println("查询节点 " + cmNode.nodeName); if(NodeCenterActions.nodeinfos.containsKey(tempNodeID))
* cmNode = NodeCenterActions.nodeinfos.get(tempNodeID);
* if (cmNode != null && !cmNode.pubKey.equals(nodePubKey)) { else continue;
* //System.out.println("第二步 : [NodeCenterActions] 找到一个依赖恢复节点,其节点名为 " + cmNode.nodeName);
* //System.out.println("查询节点 " + cmNode.nodeName);
* Map<String, String> req = new HashMap<String, String>(); req.put("action",
* "dumpCurrentState"); req.put("contractID", contractID); req.put("targetNodePubkey", if (cmNode != null && !cmNode.pubKey.equals(nodePubKey)) {
* nodePubKey); //System.out.println("第二步 : [NodeCenterActions] 找到一个依赖恢复节点,其节点名为 " + cmNode.nodeName);
*
* // NC向该节点发送请求让其存储自身当前状态并发给NC cmNode.connection.controller.sendMsg(gson.toJson(req)); Map<String, String> req = new HashMap<String, String>();
* req.put("action", "dumpCurrentState");
* return; } } req.put("contractID", contractID);
* req.put("targetNodePubkey", nodePubKey);
* if(cmNode == null){ logger.debug("[NodeCenterActions] Can't find a recover rely node!"); } }
* } // NC向该节点发送请求让其存储自身当前状态并发给NC
*/ cmNode.connection.controller.sendMsg(gson.toJson(req));
return;
}
}
if(cmNode == null){
logger.debug("[NodeCenterActions] Can't find a recover rely node!");
}
}
}
*/
// TODO // TODO
/* /* public static void restartFromStableMode(String nodePubkey,ContractRecord record){
* public static void restartFromStableMode(String nodePubkey,ContractRecord record){ logger.debug("从StableMode中恢复:");
* logger.debug("从StableMode中恢复:");
*
* String contractID = record.contractID; record.recoverFlag = RecoverFlag.Recovering;
* //先发消息让恢复节点的该合约收到消息后只加入队列不dealRequests Map<String, String> request = new HashMap<>();
* request.put("action", "setRecovering"); request.put("contractID",contractID);
* request.put("mode", ContractUnitStatus.StableMode.toString()); int lastExeSeq =
* NodeCenterActions.contractID2Members.get(contractID).ai.get() - 1;
* request.put("lastExeSeq",lastExeSeq + ""); CMNode node =
* NodeCenterActions.nodeinfos.get(nodePubkey);
* node.connection.controller.sendMsg(gson.toJson(request)); }
*/
/* String contractID = record.contractID;
* public static void unitModeCheck(String contractID){ MultiPointContractInfo mpci = record.recoverFlag = RecoverFlag.Recovering;
* NodeCenterActions.contractID2Members.get(contractID); int total = 0,online = 0; for(String //先发消息让恢复节点的该合约收到消息后只加入队列不dealRequests
* nodeId : mpci.members){ if(NodeCenterActions.nodeinfos.containsKey(nodeId)){ online++; } Map<String, String> request = new HashMap<>();
* total++; } request.put("action", "setRecovering");
* request.put("contractID",contractID);
* logger.debug("合约" + contractID + "的集群,上线节点有" + online + "个,总共节点有" + total + request.put("mode", ContractUnitStatus.StableMode.toString());
* "个. Math.ceil(total / 2)=" + Math.ceil((double)total / 2) + int lastExeSeq = NodeCenterActions.contractID2Members.get(contractID).ai.get() - 1;
* " online > Math.ceil(total / 2)" + (online > Math.ceil(total / 2)) + " mpci.unitStatus=" + request.put("lastExeSeq",lastExeSeq + "");
* mpci.unitStatus); if(online > Math.ceil((double)total / 2) && mpci.unitStatus == CMNode node = NodeCenterActions.nodeinfos.get(nodePubkey);
* ContractUnitStatus.StableMode){ logger.debug("合约" + contractID + "的集群更改模式为" + node.connection.controller.sendMsg(gson.toJson(request));
* ContractUnitStatus.CommonMode.toString()); }*/
*
* Map<String, String> req = new HashMap<String, String>(); req.put("action",
* "changeUnitStatus"); req.put("contractID", contractID);
* req.put("mode",ContractUnitStatus.CommonMode.toString()); for(String nodeId : mpci.members){
* if(NodeCenterActions.nodeinfos.containsKey(nodeId)){ CMNode cmNode =
* NodeCenterActions.nodeinfos.get(nodeId); logger.debug("发消息给节点 " + cmNode.nodeName + " 设置合约" +
* contractID + "的集群模式为CommonMode"); cmNode.connection.controller.sendMsg(gson.toJson(req)); } }
*
* mpci.unitStatus = ContractUnitStatus.CommonMode; }else if(online <= Math.ceil((double)total /
* 2) && mpci.unitStatus == ContractUnitStatus.CommonMode){ logger.debug("合约" + contractID +
* "的集群更改模式为" + ContractUnitStatus.StableMode.toString());
*
* Map<String, String> req = new HashMap<String, String>(); req.put("action",
* "changeUnitStatus"); req.put("contractID", contractID);
* req.put("mode",ContractUnitStatus.StableMode.toString()); for(String nodeId : mpci.members){
* if(NodeCenterActions.nodeinfos.containsKey(nodeId)){ CMNode cmNode =
* NodeCenterActions.nodeinfos.get(nodeId); Map<String,String> map =
* NodeCenterActions.recoverMap.get(nodeId).get(contractID).members;
* req.put("membersStr",JsonUtil.toJson(map)); //ContractRecord's members logger.debug("发消息给节点 "
* + cmNode.nodeName + " 设置合约" + contractID + "的集群模式为StableMode");
* cmNode.connection.controller.sendMsg(gson.toJson(req)); } }
*
* mpci.unitStatus = ContractUnitStatus.StableMode;
*
* //将ContractRecord中members发给集群中节点
*
* } }
*/
/* /* public static void unitModeCheck(String contractID){
* @Action(async = true) public void recoverFinish(Map<String, String> args, final MultiPointContractInfo mpci = NodeCenterActions.contractID2Members.get(contractID);
* ResultCallback rc) { ContractRecord cr = int total = 0,online = 0;
* NodeCenterActions.recoverMap.get(args.get("nodeID")).get(args.get("contractID")); for(String nodeId : mpci.members){
* logger.debug("节点" + NodeCenterActions.nodeinfos.get(args.get("nodeID")).nodeName + "恢复完成!"); if(NodeCenterActions.nodeinfos.containsKey(nodeId)){
* if(cr.recoverFlag == RecoverFlag.Recovering) cr.recoverFlag = RecoverFlag.Fine; online++;
* }
* logger.debug("恢复完成,需要检查合约" + args.get("contractID") + "的集群运行模式"); total++;
* unitModeCheck(args.get("contractID")); } }
*/
logger.debug("合约" + contractID + "的集群,上线节点有" + online + "个,总共节点有" + total + "个. Math.ceil(total / 2)=" + Math.ceil((double)total / 2) + " online > Math.ceil(total / 2)" + (online > Math.ceil(total / 2)) + " mpci.unitStatus=" + mpci.unitStatus);
if(online > Math.ceil((double)total / 2) && mpci.unitStatus == ContractUnitStatus.StableMode){
logger.debug("合约" + contractID + "的集群更改模式为" + ContractUnitStatus.CommonMode.toString());
Map<String, String> req = new HashMap<String, String>();
req.put("action", "changeUnitStatus");
req.put("contractID", contractID);
req.put("mode",ContractUnitStatus.CommonMode.toString());
for(String nodeId : mpci.members){
if(NodeCenterActions.nodeinfos.containsKey(nodeId)){
CMNode cmNode = NodeCenterActions.nodeinfos.get(nodeId);
logger.debug("发消息给节点 " + cmNode.nodeName + " 设置合约" + contractID + "的集群模式为CommonMode");
cmNode.connection.controller.sendMsg(gson.toJson(req));
}
}
mpci.unitStatus = ContractUnitStatus.CommonMode;
}else if(online <= Math.ceil((double)total / 2) && mpci.unitStatus == ContractUnitStatus.CommonMode){
logger.debug("合约" + contractID + "的集群更改模式为" + ContractUnitStatus.StableMode.toString());
Map<String, String> req = new HashMap<String, String>();
req.put("action", "changeUnitStatus");
req.put("contractID", contractID);
req.put("mode",ContractUnitStatus.StableMode.toString());
for(String nodeId : mpci.members){
if(NodeCenterActions.nodeinfos.containsKey(nodeId)){
CMNode cmNode = NodeCenterActions.nodeinfos.get(nodeId);
Map<String,String> map = NodeCenterActions.recoverMap.get(nodeId).get(contractID).members;
req.put("membersStr",JsonUtil.toJson(map)); //ContractRecord's members
logger.debug("发消息给节点 " + cmNode.nodeName + " 设置合约" + contractID + "的集群模式为StableMode");
cmNode.connection.controller.sendMsg(gson.toJson(req));
}
}
mpci.unitStatus = ContractUnitStatus.StableMode;
//将ContractRecord中members发给集群中节点
}
}*/
/* @Action(async = true)
public void recoverFinish(Map<String, String> args, final ResultCallback rc) {
ContractRecord cr = NodeCenterActions.recoverMap.get(args.get("nodeID")).get(args.get("contractID"));
logger.debug("节点" + NodeCenterActions.nodeinfos.get(args.get("nodeID")).nodeName + "恢复完成!");
if(cr.recoverFlag == RecoverFlag.Recovering)
cr.recoverFlag = RecoverFlag.Fine;
logger.debug("恢复完成,需要检查合约" + args.get("contractID") + "的集群运行模式");
unitModeCheck(args.get("contractID"));
}*/
static boolean clearCache() { static boolean clearCache() {
if (requestCache.isEmpty()) if (requestCache.isEmpty()) return true;
return true;
// final long time = System.currentTimeMillis() - 60000L; //60s // final long time = System.currentTimeMillis() - 60000L; //60s
// requestCache.entrySet() // requestCache.entrySet()
// .removeIf( // .removeIf(
// entry -> { // entry -> {
// RequestCache cache = entry.getValue(); // RequestCache cache = entry.getValue();
// if (cache == null) return true; // if (cache == null) return true;
// return cache.getTime() < time; // return cache.getTime() < time;
// }); // });
// //
// return false; // return false;
// 对每个合约只保存最近RESERVED个请求 // 对每个合约只保存最近RESERVED个请求
// for(RequestCache rc : requestCache.values()){ // for(RequestCache rc : requestCache.values()){
// int delete = rc.size() - RequestCache.RESERVED,count = 0; // int delete = rc.size() - RequestCache.RESERVED,count = 0;
// if(delete > 0){ // if(delete > 0){
// synchronized (rc){ // synchronized (rc){
// for(Iterator<Integer> iterator = rc.requests.keySet().iterator(); // for(Iterator<Integer> iterator = rc.requests.keySet().iterator();
// iterator.hasNext(); ) { // iterator.hasNext(); ) {
// Integer key = iterator.next(); // Integer key = iterator.next();
// if(count < delete){ // if(count < delete){
// iterator.remove(); // iterator.remove();
// count++; // count++;
// } // }
// } // }
// } // }
// } // }
// } // }
return false; return false;
} }
@ -224,8 +253,7 @@ public class MasterActions {
static RequestCache getCache(String contractID) { static RequestCache getCache(String contractID) {
if (contractID != null) { if (contractID != null) {
RequestCache cache = requestCache.get(contractID); RequestCache cache = requestCache.get(contractID);
if (cache != null) if (cache != null) return cache;
return cache;
else { else {
LOGGER.debug("[NodeCenterActions] create requestcache:" + contractID); LOGGER.debug("[NodeCenterActions] create requestcache:" + contractID);
RequestCache reqc = new RequestCache(); RequestCache reqc = new RequestCache();
@ -236,17 +264,26 @@ public class MasterActions {
return null; return null;
} }
/* /* @Action(async = true)
* @Action(async = true) public void sendCachedRequests(Map<String, String> args, final public void sendCachedRequests(Map<String, String> args, final ResultCallback rc) {
* ResultCallback rc) { String contractID = args.get("contractID"); int start = String contractID = args.get("contractID");
* Integer.parseInt(args.get("start")); int end = Integer.parseInt(args.get("end")); int start = Integer.parseInt(args.get("start"));
* int end = Integer.parseInt(args.get("end"));
* RequestCache cache = getCache(contractID); for(int i = start + 1;i < end;i++){ if(cache ==
* null || !cache.containsKey(i)){ //this node crash String nodeID = args.get("nodeID"); RequestCache cache = getCache(contractID);
* MasterActions.restartContracts(nodeID); } JsonObject jo = cache.get(i); if(jo == null){ for(int i = start + 1;i < end;i++){
* logger.debug("在NC中第 " + i + "个请求已经被清,无法发给恢复节点!"); }else if(cache == null || !cache.containsKey(i)){
* controller.sendMsg(JsonUtil.toJson(jo)); //this node crash
* String nodeID = args.get("nodeID");
* logger.debug("NC发送第 " + i + " " + jo.get("seq").getAsString() + " 个请求给Node"); } } MasterActions.restartContracts(nodeID);
*/ }
JsonObject jo = cache.get(i);
if(jo == null){
logger.debug("在NC中第 " + i + "个请求已经被清,无法发给恢复节点!");
}else
controller.sendMsg(JsonUtil.toJson(jo));
logger.debug("NC发送第 " + i + " " + jo.get("seq").getAsString() + " 个请求给Node");
}
}*/
} }

View File

@ -28,7 +28,11 @@ import org.bdware.server.nodecenter.searchresult.ContractMeta;
import org.bdware.server.nodecenter.searchresult.ResultModel; import org.bdware.server.nodecenter.searchresult.ResultModel;
import org.wltea.analyzer.lucene.IKAnalyzer; import org.wltea.analyzer.lucene.IKAnalyzer;
import java.io.*; import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.IOException;
import java.io.PrintStream;
import java.io.InputStreamReader;
import java.nio.charset.StandardCharsets; import java.nio.charset.StandardCharsets;
import java.nio.file.Paths; import java.nio.file.Paths;
import java.util.ArrayList; import java.util.ArrayList;
@ -49,9 +53,9 @@ public class MetaIndexAction { // public static IndexWriter indexWriter;
public static Integer page; public static Integer page;
public static boolean isEmpty = false; public static boolean isEmpty = false;
public static NodeCenterFrameHandler controller; public static NodeCenterFrameHandler controller;
// public MetaIndexAction(NodeCenterFrameHandler nodeCenterFrameHandler) { // public MetaIndexAction(NodeCenterFrameHandler nodeCenterFrameHandler) {
// controller = nodeCenterFrameHandler; // controller = nodeCenterFrameHandler;
// } // }
private static IndexWriter indexWriter; private static IndexWriter indexWriter;
static { static {
@ -90,8 +94,7 @@ public class MetaIndexAction { // public static IndexWriter indexWriter;
Query query = new TermQuery(new Term("contractID", thisDesp.contractID)); Query query = new TermQuery(new Term("contractID", thisDesp.contractID));
TopDocs docs = indexSearcher.search(query, 10); TopDocs docs = indexSearcher.search(query, 10);
LOGGER.debug(docs.scoreDocs); LOGGER.debug(docs.scoreDocs);
if (null != thisDesp.contractName if (null != thisDesp.contractName && (docs.scoreDocs == null || docs.scoreDocs.length == 0)) {
&& (docs.scoreDocs == null || docs.scoreDocs.length == 0)) {
req.addProperty("action", "requestReadMe"); req.addProperty("action", "requestReadMe");
req.addProperty("contractID", thisDesp.contractID); req.addProperty("contractID", thisDesp.contractID);
rc.onResult(req); rc.onResult(req);
@ -102,9 +105,9 @@ public class MetaIndexAction { // public static IndexWriter indexWriter;
LOGGER.warn("getting index failed! " + e.getMessage()); LOGGER.warn("getting index failed! " + e.getMessage());
} }
} }
// req.addProperty("action", "requestReadMe"); req.addProperty("action", "requestReadMe");
// req.addProperty("contractID", thisDesp.contractID); req.addProperty("contractID", thisDesp.contractID);
// rc.onResult(req); rc.onResult(req);
LOGGER.info("contract " + thisDesp.contractName + " --> actually to index"); LOGGER.info("contract " + thisDesp.contractName + " --> actually to index");
} }
if (null != indexReader) { if (null != indexReader) {
@ -129,8 +132,7 @@ public class MetaIndexAction { // public static IndexWriter indexWriter;
public static void delIndexbyCID(JsonObject jo) { public static void delIndexbyCID(JsonObject jo) {
try { try {
if (!jo.has("contractID")) if (!jo.has("contractID")) return;
return;
String contractID = jo.get("contractID").getAsString(); String contractID = jo.get("contractID").getAsString();
LOGGER.info("contractID:" + contractID + "-->actually to delete"); LOGGER.info("contractID:" + contractID + "-->actually to delete");
indexWriter.deleteDocuments(new Term("contractID", contractID)); indexWriter.deleteDocuments(new Term("contractID", contractID));
@ -142,8 +144,7 @@ public class MetaIndexAction { // public static IndexWriter indexWriter;
public static void delIndexbyOwner(JsonObject jo) { public static void delIndexbyOwner(JsonObject jo) {
try { try {
if (!jo.has("owner")) if (!jo.has("owner")) return;
return;
String owner = jo.get("owner").getAsString(); String owner = jo.get("owner").getAsString();
LOGGER.info("owner:" + owner + "-->actually to delete"); LOGGER.info("owner:" + owner + "-->actually to delete");
indexWriter.deleteDocuments(new Term("owner", owner)); indexWriter.deleteDocuments(new Term("owner", owner));
@ -170,18 +171,18 @@ public class MetaIndexAction { // public static IndexWriter indexWriter;
default: default:
return "no such search type"; return "no such search type";
} }
// if (searchReq != null) { // if (searchReq != null) {
// logger.info(searchReq.get("pubkey").getAsString() + "---->start // logger.info(searchReq.get("pubkey").getAsString() + "---->start
// search"); // search");
// DirectoryReader indexReader = DirectoryReader.open(indexDir); // DirectoryReader indexReader = DirectoryReader.open(indexDir);
// IndexSearcher indexSearcher = new IndexSearcher(indexReader); // IndexSearcher indexSearcher = new IndexSearcher(indexReader);
// BooleanQuery.Builder queryBuilder = new BooleanQuery.Builder(); // BooleanQuery.Builder queryBuilder = new BooleanQuery.Builder();
// reandler(searchReq, queryBuilder); // reandler(searchReq, queryBuilder);
// BooleanQuery searchQuery = queryBuilder.build(); // BooleanQuery searchQuery = queryBuilder.build();
// TopDocs docs = indexSearcher.search(searchQuery, 10); // TopDocs docs = indexSearcher.search(searchQuery, 10);
// return docs.scoreDocs.length + ""; // return docs.scoreDocs.length + "";
// } // }
// else return "0"; // else return "0";
} catch (Exception e) { } catch (Exception e) {
ByteArrayOutputStream bo = new ByteArrayOutputStream(); ByteArrayOutputStream bo = new ByteArrayOutputStream();
e.printStackTrace(new PrintStream(bo)); e.printStackTrace(new PrintStream(bo));
@ -191,17 +192,12 @@ public class MetaIndexAction { // public static IndexWriter indexWriter;
public static String getMetabyReadme(JsonObject jo) { public static String getMetabyReadme(JsonObject jo) {
try { try {
if (!jo.has("keyword")) if (!jo.has("keyword")) return "missing arguments: keyword";
return "missing arguments: keyword";
if (!jo.has("page")) if (!jo.has("page")) page = 1;
page = 1; else page = jo.get("page").getAsInt();
else if (page <= 0) page = 1;
page = jo.get("page").getAsInt(); if (jo.has("pageSize")) PAGE_SIZE = jo.get("pageSize").getAsInt();
if (page <= 0)
page = 1;
if (jo.has("pageSize"))
PAGE_SIZE = jo.get("pageSize").getAsInt();
String keyword = jo.get("keyword").getAsString(); String keyword = jo.get("keyword").getAsString();
// Analyzer analyzer = new StandardAnalyzer(); // Analyzer analyzer = new StandardAnalyzer();
Analyzer analyzer = new IKAnalyzer(); Analyzer analyzer = new IKAnalyzer();
@ -211,17 +207,17 @@ public class MetaIndexAction { // public static IndexWriter indexWriter;
DirectoryReader indexReader = DirectoryReader.open(indexDir); DirectoryReader indexReader = DirectoryReader.open(indexDir);
IndexSearcher indexSearcher = new IndexSearcher(indexReader); IndexSearcher indexSearcher = new IndexSearcher(indexReader);
TopDocs docs = indexSearcher.search(rmQuery, 1000); TopDocs docs = indexSearcher.search(rmQuery, 1000);
// Document document = null ; // Document document = null ;
// if (docs.scoreDocs!=null&& docs.scoreDocs.length>0) { // if (docs.scoreDocs!=null&& docs.scoreDocs.length>0) {
// document = indexSearcher.doc(docs.scoreDocs[0].doc); // document = indexSearcher.doc(docs.scoreDocs[0].doc);
// ContractMeta contractMeta = new ContractMeta(); // ContractMeta contractMeta = new ContractMeta();
// contractMeta.setContractID(document.get("contractID")); // contractMeta.setContractID(document.get("contractID"));
// contractMeta.setOwner(document.get("owner")); // contractMeta.setOwner(document.get("owner"));
// contractMeta.setPubkey(document.get("pubkey")); // contractMeta.setPubkey(document.get("pubkey"));
// contractMeta.setReadmeStr(document.get("readmeStr")); // contractMeta.setReadmeStr(document.get("readmeStr"));
// String rs = JsonUtil.toJson(contractMeta); // String rs = JsonUtil.toJson(contractMeta);
// return rs; // return rs;
// } // }
ResultModel resultModel = null; ResultModel resultModel = null;
if (docs.scoreDocs != null && docs.scoreDocs.length > 0) if (docs.scoreDocs != null && docs.scoreDocs.length > 0)
resultModel = paginate(docs, indexReader); resultModel = paginate(docs, indexReader);
@ -239,32 +235,28 @@ public class MetaIndexAction { // public static IndexWriter indexWriter;
private static String getMetabyPubkey(JsonObject jo) { private static String getMetabyPubkey(JsonObject jo) {
try { try {
if (!jo.has("pubkey")) if (!jo.has("pubkey")) return "missing arguments: pubkey";
return "missing arguments: pubkey";
if (!jo.has("page")) if (!jo.has("page")) page = 1;
page = 1; else page = jo.get("page").getAsInt();
else if (page <= 0) page = 1;
page = jo.get("page").getAsInt();
if (page <= 0)
page = 1;
String pubkey = jo.get("pubkey").getAsString(); String pubkey = jo.get("pubkey").getAsString();
DirectoryReader indexReader = DirectoryReader.open(indexDir); DirectoryReader indexReader = DirectoryReader.open(indexDir);
IndexSearcher indexSearcher = new IndexSearcher(indexReader); IndexSearcher indexSearcher = new IndexSearcher(indexReader);
Query query = new TermQuery(new Term("pubkey", pubkey)); Query query = new TermQuery(new Term("pubkey", pubkey));
TopDocs docs = indexSearcher.search(query, 10); TopDocs docs = indexSearcher.search(query, 10);
// Document document = null; // Document document = null;
// if (docs.scoreDocs!=null&& docs.scoreDocs.length>0) { // if (docs.scoreDocs!=null&& docs.scoreDocs.length>0) {
// document = indexSearcher.doc(docs.scoreDocs[0].doc); // document = indexSearcher.doc(docs.scoreDocs[0].doc);
// ContractMeta contractMeta = new ContractMeta(); // ContractMeta contractMeta = new ContractMeta();
// contractMeta.setContractID(document.get("contractID")); // contractMeta.setContractID(document.get("contractID"));
// contractMeta.setOwner(document.get("owner")); // contractMeta.setOwner(document.get("owner"));
// contractMeta.setPubkey(document.get("pubkey")); // contractMeta.setPubkey(document.get("pubkey"));
// contractMeta.setReadmeStr(document.get("readmeStr")); // contractMeta.setReadmeStr(document.get("readmeStr"));
// String rs = JsonUtil.toJson(contractMeta); // String rs = JsonUtil.toJson(contractMeta);
// return rs; // return rs;
// } // }
ResultModel resultModel = null; ResultModel resultModel = null;
if (docs.scoreDocs != null && docs.scoreDocs.length > 0) if (docs.scoreDocs != null && docs.scoreDocs.length > 0)
resultModel = paginate(docs, indexReader); resultModel = paginate(docs, indexReader);
@ -283,32 +275,28 @@ public class MetaIndexAction { // public static IndexWriter indexWriter;
private static String getMetabyCID(JsonObject jo) { private static String getMetabyCID(JsonObject jo) {
System.out.println("getMetabyCID" + jo.toString()); System.out.println("getMetabyCID" + jo.toString());
try { try {
if (!jo.has("contractID")) if (!jo.has("contractID")) return "missing arguments: contractID";
return "missing arguments: contractID";
if (!jo.has("page")) if (!jo.has("page")) page = 1;
page = 1; else page = jo.get("page").getAsInt();
else if (page <= 0) page = 1;
page = jo.get("page").getAsInt();
if (page <= 0)
page = 1;
String contractID = jo.get("contractID").getAsString(); String contractID = jo.get("contractID").getAsString();
DirectoryReader indexReader = DirectoryReader.open(indexDir); DirectoryReader indexReader = DirectoryReader.open(indexDir);
IndexSearcher indexSearcher = new IndexSearcher(indexReader); IndexSearcher indexSearcher = new IndexSearcher(indexReader);
Query query = new TermQuery(new Term("contractID", contractID)); Query query = new TermQuery(new Term("contractID", contractID));
TopDocs docs = indexSearcher.search(query, 10); TopDocs docs = indexSearcher.search(query, 10);
// Document document = null; // Document document = null;
// if (docs.scoreDocs!=null&& docs.scoreDocs.length>0) { // if (docs.scoreDocs!=null&& docs.scoreDocs.length>0) {
// document = indexSearcher.doc(docs.scoreDocs[0].doc); // document = indexSearcher.doc(docs.scoreDocs[0].doc);
// ContractMeta contractMeta = new ContractMeta(); // ContractMeta contractMeta = new ContractMeta();
// contractMeta.setContractID(document.get("contractID")); // contractMeta.setContractID(document.get("contractID"));
// contractMeta.setOwner(document.get("owner")); // contractMeta.setOwner(document.get("owner"));
// contractMeta.setPubkey(document.get("pubkey")); // contractMeta.setPubkey(document.get("pubkey"));
// contractMeta.setReadmeStr(document.get("readmeStr")); // contractMeta.setReadmeStr(document.get("readmeStr"));
// String rs = JsonUtil.toJson(contractMeta); // String rs = JsonUtil.toJson(contractMeta);
// return rs; // return rs;
// } // }
ResultModel resultModel = null; ResultModel resultModel = null;
if (docs.scoreDocs != null && docs.scoreDocs.length > 0) if (docs.scoreDocs != null && docs.scoreDocs.length > 0)
resultModel = paginate(docs, indexReader); resultModel = paginate(docs, indexReader);
@ -326,33 +314,28 @@ public class MetaIndexAction { // public static IndexWriter indexWriter;
private static String getMetabyOwner(JsonObject jo) { private static String getMetabyOwner(JsonObject jo) {
try { try {
if (!jo.has("owner")) if (!jo.has("owner")) return "missing arguments: owner";
return "missing arguments: owner";
if (!jo.has("page")) if (!jo.has("page")) page = 1;
page = 1; else page = jo.get("page").getAsInt();
else if (page <= 0) page = 1;
page = jo.get("page").getAsInt(); if (jo.has("pageSize")) PAGE_SIZE = jo.get("pageSize").getAsInt();
if (page <= 0)
page = 1;
if (jo.has("pageSize"))
PAGE_SIZE = jo.get("pageSize").getAsInt();
String owner = jo.get("owner").getAsString(); String owner = jo.get("owner").getAsString();
DirectoryReader indexReader = DirectoryReader.open(indexDir); DirectoryReader indexReader = DirectoryReader.open(indexDir);
IndexSearcher indexSearcher = new IndexSearcher(indexReader); IndexSearcher indexSearcher = new IndexSearcher(indexReader);
Query query = new TermQuery(new Term("owner", owner)); Query query = new TermQuery(new Term("owner", owner));
TopDocs docs = indexSearcher.search(query, 1000); TopDocs docs = indexSearcher.search(query, 1000);
// Document document = null; // Document document = null;
// if (docs.scoreDocs!=null&& docs.scoreDocs.length>0) { // if (docs.scoreDocs!=null&& docs.scoreDocs.length>0) {
// document = indexSearcher.doc(docs.scoreDocs[0].doc); // document = indexSearcher.doc(docs.scoreDocs[0].doc);
// ContractMeta contractMeta = new ContractMeta(); // ContractMeta contractMeta = new ContractMeta();
// contractMeta.setContractID(document.get("contractID")); // contractMeta.setContractID(document.get("contractID"));
// contractMeta.setOwner(document.get("owner")); // contractMeta.setOwner(document.get("owner"));
// contractMeta.setPubkey(document.get("pubkey")); // contractMeta.setPubkey(document.get("pubkey"));
// contractMeta.setReadmeStr(document.get("readmeStr")); // contractMeta.setReadmeStr(document.get("readmeStr"));
// String rs = JsonUtil.toJson(contractMeta); // String rs = JsonUtil.toJson(contractMeta);
// return rs; // return rs;
// } // }
ResultModel resultModel = null; ResultModel resultModel = null;
if (docs.scoreDocs != null && docs.scoreDocs.length > 0) if (docs.scoreDocs != null && docs.scoreDocs.length > 0)
resultModel = paginate(docs, indexReader); resultModel = paginate(docs, indexReader);
@ -371,15 +354,18 @@ public class MetaIndexAction { // public static IndexWriter indexWriter;
public static void reqHandler(JsonObject req, BooleanQuery.Builder query) public static void reqHandler(JsonObject req, BooleanQuery.Builder query)
throws ParseException { throws ParseException {
if (req.get("contractID").getAsString() != null) { if (req.get("contractID").getAsString() != null) {
query.add(new FuzzyQuery(new Term("contractID", req.get("contractID").getAsString())), query.add(
new FuzzyQuery(new Term("contractID", req.get("contractID").getAsString())),
BooleanClause.Occur.SHOULD); BooleanClause.Occur.SHOULD);
} }
if (req.get("owner").getAsString() != null) { if (req.get("owner").getAsString() != null) {
query.add(new FuzzyQuery(new Term("owner", req.get("owner").getAsString())), query.add(
new FuzzyQuery(new Term("owner", req.get("owner").getAsString())),
BooleanClause.Occur.SHOULD); BooleanClause.Occur.SHOULD);
} }
if (req.get("pubkey").getAsString() != null) { if (req.get("pubkey").getAsString() != null) {
query.add(new PrefixQuery(new Term("pubkey", req.get("pubkey").getAsString())), query.add(
new PrefixQuery(new Term("pubkey", req.get("pubkey").getAsString())),
BooleanClause.Occur.SHOULD); BooleanClause.Occur.SHOULD);
} }
if (req.get("readmeStr").getAsString() != null) { if (req.get("readmeStr").getAsString() != null) {
@ -418,7 +404,8 @@ public class MetaIndexAction { // public static IndexWriter indexWriter;
resultModel.setContractMetaList(contractMetaList); resultModel.setContractMetaList(contractMetaList);
resultModel.setCurPage(page); resultModel.setCurPage(page);
Long pageCount = Long pageCount =
docs.totalHits.value % PAGE_SIZE > 0 ? (docs.totalHits.value) / PAGE_SIZE + 1 docs.totalHits.value % PAGE_SIZE > 0
? (docs.totalHits.value) / PAGE_SIZE + 1
: (docs.totalHits.value) / PAGE_SIZE; : (docs.totalHits.value) / PAGE_SIZE;
resultModel.setPageCount(pageCount); resultModel.setPageCount(pageCount);
return resultModel; return resultModel;
@ -427,19 +414,23 @@ public class MetaIndexAction { // public static IndexWriter indexWriter;
@Action(async = true, userPermission = 1L) @Action(async = true, userPermission = 1L)
public synchronized void onRequestReadMe(JsonObject json, ResultCallback rc) public synchronized void onRequestReadMe(JsonObject json, ResultCallback rc)
throws IOException { throws IOException {
// try { // try {
// Thread.sleep(2000); // Thread.sleep(2000);
// } catch (InterruptedException e) { // } catch (InterruptedException e) {
// e.printStackTrace(); // e.printStackTrace();
// } // }
CMNode node = NodeCenterActions.nodeInfos.get(controller.pubKey); CMNode node = NodeCenterActions.nodeInfos.get(controller.pubKey);
String nodeAddr = getNodeAddr(node.masterAddress); String nodeAddr = getNodeAddr(node.masterAddress);
String name = json.get("name").getAsString(); String name = json.get("name").getAsString();
// /DOIP/Hello1/assets/logo.png // /DOIP/Hello1/assets/logo.png
// String nodeAddr="127.0.0.1:21030"; // String nodeAddr="127.0.0.1:21030";
String pngUrl = "http://" + nodeAddr + "/DOIP/" + name + "/assets/logo.png"; String pngUrl = "http://" + nodeAddr + "/DOIP/" + name + "/assets/logo.png";
System.out.println("node.masterAddress: " + node.masterAddress + "==========" + "nodeAddr: " System.out.println(
+ nodeAddr); "node.masterAddress: "
+ node.masterAddress
+ "=========="
+ "nodeAddr: "
+ nodeAddr);
System.out.println("name: " + name + "pngUrl: " + pngUrl); System.out.println("name: " + name + "pngUrl: " + pngUrl);
String contractID = json.get("contractID").getAsString(); String contractID = json.get("contractID").getAsString();
String status = json.get("status").getAsString(); String status = json.get("status").getAsString();
@ -478,8 +469,7 @@ public class MetaIndexAction { // public static IndexWriter indexWriter;
public void getMetabyReadme(JsonObject json, ResultCallback rc) { public void getMetabyReadme(JsonObject json, ResultCallback rc) {
String result = getMetabyReadme(json); String result = getMetabyReadme(json);
JsonObject object = new JsonObject(); JsonObject object = new JsonObject();
if (json.has("requestID")) if (json.has("requestID")) object.add("responseID", json.get("requestID"));
object.add("responseID", json.get("requestID"));
System.out.println("zzzResult" + result); System.out.println("zzzResult" + result);
object.add("result", JsonParser.parseString(result)); object.add("result", JsonParser.parseString(result));
object.addProperty("action", "getMetabyReadme"); object.addProperty("action", "getMetabyReadme");
@ -488,19 +478,15 @@ public class MetaIndexAction { // public static IndexWriter indexWriter;
@Action(async = true, userPermission = 1L) @Action(async = true, userPermission = 1L)
public void segmentWord(JsonObject json, ResultCallback rc) throws IOException { public void segmentWord(JsonObject json, ResultCallback rc) throws IOException {
// Analyzer analyzer = new IKAnalyzer(true); //Analyzer analyzer = new IKAnalyzer(true);
CharArraySet stopWords = CharArraySet stopWords = CharArraySet.unmodifiableSet(WordlistLoader.getWordSet(new InputStreamReader(Objects.requireNonNull(MetaIndexAction.class.getClassLoader().getResourceAsStream(
CharArraySet.unmodifiableSet(WordlistLoader.getWordSet(new InputStreamReader( "org/bdware/server/stopwords.txt")), StandardCharsets.UTF_8)));
Objects.requireNonNull(MetaIndexAction.class.getClassLoader()
.getResourceAsStream("org/bdware/server/stopwords.txt")),
StandardCharsets.UTF_8)));
Analyzer analyzer = new SmartChineseAnalyzer(stopWords); Analyzer analyzer = new SmartChineseAnalyzer(stopWords);
JsonObject object = new JsonObject(); JsonObject object = new JsonObject();
String words = "我喜欢区块链,我想试用一下这个,我是做大数据处理的,我是科技局的管理员"; // 从json拿 String words = "我喜欢区块链,我想试用一下这个,我是做大数据处理的,我是科技局的管理员"; // 从json拿
TokenStream stream = null; TokenStream stream = null;
if (json.has("requestID")) if (json.has("requestID")) object.add("responseID", json.get("requestID"));
object.add("responseID", json.get("requestID"));
try { try {
stream = analyzer.tokenStream("myfield", words); stream = analyzer.tokenStream("myfield", words);
CharTermAttribute charTermAtt = stream.addAttribute(CharTermAttribute.class); CharTermAttribute charTermAtt = stream.addAttribute(CharTermAttribute.class);
@ -529,8 +515,7 @@ public class MetaIndexAction { // public static IndexWriter indexWriter;
public void getMetabyCID(JsonObject json, ResultCallback rc) { public void getMetabyCID(JsonObject json, ResultCallback rc) {
String result = getMetabyCID(json); String result = getMetabyCID(json);
JsonObject object = new JsonObject(); JsonObject object = new JsonObject();
if (json.has("requestID")) if (json.has("requestID")) object.add("responseID", json.get("requestID"));
object.add("responseID", json.get("requestID"));
object.add("result", JsonParser.parseString(result)); object.add("result", JsonParser.parseString(result));
object.addProperty("action", "getMetabyCID"); object.addProperty("action", "getMetabyCID");
rc.onResult(object); rc.onResult(object);
@ -540,8 +525,7 @@ public class MetaIndexAction { // public static IndexWriter indexWriter;
public void getMetabyOwner(JsonObject json, ResultCallback rc) { public void getMetabyOwner(JsonObject json, ResultCallback rc) {
String result = getMetabyOwner(json); String result = getMetabyOwner(json);
JsonObject object = new JsonObject(); JsonObject object = new JsonObject();
if (json.has("requestID")) if (json.has("requestID")) object.add("responseID", json.get("requestID"));
object.add("responseID", json.get("requestID"));
object.add("result", JsonParser.parseString(result)); object.add("result", JsonParser.parseString(result));
object.addProperty("action", "getMetabyOwner"); object.addProperty("action", "getMetabyOwner");
rc.onResult(object); rc.onResult(object);
@ -551,8 +535,7 @@ public class MetaIndexAction { // public static IndexWriter indexWriter;
public void getMetabyPubkey(JsonObject json, ResultCallback rc) { public void getMetabyPubkey(JsonObject json, ResultCallback rc) {
String result = getMetabyPubkey(json); String result = getMetabyPubkey(json);
JsonObject object = new JsonObject(); JsonObject object = new JsonObject();
if (json.has("requestID")) if (json.has("requestID")) object.add("responseID", json.get("requestID"));
object.add("responseID", json.get("requestID"));
object.add("result", JsonParser.parseString(result)); object.add("result", JsonParser.parseString(result));
object.addProperty("action", "getMetabyPubkey"); object.addProperty("action", "getMetabyPubkey");
rc.onResult(object); rc.onResult(object);

View File

@ -6,13 +6,13 @@ import java.util.List;
import java.util.concurrent.atomic.AtomicInteger; import java.util.concurrent.atomic.AtomicInteger;
public class MultiPointContractInfo { public class MultiPointContractInfo {
public List<String> members; // pubKey public List<String> members; //pubKey
public ContractExecType type; public ContractExecType type;
AtomicInteger ai = new AtomicInteger(); AtomicInteger ai = new AtomicInteger();
public transient ContractExecutor rcf; public transient ContractExecutor rcf;
public String getNextSeq() { public String getNextSeq(){
System.out.println("MultiPointContractInfo获得下一个序号" + (ai.get() + 1)); System.out.println("MultiPointContractInfo获得下一个序号" + (ai.get() + 1));
return ai.getAndIncrement() + ""; return ai.getAndIncrement() + "";
} }

View File

@ -35,9 +35,8 @@ public class NCClientActions {
map.put("id", OtherNCProxy.instance.sm2.getPublicKeyStr()); map.put("id", OtherNCProxy.instance.sm2.getPublicKeyStr());
byte[] signature = "no signature".getBytes(); byte[] signature = "no signature".getBytes();
try { try {
signature = SM2Util.sign(OtherNCProxy.instance.sm2.getPrivateKeyParameter(), signature = SM2Util.sign(OtherNCProxy.instance.sm2.getPrivateKeyParameter(), (OtherNCProxy.instance.sm2.getPublicKeyStr() + json.get("session").getAsString())
(OtherNCProxy.instance.sm2.getPublicKeyStr() .getBytes());
+ json.get("session").getAsString()).getBytes());
} catch (CryptoException e) { } catch (CryptoException e) {
e.printStackTrace(); e.printStackTrace();
} }
@ -63,8 +62,8 @@ public class NCClientActions {
if (json.has("empty")) { if (json.has("empty")) {
LOGGER.info("receive from NC ,do not have any cp."); LOGGER.info("receive from NC ,do not have any cp.");
} else { } else {
info = JsonUtil.fromJson(json.get("contracts").getAsString(), info = JsonUtil.fromJson(json.get("contracts").getAsString(), new TypeToken<List<OtherNCInfo>>() {
new TypeToken<List<OtherNCInfo>>() {}.getType()); }.getType());
} }
LOGGER.info(JsonUtil.toJson(info)); LOGGER.info(JsonUtil.toJson(info));

View File

@ -23,7 +23,7 @@ import java.util.concurrent.Executors;
public class NCClientHandler extends SimpleChannelInboundHandler<Object> { public class NCClientHandler extends SimpleChannelInboundHandler<Object> {
private static final Logger LOGGER = LogManager.getLogger(NCClientHandler.class); private static final Logger LOGGER = LogManager.getLogger(NCClientHandler.class);
static ExecutorService executorService = Executors.newFixedThreadPool(5); static ExecutorService executorService = Executors.newFixedThreadPool(5);
public boolean hasPermission; // 是否在目标NC上有权限 public boolean hasPermission; //是否在目标NC上有权限
public NCClientActions actions; public NCClientActions actions;
Channel channel; Channel channel;
ActionExecutor<ResultCallback, JsonObject> ae; ActionExecutor<ResultCallback, JsonObject> ae;
@ -67,16 +67,21 @@ public class NCClientHandler extends SimpleChannelInboundHandler<Object> {
protected void channelRead0(ChannelHandlerContext ctx, Object msg) throws Exception { protected void channelRead0(ChannelHandlerContext ctx, Object msg) throws Exception {
ByteBuf bb = (ByteBuf) msg; ByteBuf bb = (ByteBuf) msg;
try { try {
final JsonObject arg = new JsonParser() final JsonObject arg =
.parse(new InputStreamReader(new ByteBufInputStream(bb))).getAsJsonObject(); new JsonParser()
.parse(new InputStreamReader(new ByteBufInputStream(bb)))
.getAsJsonObject();
if (arg.has("action")) { if (arg.has("action")) {
final String action = arg.get("action").getAsString(); final String action = arg.get("action").getAsString();
ae.handle(action, arg, new ResultCallback() { ae.handle(
@Override action,
public void onResult(String str) { arg,
sendMsg(str); new ResultCallback() {
} @Override
}); public void onResult(String str) {
sendMsg(str);
}
});
} }
} catch (java.lang.IllegalArgumentException e) { } catch (java.lang.IllegalArgumentException e) {
@ -95,8 +100,7 @@ public class NCClientHandler extends SimpleChannelInboundHandler<Object> {
public void close() { public void close() {
try { try {
isConnected = false; isConnected = false;
if (channel != null) if (channel != null) channel.close();
channel.close();
} catch (Exception e) { } catch (Exception e) {
e.printStackTrace(); e.printStackTrace();
} finally { } finally {

View File

@ -15,8 +15,7 @@ import java.util.concurrent.TimeUnit;
import java.util.concurrent.atomic.AtomicBoolean; import java.util.concurrent.atomic.AtomicBoolean;
public class NCElectMasterUtil { public class NCElectMasterUtil {
public static final Map<String, ElectInfo> electInfos = new ConcurrentHashMap<>(); // key is public static final Map<String, ElectInfo> electInfos = new ConcurrentHashMap<>(); //key is contractID
// contractID
private static final Logger LOGGER = LogManager.getLogger(NCElectMasterUtil.class); private static final Logger LOGGER = LogManager.getLogger(NCElectMasterUtil.class);
public static class ElectInfo { public static class ElectInfo {
@ -25,10 +24,10 @@ public class NCElectMasterUtil {
String formerMaster; String formerMaster;
String uniNumber; String uniNumber;
long lastTime = System.currentTimeMillis(); long lastTime = System.currentTimeMillis();
int onlineNum; // 除旧的master之外的在线节点数 int onlineNum; //除旧的master之外的在线节点数
String contractID; String contractID;
String mems; // 执行这个合约的所有节点的pubKey String mems; //执行这个合约的所有节点的pubKey
private Map<String, Integer> nodeID2LastExe = new ConcurrentHashMap<>(); // key is nodeID private Map<String, Integer> nodeID2LastExe = new ConcurrentHashMap<>(); //key is nodeID
private Timer timer; private Timer timer;
@ -39,10 +38,11 @@ public class NCElectMasterUtil {
uniNumber = uni; uniNumber = uni;
String[] mem = members.split(","); String[] mem = members.split(",");
/* /* try {
* try { Thread.sleep(2000); //让NC发现崩溃节点 } catch (InterruptedException e) { Thread.sleep(2000); //让NC发现崩溃节点
* e.printStackTrace(); } } catch (InterruptedException e) {
*/ e.printStackTrace();
}*/
for (String memID : mem) { for (String memID : mem) {
if (memID == null || memID.length() == 0) if (memID == null || memID.length() == 0)
@ -52,22 +52,26 @@ public class NCElectMasterUtil {
onlineNum++; onlineNum++;
} }
} }
NodeCenterServer.scheduledThreadPool.scheduleWithFixedDelay(() -> { NodeCenterServer.scheduledThreadPool.scheduleWithFixedDelay(
// cancel the election if no nodes find the master's crash in delay + 2 seconds () -> {
SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd.HH:mm:ss.SSS"); // cancel the election if no nodes find the master's crash in delay + 2 seconds
if (System.currentTimeMillis() - lastTime > (delay + 15000)) { SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd.HH:mm:ss.SSS");
LOGGER.info("lastTime=" + df.format(lastTime) + " cancel the election"); if (System.currentTimeMillis() - lastTime > (delay + 15000)) {
cancel(); LOGGER.info("lastTime=" + df.format(lastTime) + " cancel the election");
} cancel();
// start timeout election }
// if (electInfos.containsKey(contractID) && nodeID2LastExe.size() == onlineNum) { // start timeout election
// elect(); // if (electInfos.containsKey(contractID) && nodeID2LastExe.size() == onlineNum) {
// } // elect();
}, delay + 1500, delay + 1500, TimeUnit.MILLISECONDS); // }
// timer.schedule(task, dealy + 2000); },
delay + 1500,
delay + 1500,
TimeUnit.MILLISECONDS);
//timer.schedule(task, dealy + 2000);
LOGGER.info("new election of contract " + contractID + " is added to electInfos, " LOGGER.info("new election of contract " + contractID + " is added to electInfos, " +
+ onlineNum + " node is online"); onlineNum + " node is online");
} }
public void cancel() { public void cancel() {
@ -80,11 +84,10 @@ public class NCElectMasterUtil {
} }
} }
public synchronized void put(String nodeID, int lastExe, String master, String mem2, public synchronized void put(String nodeID, int lastExe, String master, String mem2, String uniNum) {
String uniNum) {
LOGGER.info("put nodeID=" + nodeID); LOGGER.info("put nodeID=" + nodeID);
// 确保该合约某时只能有一个选举,其他的选举请求被忽略 //确保该合约某时只能有一个选举,其他的选举请求被忽略
if (!master.equals(formerMaster)) { if (!master.equals(formerMaster)) {
LOGGER.debug("[NCElectMasterUtil] master error!"); LOGGER.debug("[NCElectMasterUtil] master error!");
return; return;
@ -102,14 +105,13 @@ public class NCElectMasterUtil {
} }
long now = System.currentTimeMillis(); long now = System.currentTimeMillis();
// 认为是一个新的选举之前的作废 //认为是一个新的选举之前的作废
if (now - lastTime > delay) { if (now - lastTime > delay) {
LOGGER.info("[NCElectMasterUtil] time error!"); LOGGER.info("[NCElectMasterUtil] time error!");
cancel(); cancel();
synchronized (electInfos) { synchronized (electInfos) {
// electInfos.remove(contractID); //electInfos.remove(contractID);
NCElectMasterUtil.electInfos.put(contractID, NCElectMasterUtil.electInfos.put(contractID, new ElectInfo(master, contractID, mem2, uniNum));
new ElectInfo(master, contractID, mem2, uniNum));
ElectInfo eleInfo = electInfos.get(contractID); ElectInfo eleInfo = electInfos.get(contractID);
eleInfo.put(nodeID, lastExe, master, mem2, uniNum); eleInfo.put(nodeID, lastExe, master, mem2, uniNum);
} }
@ -135,17 +137,15 @@ public class NCElectMasterUtil {
startElect.set(true); startElect.set(true);
} }
// 更新路由信息这个合约的master暂时为null //更新路由信息这个合约的master暂时为null
if (NodeCenterActions.nodeInfos.containsKey(formerMaster)) { if (NodeCenterActions.nodeInfos.containsKey(formerMaster)) {
CMNode node = NodeCenterActions.nodeInfos.get(formerMaster); CMNode node = NodeCenterActions.nodeInfos.get(formerMaster);
if (node != null) { if (node != null) {
synchronized (node) { synchronized (node) {
for (ContractDesp cd : node.contracts) { for (ContractDesp cd : node.contracts) {
if (cd.contractID.equals(contractID) if (cd.contractID.equals(contractID) || cd.contractName.equals(contractID)) {
|| cd.contractName.equals(contractID)) {
cd.setIsMaster(false); cd.setIsMaster(false);
LOGGER.debug("设置节点 " + node.pubKey.substring(0, 5) + " 的合约 " LOGGER.debug("设置节点 " + node.pubKey.substring(0, 5) + " 的合约 " + contractID + " isMaster=" + false);
+ contractID + " isMaster=" + false);
break; break;
} }
} }
@ -164,16 +164,16 @@ public class NCElectMasterUtil {
LOGGER.info("[NCElectMasterUtil] 选举出新的master " + newMaster); LOGGER.info("[NCElectMasterUtil] 选举出新的master " + newMaster);
cancel(); cancel();
// electInfos.remove(contractID); //electInfos.remove(contractID);
// 通知新的master让它发起重连操作并在所有节点重连成功之后开启master的恢复 //通知新的master让它发起重连操作并在所有节点重连成功之后开启master的恢复
try { try {
Thread.sleep(1500); Thread.sleep(1500);
} catch (InterruptedException e) { } catch (InterruptedException e) {
e.printStackTrace(); e.printStackTrace();
} }
LOGGER.info("开始计算需要连接新master的都有哪些节点:"); LOGGER.info("开始计算需要连接新master的都有哪些节点:");
StringBuilder onlineMems = new StringBuilder(); // 不包含旧的master StringBuilder onlineMems = new StringBuilder(); //不包含旧的master
for (String memID : nodeID2LastExe.keySet()) { for (String memID : nodeID2LastExe.keySet()) {
if (memID == null || memID.length() == 0) if (memID == null || memID.length() == 0)
continue; continue;

View File

@ -1,8 +1,10 @@
package org.bdware.server.nodecenter; package org.bdware.server.nodecenter;
import com.google.gson.JsonObject; import com.google.gson.JsonObject;
import com.google.gson.JsonParser;
import com.google.gson.reflect.TypeToken; import com.google.gson.reflect.TypeToken;
import io.netty.buffer.ByteBuf; import io.netty.buffer.ByteBuf;
import io.netty.buffer.ByteBufInputStream;
import io.netty.buffer.Unpooled; import io.netty.buffer.Unpooled;
import io.netty.channel.ChannelFuture; import io.netty.channel.ChannelFuture;
import io.netty.channel.ChannelFutureListener; import io.netty.channel.ChannelFutureListener;
@ -20,15 +22,13 @@ import org.bdware.server.NodeCenterServer;
import org.bdware.server.action.Action; import org.bdware.server.action.Action;
import org.bdware.server.action.ActionExecutor; import org.bdware.server.action.ActionExecutor;
import org.bdware.server.action.HttpResultCallback; import org.bdware.server.action.HttpResultCallback;
import org.bdware.server.http.HttpMethod; import org.bdware.server.http.HttpFileHandleAdapter;
import org.bdware.server.http.*; import org.bdware.server.http.URIHandler;
import org.bdware.server.http.URIPath;
import org.bdware.server.permission.Role; import org.bdware.server.permission.Role;
import org.zz.gmhelper.SM2Util; import org.zz.gmhelper.SM2Util;
import java.io.ByteArrayOutputStream; import java.io.*;
import java.io.File;
import java.io.FileFilter;
import java.io.PrintStream;
import java.net.URLDecoder; import java.net.URLDecoder;
import java.util.HashMap; import java.util.HashMap;
import java.util.List; import java.util.List;
@ -43,12 +43,9 @@ public class NCHttpHandler extends SimpleChannelInboundHandler<HttpObject> {
private static final String UNSUPPORTED_HTTP_METHOD = "{\"msg\":\"unsupported http method\"}"; private static final String UNSUPPORTED_HTTP_METHOD = "{\"msg\":\"unsupported http method\"}";
private static final String UNSUPPORTED_ACTION = "{\"msg\":\"unsupported action\"}"; private static final String UNSUPPORTED_ACTION = "{\"msg\":\"unsupported action\"}";
private static final Logger LOGGER = LogManager.getLogger(NCHttpHandler.class); private static final Logger LOGGER = LogManager.getLogger(NCHttpHandler.class);
static NCManagerAction managerAction = new NCManagerAction(null);
static LogActions logActions = new LogActions(managerAction);
static UnitActions unitActions = new UnitActions(managerAction);
private static final ActionExecutor<ResultCallback, JsonObject> actionExecutor = private static final ActionExecutor<ResultCallback, JsonObject> actionExecutor =
new ActionExecutor<ResultCallback, JsonObject>(NodeCenterFrameHandler.executorService, new ActionExecutor<ResultCallback, JsonObject>(
new NodeCenterActions(null), managerAction, logActions, unitActions) { NodeCenterFrameHandler.executorService, new NodeCenterActions(null)) {
@Override @Override
public boolean checkPermission(Action a, JsonObject arg, long per) { public boolean checkPermission(Action a, JsonObject arg, long per) {
@ -76,9 +73,15 @@ public class NCHttpHandler extends SimpleChannelInboundHandler<HttpObject> {
if (arg.has("pubKey")) { if (arg.has("pubKey")) {
pubkey = arg.get("pubKey").getAsString(); pubkey = arg.get("pubKey").getAsString();
} }
NodeCenterServer.nodeHttpLogDB.put(action, NodeCenterServer.nodeHttpLogDB.put(
"{\"action\":\"" + action + "\",\"pubKey\":\"" + pubkey + "\",\"date\":" action,
+ System.currentTimeMillis() + "}"); "{\"action\":\""
+ action
+ "\",\"pubKey\":\""
+ pubkey
+ "\",\"date\":"
+ System.currentTimeMillis()
+ "}");
LOGGER.debug("[NCHttpHandler] flag = " + flag + " flag2 = " + flag2); LOGGER.debug("[NCHttpHandler] flag = " + flag + " flag2 = " + flag2);
return flag && flag2; return flag && flag2;
} }
@ -115,57 +118,42 @@ public class NCHttpHandler extends SimpleChannelInboundHandler<HttpObject> {
ctx.flush(); ctx.flush();
} }
public static class VerifiyCallback implements ArgParser.VerifiedCallback {
@Override
public void onResult(boolean verified, JsonObject transformedParam) {
LOGGER.info("verify signature: " + verified);
if (verified) {
// 查permission
String ret = getRole(transformedParam.get("pubKey").getAsString());
long permission;
if (ret != null && ret.length() > 0) {
permission = 0x86000d41L | Role.compoundValue(ret.split(","));
} else {
permission = Role.compoundValue(ret.split(","));
}
transformedParam.addProperty("permission", permission + "");
LOGGER.debug("[CMHttpHandler] http 请求查看用户权限为 : " + permission);
} else {
transformedParam.remove("pubKey");
transformedParam.addProperty("permission", 0 + "");
}
}
}
@URIPath(method = HttpMethod.OPTIONS)
public void crossOrigin(ChannelHandlerContext ctx, FullHttpRequest request) {
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");
ChannelFuture f = ctx.write(fullResponse);
f.addListener(ChannelFutureListener.CLOSE);
LOGGER.info("[Option] received!");
}
@URIPath({"/NodeCenter", "/SCIDE/SCExecutor", "/SCIDE/CMManager", "/SCIDE/SCManager"}) @URIPath({"/NodeCenter", "/SCIDE/SCExecutor", "/SCIDE/CMManager", "/SCIDE/SCManager"})
public void parseGetAndHandle(ChannelHandlerContext ctx, FullHttpRequest req) throws Exception { public void parseGetAndHandle(ChannelHandlerContext ctx, FullHttpRequest req) {
JsonObject transformedParam = ArgParser.parseGetAndVerify(req, new VerifiyCallback()); QueryStringDecoder decoderQuery = new QueryStringDecoder(req.uri());
handleReq(transformedParam, ctx); Map<String, List<String>> params = decoderQuery.parameters();
JsonObject map = new JsonObject();
for (String key : params.keySet()) {
List<String> val = params.get(key);
if (val != null) map.addProperty(key, val.get(0));
}
String uri = URLDecoder.decode(req.uri()).split("\\?")[1];
int index = uri.lastIndexOf('&');
String str = uri;
if (index != -1) {
str = uri.substring(0, index);
}
injectPermission(map, str);
handleReq(map, ctx);
} }
@URIPath(method = org.bdware.server.http.HttpMethod.POST, @URIPath(
method = org.bdware.server.http.HttpMethod.POST,
value = {"/NodeCenter", "/SCIDE/SCExecutor", "/SCIDE/CMManager", "/SCIDE/SCManager"}) value = {"/NodeCenter", "/SCIDE/SCExecutor", "/SCIDE/CMManager", "/SCIDE/SCManager"})
public void parsePostAndHandle(ChannelHandlerContext ctx, FullHttpRequest req) public void parsePostAndHandle(ChannelHandlerContext ctx, FullHttpRequest req)
throws Exception { throws UnsupportedEncodingException {
JsonObject map = ArgParser.parsePostAndVerify(req, new VerifiyCallback()); ByteBuf content = req.content();
// injectPermission(map, str); JsonObject map =
JsonParser.parseReader(new InputStreamReader(new ByteBufInputStream(content)))
.getAsJsonObject();
// FIXME 感觉不太对劲
String uri = URLDecoder.decode(req.uri(), "utf-8").split("\\?")[1];
int index = uri.lastIndexOf('&');
String str = uri;
if (index != -1) {
str = uri.substring(0, index);
}
injectPermission(map, str);
handleReq(map, ctx); handleReq(map, ctx);
} }
@ -175,13 +163,14 @@ public class NCHttpHandler extends SimpleChannelInboundHandler<HttpObject> {
JsonObject transformedParam = new JsonObject(); JsonObject transformedParam = new JsonObject();
for (String key : parameters.keySet()) { for (String key : parameters.keySet()) {
List<String> val = parameters.get(key); List<String> val = parameters.get(key);
if (val != null) if (val != null) transformedParam.addProperty(key, val.get(0));
transformedParam.addProperty(key, val.get(0));
} }
return transformedParam; return transformedParam;
} }
@URIPath(method = org.bdware.server.http.HttpMethod.GET, value = {"/doip"}) @URIPath(
method = org.bdware.server.http.HttpMethod.GET,
value = {"/doip"})
public void handleDOIP(ChannelHandlerContext ctx, FullHttpRequest req) { public void handleDOIP(ChannelHandlerContext ctx, FullHttpRequest req) {
ByteBuf content = req.content(); ByteBuf content = req.content();
JsonObject map = parseArgInQuery(req); JsonObject map = parseArgInQuery(req);
@ -194,10 +183,11 @@ public class NCHttpHandler extends SimpleChannelInboundHandler<HttpObject> {
} }
injectPermission(map, str); injectPermission(map, str);
DefaultFullHttpResponse response = new DefaultFullHttpResponse(HttpVersion.HTTP_1_1, OK, DefaultFullHttpResponse response =
Unpooled.wrappedBuffer(MetaIndexAction.search(map).getBytes())); new DefaultFullHttpResponse(
response.headers().add("Access-Control-Allow-Origin", "*"); HttpVersion.HTTP_1_1,
response.headers().add("Access-Control-Allow-Methods", "*"); OK,
Unpooled.wrappedBuffer(MetaIndexAction.search(map).getBytes()));
ChannelFuture f = ctx.write(response); ChannelFuture f = ctx.write(response);
f.addListener(ChannelFutureListener.CLOSE); f.addListener(ChannelFutureListener.CLOSE);
@ -206,17 +196,19 @@ public class NCHttpHandler extends SimpleChannelInboundHandler<HttpObject> {
@Override @Override
public void channelRead0(ChannelHandlerContext ctx, HttpObject msg) { public void channelRead0(ChannelHandlerContext ctx, HttpObject msg) {
LOGGER.debug("[NCHttpHandler] TID:" + Thread.currentThread().getId() + msg.toString()); // logger.debug("[NCHttpHandler] TID:" + Thread.currentThread().getId() +
// msg.toString());
if (msg instanceof FullHttpRequest) { if (msg instanceof FullHttpRequest) {
FullHttpRequest request = (FullHttpRequest) msg; FullHttpRequest request = (FullHttpRequest) msg;
handler.handle(ctx, request); handler.handle(ctx, request);
} }
} }
public static String getRole(String pubKey) { public String getRole(String pubKey) {
try { try {
String ret = KeyValueDBUtil.instance.getValue(NCTables.ConfigDB.toString(), String ret =
"__CenterManager__"); KeyValueDBUtil.instance.getValue(
NCTables.ConfigDB.toString(), "__CenterManager__");
if (ret != null && ret.length() > 0) { if (ret != null && ret.length() > 0) {
boolean isCenterManager = (ret.equals(pubKey)); // 表示此节点是否是平台管理员 boolean isCenterManager = (ret.equals(pubKey)); // 表示此节点是否是平台管理员
ret = KeyValueDBUtil.instance.getValue(NCTables.NodeUser.toString(), pubKey); ret = KeyValueDBUtil.instance.getValue(NCTables.NodeUser.toString(), pubKey);
@ -246,6 +238,7 @@ public class NCHttpHandler extends SimpleChannelInboundHandler<HttpObject> {
String pubkey = map.get("pubKey").getAsString(); String pubkey = map.get("pubKey").getAsString();
boolean verify = SM2Util.plainStrVerify(pubkey, str, map.get("sign").getAsString()); boolean verify = SM2Util.plainStrVerify(pubkey, str, map.get("sign").getAsString());
LOGGER.debug("[CMHttpHandler] HTTP POST 请求验签为 " + verify); LOGGER.debug("[CMHttpHandler] HTTP POST 请求验签为 " + verify);
if (verify) { if (verify) {
// 查permission // 查permission
String ret = getRole(pubkey); String ret = getRole(pubkey);
@ -287,33 +280,30 @@ public class NCHttpHandler extends SimpleChannelInboundHandler<HttpObject> {
cb = new HttpResultCallback(ctx, map.get("callback").getAsString()); cb = new HttpResultCallback(ctx, map.get("callback").getAsString());
cb.addHeader("charset", "utf-8"); cb.addHeader("charset", "utf-8");
cb.addHeader("Content-type", "text/plain"); cb.addHeader("Content-type", "text/plain");
cb.addHeader("Access-Control-Allow-Origin", "*");
cb.addHeader("Access-Control-Allow-Methods", "*");
} else { } else {
if (map.has("callback")) if (map.has("callback"))
cb = new HttpResultCallback(ctx, map.get("callback").getAsString()); cb = new HttpResultCallback(ctx, map.get("callback").getAsString());
else else cb = new HttpResultCallback(ctx, null);
cb = new HttpResultCallback(ctx, null);
cb.addHeader("Access-Control-Allow-Origin", "*");
cb.addHeader("Access-Control-Allow-Methods", "*");
cb.addHeader("charset", "utf-8"); cb.addHeader("charset", "utf-8");
cb.addHeader("Content-type", "application/json"); cb.addHeader("Content-type", "application/json");
} }
actionExecutor.handle(action, map, cb); actionExecutor.handle(action, map, cb);
} else { } else {
DefaultFullHttpResponse response = new DefaultFullHttpResponse(HttpVersion.HTTP_1_1, DefaultFullHttpResponse response =
OK, Unpooled.wrappedBuffer(ret.getBytes())); new DefaultFullHttpResponse(
response.headers().add("Access-Control-Allow-Origin", "*"); HttpVersion.HTTP_1_1, OK, Unpooled.wrappedBuffer(ret.getBytes()));
response.headers().add("Access-Control-Allow-Methods", "*");
ChannelFuture f = ctx.write(response); ChannelFuture f = ctx.write(response);
f.addListener(ChannelFutureListener.CLOSE); f.addListener(ChannelFutureListener.CLOSE);
} }
} catch (IllegalArgumentException e) { } catch (IllegalArgumentException e) {
DefaultFullHttpResponse response = new DefaultFullHttpResponse(HttpVersion.HTTP_1_1, OK, DefaultFullHttpResponse response =
Unpooled.wrappedBuffer(e.getMessage().getBytes())); new DefaultFullHttpResponse(
response.headers().add("Access-Control-Allow-Origin", "*"); HttpVersion.HTTP_1_1,
response.headers().add("Access-Control-Allow-Methods", "*"); OK,
Unpooled.wrappedBuffer(e.getMessage().getBytes()));
ChannelFuture f = ctx.write(response); ChannelFuture f = ctx.write(response);
f.addListener(ChannelFutureListener.CLOSE); f.addListener(ChannelFutureListener.CLOSE);
@ -322,10 +312,11 @@ public class NCHttpHandler extends SimpleChannelInboundHandler<HttpObject> {
ByteArrayOutputStream bo = new ByteArrayOutputStream(); ByteArrayOutputStream bo = new ByteArrayOutputStream();
e.printStackTrace(new PrintStream(bo)); e.printStackTrace(new PrintStream(bo));
ret.put("msg", bo.toString()); ret.put("msg", bo.toString());
DefaultFullHttpResponse response = new DefaultFullHttpResponse(HttpVersion.HTTP_1_1, OK, DefaultFullHttpResponse response =
Unpooled.wrappedBuffer(JsonUtil.toJson(ret).getBytes())); new DefaultFullHttpResponse(
response.headers().add("Access-Control-Allow-Origin", "*"); HttpVersion.HTTP_1_1,
response.headers().add("Access-Control-Allow-Methods", "*"); OK,
Unpooled.wrappedBuffer(JsonUtil.toJson(ret).getBytes()));
ChannelFuture f = ctx.write(response); ChannelFuture f = ctx.write(response);
f.addListener(ChannelFutureListener.CLOSE); f.addListener(ChannelFutureListener.CLOSE);
} }

View File

@ -27,34 +27,27 @@ public class NCManagerAction {
public static final String centerManger = "__CenterManager__"; public static final String centerManger = "__CenterManager__";
public static final String clusterName = "__ClusterName__"; public static final String clusterName = "__ClusterName__";
static final String Licence = "__LICENCE___"; static final String Licence = "__LICENCE___";
static final ECPublicKeyParameters licencePub = BCECUtil.createECPublicKeyFromStrParameters( static final ECPublicKeyParameters licencePub =
"04844412ecb77b07d5ad7097c488ae9dff1013b310d2311f8bd84c491642011e1a6a7041bae8c2ad75da29c27e320bd430abc723cf6bcb0490afc82cc26e6d5637", BCECUtil.createECPublicKeyFromStrParameters(
SM2Util.CURVE, SM2Util.DOMAIN_PARAMS); "04844412ecb77b07d5ad7097c488ae9dff1013b310d2311f8bd84c491642011e1a6a7041bae8c2ad75da29c27e320bd430abc723cf6bcb0490afc82cc26e6d5637",
SM2Util.CURVE,
SM2Util.DOMAIN_PARAMS);
private static final Logger LOGGER = LogManager.getLogger(NCManagerAction.class); private static final Logger LOGGER = LogManager.getLogger(NCManagerAction.class);
String sessionID = null; String sessionID = null;
private String publicKey; String pubKey;
Random random = new Random(); Random random = new Random();
private NodeCenterWSFrameHandler handler; private NodeCenterWSFrameHandler handler;
public NCManagerAction(NodeCenterWSFrameHandler nodeCenterWSFrameHandler) { public NCManagerAction(NodeCenterWSFrameHandler nodeCenterWSFrameHandler) {
this.handler = nodeCenterWSFrameHandler; this.handler = nodeCenterWSFrameHandler;
publicKey = null; pubKey = null;
}
public String getPubKey(JsonObject jo) {
try {
if (publicKey != null)
return publicKey;
return jo.get("pubKey").getAsString();
} catch (Exception e) {
}
return null;
} }
public static boolean isCenterManager(String pubkey) { public static boolean isCenterManager(String pubkey) {
String ret = KeyValueDBUtil.instance.getValue(NCTables.ConfigDB.toString(), centerManger); String ret = KeyValueDBUtil.instance.getValue(NCTables.ConfigDB.toString(), centerManger);
LOGGER.debug("centerManger: " + ret); LOGGER.debug("centerManger: " + ret);
return !StringUtil.isNullOrEmpty(ret) && !StringUtil.isNullOrEmpty(pubkey) return !StringUtil.isNullOrEmpty(ret)
&& !StringUtil.isNullOrEmpty(pubkey)
&& pubkey.equals(ret); && pubkey.equals(ret);
} }
@ -102,8 +95,8 @@ public class NCManagerAction {
@Action(userPermission = 0) @Action(userPermission = 0)
public void setClusterName(JsonObject json, ResultCallback resultCallback) { public void setClusterName(JsonObject json, ResultCallback resultCallback) {
if (json.has("name")) { if (json.has("name")) {
KeyValueDBUtil.instance.setValue(NCTables.ConfigDB.toString(), clusterName, KeyValueDBUtil.instance.setValue(
json.get("name").getAsString()); NCTables.ConfigDB.toString(), clusterName, json.get("name").getAsString());
simpleReply(resultCallback, "onSetClusterName", "success"); simpleReply(resultCallback, "onSetClusterName", "success");
} else { } else {
simpleReply(resultCallback, "onSetClusterName", "failed"); simpleReply(resultCallback, "onSetClusterName", "failed");
@ -111,7 +104,6 @@ public class NCManagerAction {
} }
public void getRole(JsonObject json, ResultCallback resultCallback) { public void getRole(JsonObject json, ResultCallback resultCallback) {
String pubKey = getPubKey(json);
if (pubKey == null) { if (pubKey == null) {
simpleReply(resultCallback, "onLogin", Role.Anonymous.name()); simpleReply(resultCallback, "onLogin", Role.Anonymous.name());
return; return;
@ -134,14 +126,13 @@ public class NCManagerAction {
} else if (role.isEmpty()) { } else if (role.isEmpty()) {
role = Role.Anonymous.name(); role = Role.Anonymous.name();
} }
if (handler != null) handler.setPermission(Role.compoundValue(role.split(",")));
handler.setPermission(Role.compoundValue(role.split(",")));
simpleReply(resultCallback, "onLogin", role); simpleReply(resultCallback, "onLogin", role);
} else { } else {
KeyValueDBUtil.instance.setValue(NCTables.ConfigDB.toString(), centerManger, KeyValueDBUtil.instance.setValue(
pubKey); NCTables.ConfigDB.toString(), centerManger, pubKey);
KeyValueDBUtil.instance.setValue(NCTables.ConfigDB.toString(), clusterName, KeyValueDBUtil.instance.setValue(
"clusterName_" + pubKey.substring(0, 5)); NCTables.ConfigDB.toString(), clusterName, "clusterName_" + pubKey.substring(0, 5));
handler.setPermission(0x30000ffL); handler.setPermission(0x30000ffL);
simpleReply(resultCallback, "onLogin", "CenterManager"); simpleReply(resultCallback, "onLogin", "CenterManager");
} }
@ -165,7 +156,7 @@ public class NCManagerAction {
boolean result = SM2Util.plainStrVerify(pubKey, sessionID, signature); boolean result = SM2Util.plainStrVerify(pubKey, sessionID, signature);
LOGGER.debug("session:" + (sessionID)); LOGGER.debug("session:" + (sessionID));
if (result) { if (result) {
this.publicKey = pubKey; this.pubKey = pubKey;
LOGGER.debug("设置公钥" + pubKey); LOGGER.debug("设置公钥" + pubKey);
getRole(json, resultCallback); getRole(json, resultCallback);
} else { } else {
@ -175,40 +166,8 @@ public class NCManagerAction {
LOGGER.debug("time:" + (end - start)); LOGGER.debug("time:" + (end - start));
} }
@Action(userPermission = 0)
public void resetCenterManager(JsonObject json, ResultCallback resultCallback) {
getNodeRole(json, new ResultCallback() {
@Override
public void onResult(String str) {
if (str.contains(Role.CenterManager.toString())) {
if (json.has("newPubKey")) {
String newPubKey = json.get("newPubKey").getAsString();
KeyValueDBUtil.instance.setValue(NCTables.ConfigDB.toString(), centerManger,
newPubKey);
KeyValueDBUtil.instance.setValue(NCTables.NodeUser.toString(), newPubKey,
Role.CenterManager.toString());
resultCallback.onResult(
"{\"action\":\"onResetCenterManager\",\"data\":\"success\",\"pubKey\":\""
+ newPubKey + "\"}");
} else {
// just keep the same
resultCallback.onResult(
"{\"action\":\"onResetCenterManager\",\"data\":\"success\",\"pubKey\":\""
+ getPubKey(json) + "\"}");
}
} else {
resultCallback.onResult(
"{\"action\":\"onResetCenterManager\",\"data\":\"failed, no permission\"}");
}
}
});
}
@Action(userPermission = 0) @Action(userPermission = 0)
public void applyRole(JsonObject json, ResultCallback resultCallback) { public void applyRole(JsonObject json, ResultCallback resultCallback) {
String pubKey = getPubKey(json);
long start = System.currentTimeMillis(); long start = System.currentTimeMillis();
if (pubKey == null) { if (pubKey == null) {
simpleReply(resultCallback, "onApplyRole", "missing pubKey"); simpleReply(resultCallback, "onApplyRole", "missing pubKey");
@ -217,7 +176,7 @@ public class NCManagerAction {
if (json.has("role")) { if (json.has("role")) {
Role role = Role.parse(json.get("role").getAsString()); Role role = Role.parse(json.get("role").getAsString());
if (role != Role.Anonymous) { if (role != Role.Anonymous) {
applyAtDB(role, getPubKey(json), resultCallback, start); applyAtDB(role, resultCallback, start);
return; return;
} }
} }
@ -227,10 +186,14 @@ public class NCManagerAction {
@Action(userPermission = 1 << 6) @Action(userPermission = 1 << 6)
public void addNode(JsonObject json, ResultCallback resultCallback) { public void addNode(JsonObject json, ResultCallback resultCallback) {
try { try {
KeyValueDBUtil.instance.setValue(NCTables.NodeUser.toString(), KeyValueDBUtil.instance.setValue(
json.get("nodePubKey").getAsString(), Role.Node.toString()); NCTables.NodeUser.toString(),
KeyValueDBUtil.instance.setValue(NCTables.NodeTime.toString(), json.get("nodePubKey").getAsString(),
json.get("nodePubKey").getAsString(), Long.toString(new Date().getTime())); Role.Node.toString());
KeyValueDBUtil.instance.setValue(
NCTables.NodeTime.toString(),
json.get("nodePubKey").getAsString(),
Long.toString(new Date().getTime()));
simpleReply(resultCallback, "onAddNodes", "success"); simpleReply(resultCallback, "onAddNodes", "success");
} catch (Exception e) { } catch (Exception e) {
e.printStackTrace(); e.printStackTrace();
@ -238,9 +201,7 @@ public class NCManagerAction {
} }
} }
private void applyAtDB(Role role, String pubKey, ResultCallback resultCallback, long start) { private void applyAtDB(Role role, ResultCallback resultCallback, long start) {
String str = KeyValueDBUtil.instance.getValue(NCTables.ApplyRole.toString(), pubKey); String str = KeyValueDBUtil.instance.getValue(NCTables.ApplyRole.toString(), pubKey);
String already = KeyValueDBUtil.instance.getValue(NCTables.NodeUser.toString(), pubKey); String already = KeyValueDBUtil.instance.getValue(NCTables.NodeUser.toString(), pubKey);
if (already != null && already.contains(role.toString())) { if (already != null && already.contains(role.toString())) {
@ -249,14 +210,14 @@ public class NCManagerAction {
} }
if (str == null || str.length() == 0) { if (str == null || str.length() == 0) {
KeyValueDBUtil.instance.setValue(NCTables.ApplyRole.toString(), pubKey, role.name()); KeyValueDBUtil.instance.setValue(NCTables.ApplyRole.toString(), pubKey, role.name());
KeyValueDBUtil.instance.setValue(NCTables.ApplyTime.toString(), pubKey, KeyValueDBUtil.instance.setValue(
Long.toString(new Date().getTime())); NCTables.ApplyTime.toString(), pubKey, Long.toString(new Date().getTime()));
} else { } else {
if (!str.contains(role.name())) { if (!str.contains(role.name())) {
KeyValueDBUtil.instance.setValue(NCTables.ApplyRole.toString(), pubKey, KeyValueDBUtil.instance.setValue(
str + "," + role.name()); NCTables.ApplyRole.toString(), pubKey, str + "," + role.name());
KeyValueDBUtil.instance.setValue(NCTables.ApplyTime.toString(), pubKey, KeyValueDBUtil.instance.setValue(
Long.toString(new Date().getTime())); NCTables.ApplyTime.toString(), pubKey, Long.toString(new Date().getTime()));
} }
} }
simpleReply(resultCallback, "onApplyRole", "success!"); simpleReply(resultCallback, "onApplyRole", "success!");
@ -280,9 +241,6 @@ public class NCManagerAction {
long start = System.currentTimeMillis(); long start = System.currentTimeMillis();
String pubKey = json.get("pubKey").getAsString(); String pubKey = json.get("pubKey").getAsString();
boolean isAccept = json.get("isAccept").getAsBoolean(); boolean isAccept = json.get("isAccept").getAsBoolean();
if (json.has("authorizedPubKey")) {
pubKey = json.get("authorizedPubKey").getAsString();
}
LOGGER.debug("[NCManagerAction] " + json.toString()); LOGGER.debug("[NCManagerAction] " + json.toString());
if (pubKey == null || pubKey.length() == 0) { if (pubKey == null || pubKey.length() == 0) {
simpleReply(resultCallback, "onAuthNodeManager", "missing pubKey"); simpleReply(resultCallback, "onAuthNodeManager", "missing pubKey");
@ -308,8 +266,8 @@ public class NCManagerAction {
already = roles; already = roles;
} }
KeyValueDBUtil.instance.setValue(NCTables.NodeUser.toString(), pubKey, already); KeyValueDBUtil.instance.setValue(NCTables.NodeUser.toString(), pubKey, already);
KeyValueDBUtil.instance.setValue(NCTables.NodeTime.toString(), pubKey, KeyValueDBUtil.instance.setValue(
Long.toString(new Date().getTime())); NCTables.NodeTime.toString(), pubKey, Long.toString(new Date().getTime()));
KeyValueDBUtil.instance.delete(NCTables.ApplyRole.toString(), pubKey); KeyValueDBUtil.instance.delete(NCTables.ApplyRole.toString(), pubKey);
KeyValueDBUtil.instance.delete(NCTables.ApplyTime.toString(), pubKey); KeyValueDBUtil.instance.delete(NCTables.ApplyTime.toString(), pubKey);
simpleReply(resultCallback, "onAuthNodeManager", "success"); simpleReply(resultCallback, "onAuthNodeManager", "success");
@ -443,14 +401,13 @@ public class NCManagerAction {
SM2Util.verify(licencePub, content.getBytes(), ByteUtils.fromHexString(sign)); SM2Util.verify(licencePub, content.getBytes(), ByteUtils.fromHexString(sign));
if (verify) { if (verify) {
KeyValueDBUtil.instance.setValue(NCTables.ConfigDB.toString(), Licence, KeyValueDBUtil.instance.setValue(
json.toString()); NCTables.ConfigDB.toString(), Licence, json.toString());
simpleReply(resultCallback, "onUpdateLicence", "success"); simpleReply(resultCallback, "onUpdateLicence", "success");
long end = System.currentTimeMillis(); long end = System.currentTimeMillis();
LOGGER.debug("[listLicence:time]" + (end - start)); LOGGER.debug("[listLicence:time]" + (end - start));
return; return;
} else } else simpleReply(resultCallback, "onUpdateLicence", "failed");
simpleReply(resultCallback, "onUpdateLicence", "failed");
long end = System.currentTimeMillis(); long end = System.currentTimeMillis();
LOGGER.debug("[updateLicence:time]" + (end - start)); LOGGER.debug("[updateLicence:time]" + (end - start));
} }
@ -534,8 +491,14 @@ public class NCManagerAction {
Map<String, String> result = new HashMap<>(); Map<String, String> result = new HashMap<>();
result.put("action", "onTransfer"); result.put("action", "onTransfer");
result.put("data", "now start transfer contract " + contractID + " from node:" + node1ID result.put(
+ " to node:" + node2ID); "data",
"now start transfer contract "
+ contractID
+ " from node:"
+ node1ID
+ " to node:"
+ node2ID);
resultCallback.onResult(result); resultCallback.onResult(result);
} }
} }

View File

@ -1,7 +1,19 @@
package org.bdware.server.nodecenter; package org.bdware.server.nodecenter;
public enum NCTables { public enum NCTables {
NodeUser, NodeTime, ApplyRole, ApplyTime, NodeHttpLog, ContractMeta, ConfigDB, NodeTcpLog, NodesDB, TrustUnitsDB, OtherNCs, NCFile, ApplyNodeManager; NodeUser,
NodeTime,
ApplyRole,
ApplyTime,
NodeHttpLog,
ContractMeta,
ConfigDB,
NodeTcpLog,
NodesDB,
TrustUnitsDB,
OtherNCs,
NCFile,
ApplyNodeManager;
public String toString() { public String toString() {
return "NC_" + super.toString(); return "NC_" + super.toString();

View File

@ -33,21 +33,21 @@ public class NCUDPRunner extends Thread {
} }
public void run() { public void run() {
// TimerTask task = new TimerTask() { // TimerTask task = new TimerTask() {
// //
// @Override // @Override
// public void run(Timeout arg0) throws Exception { // public void run(Timeout arg0) throws Exception {
// Set<Integer> nodes = new HashSet<Integer>(); // Set<Integer> nodes = new HashSet<Integer>();
// for (Integer i:id2IP.keySet()) { // for (Integer i:id2IP.keySet()) {
// UDPNode node = id2IP.get(i); // UDPNode node = id2IP.get(i);
// if (System.currentTimeMillis()-node.lastUpdatedTime<60*1000) { // if (System.currentTimeMillis()-node.lastUpdatedTime<60*1000) {
// nodes.remove(i); // nodes.remove(i);
// } // }
// } // }
// for (Integer i:nodes) // for (Integer i:nodes)
// node.re // node.re
// } // }
// }; // };
id2IP = new HashMap<Integer, UDPNode>(); id2IP = new HashMap<Integer, UDPNode>();
int startPort = mainPort; int startPort = mainPort;
while (true) { while (true) {
@ -82,8 +82,11 @@ public class NCUDPRunner extends Thread {
private void onUDPMessage(UDPMessage msg, DatagramPacket request) { private void onUDPMessage(UDPMessage msg, DatagramPacket request) {
switch (msg.type) { switch (msg.type) {
case shakeHand: case shakeHand:
LOGGER.debug("[NCUDPRunner] shakeHand:" + request.getAddress().getHostAddress() LOGGER.debug(
+ ":" + request.getPort()); "[NCUDPRunner] shakeHand:"
+ request.getAddress().getHostAddress()
+ ":"
+ request.getPort());
id2IP.put(msg.id, new UDPNode(request.getSocketAddress())); id2IP.put(msg.id, new UDPNode(request.getSocketAddress()));
default: default:
} }

View File

@ -1,5 +1,5 @@
package org.bdware.server.nodecenter; package org.bdware.server.nodecenter;
public class NameAndID { public class NameAndID {
String name, id; String name,id;
} }

View File

@ -34,31 +34,40 @@ public class NodeCenterFrameHandler extends SimpleChannelInboundHandler<Object>
this.actions = new NodeCenterActions(this); this.actions = new NodeCenterActions(this);
MetaIndexAction.controller = this; MetaIndexAction.controller = this;
// TODO 添加那个UnitAction. // TODO 添加那个UnitAction.
ae = new ActionExecutor<ResultCallback, JsonObject>(executorService, actions, ae =
new MetaIndexAction()) { new ActionExecutor<ResultCallback, JsonObject>(
@Override executorService, actions, new MetaIndexAction()) {
public boolean checkPermission(Action a, final JsonObject args, long permission) { @Override
long val = a.userPermission(); public boolean checkPermission(
boolean flag; Action a, final JsonObject args, long permission) {
String status = "refuse"; long val = a.userPermission();
String action = args.get("action").getAsString(); boolean flag;
if (val == 0) { String status = "refuse";
flag = true; String action = args.get("action").getAsString();
status = "accept"; if (val == 0) {
} else if ((permission & val) == val) { flag = true;
flag = true; status = "accept";
status = "accept"; } else if ((permission & val) == val) {
} else { flag = true;
flag = false; status = "accept";
} } else {
if (!action.contains("checkAlive")) flag = false;
NodeCenterServer.nodeTcpLogDB.put(action, }
"{\"action\":\"" + action + "\",\"pubKey\":\"" + pubKey if (!action.contains("checkAlive"))
+ "\",\"status\":\"" + status + "\",\"date\":" NodeCenterServer.nodeTcpLogDB.put(
+ System.currentTimeMillis() + "}"); action,
return flag; "{\"action\":\""
} + action
}; + "\",\"pubKey\":\""
+ pubKey
+ "\",\"status\":\""
+ status
+ "\",\"date\":"
+ System.currentTimeMillis()
+ "}");
return flag;
}
};
LOGGER.info("create NodeCenterFrameHandler instance succeed!"); LOGGER.info("create NodeCenterFrameHandler instance succeed!");
} }
@ -71,9 +80,10 @@ public class NodeCenterFrameHandler extends SimpleChannelInboundHandler<Object>
this.ctx = ctx; this.ctx = ctx;
JsonObject map; JsonObject map;
try { try {
map = JsonParser map =
.parseReader(new InputStreamReader(new ByteBufInputStream((ByteBuf) frame))) JsonParser.parseReader(
.getAsJsonObject(); new InputStreamReader(new ByteBufInputStream((ByteBuf) frame)))
.getAsJsonObject();
} catch (Exception e) { } catch (Exception e) {
LOGGER.error("can't handle msg! " + e.getMessage()); LOGGER.error("can't handle msg! " + e.getMessage());
@ -83,12 +93,15 @@ public class NodeCenterFrameHandler extends SimpleChannelInboundHandler<Object>
try { try {
final String action = map.get("action").getAsString(); final String action = map.get("action").getAsString();
// System.out.println("[NodeCenterFramHandler] handle:" + action); // System.out.println("[NodeCenterFramHandler] handle:" + action);
ae.handle(action, map, new ResultCallback() { ae.handle(
@Override action,
public void onResult(String ret) { map,
sendMsg(ret); new ResultCallback() {
} @Override
}); public void onResult(String ret) {
sendMsg(ret);
}
});
} catch (IllegalArgumentException e) { } catch (IllegalArgumentException e) {
response = new Response(); response = new Response();
response.action = "onException"; response.action = "onException";
@ -104,9 +117,12 @@ public class NodeCenterFrameHandler extends SimpleChannelInboundHandler<Object>
StringBuilder ret = new StringBuilder(); StringBuilder ret = new StringBuilder();
int count = 0; int count = 0;
for (String s : strs) { for (String s : strs) {
if (s.contains("sun.reflect") || s.contains("java.lang.reflect") if (s.contains("sun.reflect")
|| s.contains("org.apache") || s.contains("java.util") || s.contains("java.lang.reflect")
|| s.contains("java.lang") || s.contains("io.netty")) { || s.contains("org.apache")
|| s.contains("java.util")
|| s.contains("java.lang")
|| s.contains("io.netty")) {
continue; continue;
} }
ret.append(s); ret.append(s);
@ -120,11 +136,11 @@ public class NodeCenterFrameHandler extends SimpleChannelInboundHandler<Object>
} }
} }
public synchronized void sendMsg(String json) { public void sendMsg(String json) {
if (ctx != null) { if (ctx != null) {
// System.out.println("[NodeCenterFrame send] TID:" + Thread.currentThread().getId() + " // System.out.println("[NodeCenterFrame send] TID:" + Thread.currentThread().getId() + "
// isOpen:" // isOpen:"
// + ctx.channel().isOpen() + " isActive:" + ctx.channel().isActive() + " -->" + json); // + ctx.channel().isOpen() + " isActive:" + ctx.channel().isActive() + " -->" + json);
ByteBuf buf = Unpooled.wrappedBuffer(json.getBytes()); ByteBuf buf = Unpooled.wrappedBuffer(json.getBytes());
ctx.channel().writeAndFlush(buf); ctx.channel().writeAndFlush(buf);
} }

View File

@ -39,35 +39,40 @@ public class NodeCenterWSFrameHandler extends SimpleChannelInboundHandler<WebSoc
logActions = new LogActions(managerAction); logActions = new LogActions(managerAction);
unitActions = new UnitActions(managerAction); unitActions = new UnitActions(managerAction);
fileActions = new FileActions(this); fileActions = new FileActions(this);
ae = new ActionExecutor<ResultCallback, JsonObject>(executorService, managerAction, ae =
logActions, unitActions, fileActions, new MetaIndexAction(), new TracingAction()) { new ActionExecutor<ResultCallback, JsonObject>(
@Override executorService, managerAction, logActions, unitActions, fileActions, new MetaIndexAction(), new TracingAction()) {
public boolean checkPermission(Action a, JsonObject arg, long permission) { @Override
// Permission userPermission = a.userPermission(); public boolean checkPermission(Action a, JsonObject arg, long permission) {
// long val=userPermission.getValue(); // Permission userPermission = a.userPermission();
long val = a.userPermission(); // long val=userPermission.getValue();
String pubKey = managerAction.getPubKey(null); long val = a.userPermission();
String action = arg.get("action").getAsString(); String pubKey = managerAction.pubKey;
LOGGER.debug("permission" + permission); String action = arg.get("action").getAsString();
LOGGER.debug("userPermission" + val); LOGGER.debug("permission" + permission);
NodeCenterServer.nodeHttpLogDB.put(action, LOGGER.debug("userPermission" + val);
"{\"action\":\"" + action + "\",\"pubKey\":\"" + pubKey + "\",\"date\":" NodeCenterServer.nodeHttpLogDB.put(
+ System.currentTimeMillis() + "}"); action,
"{\"action\":\""
+ action
+ "\",\"pubKey\":\""
+ pubKey
+ "\",\"date\":"
+ System.currentTimeMillis()
+ "}");
// if (val == 0) return true; // if (val == 0) return true;
// return true; // return true;
if ((permission & val) == val) { if ((permission & val) == val) {
return true; return true;
} else } else return false;
return false; }
} };
};
for (String str : wsPluginActions) { for (String str : wsPluginActions) {
Object obj = createInstanceByClzName(str); Object obj = createInstanceByClzName(str);
ae.appendHandler(obj); ae.appendHandler(obj);
} }
} }
private Object createInstanceByClzName(String clzName) { private Object createInstanceByClzName(String clzName) {
try { try {
Class<?> clz = Class.forName(clzName, true, pluginLoader); Class<?> clz = Class.forName(clzName, true, pluginLoader);
@ -76,13 +81,12 @@ public class NodeCenterWSFrameHandler extends SimpleChannelInboundHandler<WebSoc
return null; return null;
} }
} }
public ActionExecutor getAE() { public ActionExecutor getAE() {
return ae; return ae;
} }
public String getPubKey() { public String getPubKey() {
return managerAction.getPubKey(null); return managerAction.pubKey;
} }
@Override @Override
@ -108,13 +112,13 @@ public class NodeCenterWSFrameHandler extends SimpleChannelInboundHandler<WebSoc
response.action = "sendNextSegment"; response.action = "sendNextSegment";
try { try {
boolean isSegment = false; boolean isSegment = false;
if (map.has("isSegment")) if (map.has("isSegment")) isSegment = map.get("isSegment").getAsBoolean();
isSegment = map.get("isSegment").getAsBoolean();
if (isSegment) { if (isSegment) {
dataCache.append(map.get("data").getAsString()); dataCache.append(map.get("data").getAsString());
response = new Response(); response = new Response();
response.action = "sendNextSegment"; response.action = "sendNextSegment";
ctx.channel().writeAndFlush(new TextWebSocketFrame(JsonUtil.toJson(response))); ctx.channel()
.writeAndFlush(new TextWebSocketFrame(JsonUtil.toJson(response)));
return; return;
} else { } else {
if (dataCache.length() > 0) { if (dataCache.length() > 0) {
@ -127,29 +131,32 @@ public class NodeCenterWSFrameHandler extends SimpleChannelInboundHandler<WebSoc
} }
String action = map.get("action").getAsString(); String action = map.get("action").getAsString();
final JsonObject jmap = map; final JsonObject jmap = map;
ae.handle(action, map, new ResultCallback() { ae.handle(
@Override action,
public void onResult(Map jo) { map,
if (jmap.has("requestID")) { new ResultCallback() {
jo.put("responseID", jmap.get("requestID")); @Override
} public void onResult(Map jo) {
onResult(JsonUtil.toJson(jo)); if (jmap.has("requestID")) {
} jo.put("responseID", jmap.get("requestID"));
}
onResult(JsonUtil.toJson(jo));
}
@Override @Override
public void onResult(JsonObject jo) { public void onResult(JsonObject jo) {
if (jmap.has("requestID")) { if (jmap.has("requestID")) {
jo.add("responseID", jmap.get("requestID")); jo.add("responseID", jmap.get("requestID"));
} }
onResult(jo.toString()); onResult(jo.toString());
} }
@Override @Override
public void onResult(String ret) { public void onResult(String ret) {
if (ret != null) if (ret != null)
ctx.channel().writeAndFlush(new TextWebSocketFrame(ret)); ctx.channel().writeAndFlush(new TextWebSocketFrame(ret));
} }
}); });
} catch (IllegalArgumentException e) { } catch (IllegalArgumentException e) {
response = new Response(); response = new Response();
response.action = "onException"; response.action = "onException";
@ -166,22 +173,15 @@ public class NodeCenterWSFrameHandler extends SimpleChannelInboundHandler<WebSoc
String ret = ""; String ret = "";
int count = 0; int count = 0;
for (String s : strs) { for (String s : strs) {
if (s.contains("sun.reflect")) if (s.contains("sun.reflect")) continue;
continue; if (s.contains("java.lang.reflect")) continue;
if (s.contains("java.lang.reflect")) if (s.contains("org.apache")) continue;
continue; if (s.contains("java.util")) continue;
if (s.contains("org.apache")) if (s.contains("java.lang")) continue;
continue; if (s.contains("io.netty")) continue;
if (s.contains("java.util"))
continue;
if (s.contains("java.lang"))
continue;
if (s.contains("io.netty"))
continue;
ret += s; ret += s;
ret += "\n"; ret += "\n";
if (count++ > 5) if (count++ > 5) break;
break;
} }
response.data = ret; response.data = ret;
ctx.channel().writeAndFlush(new TextWebSocketFrame(JsonUtil.toJson(response))); ctx.channel().writeAndFlush(new TextWebSocketFrame(JsonUtil.toJson(response)));

View File

@ -31,12 +31,13 @@ import java.util.concurrent.TimeUnit;
public class OtherNCProxy { public class OtherNCProxy {
private static final Logger LOGGER = LogManager.getLogger(OtherNCProxy.class); private static final Logger LOGGER = LogManager.getLogger(OtherNCProxy.class);
public static OtherNCProxy instance = new OtherNCProxy(); public static OtherNCProxy instance = new OtherNCProxy();
private final TreeMap<String, List<OtherNCInfo>> otherNodeCenterInfos = new TreeMap<>(); // key为NC节点的pubkey(非一致的) private final TreeMap<String, List<OtherNCInfo>> otherNodeCenterInfos = new TreeMap<>(); //key为NC节点的pubkey(非一致的)
public Map<String, NCConnector> connList = new ConcurrentHashMap<>(); // 连接别的NC key为ip:port public Map<String, NCConnector> connList = new ConcurrentHashMap<>(); //连接别的NC key为ip:port
public Set<String> ncAdds = ConcurrentHashMap.newKeySet(); // 其他NC的ip:port public Set<String> ncAdds = ConcurrentHashMap.newKeySet(); //其他NC的ip:port
public SM2KeyPair sm2; // NC证书 public SM2KeyPair sm2; //NC证书
private OtherNCProxy() {} private OtherNCProxy() {
}
// 从DB中加载OtherNC和NCFile的信息 // 从DB中加载OtherNC和NCFile的信息
public void init() { public void init() {
@ -55,8 +56,12 @@ public class OtherNCProxy {
} }
public void periodUpdate() { public void periodUpdate() {
NodeCenterServer.scheduledThreadPool.scheduleWithFixedDelay(() -> { NodeCenterServer.scheduledThreadPool.scheduleWithFixedDelay(
}, 0, 30, TimeUnit.SECONDS); () -> {
},
0,
30,
TimeUnit.SECONDS);
} }
public void loadOtherNCs() { public void loadOtherNCs() {
@ -129,7 +134,7 @@ public class OtherNCProxy {
return KeyValueDBUtil.instance.getValue(NCTables.NCFile.toString(), "filePath"); return KeyValueDBUtil.instance.getValue(NCTables.NCFile.toString(), "filePath");
} }
// 配置其他NC //配置其他NC
public String setOtherNCs(String add) { public String setOtherNCs(String add) {
LOGGER.debug("setOtherNC: " + add); LOGGER.debug("setOtherNC: " + add);
@ -138,7 +143,7 @@ public class OtherNCProxy {
return getOtherNCs(); return getOtherNCs();
} }
// 配置NC文件 //配置NC文件
public String setNCFile(String fileName) { public String setNCFile(String fileName) {
LOGGER.debug("setNCFIle: " + fileName); LOGGER.debug("setNCFIle: " + fileName);
@ -147,18 +152,17 @@ public class OtherNCProxy {
return getNCFile(); return getNCFile();
} }
// 本地更新 //本地更新
public void updateOtherNCInfo(String nodePubkey, List<OtherNCInfo> list) { public void updateOtherNCInfo(String nodePubkey, List<OtherNCInfo> list) {
LOGGER.debug("updateOtherNCInfo: "); LOGGER.debug("updateOtherNCInfo: ");
synchronized (otherNodeCenterInfos) { synchronized (otherNodeCenterInfos) {
otherNodeCenterInfos.put(nodePubkey, list); otherNodeCenterInfos.put(nodePubkey, list);
LOGGER.debug( LOGGER.debug("update route nodePubkey=" + nodePubkey + " list=" + JsonUtil.toJson(list));
"update route nodePubkey=" + nodePubkey + " list=" + JsonUtil.toJson(list));
} }
} }
// 通过合约id或name在别的nc上查询信息 //通过合约id或name在别的nc上查询信息
public String search(String id) { public String search(String id) {
LOGGER.debug("search : " + id); LOGGER.debug("search : " + id);
synchronized (otherNodeCenterInfos) { synchronized (otherNodeCenterInfos) {
@ -166,8 +170,7 @@ public class OtherNCProxy {
List<OtherNCInfo> list = otherNodeCenterInfos.get(pubKey); List<OtherNCInfo> list = otherNodeCenterInfos.get(pubKey);
for (OtherNCInfo info : list) { for (OtherNCInfo info : list) {
if (info.contractID.equals(id) || info.contractName.equals(id)) { if (info.contractID.equals(id) || info.contractName.equals(id)) {
LOGGER.debug("[OtherNCProxy] find contract " + id + "pubKey is " + pubKey LOGGER.debug("[OtherNCProxy] find contract " + id + "pubKey is " + pubKey + " master is " + info.master + " from other NC route info");
+ " master is " + info.master + " from other NC route info");
return pubKey + ";" + info.master; return pubKey + ";" + info.master;
} }
} }
@ -176,7 +179,7 @@ public class OtherNCProxy {
} }
} }
// 向其他NC发起同步 //向其他NC发起同步
public void requestUpdate() { public void requestUpdate() {
LOGGER.debug("sendUpdate: "); LOGGER.debug("sendUpdate: ");
for (String add : instance.ncAdds) { for (String add : instance.ncAdds) {
@ -204,8 +207,7 @@ public class OtherNCProxy {
continue; continue;
for (ContractDesp desp : node.contracts) { for (ContractDesp desp : node.contracts) {
if (desp.type == ContractExecType.Sole || desp.getIsMaster()) { if (desp.type == ContractExecType.Sole || desp.getIsMaster()) {
list.add(new OtherNCInfo(desp.contractID, desp.contractName, list.add(new OtherNCInfo(desp.contractID, desp.contractName, node.masterAddress));
node.masterAddress));
} }
} }
} }
@ -225,18 +227,22 @@ public class OtherNCProxy {
b.group(group); b.group(group);
NCConnector conn = new NCConnector(target, b, new NCClientHandler()); NCConnector conn = new NCConnector(target, b, new NCClientHandler());
connList.put(target, conn); connList.put(target, conn);
b.channel(NioSocketChannel.class).handler(new ChannelInitializer<SocketChannel>() { b.channel(NioSocketChannel.class)
@Override .handler(
protected void initChannel(SocketChannel ch) { new ChannelInitializer<SocketChannel>() {
ChannelPipeline p = ch.pipeline(); @Override
p.addLast(new DelimiterCodec()).addLast(conn.handler); protected void initChannel(SocketChannel ch) {
} ChannelPipeline p = ch.pipeline();
}); p.addLast(new DelimiterCodec()).addLast(conn.handler);
}
});
if (!conn.handler.isOpen()) { if (!conn.handler.isOpen()) {
String[] ipAndPort = target.split(":"); String[] ipAndPort = target.split(":");
b.connect(ipAndPort[0], Integer.parseInt(ipAndPort[1])).sync().channel(); b.connect(ipAndPort[0], Integer.parseInt(ipAndPort[1]))
.sync()
.channel();
} }
reconnect(target); reconnect(target);
@ -251,7 +257,10 @@ public class OtherNCProxy {
NCConnector conn = connList.get(target); NCConnector conn = connList.get(target);
if (!conn.handler.isOpen()) { if (!conn.handler.isOpen()) {
String[] ipAndPort = conn.ipAndPort.split(":"); String[] ipAndPort = conn.ipAndPort.split(":");
conn.bootstrap.connect(ipAndPort[0], Integer.parseInt(ipAndPort[1])).sync().channel(); conn.bootstrap
.connect(ipAndPort[0], Integer.parseInt(ipAndPort[1]))
.sync()
.channel();
} }
} }

View File

@ -11,7 +11,7 @@ import java.io.PrintStream;
public class TracingAction { public class TracingAction {
private static JsonObject getDependentContract(JsonObject jo) { private static JsonObject getDependentContract(JsonObject jo) {
// 考虑多层依赖 //考虑多层依赖
JsonObject result = new JsonObject(); JsonObject result = new JsonObject();
JsonArray beDependent = new JsonArray(); JsonArray beDependent = new JsonArray();
String contractName = jo.get("contractName").getAsString(); String contractName = jo.get("contractName").getAsString();
@ -29,8 +29,7 @@ public class TracingAction {
dependencies.add(val); dependencies.add(val);
} }
} else { } else {
if (desp.dependentContracts != null if (desp.dependentContracts != null && desp.dependentContracts.contains(contractName)) {
&& desp.dependentContracts.contains(contractName)) {
beDependent.add(desp.contractName); beDependent.add(desp.contractName);
} }
} }

View File

@ -25,8 +25,7 @@ public class UnitActions {
private static String convertContractName(String contractID) { private static String convertContractName(String contractID) {
ContractDesp desp = NodeCenterActions.getContractByName(contractID); ContractDesp desp = NodeCenterActions.getContractByName(contractID);
if (desp != null) if (desp != null) return desp.contractID;
return desp.contractID;
return contractID; return contractID;
} }
@ -46,10 +45,12 @@ public class UnitActions {
@Action(userPermission = 1 << 6, async = true) @Action(userPermission = 1 << 6, async = true)
public void listTrustUnits(JsonObject json, ResultCallback resultCallback) { public void listTrustUnits(JsonObject json, ResultCallback resultCallback) {
long start = System.currentTimeMillis(); long start = System.currentTimeMillis();
final String pubKey = managerAction.getPubKey(json); final String pubKey = managerAction.pubKey;
List<KV> allunits = KeyValueDBUtil.instance.getKeyValues(NCTables.TrustUnitsDB.toString()); List<KV> allunits = KeyValueDBUtil.instance.getKeyValues(NCTables.TrustUnitsDB.toString());
if (pubKey != null && KeyValueDBUtil.instance if (pubKey != null
.getValue(NCTables.ConfigDB.toString(), "__CenterManager__").contains(pubKey)) { && KeyValueDBUtil.instance
.getValue(NCTables.ConfigDB.toString(), "__CenterManager__")
.contains(pubKey)) {
simpleReply(resultCallback, "onListTrustUnits", allunits); simpleReply(resultCallback, "onListTrustUnits", allunits);
LOGGER.debug("is center manager"); LOGGER.debug("is center manager");
long end = System.currentTimeMillis(); long end = System.currentTimeMillis();
@ -72,10 +73,12 @@ public class UnitActions {
@Action(userPermission = 1 << 6, async = true) @Action(userPermission = 1 << 6, async = true)
public void createTrustUnit(JsonObject json, ResultCallback resultCallback) { public void createTrustUnit(JsonObject json, ResultCallback resultCallback) {
final String pubKey = managerAction.getPubKey(json); final String pubKey = managerAction.pubKey;
LOGGER.debug("[createTrustUnit] " + json.get("data").toString()); LOGGER.debug("[createTrustUnit] " + json.get("data").toString());
KeyValueDBUtil.instance.setValue(NCTables.TrustUnitsDB.toString(), KeyValueDBUtil.instance.setValue(
pubKey + "_" + json.get("msg").getAsString(), json.get("data").toString()); NCTables.TrustUnitsDB.toString(),
pubKey + "_" + json.get("msg").getAsString(),
json.get("data").toString());
Map<String, Object> ret = new HashMap<>(); Map<String, Object> ret = new HashMap<>();
ret.put("action", "onCreateTrustUnit"); ret.put("action", "onCreateTrustUnit");
ret.put("status", "Success"); ret.put("status", "Success");
@ -84,23 +87,27 @@ public class UnitActions {
@Action(userPermission = 1 << 6, async = true) @Action(userPermission = 1 << 6, async = true)
public void deleteTrustUnit(JsonObject json, ResultCallback resultCallback) { public void deleteTrustUnit(JsonObject json, ResultCallback resultCallback) {
// final String pubKey = managerAction.pubKey; // final String pubKey = managerAction.pubKey;
LOGGER.debug("[deleteTrustUnit] before" + KeyValueDBUtil.instance LOGGER.debug(
.getValue(NCTables.TrustUnitsDB.toString(), json.get("data").getAsString())); "[deleteTrustUnit] before"
KeyValueDBUtil.instance.delete(NCTables.TrustUnitsDB.toString(), + KeyValueDBUtil.instance.getValue(
json.get("data").getAsString()); NCTables.TrustUnitsDB.toString(), json.get("data").getAsString()));
LOGGER.debug("[deleteTrustUnit] after" + KeyValueDBUtil.instance KeyValueDBUtil.instance.delete(
.getValue(NCTables.TrustUnitsDB.toString(), json.get("data").getAsString())); NCTables.TrustUnitsDB.toString(), json.get("data").getAsString());
LOGGER.debug(
"[deleteTrustUnit] after"
+ KeyValueDBUtil.instance.getValue(
NCTables.TrustUnitsDB.toString(), json.get("data").getAsString()));
Map<String, Object> ret = new HashMap<>(); Map<String, Object> ret = new HashMap<>();
ret.put("action", "onDeleteTrustUnit"); ret.put("action", "onDeleteTrustUnit");
ret.put("status", "Success"); ret.put("status", "Success");
resultCallback.onResult(ret); resultCallback.onResult(ret);
} }
// @Action(async = true) // @Action(async = true)
// public void executeContract(JsonObject args, final ResultCallback rc) { // public void executeContract(JsonObject args, final ResultCallback rc) {
// executeContractTrustfully(args, rc); // executeContractTrustfully(args, rc);
// } // }
@Action(async = true, userPermission = 1L << 6) @Action(async = true, userPermission = 1L << 6)
public void getNodeTrustUnits(JsonObject json, ResultCallback resultCallback) { public void getNodeTrustUnits(JsonObject json, ResultCallback resultCallback) {
@ -117,88 +124,89 @@ public class UnitActions {
simpleReply(resultCallback, "onGetNodeTrustUnits", nodeunits); simpleReply(resultCallback, "onGetNodeTrustUnits", nodeunits);
} }
// @Action(async = true, userPermission = 0) // @Action(async = true, userPermission = 0)
// public void executeContractTrustfully(JsonObject args, final ResultCallback rc) { // public void executeContractTrustfully(JsonObject args, final ResultCallback rc) {
// String contractID = args.get("contractID").getAsString(); // String contractID = args.get("contractID").getAsString();
// //
// contractID = convertContractName(contractID); // contractID = convertContractName(contractID);
// //
// args.remove("contractID"); // args.remove("contractID");
// args.addProperty("contractID", contractID); // args.addProperty("contractID", contractID);
// String requestID; // String requestID;
// if (!args.has("requestID")) { // if (!args.has("requestID")) {
// requestID = System.currentTimeMillis() + "_" + (int) (Math.random() * 10000); // requestID = System.currentTimeMillis() + "_" + (int) (Math.random() * 10000);
// args.addProperty("requestID", requestID); // args.addProperty("requestID", requestID);
// } else requestID = args.get("requestID").getAsString(); // } else requestID = args.get("requestID").getAsString();
// args.remove("action"); // args.remove("action");
// args.addProperty("action", "executeContractTrustfully"); // args.addProperty("action", "executeContractTrustfully");
// MultiPointContractInfo mInfo = NodeCenterActions.contractID2Members.get(contractID); // MultiPointContractInfo mInfo = NodeCenterActions.contractID2Members.get(contractID);
// args.addProperty("seq", mInfo.getNextSeq()); // args.addProperty("seq", mInfo.getNextSeq());
// args.addProperty("needSeq", ContractType.needSeq(mInfo.type)); // args.addProperty("needSeq", ContractType.needSeq(mInfo.type));
// List<String> nodes = mInfo.members; // List<String> nodes = mInfo.members;
// logger.debug("tid:" + Thread.currentThread().getId() + " contractID:" + contractID); // logger.debug("tid:" + Thread.currentThread().getId() + " contractID:" + contractID);
// if (nodes == null) { // if (nodes == null) {
// rc.onResult( // rc.onResult(
// "{\"status\":\"Error\",\"result\":\"can't locate // "{\"status\":\"Error\",\"result\":\"can't locate contract\",\"action\":\"onExecuteContractTrustfully\"}");
// contract\",\"action\":\"onExecuteContractTrustfully\"}"); // } else {
// } else { // mInfo.rcf.execute(requestID, rc, JsonUtil.toJson(args));
// mInfo.rcf.execute(requestID, rc, JsonUtil.toJson(args)); // }
// } //
// // // add request cache,only for requestAll type contract
// // add request cache,only for requestAll type contract // if (ContractType.needSeq(mInfo.type)) {
// if (ContractType.needSeq(mInfo.type)) { // RequestCache reqc = NodeCenterActions.getCache(contractID);
// RequestCache reqc = NodeCenterActions.getCache(contractID); // reqc.put(args.get("seq").getAsString(), args);
// reqc.put(args.get("seq").getAsString(), args); // }
// } // }
// }
// only for test ADSP //only for test ADSP
// public static void testExecuteContract(JsonObject args, final ResultCallback rc) { // public static void testExecuteContract(JsonObject args, final ResultCallback rc) {
// String contractID = args.get("contractID").getAsString(); // String contractID = args.get("contractID").getAsString();
// //
// contractID = convertContractName(contractID); // contractID = convertContractName(contractID);
// //
// args.remove("contractID"); // args.remove("contractID");
// args.addProperty("contractID", contractID); // args.addProperty("contractID", contractID);
// String requestID; // String requestID;
// if (!args.has("requestID")) { // if (!args.has("requestID")) {
// requestID = System.currentTimeMillis() + "_" + (int) (Math.random() * 10000); // requestID = System.currentTimeMillis() + "_" + (int) (Math.random() * 10000);
// args.addProperty("requestID", requestID); // args.addProperty("requestID", requestID);
// } else requestID = args.get("requestID").getAsString(); // } else requestID = args.get("requestID").getAsString();
// args.remove("action"); // args.remove("action");
// args.addProperty("action", "executeContractTrustfully"); // args.addProperty("action", "executeContractTrustfully");
// MultiPointContractInfo mInfo = NodeCenterActions.contractID2Members.get(contractID); // MultiPointContractInfo mInfo = NodeCenterActions.contractID2Members.get(contractID);
// System.out.println("mInfo是空吗" + mInfo == null); // System.out.println("mInfo是空吗" + mInfo == null);
// //
// args.addProperty("seq", mInfo.getNextSeq()); // args.addProperty("seq", mInfo.getNextSeq());
// args.addProperty("needSeq", ContractType.needSeq(mInfo.type)); // args.addProperty("needSeq", ContractType.needSeq(mInfo.type));
// List<String> nodes = mInfo.members; // List<String> nodes = mInfo.members;
// logger.debug("tid:" + Thread.currentThread().getId() + " contractID:" + contractID); // logger.debug("tid:" + Thread.currentThread().getId() + " contractID:" + contractID);
// if (nodes == null) { // if (nodes == null) {
// rc.onResult( // rc.onResult(
// "{\"status\":\"Error\",\"result\":\"can't locate // "{\"status\":\"Error\",\"result\":\"can't locate contract\",\"action\":\"onExecuteContractTrustfully\"}");
// contract\",\"action\":\"onExecuteContractTrustfully\"}"); // } else {
// } else { // mInfo.rcf.execute(requestID, rc, JsonUtil.toJson(args));
// mInfo.rcf.execute(requestID, rc, JsonUtil.toJson(args)); // }
// } //
// // //add request cache,only for requestAll type contract
// //add request cache,only for requestAll type contract // if(ContractType.needSeq(mInfo.type)){
// if(ContractType.needSeq(mInfo.type)){ // RequestCache reqc = NodeCenterActions.getCache(contractID);
// RequestCache reqc = NodeCenterActions.getCache(contractID); // reqc.put(args.get("seq").getAsString(),args);
// reqc.put(args.get("seq").getAsString(),args); // }
// } // }
// }
@Action(async = true, userPermission = 1L << 6) @Action(async = true, userPermission = 1L << 6)
public void listContractProcess(JsonObject args, final ResultCallback rc) { public void listContractProcess(JsonObject args, final ResultCallback rc) {
List<ContractDesp> info = new ArrayList<>(); List<ContractDesp> info = new ArrayList<>();
LOGGER.debug("[contracts] " + JsonUtil.toPrettyJson(NodeCenterActions.nodeInfos)); LOGGER.debug(
LOGGER.debug("[cid2Nodes]" + JsonUtil.toPrettyJson(NodeCenterActions.contractID2Members)); "[contracts] "
+ JsonUtil.toPrettyJson(NodeCenterActions.nodeInfos));
LOGGER.debug(
"[cid2Nodes]"
+ JsonUtil.toPrettyJson(NodeCenterActions.contractID2Members));
for (String key : NodeCenterActions.contractID2Members.keySet()) { for (String key : NodeCenterActions.contractID2Members.keySet()) {
ContractDesp desp = NodeCenterActions.getContractByID(key); ContractDesp desp = NodeCenterActions.getContractByID(key);
if (desp != null) if (desp != null) info.add(desp);
info.add(desp);
} }
simpleReply(rc, "onListContractProcess", JsonUtil.toJson(info)); simpleReply(rc, "onListContractProcess", JsonUtil.toJson(info));
} }
@ -206,12 +214,15 @@ public class UnitActions {
@Action(userPermission = 1 << 6, async = true) @Action(userPermission = 1 << 6, async = true)
public void listMultiPointContractProcess(JsonObject json, ResultCallback resultCallback) { public void listMultiPointContractProcess(JsonObject json, ResultCallback resultCallback) {
List<ContractDesp> info = new ArrayList<>(); List<ContractDesp> info = new ArrayList<>();
LOGGER.debug("[contracts] " + JsonUtil.toPrettyJson(NodeCenterActions.nodeInfos)); LOGGER.debug(
LOGGER.debug("[cid2Nodes]" + JsonUtil.toPrettyJson(NodeCenterActions.contractID2Members)); "[contracts] "
+ JsonUtil.toPrettyJson(NodeCenterActions.nodeInfos));
LOGGER.debug(
"[cid2Nodes]"
+ JsonUtil.toPrettyJson(NodeCenterActions.contractID2Members));
for (String key : NodeCenterActions.contractID2Members.keySet()) { for (String key : NodeCenterActions.contractID2Members.keySet()) {
ContractDesp desp = NodeCenterActions.getContractByID(key); ContractDesp desp = NodeCenterActions.getContractByID(key);
if (desp != null) if (desp != null) info.add(desp);
info.add(desp);
} }
simpleReply(resultCallback, "onListMultiPointContractProcess", JsonUtil.toJson(info)); simpleReply(resultCallback, "onListMultiPointContractProcess", JsonUtil.toJson(info));
} }
@ -240,8 +251,7 @@ public class UnitActions {
String[] strs = args.get("nodeIDs").getAsString().split(","); String[] strs = args.get("nodeIDs").getAsString().split(",");
Set<String> nodePubKeys = new HashSet<>(); // nodes' pubkey Set<String> nodePubKeys = new HashSet<>(); // nodes' pubkey
for (String str : strs) { for (String str : strs) {
if (str != null && str.length() > 0) if (str != null && str.length() > 0) nodePubKeys.add(str);
nodePubKeys.add(str);
} }
Map<String, String> nodes = new HashMap<>(); // node's pubKey-node'a name Map<String, String> nodes = new HashMap<>(); // node's pubKey-node'a name
for (CMNode node : NodeCenterActions.nodeInfos.values()) { for (CMNode node : NodeCenterActions.nodeInfos.values()) {
@ -254,8 +264,9 @@ public class UnitActions {
simpleReply(rc, "onDistributeYPK", "empty nodes"); simpleReply(rc, "onDistributeYPK", "empty nodes");
} }
boolean result = SM2Util.plainStrVerify(pubKey, boolean result =
"DistributeYPK|" + projectName + "|" + pubKey, signature); SM2Util.plainStrVerify(
pubKey, "DistributeYPK|" + projectName + "|" + pubKey, signature);
LOGGER.info("[UnitAcitons] 验签:" + result + " -> projectName:" + projectName); LOGGER.info("[UnitAcitons] 验签:" + result + " -> projectName:" + projectName);
String ypkType = projectName.split("_")[0]; String ypkType = projectName.split("_")[0];
@ -281,154 +292,154 @@ public class UnitActions {
} }
} }
// @Action(async = true, userPermission = 1L << 6) // @Action(async = true, userPermission = 1L << 6)
// public void startContractMultiPoint(JsonObject args, final ResultCallback rc) { // public void startContractMultiPoint(JsonObject args, final ResultCallback rc) {
// Map<String, String> request = new HashMap<String, String>(); // Map<String, String> request = new HashMap<String, String>();
// Contract contract = new Contract(); // Contract contract = new Contract();
// if (args.has("type")) { // if (args.has("type")) {
// contract.setType(ContractType.valueOf(args.get("type").getAsString())); // contract.setType(ContractType.valueOf(args.get("type").getAsString()));
// } // }
// //
// // this multiPointContractInfo problem // // this multiPointContractInfo problem
// MultiPointContractInfo multiPointContractInfo = new MultiPointContractInfo(); // MultiPointContractInfo multiPointContractInfo = new MultiPointContractInfo();
// multiPointContractInfo.type = contract.getType(); // multiPointContractInfo.type = contract.getType();
// //
// logger.debug("startContractMultiPoint:"); // logger.debug("startContractMultiPoint:");
// logger.debug(JsonUtil.toPrettyJson(args)); // logger.debug(JsonUtil.toPrettyJson(args));
// if (args.has("script")) contract.setScript(args.get("script").getAsString()); // if (args.has("script")) contract.setScript(args.get("script").getAsString());
// else if (args.has("path")) contract.setScript(args.get("path").getAsString()); // else if (args.has("path")) contract.setScript(args.get("path").getAsString());
// else if (args.has("projectName")) // else if (args.has("projectName"))
// contract.setScript("/" + args.get("projectName").getAsString()); // contract.setScript("/" + args.get("projectName").getAsString());
// // contract.setScript("/" + args.get("projectName").getAsString() + "/manifest.json"); // // contract.setScript("/" + args.get("projectName").getAsString() + "/manifest.json");
// //
// SM2 sm2 = new SM2(); // SM2 sm2 = new SM2();
// SM2KeyPair sm2Key = sm2.generateKeyPair(); // SM2KeyPair sm2Key = sm2.generateKeyPair();
// contract.setID(sm2Key.getPublicKeyStr().hashCode() + ""); // contract.setID(sm2Key.getPublicKeyStr().hashCode() + "");
// contract.setKey(sm2Key.getPrivateKey().toString(16)); // contract.setKey(sm2Key.getPrivateKey().toString(16));
// contract.setPublicKey(sm2Key.getPublicKeyStr()); // contract.setPublicKey(sm2Key.getPublicKeyStr());
// //
// contract.setNodeCenterRepoDOI(DOIPMainServer4NC.repoIdentifier); // contract.setNodeCenterRepoDOI(DOIPMainServer4NC.repoIdentifier);
// // 多点合约部署时由NC预先注册一个DOI以备使用 // // 多点合约部署时由NC预先注册一个DOI以备使用
// if (DoConfig.openContractDORegister) { // if (DoConfig.openContractDORegister) {
// try { // try {
// HandleService hs = new HandleService(HandleServiceUtils.hrRegister); // HandleService hs = new HandleService(HandleServiceUtils.hrRegister);
// String tmpDOI = hs.registerContract(DOIPMainServer4NC.repoIdentifier); // String tmpDOI = hs.registerContract(DOIPMainServer4NC.repoIdentifier);
// if (tmpDOI == "" || tmpDOI == null) // if (tmpDOI == "" || tmpDOI == null)
// contract.setDOI("RegisterFailed"); // contract.setDOI("RegisterFailed");
// else // else
// contract.setDOI(tmpDOI); // contract.setDOI(tmpDOI);
// } // }
// catch (Exception e) { // catch (Exception e) {
// e.printStackTrace(); // e.printStackTrace();
// contract.setDOI("RegisterFailed"); // contract.setDOI("RegisterFailed");
// } // }
// } // }
// //
// String[] nodeNames = // String[] nodeNames =
// args.get("peersID").getAsString().split(","); // all nodes' peerID in the unit // args.get("peersID").getAsString().split(","); // all nodes' peerID in the unit
// Set<String> nodeNameSet = new HashSet<>(); // nodes' peerID // Set<String> nodeNameSet = new HashSet<>(); // nodes' peerID
// for (String str : nodeNames) { // for (String str : nodeNames) {
// if (str != null && str.length() > 0) nodeNameSet.add(str); // if (str != null && str.length() > 0) nodeNameSet.add(str);
// } // }
// //
// List<String> udpids = new ArrayList<>(); // nodes' udpID in the unit // List<String> udpids = new ArrayList<>(); // nodes' udpID in the unit
// //
// for (CMNode node : NodeCenterActions.nodeinfos.values()) { // for (CMNode node : NodeCenterActions.nodeinfos.values()) {
// if (nodeNameSet.contains(node.nodeName)) { // if (nodeNameSet.contains(node.nodeName)) {
// udpids.add(node.udpID); // udpids.add(node.udpID);
// } // }
// } // }
// final long curr = System.currentTimeMillis(); // final long curr = System.currentTimeMillis();
// String requestID = curr + "_" + (int) (Math.random() * 10000); // String requestID = curr + "_" + (int) (Math.random() * 10000);
// NodeCenterActions.ResultCollector collector = // NodeCenterActions.ResultCollector collector =
// new NodeCenterActions.ResultCollector( // new NodeCenterActions.ResultCollector(
// requestID, // requestID,
// new ResultCallback() { // new ResultCallback() {
// @Override // @Override
// public void onResult(String str) { // public void onResult(String str) {
// Map<String, String> ret = new HashMap<>(); // Map<String, String> ret = new HashMap<>();
// ret.put("action", "onStartContractTrustfullyResult"); // ret.put("action", "onStartContractTrustfullyResult");
// ret.put("data", str); // ret.put("data", str);
// ret.put("executionTime", (System.currentTimeMillis() - curr) + ""); // ret.put("executionTime", (System.currentTimeMillis() - curr) + "");
// rc.onResult(JsonUtil.toJson(ret)); // rc.onResult(JsonUtil.toJson(ret));
// } // }
// }, // },
// udpids.size()); // udpids.size());
// NodeCenterActions.sync.sleepWithTimeout(requestID, collector, 20); // NodeCenterActions.sync.sleepWithTimeout(requestID, collector, 20);
// //
// // ArrayList<String> udpids=gson.fromJson(args.get("members"), // // ArrayList<String> udpids=gson.fromJson(args.get("members"),
// // new TypeToken<ArrayList<String>>(){}.getType()); // // new TypeToken<ArrayList<String>>(){}.getType());
// Map<String, String> members = new HashMap<>(); // nodes' <udpID,udpAddress> // Map<String, String> members = new HashMap<>(); // nodes' <udpID,udpAddress>
// for (int i = 0; i < udpids.size(); i++) { // for (int i = 0; i < udpids.size(); i++) {
// members.put( // members.put(
// udpids.get(i), // udpids.get(i),
// NodeCenterActions.runner.getUDPAddr(Integer.valueOf(udpids.get(i))) // NodeCenterActions.runner.getUDPAddr(Integer.valueOf(udpids.get(i)))
// + ":" // + ":"
// + (i == 0)); // regard the first node as the master in the unit // + (i == 0)); // regard the first node as the master in the unit
// } // }
// //
// List<String> nodes = new ArrayList<>(); // nodes' pubKey // List<String> nodes = new ArrayList<>(); // nodes' pubKey
// for (CMNode node : NodeCenterActions.nodeinfos.values()) { // for (CMNode node : NodeCenterActions.nodeinfos.values()) {
// if (nodeNameSet.contains(node.nodeName)) { // if (nodeNameSet.contains(node.nodeName)) {
// nodes.add(node.pubKey); // nodes.add(node.pubKey);
// } // }
// } // }
// //
// request.put("memberStr", JsonUtil.toJson(members)); // request.put("memberStr", JsonUtil.toJson(members));
// request.put("isPrivate", args.get("isPrivate").getAsString()); // request.put("isPrivate", args.get("isPrivate").getAsString());
// request.put("pubKey", managerAction.pubKey); // request.put("pubKey", managerAction.pubKey);
// request.put("action", "startContractTrustfully"); // request.put("action", "startContractTrustfully");
// request.put("requestID", requestID); // request.put("requestID", requestID);
// multiPointContractInfo.members = nodes; // multiPointContractInfo.members = nodes;
// //
// contract.setNumOfCopies(1); // contract.setNumOfCopies(1);
// switch (multiPointContractInfo.type) { // switch (multiPointContractInfo.type) {
// case Sole: // case Sole:
// logger.debug("Can't support Solo in multi-point mode"); // logger.debug("Can't support Solo in multi-point mode");
// return; // return;
// case RequestOnce: // case RequestOnce:
// multiPointContractInfo.rcf = new RequestOnceExecutor(multiPointContractInfo); // multiPointContractInfo.rcf = new RequestOnceExecutor(multiPointContractInfo);
// break; // break;
// case ResponseOnce: // case ResponseOnce:
// multiPointContractInfo.rcf = new ResponseOnceExecutor(multiPointContractInfo); // multiPointContractInfo.rcf = new ResponseOnceExecutor(multiPointContractInfo);
// break; // break;
// case RequestAllResponseFirst: // case RequestAllResponseFirst:
// multiPointContractInfo.rcf = new RequestAllExecutor(multiPointContractInfo, 1); // multiPointContractInfo.rcf = new RequestAllExecutor(multiPointContractInfo, 1);
// contract.setNumOfCopies(nodes.size()); // contract.setNumOfCopies(nodes.size());
// break; // break;
// case RequestAllResponseHalf: // case RequestAllResponseHalf:
// multiPointContractInfo.rcf = // multiPointContractInfo.rcf =
// new RequestAllExecutor(multiPointContractInfo, nodes.size() / 2 + 1); // new RequestAllExecutor(multiPointContractInfo, nodes.size() / 2 + 1);
// contract.setNumOfCopies(nodes.size()); // contract.setNumOfCopies(nodes.size());
// break; // break;
// case RequestAllResponseAll: // case RequestAllResponseAll:
// multiPointContractInfo.rcf = // multiPointContractInfo.rcf =
// new RequestAllExecutor(multiPointContractInfo, nodes.size()); // new RequestAllExecutor(multiPointContractInfo, nodes.size());
// contract.setNumOfCopies(nodes.size()); // contract.setNumOfCopies(nodes.size());
// break; // break;
// } // }
// NodeCenterActions.contractID2Members.put(contract.getID(), multiPointContractInfo); // NodeCenterActions.contractID2Members.put(contract.getID(), multiPointContractInfo);
// //
// request.put("contractStr", JsonUtil.toJson(contract)); // request.put("contractStr", JsonUtil.toJson(contract));
// String startReq = JsonUtil.toJson(request); // String startReq = JsonUtil.toJson(request);
// logger.debug("启动合约:" + startReq); // logger.debug("启动合约:" + startReq);
// //
// for (String nodeID : nodes) { // for (String nodeID : nodes) {
// CMNode node; // CMNode node;
// node = NodeCenterActions.nodeinfos.get(nodeID); // node = NodeCenterActions.nodeinfos.get(nodeID);
// node.connection.controller.sendMsg(startReq); // node.connection.controller.sendMsg(startReq);
// //
// if (!NodeCenterActions.recoverMap.containsKey(nodeID)) { // if (!NodeCenterActions.recoverMap.containsKey(nodeID)) {
// NodeCenterActions.recoverMap.put(nodeID, new ConcurrentHashMap<>()); // NodeCenterActions.recoverMap.put(nodeID, new ConcurrentHashMap<>());
// } // }
// ContractRecord record = new ContractRecord(contract.getID()); // ContractRecord record = new ContractRecord(contract.getID());
// record.members = new HashMap<>(members); // record.members = new HashMap<>(members);
// NodeCenterActions.recoverMap.get(nodeID).put(contract.getID(), record); // NodeCenterActions.recoverMap.get(nodeID).put(contract.getID(), record);
// } // }
// //
// rc.onResult( // rc.onResult(
// "{\"status\":\"Success\",\"result\":\"" // "{\"status\":\"Success\",\"result\":\""
// + contract.getID() // + contract.getID()
// + "\",\"action\":\"onStartTrustfulContract\"}"); // + "\",\"action\":\"onStartTrustfulContract\"}");
// } // }
} }

View File

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

View File

@ -23,7 +23,7 @@ public class PermissionHelper {
@Test @Test
public void listClusterHttpAction() { public void listClusterHttpAction() {
ActionExecutor<ResultCallback, JsonObject> ae = NCHttpHandler.getActionExecutor(); ActionExecutor<ResultCallback, JsonObject> ae = NCHttpHandler.getActionExecutor();
Map<String, ActionExecutor.Pair<Method, Object>> handlers = ae.getHandlers(); Map<String, ActionExecutor.Pair<Method, Object>> handlers = ae.getHandlers();
EnumSet<Role> set = EnumSet.allOf(Role.class); EnumSet<Role> set = EnumSet.allOf(Role.class);
set.remove(Role.ContractInstanceManager); set.remove(Role.ContractInstanceManager);
@ -44,8 +44,8 @@ public class PermissionHelper {
printActions(handlers, set); printActions(handlers, set);
} }
private void printActions(Map<String, ActionExecutor.Pair<Method, Object>> handlers, private void printActions(
EnumSet<Role> set) { Map<String, ActionExecutor.Pair<Method, Object>> handlers, EnumSet<Role> set) {
List<Line> lines = new ArrayList<>(); List<Line> lines = new ArrayList<>();
for (String str : handlers.keySet()) { for (String str : handlers.keySet()) {
Method m = handlers.get(str).first(); Method m = handlers.get(str).first();
@ -56,23 +56,23 @@ public class PermissionHelper {
l.permission = a.userPermission(); l.permission = a.userPermission();
l.roles = ""; l.roles = "";
for (Role r : set) for (Role r : set)
if ((r.getValue() & l.permission) == l.permission) if ((r.getValue() & l.permission) == l.permission) l.roles += r.name() + ";";
l.roles += r.name() + ";"; if (l.roles.equals("CenterManager;NodeManager;Node;Anonymous;")) l.roles = "任意角色";
if (l.roles.equals("CenterManager;NodeManager;Node;Anonymous;"))
l.roles = "任意角色";
} }
lines.sort(new Comparator<Line>() { lines.sort(
@Override new Comparator<Line>() {
public int compare(Line o1, Line o2) { @Override
return o1.action.compareTo(o2.action); public int compare(Line o1, Line o2) {
} return o1.action.compareTo(o2.action);
}); }
lines.sort(new Comparator<Line>() { });
@Override lines.sort(
public int compare(Line o1, Line o2) { new Comparator<Line>() {
return o1.roles.compareTo(o2.roles); @Override
} public int compare(Line o1, Line o2) {
}); return o1.roles.compareTo(o2.roles);
}
});
Gson g = new GsonBuilder().setPrettyPrinting().create(); Gson g = new GsonBuilder().setPrettyPrinting().create();
for (Line l : lines) { for (Line l : lines) {

View File

@ -18,7 +18,8 @@ public class TestServer {
public void channelActive(ChannelHandlerContext ctx) { public void channelActive(ChannelHandlerContext ctx) {
LOGGER.info("active"); LOGGER.info("active");
System.out.println("======Active======="); System.out.println("======Active=======");
ctx.channel().writeAndFlush("ACTIVE from Server") ctx.channel()
.writeAndFlush("ACTIVE from Server")
.addListener(future -> LOGGER.info("Active Send Done!!")); .addListener(future -> LOGGER.info("Active Send Done!!"));
} }

View File

@ -1,201 +1,192 @@
package org.bdware.bdserver.test; package org.bdware.bdserver.test;
public class TestADSP { public class TestADSP {
// public static Map<String,String> nodes = new HashMap<String,String>(); // public static Map<String,String> nodes = new HashMap<String,String>();
// //
// private static volatile Boolean flag = false; // private static volatile Boolean flag = false;
// private static int totalRequest = 10; // private static int totalRequest = 10;
// private static int nodeCount = 5; // private static int nodeCount = 5;
// //
// public static String resultPath = "./testADSP/" + "result.txt"; // public static String resultPath = "./testADSP/" + "result.txt";
// public static String contractID = "counter"; // public static String contractID = "counter";
// public static String action = "executeContract"; // public static String action = "executeContract";
// public static String pubkey = // public static String pubkey = "0480204f4ef341359a5f64fcb11baf9ca2e6706ac20cba36ca83066870cf2c1d5de6df67e24e68dde7934af9b31d94a6084281db3d32d5ce42ab8f75bf799aca05";
// "0480204f4ef341359a5f64fcb11baf9ca2e6706ac20cba36ca83066870cf2c1d5de6df67e24e68dde7934af9b31d94a6084281db3d32d5ce42ab8f75bf799aca05"; //
// // public static String operation = "count";
// public static String operation = "count"; // public static String arg = "1";
// public static String arg = "1"; //
// // public static String priKey = "63464fa9587bbf2a022b3d655f4ed49c7d9a4249de1079d52bd5a1fec3308719";
// public static String priKey = // public static String signature = "dfd07c00c5c89fb0f901bed132db4342f49f4560f34c15878636623d2a8716a2c93ad32eeb9ee9c4f1d905df292cb4a1a27aa0171f2856848ce07cfc8022e809";
// "63464fa9587bbf2a022b3d655f4ed49c7d9a4249de1079d52bd5a1fec3308719"; //
// public static String signature = // public static List<String> crashSeries = new ArrayList<String>();
// "dfd07c00c5c89fb0f901bed132db4342f49f4560f34c15878636623d2a8716a2c93ad32eeb9ee9c4f1d905df292cb4a1a27aa0171f2856848ce07cfc8022e809"; // public static AtomicInteger crashIndex = new AtomicInteger();
// //
// public static List<String> crashSeries = new ArrayList<String>(); // public static ConcurrentSet<String> crashSet = new ConcurrentSet<String>();
// public static AtomicInteger crashIndex = new AtomicInteger(); // public static ConcurrentSet<String> recover = new ConcurrentSet<String>();
// //
// public static ConcurrentSet<String> crashSet = new ConcurrentSet<String>(); // public static TestTask tt;
// public static ConcurrentSet<String> recover = new ConcurrentSet<String>(); // public static int period = 3000;
// //
// public static TestTask tt; // static{
// public static int period = 3000; // getSig();
// //
// static{ // nodes.put("zyx's book","0440023d13facddcefbd87f2bb622b1b2b6ca43eb84c0579b82450814233ce557bd7ad7852cd47f1d6df867c5413ecf3dd1954cdbf5a6da683e3a89095f091d83d");
// getSig(); // nodes.put("localNode1","0480f783cf63294224afbd19e175e5c7ea0c5c60ee115ed9e114fe2691eb28cc1680e5fec532d64c80d2f6b737e8b43b94d5a9c73206ac6235c50ff992133e4d38");
// // nodes.put("localNode2","044e0c127e24407ee8a8abd4fe507b32b340ce9775317b8d7b5bb8e182745d6a45c57aaf867d80a5f816a7561564f9294c6aee5916f95e93c0011e16c28b9e849a");
// nodes.put("zyx's // nodes.put("localNode3","0485040cfd94bec672bb8ba184856188963ee4ad339d247a76e2d9819f20e61bfad24ec763b1371998583f9dc0cf55c4d53cb1a2ec84c67aed1aa5203cc84fc78f");
// book","0440023d13facddcefbd87f2bb622b1b2b6ca43eb84c0579b82450814233ce557bd7ad7852cd47f1d6df867c5413ecf3dd1954cdbf5a6da683e3a89095f091d83d"); // nodes.put("localNode4","");
// nodes.put("localNode1","0480f783cf63294224afbd19e175e5c7ea0c5c60ee115ed9e114fe2691eb28cc1680e5fec532d64c80d2f6b737e8b43b94d5a9c73206ac6235c50ff992133e4d38"); // nodes.put("localNode5","");
// nodes.put("localNode2","044e0c127e24407ee8a8abd4fe507b32b340ce9775317b8d7b5bb8e182745d6a45c57aaf867d80a5f816a7561564f9294c6aee5916f95e93c0011e16c28b9e849a"); //
// nodes.put("localNode3","0485040cfd94bec672bb8ba184856188963ee4ad339d247a76e2d9819f20e61bfad24ec763b1371998583f9dc0cf55c4d53cb1a2ec84c67aed1aa5203cc84fc78f"); //
// nodes.put("localNode4",""); // //生成崩溃序列
// nodes.put("localNode5",""); // crashSeries.clear();
// // for(int i = 1;i <= totalRequest;i++){
// // int temp = i % nodeCount;
// //生成崩溃序列 // if(temp == 0)
// crashSeries.clear(); // temp = nodeCount;
// for(int i = 1;i <= totalRequest;i++){ // crashSeries.add("crash localNode" + temp);
// int temp = i % nodeCount; // crashSeries.add("recover localNode" + temp);
// if(temp == 0) // }
// temp = nodeCount; //
// crashSeries.add("crash localNode" + temp); // System.out.println("崩溃序列" + crashSeries.size());
// crashSeries.add("recover localNode" + temp); //
// } // Timer timer = new Timer();
// // tt = new TestTask();
// System.out.println("崩溃序列" + crashSeries.size()); // timer.schedule(tt, new Date(), period);
// // }
// Timer timer = new Timer(); //
// tt = new TestTask(); // static class TestTask extends TimerTask {
// timer.schedule(tt, new Date(), period); // @Override
// } // public void run() {
// // if(TestADSP.getFlag()){
// static class TestTask extends TimerTask { // int index = TestADSP.crashIndex.getAndIncrement();
// @Override // System.out.println("[TestADSP] index=" + TestADSP.crashIndex.get());
// public void run() { //
// if(TestADSP.getFlag()){ // String[] crash = TestADSP.crashSeries.get(index).split(" ");
// int index = TestADSP.crashIndex.getAndIncrement(); // String pubKey = convertNameToPubkey(crash[1]);
// System.out.println("[TestADSP] index=" + TestADSP.crashIndex.get()); // switch (crash[0]){
// // case "crash":
// String[] crash = TestADSP.crashSeries.get(index).split(" "); // if(pubKey != null){
// String pubKey = convertNameToPubkey(crash[1]); // System.out.println("[TestADSP] 令节点 " + crash[1] + "崩溃");
// switch (crash[0]){ // System.out.println(new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(new Date(System.currentTimeMillis())));
// case "crash": // crashSet.add(pubKey);
// if(pubKey != null){ // }
// System.out.println("[TestADSP] 令节点 " + crash[1] + "崩溃"); // break;
// System.out.println(new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(new // case "recover":
// Date(System.currentTimeMillis()))); // if(pubKey != null){
// crashSet.add(pubKey); // if(crashSet.contains(pubKey)){
// } // crashSet.remove(pubKey);
// break; // }
// case "recover": // recover.add(pubKey);
// if(pubKey != null){ // System.out.println("[TestADSP] 令节点 " + crash[1] + "上线");
// if(crashSet.contains(pubKey)){ // System.out.println(new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(new Date(System.currentTimeMillis())));
// crashSet.remove(pubKey); // }
// } // break;
// recover.add(pubKey); // default:
// System.out.println("[TestADSP] 令节点 " + crash[1] + "上线"); // break;
// System.out.println(new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(new // }
// Date(System.currentTimeMillis()))); //
// } //
// break; // try {
// default: // Thread.sleep(period / 2);
// break; // } catch (InterruptedException e) {
// } // e.printStackTrace();
// // }
// //
// try { //
// Thread.sleep(period / 2); //
// } catch (InterruptedException e) { // System.out.println("[TestADSP]发起请求 " + new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(new Date(System.currentTimeMillis())));
// e.printStackTrace(); // JsonObject jo = new JsonObject();
// } // jo.addProperty("action", TestADSP.action);
// // jo.addProperty("contractID", TestADSP.contractID);
// // jo.addProperty("operation", TestADSP.operation);
// // jo.addProperty("arg", TestADSP.arg);
// System.out.println("[TestADSP]发起请求 " + new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(new // jo.addProperty("pubkey",TestADSP.pubkey);
// Date(System.currentTimeMillis()))); // jo.addProperty("signature",TestADSP.signature);
// JsonObject jo = new JsonObject(); // UnitActions.testExecuteContract(jo,null);
// jo.addProperty("action", TestADSP.action); //
// jo.addProperty("contractID", TestADSP.contractID); // if(index == (TestADSP.crashSeries.size() - 1)){
// jo.addProperty("operation", TestADSP.operation); // System.out.println("测试停止!");
// jo.addProperty("arg", TestADSP.arg); // TestADSP.setFlag(false);
// jo.addProperty("pubkey",TestADSP.pubkey); // //TestADSP.check();
// jo.addProperty("signature",TestADSP.signature); // }
// UnitActions.testExecuteContract(jo,null); // }//if
// // }
// if(index == (TestADSP.crashSeries.size() - 1)){ // }
// System.out.println("测试停止!"); //
// TestADSP.setFlag(false); // public static boolean getFlag(){
// //TestADSP.check(); // boolean temp;
// } // synchronized (flag){
// }//if // temp = flag;
// } // }
// } // return temp;
// // }
// public static boolean getFlag(){ //
// boolean temp; // public static void setFlag(boolean temp){
// synchronized (flag){ // synchronized (flag){
// temp = flag; // flag = temp;
// } // System.out.println("[TestADSP]设置flag为" + flag);
// return temp; // }
// } // }
// //
// public static void setFlag(boolean temp){ // public static void getSig(){
// synchronized (flag){ // String temp = contractID + "|" + operation + "|" + arg + "|" + pubkey;
// flag = temp; // SM2 sm2 = new SM2();
// System.out.println("[TestADSP]设置flag为" + flag); // signature = sm2.sign(temp.getBytes(),priKey).toString();
// } // }
// } //
// // //查看结果输出文件
// public static void getSig(){ // public static void check() {
// String temp = contractID + "|" + operation + "|" + arg + "|" + pubkey; // tt.cancel();
// SM2 sm2 = new SM2(); //
// signature = sm2.sign(temp.getBytes(),priKey).toString(); // int correct = 0;
// } // int incorrect = 0;
// // int unavailable = 0;
// //查看结果输出文件 // int fileTotal = 0;
// public static void check() { //
// tt.cancel(); // File file = new File("./front-cluster/testADSP/result.txt");
// // System.out.println(file.getAbsolutePath());
// int correct = 0; // StringBuilder result = new StringBuilder();
// int incorrect = 0; // try{
// int unavailable = 0; // BufferedReader br = new BufferedReader(new InputStreamReader(new FileInputStream(file), "UTF-8"));//构造一个BufferedReader类来读取文件
// int fileTotal = 0; //
// // String s = null;
// File file = new File("./front-cluster/testADSP/result.txt"); // while((s = br.readLine())!=null){//使用readLine方法一次读一行
// System.out.println(file.getAbsolutePath()); // if(!s.equals("")){
// StringBuilder result = new StringBuilder(); // fileTotal++;
// try{ // String str[] = s.split(" ");
// BufferedReader br = new BufferedReader(new InputStreamReader(new FileInputStream(file), // if(str[1].equals((Integer.parseInt(str[0]) + 1) + ".0")){
// "UTF-8"));//构造一个BufferedReader类来读取文件 // correct++;
// // }else{
// String s = null; // incorrect++;
// while((s = br.readLine())!=null){//使用readLine方法一次读一行 // }
// if(!s.equals("")){ // }
// fileTotal++; // }
// String str[] = s.split(" "); // br.close();
// if(str[1].equals((Integer.parseInt(str[0]) + 1) + ".0")){ //
// correct++; // }catch(Exception e){
// }else{ // e.printStackTrace();
// incorrect++; // }
// } //
// } // unavailable = totalRequest * 2 - fileTotal;
// } //
// br.close(); // System.out.println("共有" + totalRequest * 2 + "次请求,其中" + correct + "正确," + incorrect + "不正确," + unavailable + "不可用.");
// // }
// }catch(Exception e){ //
// e.printStackTrace(); // public static String convertNameToPubkey(String nodeName){
// } // return nodes.get(nodeName);
// // }
// unavailable = totalRequest * 2 - fileTotal; //
// // public static String convertPubKeyToName(String pubkey){
// System.out.println("共有" + totalRequest * 2 + "次请求,其中" + correct + "正确," + incorrect + "不正确," // for(String key : nodes.keySet()){
// + unavailable + "不可用."); // if(nodes.get(key).equals(pubkey)){
// } // return key;
// // }
// public static String convertNameToPubkey(String nodeName){ // }
// return nodes.get(nodeName); // return null;
// } // }
// //
// public static String convertPubKeyToName(String pubkey){ // public static void main(String[] args){
// for(String key : nodes.keySet()){ // check();
// if(nodes.get(key).equals(pubkey)){ // }
// return key;
// }
// }
// return null;
// }
//
// public static void main(String[] args){
// check();
// }
} }

View File

@ -32,44 +32,44 @@ public class TestSearch {
@Test @Test
public void testIndexSearch() throws Exception { public void testIndexSearch() throws Exception {
// 1. 创建分词器(对搜索的关键词进行分词使用) //1. 创建分词器(对搜索的关键词进行分词使用)
// 注意: 分词器要和创建索引的时候使用的分词器一模一样 //注意: 分词器要和创建索引的时候使用的分词器一模一样
Analyzer analyzer = new StandardAnalyzer(); Analyzer analyzer = new StandardAnalyzer();
// 2. 创建查询对象, //2. 创建查询对象,
// 第一个参数: 默认查询域, 如果查询的关键字中带搜索的域名, 则从指定域中查询, 如果不带域名则从, 默认搜索域中查询 //第一个参数: 默认查询域, 如果查询的关键字中带搜索的域名, 则从指定域中查询, 如果不带域名则从, 默认搜索域中查询
// 第二个参数: 使用的分词器 //第二个参数: 使用的分词器
QueryParser queryParser = new QueryParser("name", analyzer); QueryParser queryParser = new QueryParser("name", analyzer);
// 3. 设置搜索关键词 //3. 设置搜索关键词
// OR // OR
Query query = queryParser.parse("华为手机"); Query query = queryParser.parse("华为手机");
// 4. 创建Directory目录对象, 指定索引库的位置 //4. 创建Directory目录对象, 指定索引库的位置
Directory dir = FSDirectory.open(Paths.get("E:\\dir")); Directory dir = FSDirectory.open(Paths.get("E:\\dir"));
// 5. 创建输入流对象 //5. 创建输入流对象
IndexReader indexReader = DirectoryReader.open(dir); IndexReader indexReader = DirectoryReader.open(dir);
// 6. 创建搜索对象 //6. 创建搜索对象
IndexSearcher indexSearcher = new IndexSearcher(indexReader); IndexSearcher indexSearcher = new IndexSearcher(indexReader);
// 7. 搜索, 并返回结果 //7. 搜索, 并返回结果
// 第二个参数: 是返回多少条数据用于展示, 分页使用 //第二个参数: 是返回多少条数据用于展示, 分页使用
TopDocs topDocs = indexSearcher.search(query, 10); TopDocs topDocs = indexSearcher.search(query, 10);
// 获取查询到的结果集的总数, 打印 //获取查询到的结果集的总数, 打印
System.out.println("=======count=======" + topDocs.totalHits); System.out.println("=======count=======" + topDocs.totalHits);
// 8. 获取结果集 //8. 获取结果集
ScoreDoc[] scoreDocs = topDocs.scoreDocs; ScoreDoc[] scoreDocs = topDocs.scoreDocs;
// 9. 遍历结果集 //9. 遍历结果集
if (scoreDocs != null) { if (scoreDocs != null) {
for (ScoreDoc scoreDoc : scoreDocs) { for (ScoreDoc scoreDoc : scoreDocs) {
// 获取查询到的文档唯一标识, 文档id, 这个id是lucene在创建文档的时候自动分配的 //获取查询到的文档唯一标识, 文档id, 这个id是lucene在创建文档的时候自动分配的
int docID = scoreDoc.doc; int docID = scoreDoc.doc;
// 通过文档id, 读取文档 //通过文档id, 读取文档
Document doc = indexSearcher.doc(docID); Document doc = indexSearcher.doc(docID);
System.out.println("=================================================="); System.out.println("==================================================");
// 通过域名, 从文档中获取域值 //通过域名, 从文档中获取域值
System.out.println("===id==" + doc.get("id")); System.out.println("===id==" + doc.get("id"));
System.out.println("===name==" + doc.get("name")); System.out.println("===name==" + doc.get("name"));
System.out.println("===price==" + doc.get("price")); System.out.println("===price==" + doc.get("price"));
@ -79,6 +79,6 @@ public class TestSearch {
} }
} }
// 10. 关闭流 //10. 关闭流
} }
} }