implement agent startup arguments and help message (#581)

This commit is contained in:
Alexander Mnich
2025-02-19 06:19:49 +01:00
committed by GitHub
parent 646b899851
commit 1a6a2a64f2

View File

@@ -3,6 +3,7 @@ package main
import ( import (
"beszel" "beszel"
"beszel/internal/agent" "beszel/internal/agent"
"flag"
"fmt" "fmt"
"log" "log"
"os" "os"
@@ -10,26 +11,53 @@ import (
) )
func main() { func main() {
// Define flags for key and port
keyFlag := flag.String("key", "", "Public key")
portFlag := flag.String("port", "45876", "Port number")
flag.Usage = func() {
fmt.Printf("Usage: %s [options] [subcommand]\n", os.Args[0])
fmt.Println("\nOptions:")
flag.PrintDefaults()
fmt.Println("\nSubcommands:")
fmt.Println(" version Display the version")
fmt.Println(" help Display this help message")
fmt.Println(" update Update the agent to the latest version")
}
// Parse the flags
flag.Parse()
// handle flags / subcommands // handle flags / subcommands
if len(os.Args) > 1 { if len(os.Args) > 1 {
switch os.Args[1] { switch os.Args[1] {
case "-v": case "version":
fmt.Println(beszel.AppName+"-agent", beszel.Version) fmt.Println(beszel.AppName+"-agent", beszel.Version)
os.Exit(0)
case "help":
flag.Usage()
os.Exit(0)
case "update": case "update":
agent.Update() agent.Update()
os.Exit(0)
} }
os.Exit(0)
} }
// Try to get the key from the KEY environment variable. var pubKey []byte
key, _ := agent.GetEnv("KEY") // Override the key if the -key flag is provided
pubKey := []byte(key) if *keyFlag != "" {
pubKey = []byte(*keyFlag)
} else {
// Try to get the key from the KEY environment variable.
key, _ := agent.GetEnv("KEY")
pubKey = []byte(key)
}
// If KEY is not set, try to read the key from the file specified by KEY_FILE. // If KEY is not set, try to read the key from the file specified by KEY_FILE.
if len(pubKey) == 0 { if len(pubKey) == 0 {
keyFile, exists := agent.GetEnv("KEY_FILE") keyFile, exists := agent.GetEnv("KEY_FILE")
if !exists { if !exists {
log.Fatal("Must set KEY or KEY_FILE environment variable") log.Fatal("Must set KEY or KEY_FILE environment variable or supply as input argument. Use 'beszel-agent help' for more information.")
} }
var err error var err error
pubKey, err = os.ReadFile(keyFile) pubKey, err = os.ReadFile(keyFile)
@@ -38,7 +66,10 @@ func main() {
} }
} }
addr := ":45876" // Init with default port
addr := ":" + *portFlag
//Use port from ENV if it exists
// TODO: change env var to ADDR // TODO: change env var to ADDR
if portEnvVar, exists := agent.GetEnv("PORT"); exists { if portEnvVar, exists := agent.GetEnv("PORT"); exists {
// allow passing an address in the form of "127.0.0.1:45876" // allow passing an address in the form of "127.0.0.1:45876"
@@ -48,5 +79,10 @@ func main() {
addr = portEnvVar addr = portEnvVar
} }
// Override the default and ENV port if the -port flag is provided and is non default
if *portFlag != "45876" {
addr = ":" + *portFlag
}
agent.NewAgent().Run(pubKey, addr) agent.NewAgent().Run(pubKey, addr)
} }