Skip to content
This repository was archived by the owner on Jun 7, 2022. It is now read-only.

Commit bbe3e61

Browse files
authored
Use ExecutorService for the local wrappers console
1 parent 4c881f2 commit bbe3e61

File tree

1 file changed

+117
-97
lines changed

1 file changed

+117
-97
lines changed

cloudnet-core/src/main/java/de/dytanic/cloudnetcore/wrapper/local/LocalCloudWrapper.java

Lines changed: 117 additions & 97 deletions
Original file line numberDiff line numberDiff line change
@@ -28,6 +28,8 @@
2828
import java.nio.file.Paths;
2929
import java.nio.file.StandardCopyOption;
3030
import java.util.Collections;
31+
import java.util.concurrent.ExecutorService;
32+
import java.util.concurrent.Executors;
3133
import java.util.concurrent.TimeUnit;
3234
import java.util.function.Consumer;
3335

@@ -39,9 +41,7 @@ public class LocalCloudWrapper implements Runnabled<OptionSet>, Closeable {
3941
private static final String WRAPPER_URL = "https://ci.cloudnetservice.eu/job/CloudNetService/job/CloudNet/job/master/lastSuccessfulBuild/artifact/cloudnet-wrapper/target/CloudNet-Wrapper.jar";
4042

4143
private Process process;
42-
private Thread consoleThread;
43-
private StringBuffer stringBuffer = new StringBuffer();
44-
private byte[] buffer = new byte[1024];
44+
private ExecutorService executorService = Executors.newFixedThreadPool(2);
4545
private boolean shutdown = false;
4646
private boolean enabled;
4747
private boolean showConsoleOutput = !Boolean.getBoolean("cloudnet.localwrapper.disableConsole");
@@ -59,6 +59,11 @@ public void setShowConsoleOutput(boolean showConsoleOutput) {
5959
this.showConsoleOutput = showConsoleOutput;
6060
}
6161

62+
public Wrapper getWrapper() {
63+
String wrapperId = this.loadWrapperConfiguration().getString("general.wrapperId");
64+
return CloudNet.getInstance().getWrappers().get(wrapperId);
65+
}
66+
6267
public Configuration loadWrapperConfiguration() {
6368
if (this.config == null || this.config.isOutdated()) {
6469
try (InputStream inputStream = Files.newInputStream(Paths.get("wrapper/config.yml"))) {
@@ -70,24 +75,37 @@ public Configuration loadWrapperConfiguration() {
7075
return this.config != null ? this.config.getConfiguration() : null;
7176
}
7277

73-
public Wrapper getWrapper() {
74-
String wrapperId = this.loadWrapperConfiguration().getString("general.wrapperId");
75-
return CloudNet.getInstance().getWrappers().get(wrapperId);
76-
}
77-
7878
public void installUpdate(WebClient webClient) {
7979
Path path = Paths.get("wrapper/CloudNet-Wrapper.jar");
8080
if (Files.exists(path)) {
81+
boolean runningBeforeUpdate = false;
82+
if (this.process != null && this.process.isAlive()) {
83+
this.shutdown = true;
84+
try {
85+
this.stop();
86+
runningBeforeUpdate = true;
87+
} catch (IOException e) {
88+
e.printStackTrace();
89+
}
90+
}
8191
webClient.updateLocalCloudWrapper(path);
92+
if (runningBeforeUpdate) {
93+
try {
94+
this.startProcess();
95+
} catch (IOException e) {
96+
e.printStackTrace();
97+
}
98+
}
8299
}
83100
}
84101

85102
@Override
86103
public void run(OptionSet obj) {
87104
if (obj.has("installWrapper")) {
88105
try {
89-
if (!Files.exists(Paths.get("wrapper")))
106+
if (!Files.exists(Paths.get("wrapper"))) {
90107
Files.createDirectories(Paths.get("wrapper"));
108+
}
91109

92110
this.setupWrapperJar();
93111
this.setupConfig();
@@ -105,35 +123,14 @@ public void run(OptionSet obj) {
105123

106124
// -------------------- SETUP --------------------
107125

108-
private void setupSpigot(OptionSet obj) {
109-
Path path = Paths.get("wrapper/local/spigot.jar");
110-
if (!obj.has("disallow_bukkit_download") && !Files.exists(path)) {
111-
try {
112-
Files.createDirectories(path.getParent());
113-
} catch (IOException e) {
114-
e.printStackTrace();
115-
}
116-
SetupSpigotVersion setup = new SetupSpigotVersion();
117-
setup.setTarget(path);
118-
setup.run(CloudNet.getLogger().getReader());
119-
}
120-
}
121-
122-
private void setupWrapperKey() {
123-
try {
124-
Files.copy(Paths.get("WRAPPER_KEY.cnd"), Paths.get("wrapper/WRAPPER_KEY.cnd"), StandardCopyOption.REPLACE_EXISTING);
125-
} catch (IOException e) {
126-
e.printStackTrace();
127-
}
128-
}
129-
130126
private void setupWrapperJar() {
131127
Path path = Paths.get("wrapper/CloudNet-Wrapper.jar");
132128
if (!Files.exists(path)) {
133129
try {
134130
System.out.println("Downloading wrapper...");
135131
URLConnection urlConnection = new URL(WRAPPER_URL).openConnection();
136-
urlConnection.setRequestProperty("User-Agent", "Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.11 (KHTML, like Gecko) Chrome/23.0.1271.95 Safari/537.11");
132+
urlConnection.setRequestProperty("User-Agent",
133+
"Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.11 (KHTML, like Gecko) Chrome/23.0.1271.95 Safari/537.11");
137134
urlConnection.connect();
138135
Files.copy(urlConnection.getInputStream(), path);
139136
System.out.println("Download completed!");
@@ -158,13 +155,20 @@ private void setupConfig() {
158155
}
159156

160157
final User finalUser = user;
161-
WrapperMeta wrapperMeta = CloudNet.getInstance().getConfig().getWrappers().stream()
162-
.filter(meta -> meta.getId().equals("Wrapper-1"))
163-
.findFirst().orElseGet(() -> {
164-
WrapperMeta newMeta = new WrapperMeta("Wrapper-1", address.getHostName(), finalUser.getName());
165-
CloudNet.getInstance().getConfig().createWrapper(newMeta);
166-
return newMeta;
167-
});
158+
WrapperMeta wrapperMeta = CloudNet.getInstance()
159+
.getConfig()
160+
.getWrappers()
161+
.stream()
162+
.filter(meta -> meta.getId()
163+
.equals("Wrapper-1"))
164+
.findFirst()
165+
.orElseGet(() -> {
166+
WrapperMeta newMeta = new WrapperMeta("Wrapper-1",
167+
address.getHostName(),
168+
finalUser.getName());
169+
CloudNet.getInstance().getConfig().createWrapper(newMeta);
170+
return newMeta;
171+
});
168172

169173
long memory = ((NetworkUtils.systemMemory() / 1048576) - 2048);
170174
if (memory < 1024) {
@@ -198,6 +202,28 @@ private void setupConfig() {
198202
}
199203
}
200204

205+
private void setupWrapperKey() {
206+
try {
207+
Files.copy(Paths.get("WRAPPER_KEY.cnd"), Paths.get("wrapper/WRAPPER_KEY.cnd"), StandardCopyOption.REPLACE_EXISTING);
208+
} catch (IOException e) {
209+
e.printStackTrace();
210+
}
211+
}
212+
213+
private void setupSpigot(OptionSet obj) {
214+
Path path = Paths.get("wrapper/local/spigot.jar");
215+
if (!obj.has("disallow_bukkit_download") && !Files.exists(path)) {
216+
try {
217+
Files.createDirectories(path.getParent());
218+
} catch (IOException e) {
219+
e.printStackTrace();
220+
}
221+
SetupSpigotVersion setup = new SetupSpigotVersion();
222+
setup.setTarget(path);
223+
setup.accept(CloudNet.getLogger().getReader());
224+
}
225+
}
226+
201227
// -------------------- SETUP --------------------
202228

203229
// -------------------- PROCESS --------------------
@@ -206,7 +232,6 @@ private void startup() {
206232
System.out.println("Starting local wrapper...");
207233
try {
208234
this.startProcess();
209-
this.initConsoleThread();
210235

211236
System.out.println("Successfully started the local wrapper!");
212237
} catch (IOException e) {
@@ -217,12 +242,57 @@ private void startup() {
217242

218243
private void startProcess() throws IOException {
219244
System.out.println("Starting wrapper process...");
220-
this.process = new ProcessBuilder("java", "-Xmx256M", "-Djline.terminal=jline.UnsupportedTerminal", "-Dcloudnet.logging.prompt.disabled=true", "-jar", "CloudNet-Wrapper.jar")
221-
.directory(new File("wrapper"))
222-
.start();
245+
this.process = new ProcessBuilder("java",
246+
"-Xmx256M",
247+
"-Djline.terminal=jline.UnsupportedTerminal",
248+
"-Dcloudnet.logging.prompt.disabled=true",
249+
"-jar",
250+
"CloudNet-Wrapper.jar").directory(new File("wrapper")).start();
251+
this.initConsoleThread();
223252
System.out.println("Successfully started the wrapper process!");
224253
}
225254

255+
private void initConsoleThread() {
256+
this.executorService.execute(() -> {
257+
InputStream inputStream = this.process.getInputStream();
258+
this.readStream(inputStream, s -> {
259+
if (this.showConsoleOutput) {
260+
System.out.println("LocalWrapper | " + s);
261+
}
262+
});
263+
if (!this.shutdown) {
264+
try {
265+
this.startProcess();
266+
} catch (IOException e) {
267+
e.printStackTrace();
268+
}
269+
} else {
270+
this.enabled = false;
271+
}
272+
});
273+
this.executorService.execute(() -> {
274+
InputStream inputStream = this.process.getErrorStream();
275+
this.readStream(inputStream, s -> {
276+
if (this.showConsoleOutput) {
277+
System.err.println("LocalWrapper | " + s);
278+
}
279+
});
280+
});
281+
}
282+
283+
private void readStream(InputStream inputStream, Consumer<String> consumer) {
284+
try (BufferedReader reader = new BufferedReader(new InputStreamReader(inputStream, StandardCharsets.UTF_8))){
285+
String line;
286+
while ((line = reader.readLine()) != null) {
287+
if (!line.isEmpty()) {
288+
consumer.accept(line);
289+
}
290+
}
291+
} catch (IOException e) {
292+
e.printStackTrace();
293+
}
294+
}
295+
226296
@Override
227297
public void close() throws IOException {
228298
this.enabled = false;
@@ -232,10 +302,6 @@ public void close() throws IOException {
232302
}
233303
}
234304

235-
public void restart() throws IOException {
236-
this.stop();
237-
}
238-
239305
private void stop() throws IOException {
240306
System.out.println("Stopping the local wrapper...");
241307
this.executeCommand("stop");
@@ -250,60 +316,14 @@ private void stop() throws IOException {
250316
}
251317

252318
public void executeCommand(String command) throws IOException {
253-
this.process.getOutputStream().write((command + "\n").getBytes(StandardCharsets.UTF_8));
319+
this.process.getOutputStream().write((command + '\n').getBytes(StandardCharsets.UTF_8));
254320
this.process.getOutputStream().flush();
255321
}
256322

257-
private void initConsoleThread() {
258-
this.consoleThread = new Thread(() -> {
259-
while (!Thread.interrupted()) {
260-
if (this.process.isAlive()) {
261-
this.readStream(this.process.getInputStream(), s -> {
262-
if (this.showConsoleOutput) {
263-
System.out.println("LocalWrapper | " + s);
264-
}
265-
});
266-
this.readStream(this.process.getErrorStream(), s -> {
267-
if (this.showConsoleOutput) {
268-
System.err.println("LocalWrapper | " + s);
269-
}
270-
});
271-
} else if (!shutdown) {
272-
try {
273-
this.startProcess();
274-
} catch (IOException e) {
275-
e.printStackTrace();
276-
}
277-
} else {
278-
this.enabled = false;
279-
Thread.currentThread().interrupt();
280-
}
281-
}
282-
}, "LocalWrapper-Console");
283-
this.consoleThread.start();
284-
}
285-
286-
private void readStream(InputStream inputStream, Consumer<String> consumer) {
287-
try {
288-
int len;
289-
while (inputStream.available() > 0 && (len = inputStream.read(this.buffer)) != -1)
290-
this.stringBuffer.append(new String(this.buffer, 0, len, StandardCharsets.UTF_8));
291-
292-
String stringText = this.stringBuffer.toString();
293-
if (!stringText.contains("\n") && !stringText.contains("\r")) return;
294-
295-
for (String input : stringText.split("\r"))
296-
for (String text : input.split("\n"))
297-
if (!text.trim().isEmpty())
298-
consumer.accept(text);
299-
300-
this.stringBuffer.setLength(0);
301-
302-
} catch (Exception ignored) {
303-
this.stringBuffer.setLength(0);
304-
}
323+
public void restart() throws IOException {
324+
this.stop();
305325
}
306326

307327
// -------------------- PROCESS --------------------
308328

309-
}
329+
}

0 commit comments

Comments
 (0)