ThreadCount #49

* #48 выполнено
This commit is contained in:
Zaxar163 2018-11-11 09:01:19 +03:00 committed by GitHub
parent ef57f8b02f
commit b2b810ddea
No known key found for this signature in database
GPG key ID: 4AEE18F83AFDEB23
12 changed files with 37 additions and 31 deletions

View file

@ -66,7 +66,6 @@
public final class LaunchServer implements Runnable, AutoCloseable { public final class LaunchServer implements Runnable, AutoCloseable {
public static final class Config extends ConfigObject { public static final class Config extends ConfigObject {
public final int port; public final int port;
// Handlers & Providers // Handlers & Providers
@ -80,7 +79,10 @@ public static final class Config extends ConfigObject {
public final HWIDHandler hwidHandler; public final HWIDHandler hwidHandler;
// Misc options // Misc options
public final int threadCount;
public final int threadCoreCount;
public final ExeConf launch4j; public final ExeConf launch4j;
public final SignConf sign; public final SignConf sign;
@ -111,6 +113,11 @@ private Config(BlockConfigEntry block, Path coredir, LaunchServer server) {
address = block.getEntry("address", StringConfigEntry.class); address = block.getEntry("address", StringConfigEntry.class);
port = VerifyHelper.verifyInt(block.getEntryValue("port", IntegerConfigEntry.class), port = VerifyHelper.verifyInt(block.getEntryValue("port", IntegerConfigEntry.class),
VerifyHelper.range(0, 65535), "Illegal LaunchServer port"); VerifyHelper.range(0, 65535), "Illegal LaunchServer port");
threadCoreCount = block.hasEntry("threadCoreCacheSize") ? VerifyHelper.verifyInt(block.getEntryValue("threadCoreCacheSize", IntegerConfigEntry.class),
VerifyHelper.range(0, 100), "Illegal LaunchServer inital thread pool cache size") : 0;
int internalThreadCount = block.hasEntry("threadCacheSize") ? VerifyHelper.verifyInt(block.getEntryValue("threadCacheSize", IntegerConfigEntry.class),
VerifyHelper.range(2, 100), "Illegal LaunchServer thread pool cache size") : (JVMHelper.OPERATING_SYSTEM_MXBEAN.getAvailableProcessors() >= 4 ? JVMHelper.OPERATING_SYSTEM_MXBEAN.getAvailableProcessors() / 2 : JVMHelper.OPERATING_SYSTEM_MXBEAN.getAvailableProcessors());
threadCount = threadCoreCount > internalThreadCount ? threadCoreCount : internalThreadCount;
authRateLimit = VerifyHelper.verifyInt(block.getEntryValue("authRateLimit", IntegerConfigEntry.class), authRateLimit = VerifyHelper.verifyInt(block.getEntryValue("authRateLimit", IntegerConfigEntry.class),
VerifyHelper.range(0, 1000000), "Illegal authRateLimit"); VerifyHelper.range(0, 1000000), "Illegal authRateLimit");
authRateLimitMilis = VerifyHelper.verifyInt(block.getEntryValue("authRateLimitMilis", IntegerConfigEntry.class), authRateLimitMilis = VerifyHelper.verifyInt(block.getEntryValue("authRateLimitMilis", IntegerConfigEntry.class),

View file

@ -44,9 +44,10 @@
import java.util.concurrent.atomic.AtomicLong; import java.util.concurrent.atomic.AtomicLong;
import java.util.concurrent.atomic.AtomicReference; import java.util.concurrent.atomic.AtomicReference;
@SuppressWarnings({"unused", "rawtypes"})
public final class NettyServerSocketHandler implements Runnable, AutoCloseable { public final class NettyServerSocketHandler implements Runnable, AutoCloseable {
private static final String WEBSOCKET_PATH = "/api"; private static final String WEBSOCKET_PATH = "/api";
private static SSLServerSocketFactory ssf; private static SSLServerSocketFactory ssf;
private static final ThreadFactory THREAD_FACTORY = r -> CommonHelper.newThread("Network Thread", true, r); private static final ThreadFactory THREAD_FACTORY = r -> CommonHelper.newThread("Network Thread", true, r);
public volatile boolean logConnections = Boolean.getBoolean("launcher.logConnections"); public volatile boolean logConnections = Boolean.getBoolean("launcher.logConnections");
@ -55,7 +56,7 @@ public final class NettyServerSocketHandler implements Runnable, AutoCloseable {
private final ExecutorService threadPool = Executors.newCachedThreadPool(THREAD_FACTORY); private final ExecutorService threadPool = Executors.newCachedThreadPool(THREAD_FACTORY);
// API // API
private final Map<String, Response.Factory> customResponses = new ConcurrentHashMap<>(2); private final Map<String, Response.Factory> customResponses = new ConcurrentHashMap<>(2);
private final AtomicLong idCounter = new AtomicLong(0L); private final AtomicLong idCounter = new AtomicLong(0L);
private Set<Socket> sockets; private Set<Socket> sockets;
private volatile Listener listener; private volatile Listener listener;

View file

@ -5,8 +5,10 @@
import java.net.ServerSocket; import java.net.ServerSocket;
import java.net.Socket; import java.net.Socket;
import java.util.concurrent.ExecutorService; import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors; import java.util.concurrent.SynchronousQueue;
import java.util.concurrent.ThreadFactory; import java.util.concurrent.ThreadFactory;
import java.util.concurrent.ThreadPoolExecutor;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.atomic.AtomicLong; import java.util.concurrent.atomic.AtomicLong;
import java.util.concurrent.atomic.AtomicReference; import java.util.concurrent.atomic.AtomicReference;
@ -35,7 +37,7 @@ public interface Listener {
// Instance // Instance
private final LaunchServer server; private final LaunchServer server;
private final AtomicReference<ServerSocket> serverSocket = new AtomicReference<>(); private final AtomicReference<ServerSocket> serverSocket = new AtomicReference<>();
private final ExecutorService threadPool = Executors.newCachedThreadPool(THREAD_FACTORY); private final ExecutorService threadPool;
public final SessionManager sessionManager; public final SessionManager sessionManager;
private final AtomicLong idCounter = new AtomicLong(0L); private final AtomicLong idCounter = new AtomicLong(0L);
@ -43,13 +45,16 @@ public interface Listener {
private volatile Listener listener; private volatile Listener listener;
public ServerSocketHandler(LaunchServer server) { public ServerSocketHandler(LaunchServer server) {
this.server = server; this(server, new SessionManager());
sessionManager = new SessionManager();
GarbageManager.registerNeedGC(sessionManager); GarbageManager.registerNeedGC(sessionManager);
} }
public ServerSocketHandler(LaunchServer server, SessionManager sessionManager) { public ServerSocketHandler(LaunchServer server, SessionManager sessionManager) {
this.server = server; this.server = server;
threadPool = new ThreadPoolExecutor(server.config.threadCoreCount, Integer.MAX_VALUE,
server.config.threadCount, TimeUnit.SECONDS,
new SynchronousQueue<Runnable>(),
THREAD_FACTORY);
this.sessionManager = sessionManager; this.sessionManager = sessionManager;
} }

View file

@ -23,6 +23,7 @@
import java.util.HashMap; import java.util.HashMap;
@SuppressWarnings({"unused", "rawtypes"})
public class WebSocketService { public class WebSocketService {
public final ChannelGroup channels; public final ChannelGroup channels;
@ -30,9 +31,8 @@ public WebSocketService(ChannelGroup channels, LaunchServer server, GsonBuilder
this.channels = channels; this.channels = channels;
this.server = server; this.server = server;
this.gsonBuiler = gson; this.gsonBuiler = gson;
this. this.gsonBuiler.registerTypeAdapter(JsonResponseInterface.class, new JsonResponseAdapter(this));
gsonBuiler.registerTypeAdapter(JsonResponseInterface.class, new JsonResponseAdapter(this)); this.gsonBuiler.registerTypeAdapter(HashedEntry.class, new HashedEntryAdapter());
gsonBuiler.registerTypeAdapter(HashedEntry.class, new HashedEntryAdapter());
this.gson = gsonBuiler.create(); this.gson = gsonBuiler.create();
} }

View file

@ -8,8 +8,6 @@
import ru.gravit.launchserver.socket.websocket.json.JsonResponseInterface; import ru.gravit.launchserver.socket.websocket.json.JsonResponseInterface;
import ru.gravit.utils.helper.LogHelper; import ru.gravit.utils.helper.LogHelper;
import java.util.UUID;
public class CheckServerResponse implements JsonResponseInterface { public class CheckServerResponse implements JsonResponseInterface {
public String serverID; public String serverID;
public String username; public String username;
@ -21,9 +19,8 @@ public String getType() {
@Override @Override
public void execute(WebSocketService service, ChannelHandlerContext ctx, Client client) throws Exception { public void execute(WebSocketService service, ChannelHandlerContext ctx, Client client) throws Exception {
UUID uuid;
try { try {
uuid = LaunchServer.server.config.authHandler[0].checkServer(username, serverID); LaunchServer.server.config.authHandler[0].checkServer(username, serverID);
} catch (AuthException e) { } catch (AuthException e) {
service.sendObject(ctx, new WebSocketService.ErrorResult(e.getMessage())); service.sendObject(ctx, new WebSocketService.ErrorResult(e.getMessage()));
return; return;

View file

@ -13,8 +13,8 @@ public class ClientWebSocketService {
public final GsonBuilder gsonBuilder; public final GsonBuilder gsonBuilder;
public final Gson gson; public final Gson gson;
public final ClientJSONPoint point; public final ClientJSONPoint point;
private HashMap<String, Class> requests; private HashMap<String, Class<RequestInterface>> requests;
private HashMap<String, Class> results; private HashMap<String, Class<ResultInterface>> results;
public ClientWebSocketService(GsonBuilder gsonBuilder, ClientJSONPoint point) { public ClientWebSocketService(GsonBuilder gsonBuilder, ClientJSONPoint point) {
requests = new HashMap<>(); requests = new HashMap<>();
@ -32,11 +32,11 @@ public void processMessage(Reader reader) {
result.process(); result.process();
} }
public Class getRequestClass(String key) { public Class<RequestInterface> getRequestClass(String key) {
return requests.get(key); return requests.get(key);
} }
public void registerRequest(String key, Class clazz) { public void registerRequest(String key, Class<RequestInterface> clazz) {
requests.put(key, clazz); requests.put(key, clazz);
} }
@ -44,7 +44,7 @@ public void registerRequests() {
} }
public void registerResult(String key, Class clazz) { public void registerResult(String key, Class<ResultInterface> clazz) {
results.put(key, clazz); results.put(key, clazz);
} }

View file

@ -14,12 +14,6 @@ public class ServerAgent {
public static Instrumentation inst; public static Instrumentation inst;
public static final class StarterVisitor extends SimpleFileVisitor<Path> { public static final class StarterVisitor extends SimpleFileVisitor<Path> {
private Instrumentation inst;
public StarterVisitor(Instrumentation inst) {
this.inst = inst;
}
@Override @Override
public FileVisitResult visitFile(Path file, BasicFileAttributes attrs) throws IOException { public FileVisitResult visitFile(Path file, BasicFileAttributes attrs) throws IOException {
if (file.toFile().getName().endsWith(".jar")) addJVMClassPath(new JarFile(file.toFile())); if (file.toFile().getName().endsWith(".jar")) addJVMClassPath(new JarFile(file.toFile()));
@ -51,7 +45,7 @@ public static void premain(String agentArgument, Instrumentation instrumentation
isAgentStarted = true; isAgentStarted = true;
try { try {
Files.walkFileTree(Paths.get("libraries"), Collections.singleton(FileVisitOption.FOLLOW_LINKS), Integer.MAX_VALUE, new StarterVisitor(inst)); Files.walkFileTree(Paths.get("libraries"), Collections.singleton(FileVisitOption.FOLLOW_LINKS), Integer.MAX_VALUE, new StarterVisitor());
} catch (IOException e) { } catch (IOException e) {
e.printStackTrace(System.err); e.printStackTrace(System.err);
} }

View file

@ -38,6 +38,7 @@ public static boolean auth(ServerWrapper wrapper) {
try { try {
LauncherConfig cfg = Launcher.getConfig(); LauncherConfig cfg = Launcher.getConfig();
Boolean auth = new AuthServerRequest(cfg, config.login, SecurityHelper.newRSAEncryptCipher(cfg.publicKey).doFinal(IOHelper.encode(config.password)), 0, config.title).request(); Boolean auth = new AuthServerRequest(cfg, config.login, SecurityHelper.newRSAEncryptCipher(cfg.publicKey).doFinal(IOHelper.encode(config.password)), 0, config.title).request();
if (auth == null) throw new Exception("Non auth!"); // security check
ProfilesRequest.Result result = new ProfilesRequest(cfg).request(); ProfilesRequest.Result result = new ProfilesRequest(cfg).request();
for (SignedObjectHolder<ClientProfile> p : result.profiles) { for (SignedObjectHolder<ClientProfile> p : result.profiles) {
LogHelper.debug("Get profile: %s", p.object.getTitle()); LogHelper.debug("Get profile: %s", p.object.getTitle());

View file

@ -265,7 +265,7 @@ private HashedDir sideDiff(HashedDir other, FileNameMatcher matcher, Deque<Strin
return diff; return diff;
} }
private HashedDir sideCompare(HashedDir other, FileNameMatcher matcher, Deque<String> path, boolean mismatchList) { public HashedDir sideCompare(HashedDir other, FileNameMatcher matcher, Deque<String> path, boolean mismatchList) {
HashedDir diff = new HashedDir(); HashedDir diff = new HashedDir();
for (Entry<String, HashedEntry> mapEntry : map.entrySet()) { for (Entry<String, HashedEntry> mapEntry : map.entrySet()) {
String name = mapEntry.getKey(); String name = mapEntry.getKey();

View file

@ -15,7 +15,7 @@ public HashedEntryAdapter() {
@Override @Override
public HashedEntry deserialize(JsonElement json, Type typeOfT, JsonDeserializationContext context) throws JsonParseException { public HashedEntry deserialize(JsonElement json, Type typeOfT, JsonDeserializationContext context) throws JsonParseException {
String typename = json.getAsJsonObject().getAsJsonPrimitive(PROP_NAME).getAsString(); String typename = json.getAsJsonObject().getAsJsonPrimitive(PROP_NAME).getAsString();
Class cls = null; Class<?> cls = null;
if (typename.equals("dir")) cls = HashedDir.class; if (typename.equals("dir")) cls = HashedDir.class;
if (typename.equals("file")) cls = HashedFile.class; if (typename.equals("file")) cls = HashedFile.class;

View file

@ -6,7 +6,8 @@
public class LauncherSSLContext { public class LauncherSSLContext {
public SSLServerSocketFactory ssf; public SSLServerSocketFactory ssf;
public SSLSocketFactory sf; public SSLSocketFactory sf;
private SSLContext sc; @SuppressWarnings("unused")
private SSLContext sc;
public LauncherSSLContext(KeyStore ks, String keypassword) throws NoSuchAlgorithmException, KeyStoreException, UnrecoverableKeyException, KeyManagementException { public LauncherSSLContext(KeyStore ks, String keypassword) throws NoSuchAlgorithmException, KeyStoreException, UnrecoverableKeyException, KeyManagementException {
TrustManager[] trustAllCerts = new TrustManager[]{ TrustManager[] trustAllCerts = new TrustManager[]{

View file

@ -115,7 +115,7 @@ public static URL[] getClassPathURL() {
return list; return list;
} }
public static void checkStackTrace(Class mainClass) { public static void checkStackTrace(Class<?> mainClass) {
LogHelper.debug("Testing stacktrace"); LogHelper.debug("Testing stacktrace");
Exception e = new Exception("Testing stacktrace"); Exception e = new Exception("Testing stacktrace");
StackTraceElement[] list = e.getStackTrace(); StackTraceElement[] list = e.getStackTrace();