Compare commits
12 Commits
336973443d
...
auth
| Author | SHA1 | Date | |
|---|---|---|---|
| dcee28d00f | |||
| d610a84718 | |||
| 806ca3d2e7 | |||
| 4b5e957eaa | |||
| 61934bb2f4 | |||
| c52e505c18 | |||
| 2497b37d21 | |||
| 318d473fec | |||
| 0a5cfe83fc | |||
| 96cc41ee43 | |||
| 988bdfcf6c | |||
| c3e17f9a80 |
75
README.md
75
README.md
@@ -22,30 +22,93 @@ Setup is easy from source, all you need is:
|
||||
- Run `./vssm` with no arguments to show usage
|
||||
|
||||
## Configuration
|
||||
**For now, the configuration file is stored in `~/.config/vssm/config.json`, but this will be configurable later.**
|
||||
The default configuration file is stored in `~/.local/share/vssm/config.json`, however you can pass the `--config <path>` flag to any command to use a custom configuration. You can also set the `VSSM_CONFIG_PATH` environment variable in lieu of using the config flag for every command.
|
||||
|
||||
The default configuration:
|
||||
```json
|
||||
{
|
||||
"storage": {
|
||||
"app_data_dir": "",
|
||||
"install_dir": "/home/user/.local/share/vssm/vssm_data/installs",
|
||||
"instances_dir": "/home/user/.local/share/vssm/vssm_data/instances",
|
||||
"backup_dir": "/home/user/.local/share/vssm/vssm_data/backups",
|
||||
"config_templates_dir": "/home/user/.local/share/vssm/vssm_data/config_templates"
|
||||
},
|
||||
"daemon": {
|
||||
"listen_address": "127.0.0.1",
|
||||
"port": 65000
|
||||
},
|
||||
"instances": {
|
||||
"test_server": {
|
||||
"Version": "1.22.3",
|
||||
"ServerName": "test_server",
|
||||
"Port": 12345,
|
||||
"config": null
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
- Storage
|
||||
- install_dir - The directory where versioned server binaries are stored
|
||||
- instances_dir - Directory for instances and their data
|
||||
- backup_dir - Directory for automatic backups of instances
|
||||
- config_templates_dir - Directory for versioned server configuration templates
|
||||
|
||||
- Daemon
|
||||
- port - The port the daemon listens on for http requests
|
||||
- listen_address - The IP address the daemon listens on
|
||||
|
||||
- Instances
|
||||
- Version - The game version
|
||||
- ServerName - The name of the instance
|
||||
- Port - The port the instance is listening on
|
||||
- config - This allows you to set ANY configuration item from the config, example below:
|
||||
|
||||
Example instance with extra configuration:
|
||||
**NOTE:** Most settings that are filepaths should be left alone in the instance config settings, as they will be overwritten automatically (like the ModPaths setting).
|
||||
**NOTE:** Roles settings must be modified in the actual instance config
|
||||
```json
|
||||
"test_server": {
|
||||
"Version": "1.22.3",
|
||||
"ServerName": "test_server",
|
||||
"Port": 12345,
|
||||
"config": {
|
||||
"AllowPvP": true,
|
||||
"WhiteListMode": 1,
|
||||
"WelcomeMessage": "Welcome to the server, {0}!",
|
||||
"WorldConfig": {
|
||||
"Seed": "superawesomeseed",
|
||||
"WorldName": "A new world",
|
||||
"PlayStyle": "surviveandbuild"
|
||||
}
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
## Web Interface
|
||||
Alongside this project, I am developing a seperate web-based dashboard that can be used to manage you servers with a very simple UI. You can get it [here](https://git.bellsworne.tech/chrisbell/vssm_web).
|
||||
Alongside this project, I am developing a seperate web-based dashboard that can be used to manage you servers with a very simple UI. You can get it [HERE](https://git.bellsworne.tech/chrisbell/vssm_web).
|
||||
|
||||
## Roadmap
|
||||
|
||||
- [ ] Configuration
|
||||
- [x] Configuration
|
||||
- [x] Custom configuration path (passed to the daemon with a flag `--config`)
|
||||
- [x] Daemon instance remembers config path (*so you don't have to pass `--config` everytime you run an ipc command*)
|
||||
- [ ] Daemon listen port (kind of implemented, could be cleaner)
|
||||
- [x] Daemon listen port
|
||||
- [x] Declarative Server configuration (Create servers in config)
|
||||
- [ ] More configuration options
|
||||
- [x] All configuration options
|
||||
- [x] Endpoint for modifying instance configuration (for web ui)
|
||||
|
||||
- [ ] Server management
|
||||
- [x] Create servers
|
||||
- [x] Automatic server binary downloading by version
|
||||
- [x] Delete servers
|
||||
- [x] Start/Stop servers
|
||||
- [ ] Server configuration
|
||||
- [x] Server configuration
|
||||
- [x] Download correct configuration template for version (see availible templates [here](https://git.bellsworne.tech/chrisbell/vssm_config_templates))
|
||||
- [x] Version
|
||||
- [x] Server Name
|
||||
- [x] Port
|
||||
- [x] Full declarative configuration support in main app config
|
||||
- [x] Multiple servers support
|
||||
- [x] List servers and their status
|
||||
- [x] Send commands to servers
|
||||
|
||||
14
config.go
14
config.go
@@ -18,25 +18,26 @@ type AppConfig struct {
|
||||
|
||||
Daemon struct {
|
||||
ListenAddress string `json:"listen_address"`
|
||||
Port int `json:"port"`
|
||||
AuthToken string `json:"auth_token"`
|
||||
} `json:"daemon"`
|
||||
|
||||
Instances map[string]VsServerConfigOptions `json:"instances"`
|
||||
Instances map[string]InstanceMetadata `json:"instances"`
|
||||
}
|
||||
|
||||
func CreateConfigWithDefaults(configPath string) *AppConfig {
|
||||
home, _ := os.UserHomeDir()
|
||||
basePath := filepath.Join(home, ".local", "share", "vssm")
|
||||
basePath := filepath.Join(filepath.Dir(configPath), "vssm_data")
|
||||
|
||||
cfg := &AppConfig{}
|
||||
cfg.Storage.AppDataDir = basePath
|
||||
cfg.Storage.InstallDir = filepath.Join(basePath, "installs")
|
||||
cfg.Storage.InstancesDir = filepath.Join(basePath, "instances")
|
||||
cfg.Storage.BackupDir = filepath.Join(basePath, "backups")
|
||||
cfg.Storage.ConfigTemplatesDir = filepath.Join(basePath, "config_templates")
|
||||
|
||||
cfg.Daemon.ListenAddress = "127.0.0.1:12345"
|
||||
cfg.Daemon.ListenAddress = "127.0.0.1"
|
||||
cfg.Daemon.Port = 65000
|
||||
|
||||
cfg.Instances = make(map[string]VsServerConfigOptions)
|
||||
cfg.Instances = make(map[string]InstanceMetadata)
|
||||
|
||||
return cfg
|
||||
}
|
||||
@@ -70,7 +71,6 @@ func LoadOrCreateConfig(configPath string) (*AppConfig, error) {
|
||||
}
|
||||
|
||||
dirs := []string{
|
||||
cfg.Storage.AppDataDir,
|
||||
cfg.Storage.InstallDir,
|
||||
cfg.Storage.InstancesDir,
|
||||
cfg.Storage.BackupDir,
|
||||
|
||||
222
daemon.go
222
daemon.go
@@ -1,18 +1,26 @@
|
||||
package main
|
||||
|
||||
import (
|
||||
"embed"
|
||||
"encoding/json"
|
||||
"fmt"
|
||||
"io"
|
||||
"io/fs"
|
||||
"net/http"
|
||||
"os"
|
||||
"os/signal"
|
||||
"path/filepath"
|
||||
"slices"
|
||||
"strconv"
|
||||
"strings"
|
||||
"sync"
|
||||
"syscall"
|
||||
"time"
|
||||
)
|
||||
|
||||
//go:embed web/dist
|
||||
var webFS embed.FS
|
||||
|
||||
type CommandPayload struct {
|
||||
Command string `json:"command"`
|
||||
}
|
||||
@@ -46,22 +54,56 @@ func StartDaemon(cfg *AppConfig, configPath string) error {
|
||||
mux.HandleFunc("/instances/list", ds.handleList)
|
||||
mux.HandleFunc("/instances/logs", ds.handleGetLogs)
|
||||
mux.HandleFunc("/instances/delete", ds.handleDelete)
|
||||
mux.HandleFunc("/instances/modify", ds.handleModify)
|
||||
mux.HandleFunc("/instances/getConfig", ds.handleGetConfig)
|
||||
mux.HandleFunc("/instances/setConfig", ds.handleSetConfig)
|
||||
|
||||
webContent, err := fs.Sub(webFS, "web/dist")
|
||||
if err != nil {
|
||||
return fmt.Errorf("failed to load embedded web assets: %w", err)
|
||||
}
|
||||
mux.Handle("/", http.FileServer(http.FS(webContent)))
|
||||
|
||||
corsWrappedHandler := http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
|
||||
w.Header().Set("Access-Control-Allow-Origin", "*")
|
||||
w.Header().Set("Access-Control-Allow-Methods", "POST, GET, OPTIONS")
|
||||
w.Header().Set("Access-Control-Allow-Headers", "Content-Type")
|
||||
w.Header().Set("Access-Control-Allow-Headers", "Content-Type, Authorization")
|
||||
|
||||
if r.Method == http.MethodOptions {
|
||||
w.WriteHeader(http.StatusOK)
|
||||
return
|
||||
}
|
||||
|
||||
authCheck := func() bool {
|
||||
if !strings.HasPrefix(r.URL.Path, "/instances/") {
|
||||
return true
|
||||
}
|
||||
|
||||
ds.RLock()
|
||||
defer ds.RUnlock()
|
||||
if ds.cfg.Daemon.AuthToken != "" {
|
||||
authHeader := r.Header.Get("Authorization")
|
||||
expected := "Bearer " + ds.cfg.Daemon.AuthToken
|
||||
if authHeader != expected {
|
||||
http.Error(w, "Unauthorized", http.StatusUnauthorized)
|
||||
return false
|
||||
}
|
||||
}
|
||||
|
||||
return true
|
||||
}()
|
||||
|
||||
if !authCheck {
|
||||
return
|
||||
}
|
||||
|
||||
mux.ServeHTTP(w, r)
|
||||
})
|
||||
|
||||
listenAddress := cfg.Daemon.ListenAddress + ":" + strconv.Itoa(cfg.Daemon.Port)
|
||||
|
||||
server := &http.Server{
|
||||
Addr: cfg.Daemon.ListenAddress,
|
||||
Addr: listenAddress,
|
||||
Handler: corsWrappedHandler,
|
||||
}
|
||||
|
||||
@@ -69,7 +111,7 @@ func StartDaemon(cfg *AppConfig, configPath string) error {
|
||||
signal.Notify(sigChan, os.Interrupt, syscall.SIGTERM)
|
||||
|
||||
go func() {
|
||||
fmt.Printf("Engine daemon actively listening on http://%s\n", cfg.Daemon.ListenAddress)
|
||||
fmt.Printf("Engine daemon actively listening on http://%s\n", listenAddress)
|
||||
if err := server.ListenAndServe(); err != http.ErrServerClosed {
|
||||
fmt.Printf("Daemon runtime failure: %v\n", err)
|
||||
}
|
||||
@@ -193,11 +235,10 @@ func (ds *DaemonServer) handleCreate(w http.ResponseWriter, r *http.Request) {
|
||||
}
|
||||
}
|
||||
|
||||
options := VsServerConfigOptions{
|
||||
metadata := InstanceMetadata{
|
||||
Version: version,
|
||||
ServerName: name,
|
||||
Port: converted_port,
|
||||
MaxClients: 10,
|
||||
}
|
||||
|
||||
err = DownloadAndExtractServer(version, ds.cfg.Storage.InstallDir)
|
||||
@@ -206,13 +247,13 @@ func (ds *DaemonServer) handleCreate(w http.ResponseWriter, r *http.Request) {
|
||||
return
|
||||
}
|
||||
|
||||
err = CreateNewInstance(name, version, options, ds.cfg)
|
||||
err = CreateNewInstance(name, version, metadata, ds.cfg)
|
||||
if err != nil {
|
||||
http.Error(w, fmt.Sprintf("Instance provisioning failed: %v", err), http.StatusInternalServerError)
|
||||
return
|
||||
}
|
||||
|
||||
ds.cfg.Instances[name] = options
|
||||
ds.cfg.Instances[name] = metadata
|
||||
|
||||
data, err := json.MarshalIndent(ds.cfg, "", " ")
|
||||
if err != nil {
|
||||
@@ -356,6 +397,16 @@ func (ds *DaemonServer) handleList(w http.ResponseWriter, r *http.Request) {
|
||||
})
|
||||
}
|
||||
|
||||
slices.SortFunc(responseList, func(a, b InstanceStatusResponse) int {
|
||||
if a.Name < b.Name {
|
||||
return -1
|
||||
}
|
||||
if a.Name > b.Name {
|
||||
return 1
|
||||
}
|
||||
return 0
|
||||
})
|
||||
|
||||
w.Header().Set("Content-Type", "application/json")
|
||||
w.WriteHeader(http.StatusOK)
|
||||
json.NewEncoder(w).Encode(responseList)
|
||||
@@ -462,3 +513,160 @@ func (ds *DaemonServer) handleDelete(w http.ResponseWriter, r *http.Request) {
|
||||
fmt.Fprintf(w, "Successfully deleted instance %s", name)
|
||||
|
||||
}
|
||||
|
||||
func (ds *DaemonServer) handleModify(w http.ResponseWriter, r *http.Request) {
|
||||
if r.Method != http.MethodPost {
|
||||
http.Error(w, "Method not allowed", http.StatusMethodNotAllowed)
|
||||
return
|
||||
}
|
||||
|
||||
name := r.URL.Query().Get("name")
|
||||
if name == "" {
|
||||
http.Error(w, "Missing name parameter", http.StatusBadRequest)
|
||||
return
|
||||
}
|
||||
|
||||
newName := r.URL.Query().Get("newName")
|
||||
if newName == "" {
|
||||
http.Error(w, "Missing newName parameter", http.StatusBadRequest)
|
||||
return
|
||||
}
|
||||
|
||||
newPort := r.URL.Query().Get("newPort")
|
||||
if newPort == "" {
|
||||
http.Error(w, "Missing newPort parameter", http.StatusBadRequest)
|
||||
return
|
||||
}
|
||||
|
||||
convertedPort, err := strconv.Atoi(newPort)
|
||||
if err != nil {
|
||||
http.Error(w, "Could not convert provided port to a valid port number", http.StatusBadRequest)
|
||||
return
|
||||
}
|
||||
|
||||
ds.Lock()
|
||||
defer ds.Unlock()
|
||||
|
||||
ds.procManager.RLock()
|
||||
defer ds.procManager.RUnlock()
|
||||
|
||||
instance, exists := ds.cfg.Instances[name]
|
||||
if !exists {
|
||||
http.Error(w, fmt.Sprintf("Cannot modify instance '%s'; Does not exist.", name), http.StatusBadRequest)
|
||||
return
|
||||
}
|
||||
|
||||
if _, running := ds.procManager.ActiveInstances[name]; running {
|
||||
http.Error(w, fmt.Sprintf("Cannot modify instance '%s'; It is currently running.", name), http.StatusBadRequest)
|
||||
return
|
||||
}
|
||||
|
||||
instance.ServerName = newName
|
||||
instance.Port = convertedPort
|
||||
ds.cfg.Instances[name] = instance
|
||||
|
||||
data, err := json.MarshalIndent(ds.cfg, "", " ")
|
||||
if err != nil {
|
||||
http.Error(w, fmt.Sprintf("Failed processing profile adjustments: %v", err), http.StatusInternalServerError)
|
||||
return
|
||||
}
|
||||
|
||||
if err := os.WriteFile(ds.configPath, data, 0644); err != nil {
|
||||
http.Error(w, fmt.Sprintf("Failed saving configuration adjustments to disk: %v", err), http.StatusInternalServerError)
|
||||
return
|
||||
}
|
||||
|
||||
instanceConfigPath := filepath.Join(ds.cfg.Storage.InstancesDir, name, "serverconfig.json")
|
||||
err = SyncInstanceConfig(instance.Version, instanceConfigPath, instance, ds.cfg)
|
||||
if err != nil {
|
||||
http.Error(w, "Failed to sync config: "+err.Error(), http.StatusInternalServerError)
|
||||
return
|
||||
}
|
||||
|
||||
w.WriteHeader(http.StatusOK)
|
||||
fmt.Fprintf(w, "Successfully modified instance %s", name)
|
||||
|
||||
}
|
||||
|
||||
func (ds *DaemonServer) handleGetConfig(w http.ResponseWriter, r *http.Request) {
|
||||
if r.Method != http.MethodGet {
|
||||
http.Error(w, "Method not allowed", http.StatusMethodNotAllowed)
|
||||
return
|
||||
}
|
||||
|
||||
name := r.URL.Query().Get("name")
|
||||
if name == "" {
|
||||
http.Error(w, "Missing name parameter", http.StatusBadRequest)
|
||||
return
|
||||
}
|
||||
|
||||
exists := func() bool {
|
||||
ds.RLock()
|
||||
defer ds.RUnlock()
|
||||
_, ok := ds.cfg.Instances[name]
|
||||
return ok
|
||||
}()
|
||||
if !exists {
|
||||
http.Error(w, fmt.Sprintf("Cannot modify instance config for: '%s'; Does not exist.", name), http.StatusBadRequest)
|
||||
return
|
||||
}
|
||||
|
||||
confPath := filepath.Join(ds.cfg.Storage.InstancesDir, name, "serverconfig.json")
|
||||
data, err := os.ReadFile(confPath)
|
||||
if err != nil {
|
||||
http.Error(w, fmt.Sprintf("Failed to get instance config: %v", err), http.StatusInternalServerError)
|
||||
return
|
||||
}
|
||||
|
||||
w.Header().Set("Content-Type", "application/json")
|
||||
w.Write(data)
|
||||
}
|
||||
|
||||
func (ds *DaemonServer) handleSetConfig(w http.ResponseWriter, r *http.Request) {
|
||||
if r.Method != http.MethodPost {
|
||||
http.Error(w, "Method not allowed", http.StatusMethodNotAllowed)
|
||||
return
|
||||
}
|
||||
|
||||
name := r.URL.Query().Get("name")
|
||||
if name == "" {
|
||||
http.Error(w, "Missing name parameter", http.StatusBadRequest)
|
||||
return
|
||||
}
|
||||
|
||||
exists := func() bool {
|
||||
ds.RLock()
|
||||
defer ds.RUnlock()
|
||||
_, ok := ds.cfg.Instances[name]
|
||||
return ok
|
||||
}()
|
||||
if !exists {
|
||||
http.Error(w, fmt.Sprintf("Cannot modify instance config for: '%s'; Does not exist.", name), http.StatusBadRequest)
|
||||
return
|
||||
}
|
||||
|
||||
running := func() bool {
|
||||
ds.procManager.RLock()
|
||||
defer ds.procManager.RUnlock()
|
||||
_, ok := ds.procManager.ActiveInstances[name]
|
||||
return ok
|
||||
}()
|
||||
if running {
|
||||
http.Error(w, fmt.Sprintf("Cannot modify instance config for: '%s'; It is currently running.", name), http.StatusBadRequest)
|
||||
return
|
||||
}
|
||||
|
||||
data, err := io.ReadAll(r.Body)
|
||||
if err != nil {
|
||||
http.Error(w, fmt.Sprintf("Failed to set instance config: %v", err), http.StatusInternalServerError)
|
||||
return
|
||||
}
|
||||
|
||||
confPath := filepath.Join(ds.cfg.Storage.InstancesDir, name, "serverconfig.json")
|
||||
if err = os.WriteFile(confPath, data, 0644); err != nil {
|
||||
http.Error(w, fmt.Sprintf("Failed to get instance config: %v", err), http.StatusInternalServerError)
|
||||
return
|
||||
}
|
||||
|
||||
w.WriteHeader(http.StatusOK)
|
||||
}
|
||||
|
||||
@@ -98,14 +98,12 @@ func patchBinaryForNixos(binaryPath string) error {
|
||||
return nil
|
||||
}
|
||||
|
||||
fmt.Println("[NixOS Detected] Patching server interpreter pathway...")
|
||||
fmt.Println("[NixOS Detected] Patching server binary...")
|
||||
|
||||
dotnetRoot := os.Getenv("DOTNET_ROOT")
|
||||
var interpreter string
|
||||
|
||||
if dotnetRoot != "" {
|
||||
// Use the glibc version that matches the active .NET runtime exactly
|
||||
// Finds the underlying ld-linux-x86-64.so.2 link within the .NET store closure
|
||||
out, err := exec.Command("patchelf", "--print-interpreter", filepath.Join(dotnetRoot, "dotnet")).Output()
|
||||
if err == nil && len(out) > 0 {
|
||||
interpreter = strings.TrimSpace(string(out))
|
||||
|
||||
@@ -13,7 +13,7 @@ const (
|
||||
StateRunning InstanceState = "RUNNING"
|
||||
)
|
||||
|
||||
func CreateNewInstance(name string, version string, options VsServerConfigOptions, cfg *AppConfig) error {
|
||||
func CreateNewInstance(name string, version string, meta InstanceMetadata, cfg *AppConfig) error {
|
||||
instanceDir := filepath.Join(cfg.Storage.InstancesDir, name)
|
||||
|
||||
dirs := []string{
|
||||
@@ -29,8 +29,8 @@ func CreateNewInstance(name string, version string, options VsServerConfigOption
|
||||
}
|
||||
|
||||
instanceConfigPath := filepath.Join(instanceDir, "serverconfig.json")
|
||||
if err := PrepareInstanceConfig(version, instanceConfigPath, options, cfg); err != nil {
|
||||
return fmt.Errorf("Failed provisioning server baseline configuration: %w", err)
|
||||
if err := PrepareInstanceConfig(version, instanceConfigPath, meta, cfg); err != nil {
|
||||
return fmt.Errorf("Failed to create baseline configuration: %w", err)
|
||||
}
|
||||
|
||||
fmt.Printf("Instance '%s' (v%s) successfully initialized\n", name, version)
|
||||
|
||||
@@ -10,23 +10,18 @@ import (
|
||||
"strings"
|
||||
)
|
||||
|
||||
type VsServerConfigOptions struct {
|
||||
type InstanceMetadata struct {
|
||||
Version string `json:"Version"`
|
||||
ServerName string `json:"ServerName"`
|
||||
Port int `json:"Port"`
|
||||
IpAddress string `json:"IpAddress"`
|
||||
MaxClients int `json:"MaxClients"`
|
||||
Password string `json:"Password"`
|
||||
DefaultRole string `json:"DefaultRole"`
|
||||
GuestRole string `json:"GuestRole"`
|
||||
PreApprovedRole string `json:"PreApprovedRole"`
|
||||
Config map[string]interface{} `json:"config"`
|
||||
}
|
||||
|
||||
func PrepareInstanceConfig(templateVersion string, instanceConfigPath string, options VsServerConfigOptions, cfg *AppConfig) error {
|
||||
return SyncInstanceConfig(templateVersion, instanceConfigPath, options, cfg)
|
||||
func PrepareInstanceConfig(templateVersion string, instanceConfigPath string, meta InstanceMetadata, cfg *AppConfig) error {
|
||||
return SyncInstanceConfig(templateVersion, instanceConfigPath, meta, cfg)
|
||||
}
|
||||
|
||||
func SyncInstanceConfig(templateVersion string, instanceConfigPath string, options VsServerConfigOptions, cfg *AppConfig) error {
|
||||
func SyncInstanceConfig(templateVersion string, instanceConfigPath string, meta InstanceMetadata, cfg *AppConfig) error {
|
||||
templatePath := filepath.Join(cfg.Storage.ConfigTemplatesDir, templateVersion, "serverconfig.json")
|
||||
|
||||
if err := ensureTemplateExists(templateVersion, templatePath, cfg); err != nil {
|
||||
@@ -66,15 +61,20 @@ func SyncInstanceConfig(templateVersion string, instanceConfigPath string, optio
|
||||
return fmt.Errorf("failed parsing configuration JSON payload: %w", err)
|
||||
}
|
||||
|
||||
rawConfig["ServerName"] = options.ServerName
|
||||
rawConfig["Port"] = options.Port
|
||||
rawConfig["MaxClients"] = options.MaxClients
|
||||
|
||||
if options.Password != "" {
|
||||
rawConfig["Password"] = options.Password
|
||||
} else {
|
||||
rawConfig["Password"] = nil
|
||||
for key, value := range meta.Config {
|
||||
if sub, ok := value.(map[string]interface{}); ok {
|
||||
if existing, ok := rawConfig[key].(map[string]interface{}); ok {
|
||||
for k, v := range sub {
|
||||
existing[k] = v
|
||||
}
|
||||
}
|
||||
} else {
|
||||
rawConfig[key] = value
|
||||
}
|
||||
}
|
||||
|
||||
rawConfig["ServerName"] = meta.ServerName
|
||||
rawConfig["Port"] = meta.Port
|
||||
|
||||
instanceDir := filepath.Dir(instanceConfigPath)
|
||||
if worldConfig, ok := rawConfig["WorldConfig"].(map[string]interface{}); ok {
|
||||
|
||||
124
main.go
124
main.go
@@ -2,6 +2,8 @@ package main
|
||||
|
||||
import (
|
||||
"bytes"
|
||||
"crypto/rand"
|
||||
"encoding/hex"
|
||||
"encoding/json"
|
||||
"flag"
|
||||
"fmt"
|
||||
@@ -13,6 +15,7 @@ import (
|
||||
"path/filepath"
|
||||
"strconv"
|
||||
"text/tabwriter"
|
||||
"time"
|
||||
)
|
||||
|
||||
func main() {
|
||||
@@ -21,7 +24,7 @@ func main() {
|
||||
log.Fatalf("Could not locate user home dir: %v", err)
|
||||
}
|
||||
|
||||
defaultConfigPath := filepath.Join(home, ".config", "vssm", "config.json")
|
||||
defaultConfigPath := filepath.Join(home, ".local", "share", "vssm", "config.json")
|
||||
|
||||
configFlag := flag.String("config", defaultConfigPath, "Explicit path targeting a custom vssm config.json profile")
|
||||
|
||||
@@ -63,16 +66,50 @@ func main() {
|
||||
log.Fatalf("Initialization failed: %v", err)
|
||||
}
|
||||
|
||||
listenAddress := cfg.Daemon.ListenAddress + ":" + strconv.Itoa(cfg.Daemon.Port)
|
||||
fmt.Printf("Got listen address from config: %s\n", listenAddress)
|
||||
|
||||
subCommand := args[0]
|
||||
|
||||
switch subCommand {
|
||||
|
||||
case "daemon":
|
||||
fmt.Printf("Initializing VS server manager background supervisor [Config: %s]...\n", absConfigPath)
|
||||
if isDaemonRunning(cfg) {
|
||||
log.Fatalf("Cannot start daemon as it is already running. Stop it first (`pkill vssm`).")
|
||||
}
|
||||
|
||||
fmt.Printf("Initializing VSSM Daemon [Config: %s]...\n", absConfigPath)
|
||||
if err := StartDaemon(cfg, absConfigPath); err != nil {
|
||||
log.Fatalf("Daemon runtime fatal error: %v", err)
|
||||
}
|
||||
|
||||
case "generate-token":
|
||||
if isDaemonRunning(cfg) {
|
||||
log.Fatalf("Cannot generate a new token while the daemon is running. Stop it first (`pkill vssm`).")
|
||||
}
|
||||
|
||||
token, err := generateToken()
|
||||
if err != nil {
|
||||
log.Fatalf("Failed to generate token: %v", err)
|
||||
}
|
||||
|
||||
overwritten := cfg.Daemon.AuthToken != ""
|
||||
cfg.Daemon.AuthToken = token
|
||||
|
||||
data, err := json.MarshalIndent(cfg, "", " ")
|
||||
if err != nil {
|
||||
log.Fatalf("Failed to marshal config: %v", err)
|
||||
}
|
||||
|
||||
if err := os.WriteFile(absConfigPath, data, 0644); err != nil {
|
||||
log.Fatalf("Failed to write config: %v", err)
|
||||
}
|
||||
|
||||
if overwritten {
|
||||
fmt.Println("Existing auth token was overwritten.")
|
||||
}
|
||||
fmt.Printf("New auth token: %s\n", token)
|
||||
|
||||
case "create":
|
||||
if len(args) < 4 {
|
||||
log.Fatalf("Usage: vssm create <instance_name> <version> <port>")
|
||||
@@ -126,25 +163,40 @@ func main() {
|
||||
|
||||
sendIPCRequest(cfg, "POST", fmt.Sprintf("/instances/delete?name=%s&purge=%s", url.QueryEscape(name), url.QueryEscape(strconv.FormatBool(*purge))), nil)
|
||||
|
||||
case "modify":
|
||||
if len(args) < 4 {
|
||||
log.Fatalf("Usage: vssm modify <instance_name> <new_name> <new_port>")
|
||||
}
|
||||
name := args[1]
|
||||
newName := args[2]
|
||||
newPort := args[3]
|
||||
sendIPCRequest(cfg, "POST", fmt.Sprintf("/instances/modify?name=%s&newName=%s&newPort=%s", url.QueryEscape(name), url.QueryEscape(newName), url.QueryEscape(newPort)), nil)
|
||||
|
||||
default:
|
||||
printUsage()
|
||||
}
|
||||
}
|
||||
|
||||
func sendIPCRequest(cfg *AppConfig, method string, path string, body io.Reader) {
|
||||
targetUrl := fmt.Sprintf("http://%s%s", cfg.Daemon.ListenAddress, path)
|
||||
listenAddress := cfg.Daemon.ListenAddress + ":" + strconv.Itoa(cfg.Daemon.Port)
|
||||
targetUrl := fmt.Sprintf("http://%s%s", listenAddress, path)
|
||||
fmt.Printf("Listen Addr: %s; Target URL: %s\n", listenAddress, targetUrl)
|
||||
req, err := http.NewRequest(method, targetUrl, body)
|
||||
if err != nil {
|
||||
log.Fatalf("Failed to construct IPC frame: %v", err)
|
||||
log.Fatalf("Failed to construct IPC request: %v", err)
|
||||
}
|
||||
|
||||
if body != nil {
|
||||
req.Header.Set("Content-Type", "application/json")
|
||||
}
|
||||
|
||||
if cfg.Daemon.AuthToken != "" {
|
||||
req.Header.Set("Authorization", "Bearer "+cfg.Daemon.AuthToken)
|
||||
}
|
||||
|
||||
resp, err := http.DefaultClient.Do(req)
|
||||
if err != nil {
|
||||
log.Fatalf("IPC connection failed. Is the vs-manager daemon running? Error: %v", err)
|
||||
log.Fatalf("IPC connection failed. Is the VSSM daemon running? Error: %v", err)
|
||||
}
|
||||
defer resp.Body.Close()
|
||||
|
||||
@@ -158,10 +210,21 @@ func sendIPCRequest(cfg *AppConfig, method string, path string, body io.Reader)
|
||||
}
|
||||
|
||||
func fetchAndPrintStatus(cfg *AppConfig) {
|
||||
targetUrl := fmt.Sprintf("http://%s/instances/list", cfg.Daemon.ListenAddress)
|
||||
resp, err := http.Get(targetUrl)
|
||||
listenAddress := cfg.Daemon.ListenAddress + ":" + strconv.Itoa(cfg.Daemon.Port)
|
||||
targetUrl := fmt.Sprintf("http://%s/instances/list", listenAddress)
|
||||
|
||||
req, err := http.NewRequest("GET", targetUrl, nil)
|
||||
if err != nil {
|
||||
log.Fatalf("IPC connection failed. Is the vs-manager daemon running? Error: %v", err)
|
||||
log.Fatalf("Failed to construct status request: %v", err)
|
||||
}
|
||||
|
||||
if cfg.Daemon.AuthToken != "" {
|
||||
req.Header.Set("Authorization", "Bearer "+cfg.Daemon.AuthToken)
|
||||
}
|
||||
|
||||
resp, err := http.DefaultClient.Do(req)
|
||||
if err != nil {
|
||||
log.Fatalf("IPC connection failed. Is the VSSM daemon running? Error: %v", err)
|
||||
}
|
||||
defer resp.Body.Close()
|
||||
|
||||
@@ -176,7 +239,7 @@ func fetchAndPrintStatus(cfg *AppConfig) {
|
||||
}
|
||||
|
||||
if len(instances) == 0 {
|
||||
fmt.Println("No instances configured yet. Use 'create' to provision one.")
|
||||
fmt.Println("No instances configured yet. Use 'create' to create one.")
|
||||
return
|
||||
}
|
||||
|
||||
@@ -190,15 +253,44 @@ func fetchAndPrintStatus(cfg *AppConfig) {
|
||||
w.Flush()
|
||||
}
|
||||
|
||||
func generateToken() (string, error) {
|
||||
bytes := make([]byte, 32)
|
||||
if _, err := rand.Read(bytes); err != nil {
|
||||
return "", err
|
||||
}
|
||||
return hex.EncodeToString(bytes), nil
|
||||
}
|
||||
|
||||
func isDaemonRunning(cfg *AppConfig) bool {
|
||||
listenAddress := cfg.Daemon.ListenAddress + ":" + strconv.Itoa(cfg.Daemon.Port)
|
||||
client := http.Client{Timeout: 500 * time.Millisecond}
|
||||
resp, err := client.Get(fmt.Sprintf("http://%s/instances/list", listenAddress))
|
||||
if err != nil {
|
||||
return false
|
||||
}
|
||||
resp.Body.Close()
|
||||
return true
|
||||
}
|
||||
|
||||
func printUsage() {
|
||||
fmt.Println("VintageStory Server Manager")
|
||||
fmt.Println("\nGlobal Options:")
|
||||
fmt.Println(" --config <path> Explicitly target a non-default config structure file location")
|
||||
|
||||
w := tabwriter.NewWriter(os.Stdout, 0, 0, 3, ' ', 0)
|
||||
fmt.Fprintln(w, " --config <path>\tExplicitly target a non-default config structure file location")
|
||||
w.Flush()
|
||||
|
||||
fmt.Println("\nUsage Commands:")
|
||||
fmt.Println(" vssm daemon Starts the background process supervisor")
|
||||
fmt.Println(" vssm create <name> <version> Provisions baseline configuration and stores instance profile")
|
||||
fmt.Println(" vssm start <name> Launches an existing server instance using stored profile")
|
||||
fmt.Println(" vssm stop <name> Gracefully shuts down a server instance")
|
||||
fmt.Println(" vssm cmd <name> \"<command>\" Dispatches a terminal console command down the pipe")
|
||||
fmt.Println(" vssm list Displays the operational matrix of all instances")
|
||||
|
||||
w = tabwriter.NewWriter(os.Stdout, 0, 0, 3, ' ', 0)
|
||||
fmt.Fprintln(w, " vssm daemon\tStarts the daemon")
|
||||
fmt.Fprintln(w, " vssm generate-token\tGenerates a new auth token and stores it in the config")
|
||||
fmt.Fprintln(w, " vssm create <name> <version> <port>\tCreates the instance configuration and profile")
|
||||
fmt.Fprintln(w, " vssm delete <name> [--purge]\tDeletes an instance profile, optionally deleting all files")
|
||||
fmt.Fprintln(w, " vssm start <name>\tLaunches an existing server instance from a stored profile")
|
||||
fmt.Fprintln(w, " vssm stop <name>\tGracefully shuts down a server instance")
|
||||
fmt.Fprintln(w, " vssm cmd <name> \"<command>\"\tSends a command to an instance")
|
||||
fmt.Fprintln(w, " vssm modify <name> <new_name> <new_port>\tRenames an instance and/or changes its port")
|
||||
fmt.Fprintln(w, " vssm list\tDisplays a list of all instances and their status")
|
||||
w.Flush()
|
||||
}
|
||||
|
||||
@@ -32,7 +32,7 @@ func NewProcessManager() *ProcessManager {
|
||||
}
|
||||
}
|
||||
|
||||
func (pm *ProcessManager) StartInstance(name string, version string, options VsServerConfigOptions, config *AppConfig) error {
|
||||
func (pm *ProcessManager) StartInstance(name string, version string, meta InstanceMetadata, config *AppConfig) error {
|
||||
pm.Lock()
|
||||
defer pm.Unlock()
|
||||
|
||||
|
||||
2
web/dist/index.html
vendored
Normal file
2
web/dist/index.html
vendored
Normal file
@@ -0,0 +1,2 @@
|
||||
<!DOCTYPE html>
|
||||
<html><body>Web UI not embedded in this build.</body></html>
|
||||
Reference in New Issue
Block a user