[REFACTOR] Moving to log4j2 logger finally

This commit is contained in:
Gravita 2021-05-10 14:51:52 +07:00
parent a4596b8c2f
commit 7a1746281d
7 changed files with 40 additions and 39 deletions

View file

@ -1,5 +1,7 @@
package pro.gravit.launchserver.socket.handlers; package pro.gravit.launchserver.socket.handlers;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import pro.gravit.launchserver.LaunchServer; import pro.gravit.launchserver.LaunchServer;
import pro.gravit.launchserver.config.LaunchServerConfig; import pro.gravit.launchserver.config.LaunchServerConfig;
import pro.gravit.launchserver.socket.LauncherNettyServer; import pro.gravit.launchserver.socket.LauncherNettyServer;
@ -8,11 +10,12 @@
import javax.net.ssl.SSLServerSocketFactory; import javax.net.ssl.SSLServerSocketFactory;
import java.net.InetSocketAddress; import java.net.InetSocketAddress;
// TODO refactor
@SuppressWarnings("unused") @SuppressWarnings("unused")
public final class NettyServerSocketHandler implements Runnable, AutoCloseable { public final class NettyServerSocketHandler implements Runnable, AutoCloseable {
private transient final LaunchServer server; private transient final LaunchServer server;
@Deprecated
public volatile boolean logConnections = Boolean.getBoolean("launcher.logConnections"); public volatile boolean logConnections = Boolean.getBoolean("launcher.logConnections");
private transient final Logger logger = LogManager.getLogger();
public LauncherNettyServer nettyServer; public LauncherNettyServer nettyServer;
private SSLServerSocketFactory ssf; private SSLServerSocketFactory ssf;
@ -30,7 +33,7 @@ public void close() {
@Override @Override
public void run() { public void run() {
LogHelper.info("Starting netty server socket thread"); logger.info("Starting netty server socket thread");
nettyServer = new LauncherNettyServer(server); nettyServer = new LauncherNettyServer(server);
for (LaunchServerConfig.NettyBindAddress address : server.config.netty.binds) { for (LaunchServerConfig.NettyBindAddress address : server.config.netty.binds) {
nettyServer.bind(new InetSocketAddress(address.address, address.port)); nettyServer.bind(new InetSocketAddress(address.address, address.port));

View file

@ -5,6 +5,8 @@
import io.netty.channel.ChannelHandlerContext; import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.SimpleChannelInboundHandler; import io.netty.channel.SimpleChannelInboundHandler;
import io.netty.handler.codec.http.*; import io.netty.handler.codec.http.*;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import pro.gravit.launcher.Launcher; import pro.gravit.launcher.Launcher;
import pro.gravit.launchserver.socket.NettyConnectContext; import pro.gravit.launchserver.socket.NettyConnectContext;
import pro.gravit.utils.helper.LogHelper; import pro.gravit.utils.helper.LogHelper;
@ -22,6 +24,7 @@
public class NettyWebAPIHandler extends SimpleChannelInboundHandler<FullHttpRequest> { public class NettyWebAPIHandler extends SimpleChannelInboundHandler<FullHttpRequest> {
private static final TreeSet<SeverletPathPair> severletList = new TreeSet<>(Comparator.comparingInt((e) -> -e.key.length())); private static final TreeSet<SeverletPathPair> severletList = new TreeSet<>(Comparator.comparingInt((e) -> -e.key.length()));
private final NettyConnectContext context; private final NettyConnectContext context;
private transient final Logger logger = LogManager.getLogger();
public NettyWebAPIHandler(NettyConnectContext context) { public NettyWebAPIHandler(NettyConnectContext context) {
super(); super();
@ -52,7 +55,7 @@ protected void channelRead0(ChannelHandlerContext ctx, FullHttpRequest msg) thro
try { try {
pair.callback.handle(ctx, msg, context); pair.callback.handle(ctx, msg, context);
} catch (Throwable e) { } catch (Throwable e) {
LogHelper.error(e); logger.error(e);
ctx.writeAndFlush(new DefaultFullHttpResponse(HTTP_1_1, HttpResponseStatus.INTERNAL_SERVER_ERROR, Unpooled.wrappedBuffer("Internal Server Error 500".getBytes())), ctx.voidPromise()); ctx.writeAndFlush(new DefaultFullHttpResponse(HTTP_1_1, HttpResponseStatus.INTERNAL_SERVER_ERROR, Unpooled.wrappedBuffer("Internal Server Error 500".getBytes())), ctx.voidPromise());
} }
isNext = false; isNext = false;

View file

@ -5,6 +5,8 @@
import io.netty.channel.SimpleChannelInboundHandler; import io.netty.channel.SimpleChannelInboundHandler;
import io.netty.handler.codec.http.websocketx.*; import io.netty.handler.codec.http.websocketx.*;
import io.netty.util.concurrent.ScheduledFuture; import io.netty.util.concurrent.ScheduledFuture;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import pro.gravit.launchserver.LaunchServer; import pro.gravit.launchserver.LaunchServer;
import pro.gravit.launchserver.socket.Client; import pro.gravit.launchserver.socket.Client;
import pro.gravit.launchserver.socket.NettyConnectContext; import pro.gravit.launchserver.socket.NettyConnectContext;
@ -22,6 +24,7 @@ public class WebSocketFrameHandler extends SimpleChannelInboundHandler<WebSocket
public final WebSocketService service; public final WebSocketService service;
public final BiHookSet<ChannelHandlerContext, WebSocketFrame> hooks = new BiHookSet<>(); public final BiHookSet<ChannelHandlerContext, WebSocketFrame> hooks = new BiHookSet<>();
private final UUID connectUUID = UUID.randomUUID(); private final UUID connectUUID = UUID.randomUUID();
private transient final Logger logger = LogManager.getLogger();
public NettyConnectContext context; public NettyConnectContext context;
private Client client; private Client client;
private ScheduledFuture<?> future; private ScheduledFuture<?> future;
@ -48,9 +51,7 @@ public final UUID getConnectUUID() {
@Override @Override
public void channelActive(ChannelHandlerContext ctx) { public void channelActive(ChannelHandlerContext ctx) {
if (LogHelper.isDevEnabled()) { logger.trace("New client {}", IOHelper.getIP(ctx.channel().remoteAddress()));
LogHelper.dev("New client %s", IOHelper.getIP(ctx.channel().remoteAddress()));
}
client = new Client(null); client = new Client(null);
Channel ch = ctx.channel(); Channel ch = ctx.channel();
service.registerClient(ch); service.registerClient(ch);
@ -63,20 +64,16 @@ protected void channelRead0(ChannelHandlerContext ctx, WebSocketFrame frame) {
try { try {
if (hooks.hook(ctx, frame)) return; if (hooks.hook(ctx, frame)) return;
} catch (Throwable ex) { } catch (Throwable ex) {
LogHelper.error(ex); logger.error(ex);
} }
if (frame instanceof TextWebSocketFrame) { if (frame instanceof TextWebSocketFrame) {
try { try {
service.process(ctx, (TextWebSocketFrame) frame, client, context.ip); service.process(ctx, (TextWebSocketFrame) frame, client, context.ip);
} catch (Throwable ex) { } catch (Throwable ex) {
if (LogHelper.isDebugEnabled()) { logger.warn("Client {} send invalid request. Connection force closed.", context.ip == null ? IOHelper.getIP(ctx.channel().remoteAddress()) : context.ip);
LogHelper.warning("Client %s send invalid request. Connection force closed.", context.ip == null ? IOHelper.getIP(ctx.channel().remoteAddress()) : context.ip); if(logger.isTraceEnabled()) {
if (LogHelper.isDevEnabled()) { logger.trace("Client message: {}", ((TextWebSocketFrame) frame).text());
LogHelper.dev("Client message: %s", ((TextWebSocketFrame) frame).text()); logger.error(ex);
}
if (LogHelper.isStacktraceEnabled()) {
LogHelper.error(ex);
}
} }
ctx.channel().close(); ctx.channel().close();
} }
@ -85,28 +82,28 @@ protected void channelRead0(ChannelHandlerContext ctx, WebSocketFrame frame) {
ctx.channel().writeAndFlush(new PongWebSocketFrame(frame.content())); ctx.channel().writeAndFlush(new PongWebSocketFrame(frame.content()));
//return; //return;
} else if ((frame instanceof PongWebSocketFrame)) { } else if ((frame instanceof PongWebSocketFrame)) {
LogHelper.dev("WebSocket Client received pong"); logger.trace("WebSocket Client received pong");
} else if ((frame instanceof CloseWebSocketFrame)) { } else if ((frame instanceof CloseWebSocketFrame)) {
int statusCode = ((CloseWebSocketFrame) frame).statusCode(); int statusCode = ((CloseWebSocketFrame) frame).statusCode();
ctx.channel().close(); ctx.channel().close();
} else { } else {
String message = "unsupported frame type: " + frame.getClass().getName(); String message = "unsupported frame type: " + frame.getClass().getName();
LogHelper.error(new UnsupportedOperationException(message)); // prevent strange crash here. logger.error(new UnsupportedOperationException(message)); // prevent strange crash here.
} }
} }
@Override @Override
public void channelInactive(ChannelHandlerContext ctx) throws Exception { public void channelInactive(ChannelHandlerContext ctx) throws Exception {
if (future != null) future.cancel(true); if (future != null) future.cancel(true);
if (LogHelper.isDevEnabled()) { if(logger.isTraceEnabled()) {
LogHelper.dev("Client %s disconnected", IOHelper.getIP(ctx.channel().remoteAddress())); logger.trace("Client {} disconnected", IOHelper.getIP(ctx.channel().remoteAddress()));
} }
int refCount = client.refCount.decrementAndGet(); int refCount = client.refCount.decrementAndGet();
if (client.session != null) { if (client.session != null) {
if (refCount == 0) { if (refCount == 0) {
srv.sessionManager.addClient(client); srv.sessionManager.addClient(client);
} else if (refCount < 0) { } else if (refCount < 0) {
LogHelper.warning("Client session %s reference counter invalid - %d", client.session, refCount); logger.warn("Client session {} reference counter invalid - {}", client.session, refCount);
} }
} }
super.channelInactive(ctx); super.channelInactive(ctx);

View file

@ -229,10 +229,7 @@ public void channelRead0(ChannelHandlerContext ctx, FullHttpRequest request) thr
sendNotModified(ctx); sendNotModified(ctx);
return; return;
} }
} catch (UnsupportedTemporalTypeException e) { } catch (UnsupportedTemporalTypeException ignored) {
if (LogHelper.isDebugEnabled()) {
LogHelper.warning("Request access If-Modifed-Since: %s not parsed correctly", ifModifiedSince);
}
} }
} }

View file

@ -1,6 +1,8 @@
package pro.gravit.launchserver.socket.response.auth; package pro.gravit.launchserver.socket.response.auth;
import io.netty.channel.ChannelHandlerContext; import io.netty.channel.ChannelHandlerContext;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import pro.gravit.launcher.events.request.AuthRequestEvent; import pro.gravit.launcher.events.request.AuthRequestEvent;
import pro.gravit.launcher.request.auth.AuthRequest; import pro.gravit.launcher.request.auth.AuthRequest;
import pro.gravit.launcher.request.auth.password.*; import pro.gravit.launcher.request.auth.password.*;
@ -27,7 +29,7 @@
import java.util.UUID; import java.util.UUID;
public class AuthResponse extends SimpleResponse { public class AuthResponse extends SimpleResponse {
public final transient static Random random = new SecureRandom(); private transient final Logger logger = LogManager.getLogger();
public String login; public String login;
public String client; public String client;
public boolean getSession; public boolean getSession;
@ -52,9 +54,6 @@ public void execute(ChannelHandlerContext ctx, Client clientData) throws Excepti
} }
if (clientData.isAuth) { if (clientData.isAuth) {
if (LogHelper.isDevEnabled()) {
LogHelper.warning("Client %s double auth", clientData.username == null ? ip : clientData.username);
}
sendError("You are already logged in"); sendError("You are already logged in");
return; return;
} }
@ -113,8 +112,8 @@ public void execute(ChannelHandlerContext ctx, Client clientData) throws Excepti
} }
if (authType == ConnectTypes.CLIENT && server.config.protectHandler.allowGetAccessToken(context)) { if (authType == ConnectTypes.CLIENT && server.config.protectHandler.allowGetAccessToken(context)) {
clientData.uuid = pair.handler.auth(aresult); clientData.uuid = pair.handler.auth(aresult);
if (LogHelper.isDebugEnabled()) { if (logger.isDebugEnabled()) {
LogHelper.debug("Auth: %s accessToken %s uuid: %s", login, result.accessToken, clientData.uuid.toString()); logger.debug("Auth: {} accessToken {} uuid: {}", login, result.accessToken, clientData.uuid.toString());
} }
} else { } else {
clientData.uuid = pair.handler.usernameToUUID(aresult.username); clientData.uuid = pair.handler.usernameToUUID(aresult.username);

View file

@ -1,6 +1,8 @@
package pro.gravit.launchserver.socket.response.auth; package pro.gravit.launchserver.socket.response.auth;
import io.netty.channel.ChannelHandlerContext; import io.netty.channel.ChannelHandlerContext;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import pro.gravit.launcher.events.request.CheckServerRequestEvent; import pro.gravit.launcher.events.request.CheckServerRequestEvent;
import pro.gravit.launchserver.auth.AuthException; import pro.gravit.launchserver.auth.AuthException;
import pro.gravit.launchserver.socket.Client; import pro.gravit.launchserver.socket.Client;
@ -13,6 +15,7 @@ public class CheckServerResponse extends SimpleResponse {
public String serverID; public String serverID;
public String username; public String username;
public String client; public String client;
private transient final Logger logger = LogManager.getLogger();
@Override @Override
public String getType() { public String getType() {
@ -31,14 +34,12 @@ public void execute(ChannelHandlerContext ctx, Client pClient) {
result.uuid = pClient.auth.handler.checkServer(username, serverID); result.uuid = pClient.auth.handler.checkServer(username, serverID);
if (result.uuid != null) if (result.uuid != null)
result.playerProfile = ProfileByUUIDResponse.getProfile(result.uuid, username, client, pClient.auth.textureProvider); result.playerProfile = ProfileByUUIDResponse.getProfile(result.uuid, username, client, pClient.auth.textureProvider);
if (LogHelper.isDebugEnabled()) { logger.debug("checkServer: {} uuid: {} serverID: {}", result.playerProfile.username, result.uuid, serverID);
LogHelper.debug("checkServer: %s uuid: %s serverID: %s", result.playerProfile.username, result.uuid.toString(), serverID);
}
} catch (AuthException | HookException e) { } catch (AuthException | HookException e) {
sendError(e.getMessage()); sendError(e.getMessage());
return; return;
} catch (Exception e) { } catch (Exception e) {
LogHelper.error(e); logger.error(e);
sendError("Internal authHandler error"); sendError("Internal authHandler error");
return; return;
} }

View file

@ -1,6 +1,8 @@
package pro.gravit.launchserver.socket.response.auth; package pro.gravit.launchserver.socket.response.auth;
import io.netty.channel.ChannelHandlerContext; import io.netty.channel.ChannelHandlerContext;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import pro.gravit.launcher.events.request.JoinServerRequestEvent; import pro.gravit.launcher.events.request.JoinServerRequestEvent;
import pro.gravit.launchserver.auth.AuthException; import pro.gravit.launchserver.auth.AuthException;
import pro.gravit.launchserver.auth.protect.interfaces.JoinServerProtectHandler; import pro.gravit.launchserver.auth.protect.interfaces.JoinServerProtectHandler;
@ -13,6 +15,7 @@ public class JoinServerResponse extends SimpleResponse {
public String serverID; public String serverID;
public String accessToken; public String accessToken;
public String username; public String username;
private transient final Logger logger = LogManager.getLogger();
@Override @Override
public String getType() { public String getType() {
@ -40,17 +43,15 @@ public void execute(ChannelHandlerContext ctx, Client client) {
} }
} }
if (client.auth == null) { if (client.auth == null) {
LogHelper.warning("Client auth is null. Using default."); logger.warn("Client auth is null. Using default.");
success = server.config.getAuthProviderPair().handler.joinServer(username, accessToken, serverID); success = server.config.getAuthProviderPair().handler.joinServer(username, accessToken, serverID);
} else success = client.auth.handler.joinServer(username, accessToken, serverID); } else success = client.auth.handler.joinServer(username, accessToken, serverID);
if (LogHelper.isDebugEnabled()) { logger.debug("joinServer: {} accessToken: {} serverID: {}", username, accessToken, serverID);
LogHelper.debug("joinServer: %s accessToken: %s serverID: %s", username, accessToken, serverID);
}
} catch (AuthException | HookException | SecurityException e) { } catch (AuthException | HookException | SecurityException e) {
sendError(e.getMessage()); sendError(e.getMessage());
return; return;
} catch (Exception e) { } catch (Exception e) {
LogHelper.error(e); logger.error(e);
sendError("Internal authHandler error"); sendError("Internal authHandler error");
return; return;
} }