-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathmain.go
More file actions
418 lines (310 loc) · 10.1 KB
/
main.go
File metadata and controls
418 lines (310 loc) · 10.1 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
package main
import (
"encoding/json"
"flag"
"fmt"
"os"
"os/signal"
"strings"
"syscall"
"time"
"github.com/gamemann/Rust-Auto-Wipe/internal/autoaddservers"
"github.com/gamemann/Rust-Auto-Wipe/internal/config"
"github.com/gamemann/Rust-Auto-Wipe/internal/wipe"
"github.com/gamemann/Rust-Auto-Wipe/pkg/chttp"
"github.com/gamemann/Rust-Auto-Wipe/pkg/debug"
"github.com/gamemann/Rust-Auto-Wipe/pkg/format"
"github.com/gamemann/Rust-Auto-Wipe/pkg/misc"
cron "github.com/robfig/cron/v3"
)
const HELP_MENU = "Help Options\n\t-cfg= --cfg -cfg <path> > Path to config file override.\n\t-l --list > Print out full config.\n\t-v --version > Print out version and exit.\n\t-h --help > Display help menu.\n\n"
const VERSION = "1.0.0"
func wipe_server(cfg *config.Config, srv *config.Server, data *wipe.Data) {
debug.SendDebugMsg(srv.UUID, data.DebugLevel, 1, "Wiping server...")
// Add data for hooks.
hook_data := make(map[string]interface{})
hook_data["identifier"] = srv.UUID
hook_data["uuid"] = srv.LongID
hook_data["name"] = srv.Name
hook_data["ip"] = srv.IP
hook_data["port"] = srv.Port
hook_data["pre"] = false
hook_data["post"] = false
// Check if we need to send a prehook.
if len(cfg.PreHook) > 0 {
// Set wipe type.
hook_data["pre"] = true
// Send HTTP request to prehook endpoint.
d, _, err := chttp.SendHTTPReq(cfg.PreHook, cfg.PreHookAuth, "POST", hook_data)
debug.SendDebugMsg(srv.UUID, data.DebugLevel, 3, "Sending prehook. Request => "+cfg.PreHook+". Post data => "+misc.CreateKeyPairs(hook_data)+".")
debug.SendDebugMsg(srv.UUID, data.DebugLevel, 4, "Prehook return data => "+d+".")
if err != nil {
debug.SendDebugMsg(srv.UUID, data.DebugLevel, 0, "Failed to send prehook request.")
fmt.Println(err)
}
}
// Process world info.
if data.ChangeWorldInfo {
debug.SendDebugMsg(srv.UUID, data.DebugLevel, 2, "Processing world info...")
wipe.ProcessWorldInfo(data, srv.UUID)
}
// Process host name.
if data.ChangeHostName {
debug.SendDebugMsg(srv.UUID, data.DebugLevel, 2, "Processing hostname...")
wipe.ProcessHostName(data, srv.UUID)
}
debug.SendDebugMsg(srv.UUID, data.DebugLevel, 2, "Stopping server...")
// We should stop the server
wipe.StopServer(data, srv.UUID)
// Wait until the server is confirmed stopped.
i := 0
for true {
// Check if the server is running and when it is confirmed stop, break the loop.
state, err := wipe.GetServerState(data, srv.UUID)
// Check for error. Otherwise, break if we're not running.
if err != nil {
fmt.Println(err)
} else {
if state == "offline" {
debug.SendDebugMsg(srv.UUID, data.DebugLevel, 4, "Found server offline. Continuing..")
break
}
}
// Increment i.
i++
// Kill the server after 15 seconds.
if i == 15 {
debug.SendDebugMsg(srv.UUID, data.DebugLevel, 2, "Found up for 15 seconds. Trying to kill server...")
wipe.KillServer(data, srv.UUID)
}
// Give up after a minute.
if i > 60 {
debug.SendDebugMsg(srv.UUID, data.DebugLevel, 2, "Server halt timed out...")
break
}
// Sleep every second to avoid unnecessary CPU cycles.
time.Sleep(time.Duration(time.Second))
}
debug.SendDebugMsg(srv.UUID, data.DebugLevel, 2, "Processing files...")
// Process and delete files.
wipe.ProcessFiles(data, srv.UUID)
debug.SendDebugMsg(srv.UUID, data.DebugLevel, 2, "Starting server back up...")
// Start server back up.
wipe.StartServer(data, srv.UUID)
// Make sure the server starts back up.
i = 0
failed := 0
for true {
// Check if the server is running or starting. If confirmed, break loop.
state, err := wipe.GetServerState(data, srv.UUID)
// Check for error. Otherwise, break if we're not running.
if err != nil {
fmt.Println(err)
} else {
if state == "starting" || state == "running" {
debug.SendDebugMsg(srv.UUID, data.DebugLevel, 4, "Found server starting/running. Continuing..")
break
}
}
// Increment i.
i++
// If we hit 15, start server again and reset i.
if i == 15 {
wipe.StartServer(data, srv.UUID)
failed++
i = 0
}
// Give up after 5 attempts.
if failed > 5 {
break
}
// Sleep every second to avoid unnecessary CPU cycles.
time.Sleep(time.Duration(time.Second))
}
// Check if we need to send a posthook.
if len(cfg.PostHook) > 0 {
// Set wipe type.
hook_data["post"] = true
// Send HTTP request to posthook endpoint.
d, _, err := chttp.SendHTTPReq(cfg.PostHook, cfg.PostHook, "POST", hook_data)
debug.SendDebugMsg(srv.UUID, data.DebugLevel, 3, "Sending posthook. Request => "+cfg.PostHook+". Post data => "+misc.CreateKeyPairs(hook_data)+".")
debug.SendDebugMsg(srv.UUID, data.DebugLevel, 4, "Posthook return data => "+d+".")
if err != nil {
debug.SendDebugMsg(srv.UUID, data.DebugLevel, 0, "Failed to send posthook request.")
fmt.Println(err)
}
}
}
func srv_handler(cfg *config.Config, srv *config.Server) error {
var err error
// Environmental overrides.
wipe.EnvOverride(cfg, srv)
// We need to retrieve the wipe data information first.
var data wipe.Data
// Process wipe data first.
wipe.ProcessData(&data, cfg, srv)
// Create cron job handler.
c := cron.New()
// If we have a single string, spawn a single cron job.
for _, c_str := range data.CronStr {
_, err = c.AddFunc("CRON_TZ="+data.TimeZone+" "+c_str, func() {
wipe_server(cfg, srv, &data)
next_wipe := "N/A"
earliest := int64(1<<63 - 1)
for _, cron := range c.Entries() {
wipe_time := cron.Next.Unix()
// If it's earlier, choose this one.
//fmt.Println(strconv.FormatInt(wipe_time, 10) + " < " + strconv.FormatInt(earliest, 10))
if wipe_time < earliest {
earliest = wipe_time
tz, err := time.LoadLocation(data.TimeZone)
if err != nil {
fmt.Println(err)
continue
}
next_wipe = cron.Next.In(tz).Format("01-02-2006 3:04 PM MST")
}
}
debug.SendDebugMsg(srv.UUID, data.DebugLevel, 1, "Server wiped. Next wipe date => "+next_wipe+".")
})
if err != nil {
fmt.Println(err)
}
}
// Start cron job.
c.Start()
// Loop through each cron entry and print the next wipe date for debug.
for _, job := range c.Entries() {
tz, err := time.LoadLocation(data.TimeZone)
if err != nil {
fmt.Println(err)
continue
}
// Retrieve the next time the job will be ran (Unix timestamp).
next := job.Next.In(tz).Format("01-02-2006 3:04 PM MST")
debug.SendDebugMsg(srv.UUID, data.DebugLevel, 1, "Next wipe date => "+next+".")
}
// See if we need to do a startup/first wipe.
if srv.WipeFirst {
wipe_server(cfg, srv, &data)
}
for true {
// Loop through each cron entry.
for _, job := range c.Entries() {
// Retrieve the next time the job will be ran (Unix timestamp).
now := time.Now().Unix()
next := job.Next.Unix()
// Loop through warning messages.
for _, warning := range data.WarningMessages {
wt := next - now
// If what's remaining equals the warning time, we need to warn.
if wt == int64(warning.WarningTime) {
// Check if we're in running state.
state, err := wipe.GetServerState(&data, srv.UUID)
if err != nil {
time.Sleep(time.Duration(time.Second))
continue
}
if state != "running" {
time.Sleep(time.Duration(time.Second))
continue
}
warning_msg := *warning.Message
format.FormatString(&warning_msg, int(wt))
debug.SendDebugMsg(srv.UUID, data.DebugLevel, 2, "Sending warning message => "+warning_msg+".")
err = wipe.SendMessage(&data, srv.UUID, warning_msg)
if err != nil {
fmt.Println(err)
}
}
}
}
// Sleep for one second to avoid unnecessary CPU cycles.
time.Sleep(time.Duration(time.Second))
}
return err
}
func main() {
var list bool
var version bool
var help bool
// Setup simple flags (booleans).
flag.BoolVar(&list, "list", false, "Print out config and exit.")
flag.BoolVar(&list, "l", false, "Print out config and exit.")
flag.BoolVar(&version, "version", false, "Print out version and exit.")
flag.BoolVar(&version, "v", false, "Print out version and exit.")
flag.BoolVar(&help, "help", false, "Print out help menu and exit.")
flag.BoolVar(&help, "h", false, "Print out help menu and exit.")
// Look for 'cfg' flag in command line arguments (default path: /etc/raw/raw.conf).
configFile := flag.String("cfg", "/etc/raw/raw.conf", "The path to the Rust Auto Wipe config file.")
// Parse flags.
flag.Parse()
// Check for version flag.
if version {
fmt.Print(VERSION)
os.Exit(0)
}
// Check for help flag.
if help {
fmt.Print(HELP_MENU)
os.Exit(0)
}
// Create config struct.
cfg := config.Config{}
// Set config defaults.
cfg.SetDefaults()
// Attempt to read config.
err := cfg.LoadConfig(*configFile)
// If we have no config, create the file with the defaults.
if err != nil {
// If there's an error and it contains "no such file", try to create the file with defaults.
if strings.Contains(err.Error(), "no such file") {
err = cfg.WriteDefaultsToFile(*configFile)
if err != nil {
fmt.Println("Failed to open config file and cannot create file.")
fmt.Println(err)
os.Exit(1)
}
}
fmt.Println("WARNING - No config file found. Created config file at " + *configFile + " with defaults.")
} else {
// See if we want to automatically add servers.
autoaddservers.AddServers(&cfg)
}
// Check for list flag.
if list {
// Process environmental data before returning list.
for i := 0; i < len(cfg.Servers); i++ {
srv := &cfg.Servers[i]
wipe.EnvOverride(&cfg, srv)
}
// Encode config as JSON string.
json_data, err := json.MarshalIndent(cfg, "", " ")
if err != nil {
fmt.Println(err)
os.Exit(1)
}
fmt.Println(string(json_data))
os.Exit(0)
}
// If we don't have any servers, what's the point?
if len(cfg.Servers) < 1 {
fmt.Println("[ERR] No servers found.")
os.Exit(1)
}
// Loop through each server and execute Go routine.
for _, srv := range cfg.Servers {
// Check if we're enabled.
if !srv.Enabled {
continue
}
var srv_two config.Server = srv
// Spawn Go routine.
go srv_handler(&cfg, &srv_two)
}
// Signal.
sigc := make(chan os.Signal, 1)
signal.Notify(sigc, syscall.SIGINT, syscall.SIGTERM)
<-sigc
os.Exit(0)
}