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 28, 2024
1 parent 23821e3 commit a0aa9ca
Show file tree
Hide file tree
Showing 13 changed files with 160 additions and 147 deletions.
136 changes: 62 additions & 74 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> {
private static IceAdapter INSTANCE;
private static String VERSION = "SNAPSHOT";
private static volatile GameSession GAME_SESSION;

@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;

public static String VERSION = "SNAPSHOT";

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;

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

public static volatile GameSession gameSession;
private 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 All @@ -94,7 +74,7 @@ public static void onHostGame(String mapName) {
public static void onJoinGame(String remotePlayerLogin, int remotePlayerId) {
log.info("onJoinGame {} {}", remotePlayerId, remotePlayerLogin);
createGameSession();
int port = gameSession.connectToPeer(remotePlayerLogin, remotePlayerId, false, 0);
int port = GAME_SESSION.connectToPeer(remotePlayerLogin, remotePlayerId, false, 0);

GPGNetServer.clientFuture.thenAccept(gpgNetClient -> {
gpgNetClient.getLobbyFuture().thenRun(() -> {
Expand All @@ -113,7 +93,7 @@ public static void onConnectToPeer(String remotePlayerLogin, int remotePlayerId,
}

log.info("onConnectToPeer {} {}, offer: {}", remotePlayerId, remotePlayerLogin, String.valueOf(offer));
int port = gameSession.connectToPeer(remotePlayerLogin, remotePlayerId, offer, 0);
int port = GAME_SESSION.connectToPeer(remotePlayerLogin, remotePlayerId, offer, 0);

GPGNetServer.clientFuture.thenAccept(gpgNetClient -> {
gpgNetClient.getLobbyFuture().thenRun(() -> {
Expand All @@ -124,7 +104,7 @@ public static void onConnectToPeer(String remotePlayerLogin, int remotePlayerId,

public static void onDisconnectFromPeer(int remotePlayerId) {
log.info("onDisconnectFromPeer {}", remotePlayerId);
gameSession.disconnectFromPeer(remotePlayerId);
GAME_SESSION.disconnectFromPeer(remotePlayerId);

GPGNetServer.clientFuture.thenAccept(gpgNetClient -> {
gpgNetClient.getLobbyFuture().thenRun(() -> {
Expand All @@ -134,23 +114,23 @@ public static void onDisconnectFromPeer(int remotePlayerId) {
}

private static synchronized void createGameSession() {
if (gameSession != null) {
gameSession.close();
gameSession = null;
if (GAME_SESSION != null) {
GAME_SESSION.close();
GAME_SESSION = null;
}

gameSession = new GameSession();
GAME_SESSION = new GameSession();
}

/**
* Triggered by losing gpgnet connection to FA.
* Closes the active Game/ICE session
*/
public static synchronized void onFAShutdown() {
if (gameSession != null) {
if (GAME_SESSION != null) {
log.info("FA SHUTDOWN, closing everything");
gameSession.close();
gameSession = null;
GAME_SESSION.close();
GAME_SESSION = null;
// Do not put code outside of this if clause, else it will be executed multiple times
}
}
Expand All @@ -171,36 +151,44 @@ 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 String getVersion() {
return VERSION;
}

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

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;
}

public static GameSession getGameSession() {
return GAME_SESSION;
}

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 @@ -68,7 +68,7 @@ public void start(Stage stage) {
scene = new Scene(root, WIDTH, HEIGHT);

stage.setScene(scene);
stage.setTitle("FAF ICE adapter - Debugger - Build: %s".formatted(IceAdapter.VERSION));
stage.setTitle("FAF ICE adapter - Debugger - Build: %s".formatted(IceAdapter.getVersion()));
// stage.setOnCloseRequest(Event::consume);
// stage.show();

Expand Down Expand Up @@ -98,19 +98,19 @@ public void startupComplete() {
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.versionLabel.setText("Version: %s".formatted(IceAdapter.getVersion()));
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()));
});
}

public void initPeers() {
runOnUIThread(() -> {
synchronized (peers) {
peers.clear();
for (Peer peer : IceAdapter.gameSession.getPeers().values()) {
for (Peer peer : IceAdapter.getGameSession().getPeers().values()) {
DebugPeer p = new DebugPeer(peer);
p.stateChangedUpdate(peer);
p.connectivityUpdate(peer);
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -54,7 +54,7 @@ public void onKillAdapterClicked(ActionEvent actionEvent) {

public void reconnectToPeer(DebugWindow.DebugPeer peer) {
if (Objects.nonNull(peer)) {
new Thread(() -> IceAdapter.gameSession.reconnectToPeer(peer.getId())).start();
new Thread(() -> IceAdapter.getGameSession().reconnectToPeer(peer.getId())).start();
}
}

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.getVersion(), 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 All @@ -106,8 +109,8 @@ private void processGpgnetMessage(String command, List<Object> args) {
debug().gameStateChanged();
}
case "GameEnded" -> {
if (IceAdapter.gameSession != null) {
IceAdapter.gameSession.setGameEnded(true);
if (IceAdapter.getGameSession() != null) {
IceAdapter.getGameSession().setGameEnded(true);
log.info("GameEnded received, stopping reconnects...");
}
}
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
Loading

0 comments on commit a0aa9ca

Please sign in to comment.