Skip to content

Commit

Permalink
De-static IceAdapter class
Browse files Browse the repository at this point in the history
Prepare a slow transition from static-everything to dependency injection
  • Loading branch information
Brutus5000 committed Nov 26, 2024
1 parent 23821e3 commit a509f31
Show file tree
Hide file tree
Showing 12 changed files with 133 additions and 128 deletions.
108 changes: 44 additions & 64 deletions ice-adapter/src/main/java/com/faforever/iceadapter/IceAdapter.java
Original file line number Diff line number Diff line change
Expand Up @@ -6,6 +6,7 @@
import com.faforever.iceadapter.gpgnet.GPGNetServer;
import com.faforever.iceadapter.gpgnet.GameState;
import com.faforever.iceadapter.ice.GameSession;
import com.faforever.iceadapter.ice.PeerIceModule;
import com.faforever.iceadapter.rpc.RPCService;
import com.faforever.iceadapter.util.Executor;
import com.faforever.iceadapter.util.TrayIcon;
Expand All @@ -20,62 +21,41 @@
description = "An ice (RFC 5245) based network bridge between FAF client and ForgedAlliance.exe")
@Slf4j
public class IceAdapter implements Callable<Integer> {
@CommandLine.ArgGroup(exclusive = false)
private IceOptions iceOptions;

public static String TELEMETRY_SERVER;

public static boolean ALLOW_HOST = true;
public static boolean ALLOW_REFLEXIVE = true;
public static boolean ALLOW_RELAY = true;

public static volatile boolean running = true;

private static IceAdapter INSTANCE;
public static String VERSION = "SNAPSHOT";
public static volatile GameSession gameSession;

public static int id = -1;
public static int gameId = -1;
public static String login;
public static int RPC_PORT;
public static int GPGNET_PORT = 0;
public static int LOBBY_PORT = 0;
@CommandLine.ArgGroup(exclusive = false)
private IceOptions iceOptions;

public static int PING_COUNT = 1;
public static double ACCEPTABLE_LATENCY = 250.0;

public static volatile GameSession gameSession;
public volatile boolean running = true;

public static void main(String[] args) {
new CommandLine(new IceAdapter()).setUnmatchedArgumentsAllowed(true).execute(args);
}

@Override
public Integer call() {
IceAdapter.start(iceOptions);
INSTANCE = this;

start();
return 0;
}

public static void start(IceOptions iceOptions) {
public void start() {
determineVersion();
log.info("Version: {}", VERSION);

loadOptions(iceOptions);
Debug.DELAY_UI_MS = iceOptions.getDelayUi();
Debug.ENABLE_DEBUG_WINDOW = iceOptions.isDebugWindow();
Debug.ENABLE_INFO_WINDOW = iceOptions.isInfoWindow();
Debug.init();

TrayIcon.create();

// Configure file appender
// RollingFileAppender fileAppender =
// (ch.qos.logback.core.rolling.RollingFileAppender)((ch.qos.logback.classic.Logger)log).getAppender("FILE");
// if (logDirectory != null) {
// Util.mkdir(Paths.get(logDirectory).toFile());
// //TODO: set log dir
// } else {
//// fileAppender.stop();
// }

log.info("Version: {}", VERSION);

GPGNetServer.init();
RPCService.init();
PeerIceModule.setForceRelay(iceOptions.isForceRelay());
GPGNetServer.init(iceOptions.getGpgnetPort(), iceOptions.getLobbyPort());
RPCService.init(iceOptions.getRpcPort());

debug().startupComplete();
}
Expand Down Expand Up @@ -171,36 +151,36 @@ public static void close() {
System.exit(0);
}

/**
* Read command line arguments and set global, constant values
* @param iceOptions The arguments to be read
*/
public static void loadOptions(IceOptions iceOptions) {
TELEMETRY_SERVER = iceOptions.getTelemetryServer();
id = iceOptions.getId();
gameId = iceOptions.getGameId();
login = iceOptions.getLogin();
RPC_PORT = iceOptions.getRpcPort();
GPGNET_PORT = iceOptions.getGpgnetPort();
LOBBY_PORT = iceOptions.getLobbyPort();

if (iceOptions.isForceRelay()) {
ALLOW_HOST = false;
ALLOW_REFLEXIVE = false;
ALLOW_RELAY = true;
}
public static int getId() {
return INSTANCE.iceOptions.getId();
}

Debug.DELAY_UI_MS = iceOptions.getDelayUi();
PING_COUNT = iceOptions.getPingCount();
ACCEPTABLE_LATENCY = iceOptions.getAcceptableLatency();
public static int getGameId() {
return INSTANCE.iceOptions.getGameId();
}

Debug.ENABLE_DEBUG_WINDOW = iceOptions.isDebugWindow();
Debug.ENABLE_INFO_WINDOW = iceOptions.isInfoWindow();
Debug.init();
public static String getLogin() {
return INSTANCE.iceOptions.getLogin();
}

public static String getTelemetryServer() {
return INSTANCE.iceOptions.getTelemetryServer();
}

public static int getPingCount() {
return INSTANCE.iceOptions.getPingCount();
}

public static double getAcceptableLatency() {
return INSTANCE.iceOptions.getAcceptableLatency();
}

public static boolean isRunning() {
return INSTANCE.running;
}

private static void determineVersion() {
String versionFromGradle = IceAdapter.class.getPackage().getImplementationVersion();
private void determineVersion() {
String versionFromGradle = getClass().getPackage().getImplementationVersion();
if (versionFromGradle != null) {
VERSION = versionFromGradle;
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -15,6 +15,8 @@ public class Debug {
public static boolean ENABLE_INFO_WINDOW = false;
public static int DELAY_UI_MS = 0; // delays the launch of the user interface by X ms

public static int RPC_PORT;

private static final DebugFacade debugFacade = new DebugFacade();

public static void register(Debugger debugger) {
Expand All @@ -26,7 +28,7 @@ public static void remove(Debugger debugger) {
}

public static void init() {
new TelemetryDebugger(IceAdapter.TELEMETRY_SERVER, IceAdapter.gameId, IceAdapter.id);
new TelemetryDebugger(IceAdapter.getTelemetryServer(), IceAdapter.getGameId(), IceAdapter.getId());

// Debugger window is started and set to debugFuture when either window is requested as the info window can be
// used to open the debug window
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -99,10 +99,10 @@ public void initStaticVariables() {

runOnUIThread(() -> {
controller.versionLabel.setText("Version: %s".formatted(IceAdapter.VERSION));
controller.userLabel.setText("User: %s(%d)".formatted(IceAdapter.login, IceAdapter.id));
controller.rpcPortLabel.setText("RPC_PORT: %d".formatted(IceAdapter.RPC_PORT));
controller.gpgnetPortLabel.setText("GPGNET_PORT: %d".formatted(IceAdapter.GPGNET_PORT));
controller.lobbyPortLabel.setText("LOBBY_PORT: %d".formatted(IceAdapter.LOBBY_PORT));
controller.userLabel.setText("User: %s(%d)".formatted(IceAdapter.getLogin(), IceAdapter.getId()));
controller.rpcPortLabel.setText("RPC_PORT: %d".formatted(Debug.RPC_PORT));
controller.gpgnetPortLabel.setText("GPGNET_PORT: %d".formatted(GPGNetServer.getGpgnetPort()));
controller.lobbyPortLabel.setText("LOBBY_PORT: %d".formatted(GPGNetServer.getLobbyPort()));
});
}

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -36,7 +36,10 @@ public void onShowDebugWindowClicked(ActionEvent actionEvent) {
@SneakyThrows
public void onTelemetryWebUiClicked(ActionEvent actionEvent) {
String url = "%s/app.html?gameId=%d&playerId=%d"
.formatted(IceAdapter.TELEMETRY_SERVER.replaceFirst("ws", "http"), IceAdapter.gameId, IceAdapter.id);
.formatted(
IceAdapter.getTelemetryServer().replaceFirst("ws", "http"),
IceAdapter.getGameId(),
IceAdapter.getId());

new Thread(() -> {
try {
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -134,7 +134,8 @@ public void startupComplete() {
log.error("Failed to connect to telemetry websocket", e);
}

sendMessage(new RegisterAsPeer(UUID.randomUUID(), "java-ice-adapter/" + IceAdapter.VERSION, IceAdapter.login));
sendMessage(
new RegisterAsPeer(UUID.randomUUID(), "java-ice-adapter/" + IceAdapter.VERSION, IceAdapter.getLogin()));
}

@Override
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -19,6 +19,8 @@

@Slf4j
public class GPGNetServer {
private static int GPGNET_PORT;
private static int LOBBY_PORT;
private static ServerSocket serverSocket;
private static volatile GPGNetClient currentClient;

Expand All @@ -27,28 +29,29 @@ public class GPGNetServer {

public static volatile LobbyInitMode lobbyInitMode = LobbyInitMode.NORMAL;

public static void init() {
if (IceAdapter.GPGNET_PORT == 0) {
IceAdapter.GPGNET_PORT = NetworkToolbox.findFreeTCPPort(20000, 65536);
log.info("Generated GPGNET_PORT: {}", IceAdapter.GPGNET_PORT);
public static void init(int gpgnetPort, int lobbyPort) {
if (gpgnetPort == 0) {
GPGNET_PORT = NetworkToolbox.findFreeTCPPort(20000, 65536);
log.info("Generated GPGNET_PORT: {}", GPGNET_PORT);
} else {
log.info("Using GPGNET_PORT: {}", IceAdapter.GPGNET_PORT);
GPGNET_PORT = gpgnetPort;
log.info("Using GPGNET_PORT: {}", GPGNET_PORT);
}

if (IceAdapter.LOBBY_PORT == 0) {
IceAdapter.LOBBY_PORT = NetworkToolbox.findFreeUDPPort(20000, 65536);
log.info("Generated LOBBY_PORT: {}", IceAdapter.LOBBY_PORT);
if (lobbyPort == 0) {
LOBBY_PORT = NetworkToolbox.findFreeUDPPort(20000, 65536);
log.info("Generated LOBBY_PORT: {}", LOBBY_PORT);
} else {
log.info("Using LOBBY_PORT: {}", IceAdapter.LOBBY_PORT);
LOBBY_PORT = lobbyPort;
log.info("Using LOBBY_PORT: {}", LOBBY_PORT);
}

try {
serverSocket = new ServerSocket(IceAdapter.GPGNET_PORT);
serverSocket = new ServerSocket(GPGNetServer.getGpgnetPort());
} catch (IOException e) {
log.error("Couldn't start GPGNetServer", e);
System.exit(-1);
}

new Thread(GPGNetServer::acceptThread).start();
log.info("GPGNetServer started");
}
Expand Down Expand Up @@ -95,9 +98,9 @@ private void processGpgnetMessage(String command, List<Object> args) {
sendGpgnetMessage(
"CreateLobby",
lobbyInitMode.getId(),
IceAdapter.LOBBY_PORT,
IceAdapter.login,
IceAdapter.id,
GPGNetServer.getLobbyPort(),
IceAdapter.getLogin(),
IceAdapter.getId(),
1);
} else if (gameState == GameState.LOBBY) {
lobbyFuture.complete(this);
Expand Down Expand Up @@ -209,7 +212,7 @@ private static void onGpgnetConnectionLost() {
* Listens for incoming connections from a game instance
*/
private static void acceptThread() {
while (IceAdapter.running) {
while (IceAdapter.isRunning()) {
try {
Socket socket = serverSocket.accept();
synchronized (serverSocket) {
Expand Down Expand Up @@ -245,6 +248,14 @@ public static Optional<GameState> getGameState() {
return Optional.ofNullable(currentClient).map(GPGNetClient::getGameState);
}

public static int getGpgnetPort() {
return GPGNET_PORT;
}

public static int getLobbyPort() {
return LOBBY_PORT;
}

/**
* Stops the GPGNetServer and thereby the connection to a currently connected client
*/
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -115,7 +115,7 @@ public static void setIceServers(List<Map<String, Object>> iceServersData) {
.build(new CacheLoader<>() {
@Override
public CompletableFuture<OptionalDouble> load(String host) {
return PingWrapper.getLatency(host, IceAdapter.PING_COUNT)
return PingWrapper.getLatency(host, IceAdapter.getPingCount())
.thenApply(OptionalDouble::of)
.exceptionally(ex -> OptionalDouble.empty());
}
Expand Down Expand Up @@ -172,7 +172,7 @@ public CompletableFuture<OptionalDouble> load(String host) {
default -> log.warn("Invalid ICE server protocol: {}", uri);
}

if (IceAdapter.PING_COUNT > 0) {
if (IceAdapter.getPingCount() > 0) {
iceServer.setRoundTripTime(hostRTTCache.getUnchecked(host));
}

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -22,6 +22,6 @@ public class IceServer {

public boolean hasAcceptableLatency() {
OptionalDouble rtt = this.getRoundTripTime().join();
return !rtt.isPresent() || rtt.getAsDouble() < IceAdapter.ACCEPTABLE_LATENCY;
return rtt.isEmpty() || rtt.getAsDouble() < IceAdapter.getAcceptableLatency();
}
}
12 changes: 5 additions & 7 deletions ice-adapter/src/main/java/com/faforever/iceadapter/ice/Peer.java
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
package com.faforever.iceadapter.ice;

import com.faforever.iceadapter.IceAdapter;
import com.faforever.iceadapter.gpgnet.GPGNetServer;
import java.io.IOException;
import java.net.*;
import lombok.Getter;
Expand Down Expand Up @@ -33,10 +34,7 @@ public Peer(GameSession gameSession, int remoteId, String remoteLogin, boolean l
this.preferredPort = preferredPort;

log.debug(
"Peer created: {}, localOffer: {}, preferredPort: {}",
getPeerIdentifier(),
String.valueOf(localOffer),
preferredPort);
"Peer created: {}, localOffer: {}, preferredPort: {}", getPeerIdentifier(), localOffer, preferredPort);

initForwarding(preferredPort);

Expand Down Expand Up @@ -68,8 +66,8 @@ private void initForwarding(int port) {
*/
synchronized void onIceDataReceived(byte data[], int offset, int length) {
try {
DatagramPacket packet =
new DatagramPacket(data, offset, length, InetAddress.getByName("127.0.0.1"), IceAdapter.LOBBY_PORT);
DatagramPacket packet = new DatagramPacket(
data, offset, length, InetAddress.getByName("127.0.0.1"), GPGNetServer.getLobbyPort());
faSocket.send(packet);
} catch (UnknownHostException e) {
} catch (IOException e) {
Expand All @@ -90,7 +88,7 @@ synchronized void onIceDataReceived(byte data[], int offset, int length) {
private void faListener() {
byte data[] = new byte
[65536]; // 64KiB = UDP MTU, in practice due to ethernet frames being <= 1500 B, this is often not used
while (IceAdapter.running && IceAdapter.gameSession == gameSession) {
while (IceAdapter.isRunning() && IceAdapter.gameSession == gameSession) {
try {
DatagramPacket packet = new DatagramPacket(data, data.length);
faSocket.receive(packet);
Expand Down
Loading

0 comments on commit a509f31

Please sign in to comment.