forked from devcordde/plugin-jam-bot
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathServerService.java
More file actions
162 lines (147 loc) · 6.13 KB
/
Copy pathServerService.java
File metadata and controls
162 lines (147 loc) · 6.13 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
/*
* SPDX-License-Identifier: AGPL-3.0-only
*
* Copyright (C) 2022 DevCord Team and Contributor
*/
package de.chojo.gamejam.server;
import com.fasterxml.jackson.core.JsonProcessingException;
import de.chojo.gamejam.configuration.Configuration;
import de.chojo.gamejam.data.access.Teams;
import de.chojo.gamejam.data.dao.guild.jams.jam.teams.Team;
import de.chojo.gamejam.util.Mapper;
import de.chojo.pluginjam.payload.Registration;
import org.slf4j.Logger;
import java.io.IOException;
import java.net.URI;
import java.net.http.HttpClient;
import java.net.http.HttpRequest;
import java.net.http.HttpResponse;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Stack;
import java.util.concurrent.CompletableFuture;
import java.util.concurrent.ScheduledExecutorService;
import java.util.concurrent.TimeUnit;
import java.util.stream.IntStream;
import static org.slf4j.LoggerFactory.getLogger;
public class ServerService implements Runnable {
private static final Logger log = getLogger(ServerService.class);
private final Map<Team, TeamServer> server = new HashMap<>();
private Teams teams;
private final Configuration configuration;
private final Stack<Integer> freePorts = new Stack<>();
private final DockerService dockerService;
public static ServerService create(ScheduledExecutorService executorService, Configuration configuration) {
var serverService = new ServerService(configuration);
executorService.scheduleAtFixedRate(serverService, 10, 10, TimeUnit.SECONDS);
return serverService;
}
private ServerService(Configuration configuration) {
this.configuration = configuration;
IntStream.rangeClosed(configuration.serverManagement().minPort(), configuration.serverManagement().maxPort())
.forEach(freePorts::add);
this.dockerService = new DockerService(configuration.docker());
this.dockerService.initDockerClient();
}
public void shutdown() {
server.forEach((team, teamServer) -> {
teamServer.stop();
});
}
@Override
public void run() {
for (var value : server.values()) {
if (!value.running()) continue;
try {
value.serverRequests()
.ifPresent(server -> {
if (server.restart()) {
log.info("Server of team {} requested restart", value.team());
value.restart();
}
});
} catch (RuntimeException e) {
log.error("Could not reach server {}", value);
}
}
}
public CompletableFuture<Boolean> syncVelocity() {
return CompletableFuture.supplyAsync(() -> {
log.info("Syncing server with velocity instance.");
freePorts.clear();
IntStream.rangeClosed(configuration.serverManagement().minPort(), configuration.serverManagement().maxPort())
.forEach(freePorts::add);
var velocityPort = configuration.serverManagement().velocityPort();
var velocityHost = configuration.serverManagement().getVelocityHost();
var httpClient = HttpClient.newHttpClient();
var req = HttpRequest.newBuilder(URI.create("http://%s:%d/v1/server".formatted(velocityHost, velocityPort)))
.GET()
.build();
HttpResponse<String> response = null;
var retries = 0;
while (retries < 5) {
try {
response = httpClient.send(req, HttpResponse.BodyHandlers.ofString());
break;
} catch (IOException e) {
log.error("Could not reach velocity instance");
} catch (InterruptedException e) {
log.error("Interrupted", e);
}
retries++;
try {
Thread.sleep(5000);
} catch (InterruptedException e) {
return false;
}
}
if (retries == 5) return false;
var collectionType = Mapper.MAPPER.getTypeFactory()
.constructCollectionType(List.class, Registration.class);
List<Registration> registrations;
try {
registrations = Mapper.MAPPER.readValue(response.body(), collectionType);
} catch (JsonProcessingException e) {
log.error("Could not map response");
return false;
}
server.clear();
for (var registration : registrations) {
var optTeam = teams.byId(registration.id());
if (optTeam.isEmpty()) {
log.warn("Could not find a matching team for id {} of team {}", registration.id(), registration.name());
continue;
}
var team = optTeam.get();
log.info("Registered server for team {} with id {}", team.meta().name(), team.id());
var teamServer = new TeamServer(this, dockerService, team, configuration, registration.port(), registration.apiPort());
teamServer.running(true);
server.put(team, teamServer);
freePorts.removeElement(registration.apiPort());
freePorts.removeElement(registration.port());
}
return true;
});
}
public TeamServer get(Team team) {
return server.computeIfAbsent(team, key -> new TeamServer(this, dockerService, key, configuration, nextPort(), nextPort()));
}
private int nextPort() {
if (!freePorts.isEmpty()) {
return freePorts.pop();
}
throw new RuntimeException("Ports exhausted");
}
void stopped(TeamServer server, boolean restart) {
this.server.remove(server.team());
freePorts.push(server.port());
freePorts.push(server.apiPort());
if (restart) {
get(server.team()).start();
}
}
public void inject(Teams teams) {
this.teams = teams;
}
}