add ClusterUtil

update @Router arguments
add DOIPUtilTest
update log4j2.properties
This commit is contained in:
CaiHQ 2022-06-26 17:48:03 +08:00
parent 5f42ed082c
commit e5e16a5e1d
11 changed files with 160 additions and 29 deletions

View File

@ -6,7 +6,7 @@ plugins {
} }
group = "org.bdware.sc" group = "org.bdware.sc"
version = "1.6.0" version = "1.6.2"
repositories { repositories {
mavenCentral() mavenCentral()
mavenLocal() mavenLocal()
@ -58,7 +58,7 @@ jar {
} }
from { from {
// uncomment this when publish! // uncomment this when publish!
// configurations.compile.collect { it.isDirectory() ? it : zipTree(it) } // configurations.compile.collect { it.isDirectory() ? it : zipTree(it) }
} }
manifest { manifest {
attributes 'Manifest-Version': project.version attributes 'Manifest-Version': project.version
@ -75,12 +75,10 @@ task copyLibs(type: Copy, dependsOn: ":common:jar") {
from configurations.runtimeClasspath from configurations.runtimeClasspath
} }
task copyJar(type: Copy, dependsOn: [":cp:jar",":copyLog4jProp"]) { task copyJar(type: Copy, dependsOn: [":cp:jar", ":cp:copyLog4jProp"]) {
into "./build/output/" into "./build/output/"
from "./build/libs/$project.name-${version}.jar" from "./build/libs/$project.name-${version}.jar"
rename { String fileName -> "yjs.jar" } rename { String fileName -> "yjs.jar" }
from "./src/main/resources/log4j2.debug.properties"
from "./src/main/resources/log4j2.properties"
} }
task copyLog4jProp(type: Copy) { task copyLog4jProp(type: Copy) {
into "./build/output/" into "./build/output/"

View File

@ -27,6 +27,7 @@ import org.bdware.sc.conn.ByteUtil;
import org.bdware.sc.conn.ServiceServer; import org.bdware.sc.conn.ServiceServer;
import org.bdware.sc.conn.SocketGet; import org.bdware.sc.conn.SocketGet;
import org.bdware.sc.engine.DesktopEngine; import org.bdware.sc.engine.DesktopEngine;
import org.bdware.sc.engine.JSONTool;
import org.bdware.sc.engine.hook.*; import org.bdware.sc.engine.hook.*;
import org.bdware.sc.handler.ContractHandler; import org.bdware.sc.handler.ContractHandler;
import org.bdware.sc.index.TimeSerialIndex; import org.bdware.sc.index.TimeSerialIndex;
@ -38,6 +39,7 @@ import org.bdware.sc.util.JsonUtil;
import org.objectweb.asm.ClassReader; import org.objectweb.asm.ClassReader;
import org.objectweb.asm.tree.ClassNode; import org.objectweb.asm.tree.ClassNode;
import org.objectweb.asm.tree.MethodNode; import org.objectweb.asm.tree.MethodNode;
import wrp.jdk.nashorn.api.scripting.ScriptObjectMirror;
import javax.script.ScriptContext; import javax.script.ScriptContext;
import javax.script.ScriptEngine; import javax.script.ScriptEngine;
@ -106,15 +108,15 @@ public class ContractProcess {
Scanner sc = new Scanner(pidInput); Scanner sc = new Scanner(pidInput);
for (String str; sc.hasNextLine(); ) { for (String str; sc.hasNextLine(); ) {
str = sc.nextLine(); str = sc.nextLine();
System.out.println("[CP From STDIN] " + str); LOGGER.info("[CP From STDIN] " + str);
if (str.contains("CP PID:")) { if (str.contains("CP PID:")) {
int pid = Integer.parseInt(str.replace("CP PID:", "")); int pid = Integer.parseInt(str.replace("CP PID:", ""));
System.setProperty("io.netty.processId", pid + ""); System.setProperty("io.netty.processId", pid + "");
System.out.println("[CP SET PID DONE] " + str); LOGGER.info("[CP SET PID DONE] " + str);
break; break;
} }
} }
System.out.println("[Create CP]"); LOGGER.info("[Create CP]");
instance = new ContractProcess(port, cmi); instance = new ContractProcess(port, cmi);
} }
@ -449,6 +451,13 @@ public class ContractProcess {
return ""; return "";
} }
public String setMembers(List<String> members) {
JavaScriptEntry.members = members;
if (members != null)
return members.size() + "";
else return "0";
}
public String setContractBundle(Contract contract) { public String setContractBundle(Contract contract) {
try { try {
// long start = System.currentTimeMillis(); // long start = System.currentTimeMillis();
@ -733,6 +742,11 @@ public class ContractProcess {
invoke(start, onCreate, funNode); invoke(start, onCreate, funNode);
} }
public void resetContractName(String name) {
if (name != null)
cn.resetContractName(name);
}
private void invokeOnRecover(JsonElement arg) { private void invokeOnRecover(JsonElement arg) {
long start = System.currentTimeMillis(); long start = System.currentTimeMillis();
ContractRequest onRecover = new ContractRequest(); ContractRequest onRecover = new ContractRequest();
@ -853,8 +867,12 @@ public class ContractProcess {
JsonObject body = JsonUtil.parseString(arg).getAsJsonObject(); JsonObject body = JsonUtil.parseString(arg).getAsJsonObject();
String funcName = body.get("funcName").getAsString(); String funcName = body.get("funcName").getAsString();
JsonArray arr = body.getAsJsonArray("funcArgs"); JsonArray arr = body.getAsJsonArray("funcArgs");
Object[] funcArgs = JsonUtil.fromJson(arr, Object[].class); Object[] funcArgs = new Object[arr.size()];
for (int i = 0; i < arr.size(); i++) {
funcArgs[i] = JSONTool.convertJsonElementToMirror(arr.get(i));
}
Object result = engine.invokeFunction(funcName, funcArgs); Object result = engine.invokeFunction(funcName, funcArgs);
result = JSONTool.convertMirrorToJson(result);
return JsonUtil.toJson(result); return JsonUtil.toJson(result);
} catch (Exception e) { } catch (Exception e) {
ByteArrayOutputStream bo = new ByteArrayOutputStream(); ByteArrayOutputStream bo = new ByteArrayOutputStream();

View File

@ -60,11 +60,25 @@ public class JavaScriptEntry {
public static boolean isDebug; public static boolean isDebug;
public static List<REvent> msgList; public static List<REvent> msgList;
public static int shardingID; public static int shardingID;
public static List<String> members;
// private static SM2KeyPair keyPair = new SM2().generateKeyPair(); // TODO 本地服务器的,39上运行39的 // private static SM2KeyPair keyPair = new SM2().generateKeyPair(); // TODO 本地服务器的,39上运行39的
// public static String privKey; // public static String privKey;
// public static String pubKey; // public static String pubKey;
private static SM2KeyPair keyPair; private static SM2KeyPair keyPair;
public static boolean resetContractName(String name) {
StackTraceElement[] stacktrace = Thread.currentThread().getStackTrace();
String method = null;
if (stacktrace.length > 2) {
method = stacktrace[2].getMethodName();
}
if (method != null && method.equals("onCreate")) {
ContractProcess.instance.resetContractName(name);
return true;
}
return false;
}
public static void setSM2KeyPair(String pubKey, String privKey) { public static void setSM2KeyPair(String pubKey, String privKey) {
keyPair = keyPair =
new SM2KeyPair( new SM2KeyPair(

View File

@ -0,0 +1,58 @@
package org.bdware.sc.boundry.utils;
import com.google.gson.JsonArray;
import org.bdware.sc.boundry.JavaScriptEntry;
import org.bdware.sc.compiler.PermissionStub;
import org.bdware.sc.engine.JSONTool;
import org.bdware.sc.node.Permission;
import org.bdware.sc.util.JsonUtil;
import wrp.jdk.nashorn.internal.objects.NativeArray;
import wrp.jdk.nashorn.internal.runtime.PropertyMap;
import wrp.jdk.nashorn.internal.runtime.ScriptObject;
import wrp.jdk.nashorn.internal.scripts.JO;
import javax.crypto.*;
import javax.crypto.spec.IvParameterSpec;
import javax.crypto.spec.SecretKeySpec;
import javax.xml.bind.DatatypeConverter;
import java.security.InvalidAlgorithmParameterException;
import java.security.InvalidKeyException;
import java.security.NoSuchAlgorithmException;
@PermissionStub(permission = Permission.Cluster)
public class ClusterUtil {
public static int getShardingID() {
return JavaScriptEntry.shardingID;
}
public static Object getMembers() {
if (JavaScriptEntry.members == null) {
return new NativeArray();
}
NativeArray narray = new NativeArray();
for (int i = 0; i < JavaScriptEntry.members.size(); i++)
NativeArray.push(narray, JavaScriptEntry.members.get(i));
return narray;
}
public static String getMember(int i) {
return JavaScriptEntry.members.get(i);
}
public static int getMembersSize() {
if (JavaScriptEntry.members != null)
return JavaScriptEntry.members.size();
return 1;
}
public static Object getCurrentNodeID() {
if (isCluster()) {
return JavaScriptEntry.members.get(JavaScriptEntry.shardingID);
}
return null;
}
public static boolean isCluster() {
return (JavaScriptEntry.members != null);
}
}

View File

@ -116,7 +116,6 @@ public class RocksDBUtil {
} }
public ScriptObject getNext(RocksIterator iter) { public ScriptObject getNext(RocksIterator iter) {
if (iter.isValid()) { if (iter.isValid()) {
JO ret = new JO(PropertyMap.newMap()); JO ret = new JO(PropertyMap.newMap());
ret.put("key", new String(iter.key()), false); ret.put("key", new String(iter.key()), false);

View File

@ -19,8 +19,9 @@ import org.bdware.sc.node.FunctionNode;
public class ArgSchemaHandler implements AnnotationHook { public class ArgSchemaHandler implements AnnotationHook {
private AnnotationNode a; private AnnotationNode a;
private static final Logger LOGGER = LogManager.getLogger(ArgSchemaHandler.class); private static final Logger LOGGER = LogManager.getLogger(ArgSchemaHandler.class);
public ArgSchemaHandler(AnnotationNode annoNode){
a=annoNode; public ArgSchemaHandler(AnnotationNode annoNode) {
a = annoNode;
String arg = a.getArgs().get(0); String arg = a.getArgs().get(0);
// if (arg.startsWith("/")){ // if (arg.startsWith("/")){
@ -29,25 +30,25 @@ public class ArgSchemaHandler implements AnnotationHook {
// ; // ;
// } // }
} }
public static ArgSchemaHandler fromAnnotationNode(FunctionNode funNode, AnnotationNode annoNode){
public static ArgSchemaHandler fromAnnotationNode(FunctionNode funNode, AnnotationNode annoNode) {
//a= annoNode; //a= annoNode;
return new ArgSchemaHandler(annoNode); return new ArgSchemaHandler(annoNode);
} }
@Override @Override
public Object handle(ContractRequest input, JSEngine Engine, Object ret) throws ScriptReturnException { public Object handle(ContractRequest input, JSEngine Engine, Object ret) throws ScriptReturnException {
//input.getArg(); //input.getArg();
DesktopEngine desktopEngine = (DesktopEngine) Engine; JsonElement je = input.getArg();
ArgSchemaVisitor visitor = new ArgSchemaVisitor(JsonParser.parseString(input.getArg().getAsString())); ArgSchemaVisitor visitor;
if (je.isJsonObject())
visitor = new ArgSchemaVisitor(input.getArg().getAsJsonObject());
System.out.println(JsonParser.parseString(input.getArg().getAsString())); else
System.out.println(JsonParser.parseString(a.getArgs().get(0))); visitor = new ArgSchemaVisitor(JsonParser.parseString(input.getArg().toString()));
if (je.toString().isEmpty() && !a.getArgs().get(0).equals("")) {
if(input.getArg().getAsString().isEmpty()&&!a.getArgs().get(0).equals("")){
JsonObject jo = new JsonObject(); JsonObject jo = new JsonObject();
jo.addProperty("msg", "[Empty argument] argument should not be empty"); jo.addProperty("msg", "[Empty argument] argument should not be empty");
jo.addProperty("code", 1003); jo.addProperty("code", 1003);
//jo.add("code":);
throw new ScriptReturnException(jo); throw new ScriptReturnException(jo);
} }
visitor.visit(JsonParser.parseString(a.getArgs().get(0))); visitor.visit(JsonParser.parseString(a.getArgs().get(0)));
@ -55,7 +56,6 @@ public class ArgSchemaHandler implements AnnotationHook {
JsonObject jo = new JsonObject(); JsonObject jo = new JsonObject();
jo.addProperty("msg", visitor.getException()); jo.addProperty("msg", visitor.getException());
jo.addProperty("code", visitor.errorCode); jo.addProperty("code", visitor.errorCode);
//jo.add("code":);
throw new ScriptReturnException(jo); throw new ScriptReturnException(jo);
} }
return ret; return ret;

View File

@ -1,5 +1,6 @@
package org.bdware.sc.handler; package org.bdware.sc.handler;
import com.google.gson.reflect.TypeToken;
import org.apache.logging.log4j.LogManager; import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger; import org.apache.logging.log4j.Logger;
import org.bdware.sc.ContractProcess; import org.bdware.sc.ContractProcess;
@ -12,6 +13,7 @@ import org.bdware.sc.get.GetMessage;
import org.bdware.sc.util.JsonUtil; import org.bdware.sc.util.JsonUtil;
import java.util.HashMap; import java.util.HashMap;
import java.util.List;
import java.util.Map; import java.util.Map;
public class ContractHandler extends MsgHandler implements Runnable { public class ContractHandler extends MsgHandler implements Runnable {
@ -100,6 +102,10 @@ public class ContractHandler extends MsgHandler implements Runnable {
cb.onResult(cs.setContractBundle(JsonUtil.fromJson(msg.arg, Contract.class))); cb.onResult(cs.setContractBundle(JsonUtil.fromJson(msg.arg, Contract.class)));
} }
@Description("set members")
public void setMembers(GetMessage msg, ResultCallback cb) {
cb.onResult(cs.setMembers(JsonUtil.fromJson(msg.arg,new TypeToken<List<String>>(){}.getType())));
}
@Description("get current contract name") @Description("get current contract name")
public void getContractName(GetMessage msg, ResultCallback cb) { public void getContractName(GetMessage msg, ResultCallback cb) {
cb.onResult(cs.getContractName()); cb.onResult(cs.getContractName());

View File

@ -7,4 +7,3 @@ appender.console.layout.pattern=%highlight{[%-5p] %d{HH:mm:ss.SSS} %m (%F:%L)[%M
rootLogger.level=all rootLogger.level=all
rootLogger.appenderRef.stdout.ref=STDOUT rootLogger.appenderRef.stdout.ref=STDOUT
rootLogger.appenderRef.log.ref=log

View File

@ -1,5 +1,5 @@
filter.threshold.type=ThresholdFilter filter.threshold.type=ThresholdFilter
filter.threshold.level=error filter.threshold.level=all
appender.console.type=Console appender.console.type=Console
appender.console.name=STDOUT appender.console.name=STDOUT
appender.console.layout.type=PatternLayout appender.console.layout.type=PatternLayout
@ -7,4 +7,4 @@ appender.console.layout.pattern=%highlight{[%-5p] %d{HH:mm:ss.SSS} %m (%F:%L)[%M
rootLogger.level=error rootLogger.level=error
rootLogger.appenderRef.stdout.ref=STDOUT rootLogger.appenderRef.stdout.ref=STDOUT
rootLogger.appenderRef.log.ref=log rootLogger.appenderRef.stdout.level=error

View File

@ -0,0 +1,39 @@
package org.bdware.sc;
import com.google.gson.JsonArray;
import com.google.gson.JsonObject;
import jdk.nashorn.internal.objects.Global;
import org.bdware.sc.bean.Contract;
import org.bdware.sc.engine.JSONTool;
import org.bdware.sc.util.JsonUtil;
import org.junit.Test;
public class ExecuteFunctionWithoutLimitTest {
@Test
public void go(){
String arg = "{\"funcName\":\"getWriteCandidates\",\"funcArgs\":[\"041016acfbc8f4068a24d38a99a1355449ba958f7e905d66617cec9eda311e3001f8d15a4440b6eb61d7b7bd94bb434b30a518623c1593540e7d32eb72fe8088e1\",[\"04a68e0f34cd28484f67cf4e108eb64b8d565d18ecd916e9049151f97d1553872bf8706b3be9e418b7e6136e627d8e81c82a7ce3fd7045ed5382ae3196aa3ac418\",\"041016acfbc8f4068a24d38a99a1355449ba958f7e905d66617cec9eda311e3001f8d15a4440b6eb61d7b7bd94bb434b30a518623c1593540e7d32eb72fe8088e1\",\"04cd228cc3eeec97d912a5158eb25edfcb37947f9934a7645a3311eeeb06f1af05f155f2019ff1edc716d3d10a79a67714284a06ef16d61ccea80aa6816110d157\"],3,{\"doId\":\"abc\",\"body\":\"abcdefg\"}]}";
JsonObject body = JsonUtil.parseString(arg).getAsJsonObject();
String funcName = body.get("funcName").getAsString();
JsonArray arr = body.getAsJsonArray("funcArgs");
Object[] funcArgs = JsonUtil.fromJson(arr, Object[].class);
System.out.println(funcArgs);
}
@Test
public void go2(){
ContractProcess instance = new ContractProcess(124,"bac");
Contract c = new Contract();
c.setScript("contract abc{}");
instance.setContract(c);
String arg = "{\"funcName\":\"getWriteCandidates\",\"funcArgs\":[\"041016acfbc8f4068a24d38a99a1355449ba958f7e905d66617cec9eda311e3001f8d15a4440b6eb61d7b7bd94bb434b30a518623c1593540e7d32eb72fe8088e1\",[\"04a68e0f34cd28484f67cf4e108eb64b8d565d18ecd916e9049151f97d1553872bf8706b3be9e418b7e6136e627d8e81c82a7ce3fd7045ed5382ae3196aa3ac418\",\"041016acfbc8f4068a24d38a99a1355449ba958f7e905d66617cec9eda311e3001f8d15a4440b6eb61d7b7bd94bb434b30a518623c1593540e7d32eb72fe8088e1\",\"04cd228cc3eeec97d912a5158eb25edfcb37947f9934a7645a3311eeeb06f1af05f155f2019ff1edc716d3d10a79a67714284a06ef16d61ccea80aa6816110d157\"],3,{\"doId\":\"abc\",\"body\":\"abcdefg\"}]}";
JsonObject body = JsonUtil.parseString(arg).getAsJsonObject();
String funcName = body.get("funcName").getAsString();
JsonArray arr = body.getAsJsonArray("funcArgs");
Object[] funcArgs = new Object[arr.size()];
for (int i = 0; i < arr.size(); i++) {
funcArgs[i] = JSONTool.convertJsonElementToMirror(arr.get(i));
}
System.out.println(funcArgs);
}
}

View File

@ -1,7 +1,7 @@
package org.bdware.sc.boundry.utils.test; package org.bdware.sc.boundry.utils.test;
import org.apache.log4j.LogManager; import org.apache.logging.log4j.LogManager;
import org.apache.log4j.Logger; import org.apache.logging.log4j.Logger;
import org.bdware.sc.boundry.utils.DOIPUtil; import org.bdware.sc.boundry.utils.DOIPUtil;
import org.junit.Test; import org.junit.Test;