forked from itzg/mc-server-runner
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathmain.go
274 lines (228 loc) · 7 KB
/
main.go
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
package main
import (
"context"
"errors"
"flag"
"fmt"
"io"
"log"
"os"
"os/exec"
"os/signal"
"strings"
"syscall"
"time"
"github.com/itzg/go-flagsfiller"
"github.com/itzg/zapconfigs"
"go.uber.org/zap"
)
type Args struct {
Debug bool `usage:"Enable debug logging"`
Bootstrap string `usage:"Specifies a file with commands to initially send to the server"`
StopDuration time.Duration `usage:"Amount of time in Golang duration to wait after sending the 'stop' command."`
StopServerAnnounceDelay time.Duration `default:"0s" usage:"Amount of time in Golang duration to wait after announcing server shutdown"`
DetachStdin bool `usage:"Don't forward stdin and allow process to be put in background"`
RemoteConsole bool `usage:"Allow remote shell connections over SSH to server console"`
Shell string `usage:"When set, pass the arguments to this shell"`
NamedPipe string `usage:"Optional path to create and read a named pipe for console input"`
}
func main() {
signalChan := make(chan os.Signal, 1)
// docker stop sends a SIGTERM, so intercept that and send a 'stop' command to the server
signal.Notify(signalChan, syscall.SIGTERM)
var args Args
err := flagsfiller.Parse(&args)
if err != nil {
log.Fatal(err)
}
var logger *zap.Logger
if args.Debug {
logger = zapconfigs.NewDebugLogger()
} else {
logger = zapconfigs.NewDefaultLogger()
}
//goland:noinspection GoUnhandledErrorResult
defer logger.Sync()
logger = logger.Named("mc-server-runner")
var cmd *exec.Cmd
if flag.NArg() < 1 {
logger.Fatal("Missing executable arguments")
}
if args.Shell != "" {
cmd = exec.Command(args.Shell, flag.Args()...)
} else {
cmd = exec.Command(flag.Arg(0), flag.Args()[1:]...)
}
stdin, err := cmd.StdinPipe()
if err != nil {
logger.Error("Unable to get stdin", zap.Error(err))
}
if args.RemoteConsole {
stdout, err := cmd.StdoutPipe()
if err != nil {
logger.Error("Unable to get stdout", zap.Error(err))
}
stderr, err := cmd.StderrPipe()
if err != nil {
logger.Error("Unable to get stderr", zap.Error(err))
}
console := makeConsole(stdin, stdout, stderr)
// Relay stdin between outside and server
if !args.DetachStdin {
go consoleInRoutine(os.Stdin, console, logger)
}
go consoleOutRoutine(os.Stdout, console, stdOutTarget, logger)
go consoleOutRoutine(os.Stderr, console, stdErrTarget, logger)
go runRemoteShellServer(console, logger)
logger.Info("Running with remote console support")
} else {
logger.Debug("Directly assigning stdout/stderr")
// directly assign stdout/err to pass through terminal, if applicable
cmd.Stdout = os.Stdout
cmd.Stderr = os.Stderr
if hasRconCli() && args.NamedPipe == "" {
logger.Debug("Directly assigning stdin")
cmd.Stdin = os.Stdin
stdin = os.Stdin
} else {
go relayStdin(logger, stdin)
}
}
err = cmd.Start()
if err != nil {
logger.Error("Failed to start", zap.Error(err))
}
if args.Bootstrap != "" {
bootstrapContent, err := os.ReadFile(args.Bootstrap)
if err != nil {
logger.Error("Failed to read bootstrap commands", zap.Error(err))
}
_, err = stdin.Write(bootstrapContent)
if err != nil {
logger.Error("Failed to write bootstrap content", zap.Error(err))
}
}
ctx, cancel := context.WithCancel(context.Background())
errorChan := make(chan error, 1)
if args.NamedPipe != "" {
err2 := handleNamedPipe(ctx, args.NamedPipe, stdin, errorChan)
if err2 != nil {
logger.Fatal("Failed to setup named pipe", zap.Error(err2))
}
}
cmdExitChan := make(chan int, 1)
go func() {
waitErr := cmd.Wait()
if waitErr != nil {
var exitErr *exec.ExitError
if errors.As(waitErr, &exitErr) {
exitCode := exitErr.ExitCode()
logger.Warn("Minecraft server failed. Inspect logs above for errors that indicate cause. DO NOT report this line as an error.",
zap.Int("exitCode", exitCode))
cmdExitChan <- exitCode
}
return
} else {
cmdExitChan <- 0
}
}()
for {
select {
case <-signalChan:
if args.StopServerAnnounceDelay > 0 {
announceStop(logger, stdin, args.StopServerAnnounceDelay)
logger.Info("Sleeping before server stop", zap.Duration("sleepTime", args.StopServerAnnounceDelay))
time.Sleep(args.StopServerAnnounceDelay)
}
if hasRconCli() {
err := stopWithRconCli()
if err != nil {
logger.Error("Failed to stop using rcon-cli", zap.Error(err))
stopViaConsole(logger, stdin)
}
} else {
stopViaConsole(logger, stdin)
}
logger.Info("Waiting for completion...")
if args.StopDuration != 0 {
time.AfterFunc(args.StopDuration, func() {
logger.Error("Took too long, so killing server process")
err := cmd.Process.Kill()
if err != nil {
logger.Error("Failed to forcefully kill process")
}
})
}
case namedPipeErr := <-errorChan:
logger.Error("Error during named pipe handling", zap.Error(namedPipeErr))
case exitCode := <-cmdExitChan:
cancel()
logger.Info("Done")
os.Exit(exitCode)
}
}
}
func relayStdin(logger *zap.Logger, stdin io.WriteCloser) {
_, err := io.Copy(stdin, os.Stdin)
if err != nil {
logger.Error("Failed to relay standard input", zap.Error(err))
}
}
func hasRconCli() bool {
if strings.ToUpper(os.Getenv("ENABLE_RCON")) == "TRUE" {
_, err := exec.LookPath("rcon-cli")
return err == nil
} else {
return false
}
}
func sendRconCommand(cmd ...string) error {
rconConfigFile := os.Getenv("RCON_CONFIG_FILE")
if rconConfigFile == "" {
port := os.Getenv("RCON_PORT")
if port == "" {
port = "25575"
}
password := os.Getenv("RCON_PASSWORD")
if password == "" {
password = "minecraft"
}
args := []string{"--port", port,
"--password", password}
args = append(args, cmd...)
rconCliCmd := exec.Command("rcon-cli", args...)
return rconCliCmd.Run()
} else {
args := []string{"--config", rconConfigFile}
args = append(args, cmd...)
rconCliCmd := exec.Command("rcon-cli", args...)
return rconCliCmd.Run()
}
}
// sendCommand will send the given command via RCON when available, otherwise it will write to the given stdin
func sendCommand(stdin io.Writer, cmd ...string) error {
if hasRconCli() {
return sendRconCommand(cmd...)
} else {
_, err := stdin.Write([]byte(strings.Join(cmd, " ")))
return err
}
}
func announceStop(logger *zap.Logger, stdin io.Writer, shutdownDelay time.Duration) {
logger.Info("Sending shutdown announce 'say' to Minecraft server")
err := sendCommand(stdin, "say", fmt.Sprintf("Server shutting down in %0.f seconds", shutdownDelay.Seconds()))
if err != nil {
logger.Error("Failed to send 'say' command", zap.Error(err))
}
}
func stopWithRconCli() error {
log.Println("Stopping with rcon-cli")
return sendRconCommand("stop")
}
func stopViaConsole(logger *zap.Logger, stdin io.Writer) {
logger.Info("Sending 'stop' to Minecraft server...")
_, err := stdin.Write([]byte("stop\n"))
if err != nil {
logger.Error("Failed to write stop command to server console", zap.Error(err))
}
}