-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathServerController.java
More file actions
553 lines (516 loc) · 23.6 KB
/
Copy pathServerController.java
File metadata and controls
553 lines (516 loc) · 23.6 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
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.time.Duration;
import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.TimeUnit;
public class ServerController {
private static final Path WEBROOT = Paths.get("/srv/www/mevzuatraporu");
private static final Path RUNDIR = Paths.get("/var/run/servercontroller");
private static final Path LOGDIR = Paths.get("/var/log/servercontroller");
// fallback to user-local dirs if /var is not writable
private static final Path USER_RUNDIR = Paths.get(System.getProperty("user.home"), ".servercontroller", "run");
private static final Path USER_LOGDIR = Paths.get(System.getProperty("user.home"), ".servercontroller", "log");
private static final Path USER_CONFIG = Paths.get(System.getProperty("user.home"), ".servercontroller", "config.properties");
// PID files are written to whichever run dir is actually usable at runtime
public static void main(String[] args) throws Exception {
if (args.length == 0) {
usage();
return;
}
switch (args[0]) {
case "on":
startAll();
break;
case "off":
stopAll();
break;
case "gui":
javax.swing.SwingUtilities.invokeLater(() -> {
try {
ServerControllerGUI.createAndShowGUI();
} catch (Exception e) {
e.printStackTrace();
}
});
break;
default:
usage();
}
}
private static java.util.Properties loadConfig() throws IOException {
java.util.Properties p = new java.util.Properties();
Path cfg = USER_CONFIG;
if (Files.exists(cfg)) {
try (java.io.InputStream in = Files.newInputStream(cfg)) {
p.load(in);
}
}
return p;
}
private static void usage() {
System.out.println("Usage: java ServerController on|off|gui");
}
public static void startAll() throws Exception {
ensureDirs();
System.out.println("starting apache and mysql (if present)...");
startApache();
startMysql();
// if Apache is active, prefer it. Otherwise start the PHP built-in server.
if (isServiceActive("apache2")) {
System.out.println("apache active; skipping PHP built-in server");
// wait for Apache on port 80
waitForPort(80, Duration.ofSeconds(10));
} else {
System.out.println("starting php server...");
startPhp();
waitForPort(8000, Duration.ofSeconds(10));
}
System.out.println("starting ngrok tunnel...");
startNgrok();
waitForNgrok(Duration.ofSeconds(10));
System.out.println("all services appear up");
}
private static void ensureDirs() {
try {
if (!Files.exists(RUNDIR) || !Files.isWritable(RUNDIR)) {
Files.createDirectories(USER_RUNDIR);
} else {
Files.createDirectories(RUNDIR);
}
if (!Files.exists(LOGDIR) || !Files.isWritable(LOGDIR)) {
Files.createDirectories(USER_LOGDIR);
} else {
Files.createDirectories(LOGDIR);
}
} catch (Exception e) {
// best-effort; ignore and rely on fallback paths when used
}
}
public static void stopAll() throws IOException, InterruptedException {
killPidFile(getRunDir().resolve("phpserverpid"));
killPidFile(getRunDir().resolve("ngrokpid"));
System.out.println("stopped services");
}
private static void startPhp() throws IOException {
Path logdir = Files.exists(LOGDIR) && Files.isWritable(LOGDIR) ? LOGDIR : USER_LOGDIR;
String log = logdir.resolve("phpout.log").toString();
// bind to 127.0.0.1 to avoid systems where "localhost" resolves to IPv6 ::1 only
ProcessBuilder pb = new ProcessBuilder("bash", "-c",
"cd " + WEBROOT + " && php -S 127.0.0.1:8000 -t . > " + log + " 2>&1 & echo $!");
Process p = pb.start();
try (BufferedReader r = new BufferedReader(new InputStreamReader(p.getInputStream()))) {
String pid = r.readLine();
if (pid != null && !pid.isBlank()) {
Files.writeString(getRunDir().resolve("phpserverpid"), pid);
}
}
}
public static void startNgrok() throws IOException, InterruptedException {
String hostname = System.getenv("NGROK_HOSTNAME");
// if Apache is active prefer port 80, otherwise the PHP built-in on 127.0.0.1:8000
String target = "127.0.0.1:8000";
try {
if (isServiceActive("apache2")) target = "127.0.0.1:80";
} catch (Exception e) {
// ignore and use default
}
// determine ngrok executable path and construct command
String ngrokExec = resolveNgrokExec();
// verify ngrok version is supported
try {
String ver = getNgrokVersion();
if (ver == null) throw new IOException("ngrok binary not found or not executable");
if (!isNgrokSupported(ver)) {
throw new IOException("ngrok agent too old: " + ver + " (minimum 3.20.0). Please update ngrok from https://ngrok.com/download");
}
} catch (IOException e) {
throw e;
} catch (Exception ignored) {
// if version cannot be determined, fail start to avoid running incompatible agent
throw new IOException("unable to determine ngrok version; please ensure ngrok v3 is installed");
}
String cmd = ngrokExec + " http " + target;
if (hostname != null && !hostname.isBlank()) {
cmd = ngrokExec + " http --hostname=" + hostname + " " + target;
}
Path logdir = Files.exists(LOGDIR) && Files.isWritable(LOGDIR) ? LOGDIR : USER_LOGDIR;
Files.createDirectories(logdir);
Files.createDirectories(getRunDir());
String log = logdir.resolve("ngrok.log").toString();
// use nohup to keep process running after parent exits and echo the PID
String startCmd = "nohup " + cmd + " > " + log + " 2>&1 & echo $!";
ProcessBuilder pb = new ProcessBuilder("bash", "-c", startCmd);
Process p = pb.start();
String pid = null;
try (BufferedReader r = new BufferedReader(new InputStreamReader(p.getInputStream()))) {
pid = r.readLine();
}
if (pid == null || pid.isBlank()) {
// read tail of log to provide context
String tail = "";
try {
Process tailp = new ProcessBuilder("bash", "-c", "tail -n 50 " + log + " 2>/dev/null || true").start();
try (BufferedReader tr = new BufferedReader(new InputStreamReader(tailp.getInputStream()))) {
StringBuilder sb = new StringBuilder();
String line;
while ((line = tr.readLine()) != null) sb.append(line).append('\n');
tail = sb.toString();
}
} catch (Exception ignore) {}
throw new IOException("failed to start ngrok (no pid). Log tail:\n" + tail);
}
pid = pid.trim();
// verify process exists
if (!Files.exists(Paths.get("/proc").resolve(pid))) {
throw new IOException("ngrok process not found after start (pid=" + pid + ")");
}
Files.writeString(getRunDir().resolve("ngrokpid"), pid);
}
public static void stopNgrok() throws IOException, InterruptedException {
// prefer stopping a systemd unit if present (user or system), otherwise fall back to pidfile or pkill
try {
if (systemdUnitExists("ngrok")) {
stopService("ngrok", Duration.ofSeconds(5));
Files.deleteIfExists(getRunDir().resolve("ngrokpid"));
// wait briefly for processes to exit
for (int i = 0; i < 10; i++) {
if (!isNgrokRunning()) break;
Thread.sleep(300);
}
return;
}
} catch (Exception e) {
// ignore and continue to fallback
}
Path pidFile = getRunDir().resolve("ngrokpid");
// if we have a pidfile, validate it points to an ngrok instance and kill it
if (Files.exists(pidFile)) {
String pid = Files.readString(pidFile).trim();
if (!pid.isBlank() && Files.exists(Paths.get("/proc").resolve(pid))) {
try {
// check cmdline contains ngrok or the resolved binary
String cmdline = Files.readString(Paths.get("/proc").resolve(pid).resolve("cmdline")).replace('\0',' ');
String resolved = resolveNgrokExec();
if (cmdline.contains("ngrok") || (resolved != null && !resolved.isBlank() && cmdline.contains(resolved))) {
// try graceful kill
new ProcessBuilder("kill", pid).start().waitFor();
for (int i = 0; i < 10; i++) {
if (!Files.exists(Paths.get("/proc").resolve(pid))) break;
Thread.sleep(300);
}
if (Files.exists(Paths.get("/proc").resolve(pid))) {
new ProcessBuilder("kill", "-9", pid).start().waitFor();
}
}
} catch (Exception ignore) {}
}
Files.deleteIfExists(pidFile);
// ensure no other ngrok processes remain
if (!isNgrokRunning()) return;
}
// No pidfile or still running: try pkill by resolved path then by process name
String resolved = resolveNgrokExec();
try {
if (resolved != null && !resolved.isBlank()) {
new ProcessBuilder("bash", "-c", "pkill -u $(id -u) -f '" + resolved.replace("'","'\\''") + "' || true").start().waitFor();
}
} catch (Exception ignore) {}
// fallback to generic pkill of any ngrok processes owned by this user
try {
new ProcessBuilder("bash", "-c", "pkill -u $(id -u) -f ngrok || true").start().waitFor();
} catch (Exception ignore) {}
// wait for processes to disappear, else force kill
for (int i = 0; i < 10; i++) {
if (!isNgrokRunning()) break;
Thread.sleep(300);
}
if (isNgrokRunning()) {
try { new ProcessBuilder("bash", "-c", "pkill -9 -u $(id -u) -f ngrok || true").start().waitFor(); } catch (Exception ignore) {}
}
Files.deleteIfExists(pidFile);
}
public static boolean isNgrokRunning() {
try {
Path pidFile = getRunDir().resolve("ngrokpid");
if (Files.exists(pidFile)) {
String pid = Files.readString(pidFile).trim();
if (!pid.isEmpty() && Files.exists(Paths.get("/proc").resolve(pid))) return true;
}
// fallback: check for running ngrok processes for this user
Process p = new ProcessBuilder("bash", "-c", "pgrep -u $(id -u) -a ngrok || true").start();
try (BufferedReader r = new BufferedReader(new InputStreamReader(p.getInputStream()))) {
String line;
while ((line = r.readLine()) != null) {
if (!line.isBlank()) return true;
}
}
} catch (Exception e) {
// ignore
}
return false;
}
private static boolean systemdUnitExists(String name) throws IOException, InterruptedException {
// check user unit first, then system unit
Process pUser = new ProcessBuilder("bash", "-c", "systemctl --user cat " + name + ".service >/dev/null 2>&1 && echo yes || true").start();
if (pUser.waitFor(2, TimeUnit.SECONDS)) {
try (BufferedReader r = new BufferedReader(new InputStreamReader(pUser.getInputStream()))) {
String out = r.readLine();
if (out != null && out.trim().equals("yes")) return true;
}
}
Process pSystem = new ProcessBuilder("bash", "-c", "systemctl cat " + name + ".service >/dev/null 2>&1 && echo yes || true").start();
if (pSystem.waitFor(2, TimeUnit.SECONDS)) {
try (BufferedReader r = new BufferedReader(new InputStreamReader(pSystem.getInputStream()))) {
String out = r.readLine();
return out != null && out.trim().equals("yes");
}
}
return false;
}
public static boolean isPhpRunning() {
try {
return Files.exists(getRunDir().resolve("phpserverpid"));
} catch (Exception e) {
return false;
}
}
private static Path getRunDir() {
try {
if (Files.exists(RUNDIR) && Files.isWritable(RUNDIR)) return RUNDIR;
} catch (Exception e) {
// fallthrough to user dir
}
return USER_RUNDIR;
}
private static Path getLogDir() {
try {
if (Files.exists(LOGDIR) && Files.isWritable(LOGDIR)) return LOGDIR;
} catch (Exception e) {
// fallthrough to user log dir
}
return USER_LOGDIR;
}
public static void startApache() throws IOException {
// attempt to start apache via sudo and wait for it to become active
try {
startService("apache2", Duration.ofSeconds(10));
} catch (InterruptedException e) {
Thread.currentThread().interrupt();
}
}
public static void stopApache() throws IOException, InterruptedException {
stopService("apache2", Duration.ofSeconds(10));
}
public static void startMysql() throws IOException {
// try common service names via sudo and wait for one to become active
try {
if (startService("mysql", Duration.ofSeconds(10))) return;
if (startService("mariadb", Duration.ofSeconds(10))) return;
startService("mysqld", Duration.ofSeconds(10));
} catch (InterruptedException e) {
Thread.currentThread().interrupt();
}
}
public static void stopMysql() throws IOException, InterruptedException {
// stop all common service names and wait for inactive
stopService("mysql", Duration.ofSeconds(10));
stopService("mariadb", Duration.ofSeconds(10));
stopService("mysqld", Duration.ofSeconds(10));
}
private static boolean startService(String name, Duration timeout) throws IOException, InterruptedException {
Path log = getLogDir().resolve(name + ".ctl.log");
Files.createDirectories(log.getParent());
ProcessBuilder pb = new ProcessBuilder("bash", "-c", "sudo systemctl start " + name + " || true");
pb.redirectErrorStream(true);
// append process output directly to the log file to avoid blocking reads
pb.redirectOutput(java.lang.ProcessBuilder.Redirect.appendTo(log.toFile()));
Process p = pb.start();
// give the command a short moment to run, but we don't block reading its output here
p.waitFor(5, TimeUnit.SECONDS);
long start = System.nanoTime();
while (Duration.ofNanos(System.nanoTime() - start).compareTo(timeout) < 0) {
try {
if (isServiceActive(name)) return true;
} catch (Exception e) {
// ignore and retry
}
Thread.sleep(500);
}
return false;
}
private static boolean stopService(String name, Duration timeout) throws IOException, InterruptedException {
Path log = getLogDir().resolve(name + ".ctl.log");
Files.createDirectories(log.getParent());
ProcessBuilder pb = new ProcessBuilder("bash", "-c", "sudo systemctl stop " + name + " || true");
pb.redirectErrorStream(true);
// append process output directly to the log file to avoid blocking reads
pb.redirectOutput(java.lang.ProcessBuilder.Redirect.appendTo(log.toFile()));
Process p = pb.start();
// give the command a short moment to run, but we don't block reading its output here
p.waitFor(5, TimeUnit.SECONDS);
long start = System.nanoTime();
while (Duration.ofNanos(System.nanoTime() - start).compareTo(timeout) < 0) {
try {
if (!isServiceActive(name)) return true;
} catch (Exception e) {
// if isServiceActive fails, assume stopped and return true
return true;
}
Thread.sleep(500);
}
return false;
}
public static boolean isServiceActive(String name) throws IOException, InterruptedException {
Process p = new ProcessBuilder("bash", "-c", "systemctl is-active " + name).start();
if (p.waitFor(3, TimeUnit.SECONDS) && p.exitValue() == 0) {
try (BufferedReader r = new BufferedReader(new InputStreamReader(p.getInputStream()))) {
String out = r.readLine();
return out != null && out.trim().equals("active");
}
}
return false;
}
public static List<String> getLocalIPs() throws IOException {
List<String> ips = new ArrayList<>();
try {
Process p = new ProcessBuilder("bash", "-c", "hostname -I 2>/dev/null || true").start();
try (BufferedReader r = new BufferedReader(new InputStreamReader(p.getInputStream()))) {
String line = r.readLine();
if (line != null && !line.isBlank()) {
for (String ip : line.trim().split("\\s+")) {
if (!ip.startsWith("127.")) ips.add(ip);
}
}
}
} catch (Exception e) {
// ignore
}
return ips;
}
private static void waitForPort(int port, Duration timeout) throws IOException, InterruptedException {
long start = System.nanoTime();
while (Duration.ofNanos(System.nanoTime() - start).compareTo(timeout) < 0) {
Process p = new ProcessBuilder("bash", "-c", "ss -ltn | awk '{print $4}'").start();
try (BufferedReader r = new BufferedReader(new InputStreamReader(p.getInputStream()))) {
String line;
while ((line = r.readLine()) != null) {
if (line.endsWith(":" + port) || line.endsWith("." + port)) {
return;
}
}
}
Thread.sleep(500);
}
throw new IOException("timeout waiting for port " + port);
}
private static void waitForUrl(String url, Duration timeout) throws IOException, InterruptedException {
// removed: this helper was unused. Use external curl checks when needed.
}
private static void waitForNgrok(Duration timeout) throws IOException, InterruptedException {
long start = System.nanoTime();
while (Duration.ofNanos(System.nanoTime() - start).compareTo(timeout) < 0) {
String exec = resolveNgrokExec();
Process p = new ProcessBuilder(exec, "api", "tunnels", "list").start();
if (p.waitFor(3, TimeUnit.SECONDS) && p.exitValue() == 0) {
return;
}
Thread.sleep(500);
}
throw new IOException("timeout waiting for ngrok API");
}
private static void killPidFile(Path pidFile) throws IOException, InterruptedException {
if (Files.exists(pidFile)) {
String pid = Files.readString(pidFile).trim();
if (!pid.isEmpty()) {
// try graceful termination then force if still running
try {
new ProcessBuilder("kill", pid).start().waitFor();
} catch (Exception e) {
// ignore
}
// wait up to 5s for process to exit
try {
for (int i = 0; i < 10; i++) {
if (!Files.exists(Paths.get("/proc").resolve(pid))) break;
Thread.sleep(500);
}
if (Files.exists(Paths.get("/proc").resolve(pid))) {
// force kill
try { new ProcessBuilder("kill", "-9", pid).start().waitFor(); } catch (Exception ex) {}
}
} catch (InterruptedException ie) {
// restore interrupt
Thread.currentThread().interrupt();
}
}
Files.deleteIfExists(pidFile);
}
}
private static String resolveNgrokExec() {
String ngrokExec = "ngrok";
try {
java.util.Properties cfg = loadConfig();
String cfgPath = cfg.getProperty("ngrok.path");
if (cfgPath != null && !cfgPath.isBlank()) ngrokExec = cfgPath;
} catch (Exception ignored) {}
Path userLocal = Paths.get(System.getProperty("user.home"), ".local", "bin", "ngrok");
if ((ngrokExec == null || ngrokExec.equals("ngrok")) && Files.exists(userLocal) && Files.isExecutable(userLocal)) {
ngrokExec = userLocal.toString();
}
if (ngrokExec.equals("ngrok")) {
try {
Process p = new ProcessBuilder("bash", "-c", "command -v ngrok || true").start();
if (p.waitFor(2, TimeUnit.SECONDS)) {
try (BufferedReader r = new BufferedReader(new InputStreamReader(p.getInputStream()))) {
String line = r.readLine();
if (line != null && !line.isBlank()) ngrokExec = line.trim();
}
}
} catch (Exception ignored) {}
}
return ngrokExec;
}
public static String getNgrokVersion() throws IOException, InterruptedException {
String exec = resolveNgrokExec();
if (exec == null || exec.isBlank()) return null;
Process p = new ProcessBuilder(exec, "version").start();
if (p.waitFor(3, TimeUnit.SECONDS)) {
try (BufferedReader r = new BufferedReader(new InputStreamReader(p.getInputStream()))) {
String line;
StringBuilder sb = new StringBuilder();
while ((line = r.readLine()) != null) {
sb.append(line).append('\n');
}
String out = sb.toString().trim();
if (out.isEmpty()) return null;
// expected formats: 'ngrok version 3.20.0' or 'ngrok version 2.3.41'
java.util.regex.Matcher m = java.util.regex.Pattern.compile("(\\d+\\.\\d+(?:\\.\\d+)?)").matcher(out);
if (m.find()) return m.group(1);
return out.split("\\s+")[0];
}
}
return null;
}
public static boolean isNgrokSupported(String ver) {
if (ver == null) return false;
try {
String[] parts = ver.split("\\.");
int major = Integer.parseInt(parts[0]);
int minor = parts.length > 1 ? Integer.parseInt(parts[1]) : 0;
int patch = parts.length > 2 ? Integer.parseInt(parts[2]) : 0;
if (major > 3) return true;
if (major < 3) return false;
// major == 3
if (minor > 20) return true;
if (minor < 20) return false;
return patch >= 0; // any 3.20.x or greater
} catch (Exception e) {
return false;
}
}
}